Value.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/AllOf.h>
  9. #include <AK/Assertions.h>
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/String.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/Utf8View.h>
  14. #include <LibCrypto/BigInt/SignedBigInteger.h>
  15. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/Accessor.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BigInt.h>
  20. #include <LibJS/Runtime/BigIntObject.h>
  21. #include <LibJS/Runtime/BooleanObject.h>
  22. #include <LibJS/Runtime/BoundFunction.h>
  23. #include <LibJS/Runtime/Completion.h>
  24. #include <LibJS/Runtime/Error.h>
  25. #include <LibJS/Runtime/FunctionObject.h>
  26. #include <LibJS/Runtime/GlobalObject.h>
  27. #include <LibJS/Runtime/NativeFunction.h>
  28. #include <LibJS/Runtime/NumberObject.h>
  29. #include <LibJS/Runtime/Object.h>
  30. #include <LibJS/Runtime/PrimitiveString.h>
  31. #include <LibJS/Runtime/ProxyObject.h>
  32. #include <LibJS/Runtime/RegExpObject.h>
  33. #include <LibJS/Runtime/StringObject.h>
  34. #include <LibJS/Runtime/StringPrototype.h>
  35. #include <LibJS/Runtime/SymbolObject.h>
  36. #include <LibJS/Runtime/VM.h>
  37. #include <LibJS/Runtime/Value.h>
  38. #include <math.h>
  39. namespace JS {
  40. static inline bool same_type_for_equality(Value const& lhs, Value const& rhs)
  41. {
  42. // If the top two bytes are identical then either:
  43. // both are NaN boxed Values with the same type
  44. // or they are doubles which happen to have the same top bytes.
  45. if ((lhs.encoded() & TAG_EXTRACTION) == (rhs.encoded() & TAG_EXTRACTION))
  46. return true;
  47. if (lhs.is_number() && rhs.is_number())
  48. return true;
  49. // One of the Values is not a number and they do not have the same tag
  50. return false;
  51. }
  52. static const Crypto::SignedBigInteger BIGINT_ZERO { 0 };
  53. ALWAYS_INLINE bool both_number(Value const& lhs, Value const& rhs)
  54. {
  55. return lhs.is_number() && rhs.is_number();
  56. }
  57. ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs)
  58. {
  59. return lhs.is_bigint() && rhs.is_bigint();
  60. }
  61. // 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring
  62. static String double_to_string(double d)
  63. {
  64. if (isnan(d))
  65. return "NaN";
  66. if (d == +0.0 || d == -0.0)
  67. return "0";
  68. if (d < +0.0) {
  69. StringBuilder builder;
  70. builder.append('-');
  71. builder.append(double_to_string(-d));
  72. return builder.to_string();
  73. }
  74. if (d == static_cast<double>(INFINITY))
  75. return "Infinity";
  76. StringBuilder number_string_builder;
  77. size_t start_index = 0;
  78. size_t end_index = 0;
  79. size_t int_part_end = 0;
  80. // generate integer part (reversed)
  81. double int_part;
  82. double frac_part;
  83. frac_part = modf(d, &int_part);
  84. while (int_part > 0) {
  85. number_string_builder.append('0' + (int)fmod(int_part, 10));
  86. end_index++;
  87. int_part = floor(int_part / 10);
  88. }
  89. auto reversed_integer_part = number_string_builder.to_string().reverse();
  90. number_string_builder.clear();
  91. number_string_builder.append(reversed_integer_part);
  92. int_part_end = end_index;
  93. int exponent = 0;
  94. // generate fractional part
  95. while (frac_part > 0) {
  96. double old_frac_part = frac_part;
  97. frac_part *= 10;
  98. frac_part = modf(frac_part, &int_part);
  99. if (old_frac_part == frac_part)
  100. break;
  101. number_string_builder.append('0' + (int)int_part);
  102. end_index++;
  103. exponent--;
  104. }
  105. auto number_string = number_string_builder.to_string();
  106. // FIXME: Remove this hack.
  107. // FIXME: Instead find the shortest round-trippable representation.
  108. // Remove decimals after the 15th position
  109. if (end_index > int_part_end + 15) {
  110. exponent += end_index - int_part_end - 15;
  111. end_index = int_part_end + 15;
  112. }
  113. // remove leading zeroes
  114. while (start_index < end_index && number_string[start_index] == '0') {
  115. start_index++;
  116. }
  117. // remove trailing zeroes
  118. while (end_index > 0 && number_string[end_index - 1] == '0') {
  119. end_index--;
  120. exponent++;
  121. }
  122. if (end_index <= start_index)
  123. return "0";
  124. auto digits = number_string.substring_view(start_index, end_index - start_index);
  125. int number_of_digits = end_index - start_index;
  126. exponent += number_of_digits;
  127. StringBuilder builder;
  128. if (number_of_digits <= exponent && exponent <= 21) {
  129. builder.append(digits);
  130. builder.append(String::repeated('0', exponent - number_of_digits));
  131. return builder.to_string();
  132. }
  133. if (0 < exponent && exponent <= 21) {
  134. builder.append(digits.substring_view(0, exponent));
  135. builder.append('.');
  136. builder.append(digits.substring_view(exponent));
  137. return builder.to_string();
  138. }
  139. if (-6 < exponent && exponent <= 0) {
  140. builder.append("0."sv);
  141. builder.append(String::repeated('0', -exponent));
  142. builder.append(digits);
  143. return builder.to_string();
  144. }
  145. if (number_of_digits == 1) {
  146. builder.append(digits);
  147. builder.append('e');
  148. if (exponent - 1 > 0)
  149. builder.append('+');
  150. else
  151. builder.append('-');
  152. builder.append(String::number(AK::abs(exponent - 1)));
  153. return builder.to_string();
  154. }
  155. builder.append(digits[0]);
  156. builder.append('.');
  157. builder.append(digits.substring_view(1));
  158. builder.append('e');
  159. if (exponent - 1 > 0)
  160. builder.append('+');
  161. else
  162. builder.append('-');
  163. builder.append(String::number(AK::abs(exponent - 1)));
  164. return builder.to_string();
  165. }
  166. // 7.2.2 IsArray ( argument ), https://tc39.es/ecma262/#sec-isarray
  167. ThrowCompletionOr<bool> Value::is_array(VM& vm) const
  168. {
  169. if (!is_object())
  170. return false;
  171. auto& object = as_object();
  172. if (is<Array>(object))
  173. return true;
  174. if (is<ProxyObject>(object)) {
  175. auto& proxy = static_cast<ProxyObject const&>(object);
  176. if (proxy.is_revoked())
  177. return vm.throw_completion<TypeError>(ErrorType::ProxyRevoked);
  178. return Value(&proxy.target()).is_array(vm);
  179. }
  180. return false;
  181. }
  182. Array& Value::as_array()
  183. {
  184. VERIFY(is_object() && is<Array>(as_object()));
  185. return static_cast<Array&>(as_object());
  186. }
  187. // 7.2.3 IsCallable ( argument ), https://tc39.es/ecma262/#sec-iscallable
  188. bool Value::is_function() const
  189. {
  190. return is_object() && as_object().is_function();
  191. }
  192. FunctionObject& Value::as_function()
  193. {
  194. VERIFY(is_function());
  195. return static_cast<FunctionObject&>(as_object());
  196. }
  197. FunctionObject const& Value::as_function() const
  198. {
  199. VERIFY(is_function());
  200. return static_cast<FunctionObject const&>(as_object());
  201. }
  202. // 7.2.4 IsConstructor ( argument ), https://tc39.es/ecma262/#sec-isconstructor
  203. bool Value::is_constructor() const
  204. {
  205. // 1. If Type(argument) is not Object, return false.
  206. if (!is_function())
  207. return false;
  208. // 2. If argument has a [[Construct]] internal method, return true.
  209. if (as_function().has_constructor())
  210. return true;
  211. // 3. Return false.
  212. return false;
  213. }
  214. // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
  215. ThrowCompletionOr<bool> Value::is_regexp(VM& vm) const
  216. {
  217. if (!is_object())
  218. return false;
  219. auto matcher = TRY(as_object().get(*vm.well_known_symbol_match()));
  220. if (!matcher.is_undefined())
  221. return matcher.to_boolean();
  222. return is<RegExpObject>(as_object());
  223. }
  224. // 13.5.3 The typeof Operator, https://tc39.es/ecma262/#sec-typeof-operator
  225. String Value::typeof() const
  226. {
  227. if (is_number())
  228. return "number";
  229. switch (m_value.tag) {
  230. case UNDEFINED_TAG:
  231. return "undefined";
  232. case NULL_TAG:
  233. return "object";
  234. case STRING_TAG:
  235. return "string";
  236. case OBJECT_TAG:
  237. // B.3.7.3 Changes to the typeof Operator, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-typeof
  238. if (as_object().is_htmldda())
  239. return "undefined";
  240. if (is_function())
  241. return "function";
  242. return "object";
  243. case BOOLEAN_TAG:
  244. return "boolean";
  245. case SYMBOL_TAG:
  246. return "symbol";
  247. case BIGINT_TAG:
  248. return "bigint";
  249. default:
  250. VERIFY_NOT_REACHED();
  251. }
  252. }
  253. String Value::to_string_without_side_effects() const
  254. {
  255. if (is_double())
  256. return double_to_string(m_value.as_double);
  257. switch (m_value.tag) {
  258. case UNDEFINED_TAG:
  259. return "undefined";
  260. case NULL_TAG:
  261. return "null";
  262. case BOOLEAN_TAG:
  263. return as_bool() ? "true" : "false";
  264. case INT32_TAG:
  265. return String::number(as_i32());
  266. case STRING_TAG:
  267. return as_string().string();
  268. case SYMBOL_TAG:
  269. return as_symbol().to_string();
  270. case BIGINT_TAG:
  271. return as_bigint().to_string();
  272. case OBJECT_TAG:
  273. return String::formatted("[object {}]", as_object().class_name());
  274. case ACCESSOR_TAG:
  275. return "<accessor>";
  276. default:
  277. VERIFY_NOT_REACHED();
  278. }
  279. }
  280. ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm)
  281. {
  282. if (is_string())
  283. return &as_string();
  284. auto string = TRY(to_string(vm));
  285. return js_string(vm, string);
  286. }
  287. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  288. ThrowCompletionOr<String> Value::to_string(VM& vm) const
  289. {
  290. if (is_double())
  291. return double_to_string(m_value.as_double);
  292. switch (m_value.tag) {
  293. case UNDEFINED_TAG:
  294. return "undefined"sv;
  295. case NULL_TAG:
  296. return "null"sv;
  297. case BOOLEAN_TAG:
  298. return as_bool() ? "true"sv : "false"sv;
  299. case INT32_TAG:
  300. return String::number(as_i32());
  301. case STRING_TAG:
  302. return as_string().string();
  303. case SYMBOL_TAG:
  304. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "string");
  305. case BIGINT_TAG:
  306. return as_bigint().big_integer().to_base(10);
  307. case OBJECT_TAG: {
  308. auto primitive_value = TRY(to_primitive(vm, PreferredType::String));
  309. return primitive_value.to_string(vm);
  310. }
  311. default:
  312. VERIFY_NOT_REACHED();
  313. }
  314. }
  315. ThrowCompletionOr<Utf16String> Value::to_utf16_string(VM& vm) const
  316. {
  317. if (is_string())
  318. return as_string().utf16_string();
  319. auto utf8_string = TRY(to_string(vm));
  320. return Utf16String(utf8_string);
  321. }
  322. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  323. bool Value::to_boolean() const
  324. {
  325. if (is_double()) {
  326. if (is_nan())
  327. return false;
  328. return m_value.as_double != 0;
  329. }
  330. switch (m_value.tag) {
  331. case UNDEFINED_TAG:
  332. case NULL_TAG:
  333. return false;
  334. case BOOLEAN_TAG:
  335. return as_bool();
  336. case INT32_TAG:
  337. return as_i32() != 0;
  338. case STRING_TAG:
  339. return !as_string().is_empty();
  340. case SYMBOL_TAG:
  341. return true;
  342. case BIGINT_TAG:
  343. return as_bigint().big_integer() != BIGINT_ZERO;
  344. case OBJECT_TAG:
  345. // B.3.7.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  346. if (as_object().is_htmldda())
  347. return false;
  348. return true;
  349. default:
  350. VERIFY_NOT_REACHED();
  351. }
  352. }
  353. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  354. ThrowCompletionOr<Value> Value::to_primitive(VM& vm, PreferredType preferred_type) const
  355. {
  356. auto get_hint_for_preferred_type = [&]() -> String {
  357. switch (preferred_type) {
  358. case PreferredType::Default:
  359. return "default";
  360. case PreferredType::String:
  361. return "string";
  362. case PreferredType::Number:
  363. return "number";
  364. default:
  365. VERIFY_NOT_REACHED();
  366. }
  367. };
  368. if (is_object()) {
  369. auto to_primitive_method = TRY(get_method(vm, *vm.well_known_symbol_to_primitive()));
  370. if (to_primitive_method) {
  371. auto hint = get_hint_for_preferred_type();
  372. auto result = TRY(call(vm, *to_primitive_method, *this, js_string(vm, hint)));
  373. if (!result.is_object())
  374. return result;
  375. return vm.throw_completion<TypeError>(ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  376. }
  377. if (preferred_type == PreferredType::Default)
  378. preferred_type = PreferredType::Number;
  379. return as_object().ordinary_to_primitive(preferred_type);
  380. }
  381. return *this;
  382. }
  383. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  384. ThrowCompletionOr<Object*> Value::to_object(VM& vm) const
  385. {
  386. auto& realm = *vm.current_realm();
  387. VERIFY(!is_empty());
  388. if (is_number())
  389. return NumberObject::create(realm, as_double());
  390. switch (m_value.tag) {
  391. case UNDEFINED_TAG:
  392. case NULL_TAG:
  393. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  394. case BOOLEAN_TAG:
  395. return BooleanObject::create(realm, as_bool());
  396. case STRING_TAG:
  397. return StringObject::create(realm, const_cast<JS::PrimitiveString&>(as_string()), *realm.intrinsics().string_prototype());
  398. case SYMBOL_TAG:
  399. return SymbolObject::create(realm, const_cast<JS::Symbol&>(as_symbol()));
  400. case BIGINT_TAG:
  401. return BigIntObject::create(realm, const_cast<JS::BigInt&>(as_bigint()));
  402. case OBJECT_TAG:
  403. return &const_cast<Object&>(as_object());
  404. default:
  405. VERIFY_NOT_REACHED();
  406. }
  407. }
  408. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  409. FLATTEN ThrowCompletionOr<Value> Value::to_numeric(VM& vm) const
  410. {
  411. auto primitive = TRY(to_primitive(vm, Value::PreferredType::Number));
  412. if (primitive.is_bigint())
  413. return primitive;
  414. return primitive.to_number(vm);
  415. }
  416. constexpr bool is_ascii_number(u32 code_point)
  417. {
  418. return is_ascii_digit(code_point) || code_point == '.' || (code_point == 'e' || code_point == 'E') || code_point == '+' || code_point == '-';
  419. }
  420. struct NumberParseResult {
  421. StringView literal;
  422. u8 base;
  423. };
  424. static Optional<NumberParseResult> parse_number_text(StringView text)
  425. {
  426. NumberParseResult result {};
  427. auto check_prefix = [&](auto lower_prefix, auto upper_prefix) {
  428. if (text.length() <= 2)
  429. return false;
  430. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  431. return false;
  432. return true;
  433. };
  434. // https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
  435. if (check_prefix("0b"sv, "0B"sv)) {
  436. if (!all_of(text.substring_view(2), is_ascii_binary_digit))
  437. return {};
  438. result.literal = text.substring_view(2);
  439. result.base = 2;
  440. } else if (check_prefix("0o"sv, "0O"sv)) {
  441. if (!all_of(text.substring_view(2), is_ascii_octal_digit))
  442. return {};
  443. result.literal = text.substring_view(2);
  444. result.base = 8;
  445. } else if (check_prefix("0x"sv, "0X"sv)) {
  446. if (!all_of(text.substring_view(2), is_ascii_hex_digit))
  447. return {};
  448. result.literal = text.substring_view(2);
  449. result.base = 16;
  450. } else {
  451. if (!all_of(text, is_ascii_number))
  452. return {};
  453. result.literal = text;
  454. result.base = 10;
  455. }
  456. return result;
  457. }
  458. // 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber
  459. static Optional<Value> string_to_number(StringView string)
  460. {
  461. // 1. Let text be StringToCodePoints(str).
  462. String text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  463. // 2. Let literal be ParseText(text, StringNumericLiteral).
  464. if (text.is_empty())
  465. return Value(0);
  466. if (text == "Infinity" || text == "+Infinity")
  467. return js_infinity();
  468. if (text == "-Infinity")
  469. return js_negative_infinity();
  470. auto result = parse_number_text(text);
  471. // 3. If literal is a List of errors, return NaN.
  472. if (!result.has_value())
  473. return js_nan();
  474. // 4. Return StringNumericValue of literal.
  475. if (result->base != 10) {
  476. auto bigint = Crypto::UnsignedBigInteger::from_base(result->base, result->literal);
  477. return Value(bigint.to_double());
  478. }
  479. char* endptr;
  480. auto parsed_double = strtod(text.characters(), &endptr);
  481. if (*endptr)
  482. return js_nan();
  483. return Value(parsed_double);
  484. }
  485. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  486. ThrowCompletionOr<Value> Value::to_number(VM& vm) const
  487. {
  488. VERIFY(!is_empty());
  489. if (is_number())
  490. return *this;
  491. switch (m_value.tag) {
  492. case UNDEFINED_TAG:
  493. return js_nan();
  494. case NULL_TAG:
  495. return Value(0);
  496. case BOOLEAN_TAG:
  497. return Value(as_bool() ? 1 : 0);
  498. case STRING_TAG:
  499. return string_to_number(as_string().string().view());
  500. case SYMBOL_TAG:
  501. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "number");
  502. case BIGINT_TAG:
  503. return vm.throw_completion<TypeError>(ErrorType::Convert, "BigInt", "number");
  504. case OBJECT_TAG: {
  505. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  506. return primitive.to_number(vm);
  507. }
  508. default:
  509. VERIFY_NOT_REACHED();
  510. }
  511. }
  512. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  513. ThrowCompletionOr<BigInt*> Value::to_bigint(VM& vm) const
  514. {
  515. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  516. VERIFY(!primitive.is_empty());
  517. if (primitive.is_number())
  518. return vm.throw_completion<TypeError>(ErrorType::Convert, "number", "BigInt");
  519. switch (primitive.m_value.tag) {
  520. case UNDEFINED_TAG:
  521. return vm.throw_completion<TypeError>(ErrorType::Convert, "undefined", "BigInt");
  522. case NULL_TAG:
  523. return vm.throw_completion<TypeError>(ErrorType::Convert, "null", "BigInt");
  524. case BOOLEAN_TAG: {
  525. auto value = primitive.as_bool() ? 1 : 0;
  526. return js_bigint(vm, Crypto::SignedBigInteger { value });
  527. }
  528. case BIGINT_TAG:
  529. return &primitive.as_bigint();
  530. case STRING_TAG: {
  531. // 1. Let n be ! StringToBigInt(prim).
  532. auto bigint = primitive.string_to_bigint(vm);
  533. // 2. If n is undefined, throw a SyntaxError exception.
  534. if (!bigint.has_value())
  535. return vm.throw_completion<SyntaxError>(ErrorType::BigIntInvalidValue, primitive);
  536. // 3. Return n.
  537. return bigint.release_value();
  538. }
  539. case SYMBOL_TAG:
  540. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "BigInt");
  541. default:
  542. VERIFY_NOT_REACHED();
  543. }
  544. }
  545. struct BigIntParseResult {
  546. StringView literal;
  547. u8 base { 10 };
  548. bool is_negative { false };
  549. };
  550. static Optional<BigIntParseResult> parse_bigint_text(StringView text)
  551. {
  552. BigIntParseResult result {};
  553. auto parse_for_prefixed_base = [&](auto lower_prefix, auto upper_prefix, auto validator) {
  554. if (text.length() <= 2)
  555. return false;
  556. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  557. return false;
  558. return all_of(text.substring_view(2), validator);
  559. };
  560. if (parse_for_prefixed_base("0b"sv, "0B"sv, is_ascii_binary_digit)) {
  561. result.literal = text.substring_view(2);
  562. result.base = 2;
  563. } else if (parse_for_prefixed_base("0o"sv, "0O"sv, is_ascii_octal_digit)) {
  564. result.literal = text.substring_view(2);
  565. result.base = 8;
  566. } else if (parse_for_prefixed_base("0x"sv, "0X"sv, is_ascii_hex_digit)) {
  567. result.literal = text.substring_view(2);
  568. result.base = 16;
  569. } else {
  570. if (text.starts_with('-')) {
  571. text = text.substring_view(1);
  572. result.is_negative = true;
  573. } else if (text.starts_with('+')) {
  574. text = text.substring_view(1);
  575. }
  576. if (!all_of(text, is_ascii_digit))
  577. return {};
  578. result.literal = text;
  579. result.base = 10;
  580. }
  581. return result;
  582. }
  583. // 7.1.14 StringToBigInt ( str ), https://tc39.es/ecma262/#sec-stringtobigint
  584. Optional<BigInt*> Value::string_to_bigint(VM& vm) const
  585. {
  586. VERIFY(is_string());
  587. // 1. Let text be StringToCodePoints(str).
  588. auto text = as_string().string().view().trim_whitespace();
  589. // 2. Let literal be ParseText(text, StringIntegerLiteral).
  590. auto result = parse_bigint_text(text);
  591. // 3. If literal is a List of errors, return undefined.
  592. if (!result.has_value())
  593. return {};
  594. // 4. Let mv be the MV of literal.
  595. // 5. Assert: mv is an integer.
  596. auto bigint = Crypto::SignedBigInteger::from_base(result->base, result->literal);
  597. if (result->is_negative && (bigint != BIGINT_ZERO))
  598. bigint.negate();
  599. // 6. Return ℤ(mv).
  600. return js_bigint(vm, move(bigint));
  601. }
  602. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/#sec-tobigint64
  603. ThrowCompletionOr<i64> Value::to_bigint_int64(VM& vm) const
  604. {
  605. auto* bigint = TRY(to_bigint(vm));
  606. return static_cast<i64>(bigint->big_integer().to_u64());
  607. }
  608. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/#sec-tobiguint64
  609. ThrowCompletionOr<u64> Value::to_bigint_uint64(VM& vm) const
  610. {
  611. auto* bigint = TRY(to_bigint(vm));
  612. return bigint->big_integer().to_u64();
  613. }
  614. ThrowCompletionOr<double> Value::to_double(VM& vm) const
  615. {
  616. return TRY(to_number(vm)).as_double();
  617. }
  618. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  619. ThrowCompletionOr<PropertyKey> Value::to_property_key(VM& vm) const
  620. {
  621. if (is_int32() && as_i32() >= 0)
  622. return PropertyKey { as_i32() };
  623. auto key = TRY(to_primitive(vm, PreferredType::String));
  624. if (key.is_symbol())
  625. return &key.as_symbol();
  626. return TRY(key.to_string(vm));
  627. }
  628. ThrowCompletionOr<i32> Value::to_i32_slow_case(VM& vm) const
  629. {
  630. VERIFY(!is_int32());
  631. double value = TRY(to_number(vm)).as_double();
  632. if (!isfinite(value) || value == 0)
  633. return 0;
  634. auto abs = fabs(value);
  635. auto int_val = floor(abs);
  636. if (signbit(value))
  637. int_val = -int_val;
  638. auto remainder = fmod(int_val, 4294967296.0);
  639. auto int32bit = remainder >= 0.0 ? remainder : remainder + 4294967296.0; // The notation “x modulo y” computes a value k of the same sign as y
  640. if (int32bit >= 2147483648.0)
  641. int32bit -= 4294967296.0;
  642. return static_cast<i32>(int32bit);
  643. }
  644. ThrowCompletionOr<i32> Value::to_i32(VM& vm) const
  645. {
  646. if (is_int32())
  647. return as_i32();
  648. return to_i32_slow_case(vm);
  649. }
  650. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  651. ThrowCompletionOr<u32> Value::to_u32(VM& vm) const
  652. {
  653. double value = TRY(to_number(vm)).as_double();
  654. if (!isfinite(value) || value == 0)
  655. return 0;
  656. auto int_val = floor(fabs(value));
  657. if (signbit(value))
  658. int_val = -int_val;
  659. auto int32bit = fmod(int_val, NumericLimits<u32>::max() + 1.0);
  660. // Cast to i64 here to ensure that the double --> u32 cast doesn't invoke undefined behavior
  661. // Otherwise, negative numbers cause a UBSAN warning.
  662. return static_cast<u32>(static_cast<i64>(int32bit));
  663. }
  664. // 7.1.8 ToInt16 ( argument ), https://tc39.es/ecma262/#sec-toint16
  665. ThrowCompletionOr<i16> Value::to_i16(VM& vm) const
  666. {
  667. double value = TRY(to_number(vm)).as_double();
  668. if (!isfinite(value) || value == 0)
  669. return 0;
  670. auto abs = fabs(value);
  671. auto int_val = floor(abs);
  672. if (signbit(value))
  673. int_val = -int_val;
  674. auto remainder = fmod(int_val, 65536.0);
  675. auto int16bit = remainder >= 0.0 ? remainder : remainder + 65536.0; // The notation “x modulo y” computes a value k of the same sign as y
  676. if (int16bit >= 32768.0)
  677. int16bit -= 65536.0;
  678. return static_cast<i16>(int16bit);
  679. }
  680. // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16
  681. ThrowCompletionOr<u16> Value::to_u16(VM& vm) const
  682. {
  683. double value = TRY(to_number(vm)).as_double();
  684. if (!isfinite(value) || value == 0)
  685. return 0;
  686. auto int_val = floor(fabs(value));
  687. if (signbit(value))
  688. int_val = -int_val;
  689. auto int16bit = fmod(int_val, NumericLimits<u16>::max() + 1.0);
  690. if (int16bit < 0)
  691. int16bit += NumericLimits<u16>::max() + 1.0;
  692. return static_cast<u16>(int16bit);
  693. }
  694. // 7.1.10 ToInt8 ( argument ), https://tc39.es/ecma262/#sec-toint8
  695. ThrowCompletionOr<i8> Value::to_i8(VM& vm) const
  696. {
  697. double value = TRY(to_number(vm)).as_double();
  698. if (!isfinite(value) || value == 0)
  699. return 0;
  700. auto abs = fabs(value);
  701. auto int_val = floor(abs);
  702. if (signbit(value))
  703. int_val = -int_val;
  704. auto remainder = fmod(int_val, 256.0);
  705. auto int8bit = remainder >= 0.0 ? remainder : remainder + 256.0; // The notation “x modulo y” computes a value k of the same sign as y
  706. if (int8bit >= 128.0)
  707. int8bit -= 256.0;
  708. return static_cast<i8>(int8bit);
  709. }
  710. // 7.1.11 ToUint8 ( argument ), https://tc39.es/ecma262/#sec-touint8
  711. ThrowCompletionOr<u8> Value::to_u8(VM& vm) const
  712. {
  713. double value = TRY(to_number(vm)).as_double();
  714. if (!isfinite(value) || value == 0)
  715. return 0;
  716. auto int_val = floor(fabs(value));
  717. if (signbit(value))
  718. int_val = -int_val;
  719. auto int8bit = fmod(int_val, NumericLimits<u8>::max() + 1.0);
  720. if (int8bit < 0)
  721. int8bit += NumericLimits<u8>::max() + 1.0;
  722. return static_cast<u8>(int8bit);
  723. }
  724. // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp
  725. ThrowCompletionOr<u8> Value::to_u8_clamp(VM& vm) const
  726. {
  727. auto number = TRY(to_number(vm));
  728. if (number.is_nan())
  729. return 0;
  730. double value = number.as_double();
  731. if (value <= 0.0)
  732. return 0;
  733. if (value >= 255.0)
  734. return 255;
  735. auto int_val = floor(value);
  736. if (int_val + 0.5 < value)
  737. return static_cast<u8>(int_val + 1.0);
  738. if (value < int_val + 0.5)
  739. return static_cast<u8>(int_val);
  740. if (fmod(int_val, 2.0) == 1.0)
  741. return static_cast<u8>(int_val + 1.0);
  742. return static_cast<u8>(int_val);
  743. }
  744. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  745. ThrowCompletionOr<size_t> Value::to_length(VM& vm) const
  746. {
  747. auto len = TRY(to_integer_or_infinity(vm));
  748. if (len <= 0)
  749. return 0;
  750. // FIXME: The spec says that this function's output range is 0 - 2^53-1. But we don't want to overflow the size_t.
  751. constexpr double length_limit = sizeof(void*) == 4 ? NumericLimits<size_t>::max() : MAX_ARRAY_LIKE_INDEX;
  752. return min(len, length_limit);
  753. }
  754. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  755. ThrowCompletionOr<size_t> Value::to_index(VM& vm) const
  756. {
  757. if (is_undefined())
  758. return 0;
  759. auto integer_index = TRY(to_integer_or_infinity(vm));
  760. if (integer_index < 0)
  761. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  762. auto index = MUST(Value(integer_index).to_length(vm));
  763. if (integer_index != index)
  764. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  765. return index;
  766. }
  767. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  768. ThrowCompletionOr<double> Value::to_integer_or_infinity(VM& vm) const
  769. {
  770. auto number = TRY(to_number(vm));
  771. if (number.is_nan() || number.as_double() == 0)
  772. return 0;
  773. if (number.is_infinity())
  774. return number.as_double();
  775. auto integer = floor(fabs(number.as_double()));
  776. if (number.as_double() < 0 && integer != 0)
  777. integer = -integer;
  778. return integer;
  779. }
  780. // Standalone variant using plain doubles for cases where we already got numbers and know the AO won't throw.
  781. double to_integer_or_infinity(double number)
  782. {
  783. // 1. Let number be ? ToNumber(argument).
  784. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
  785. if (isnan(number) || number == 0)
  786. return 0;
  787. // 3. If number is +∞𝔽, return +∞.
  788. if (__builtin_isinf_sign(number) > 0)
  789. return static_cast<double>(INFINITY);
  790. // 4. If number is -∞𝔽, return -∞.
  791. if (__builtin_isinf_sign(number) < 0)
  792. return static_cast<double>(-INFINITY);
  793. // 5. Let integer be floor(abs(ℝ(number))).
  794. auto integer = floor(fabs(number));
  795. // 6. If number < -0𝔽, set integer to -integer.
  796. if (number < 0 && integer != 0)
  797. integer = -integer;
  798. // 7. Return integer.
  799. return integer;
  800. }
  801. // 7.3.3 GetV ( V, P ), https://tc39.es/ecma262/#sec-getv
  802. ThrowCompletionOr<Value> Value::get(VM& vm, PropertyKey const& property_key) const
  803. {
  804. // 1. Assert: IsPropertyKey(P) is true.
  805. VERIFY(property_key.is_valid());
  806. // 2. Let O be ? ToObject(V).
  807. auto* object = TRY(to_object(vm));
  808. // 3. Return ? O.[[Get]](P, V).
  809. return TRY(object->internal_get(property_key, *this));
  810. }
  811. // 7.3.11 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  812. ThrowCompletionOr<FunctionObject*> Value::get_method(VM& vm, PropertyKey const& property_key) const
  813. {
  814. // 1. Assert: IsPropertyKey(P) is true.
  815. VERIFY(property_key.is_valid());
  816. // 2. Let func be ? GetV(V, P).
  817. auto function = TRY(get(vm, property_key));
  818. // 3. If func is either undefined or null, return undefined.
  819. if (function.is_nullish())
  820. return nullptr;
  821. // 4. If IsCallable(func) is false, throw a TypeError exception.
  822. if (!function.is_function())
  823. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, function.to_string_without_side_effects());
  824. // 5. Return func.
  825. return &function.as_function();
  826. }
  827. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  828. ThrowCompletionOr<Value> greater_than(VM& vm, Value lhs, Value rhs)
  829. {
  830. if (lhs.is_int32() && rhs.is_int32())
  831. return lhs.as_i32() > rhs.as_i32();
  832. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  833. if (relation == TriState::Unknown)
  834. return Value(false);
  835. return Value(relation == TriState::True);
  836. }
  837. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  838. ThrowCompletionOr<Value> greater_than_equals(VM& vm, Value lhs, Value rhs)
  839. {
  840. if (lhs.is_int32() && rhs.is_int32())
  841. return lhs.as_i32() >= rhs.as_i32();
  842. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  843. if (relation == TriState::Unknown || relation == TriState::True)
  844. return Value(false);
  845. return Value(true);
  846. }
  847. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  848. ThrowCompletionOr<Value> less_than(VM& vm, Value lhs, Value rhs)
  849. {
  850. if (lhs.is_int32() && rhs.is_int32())
  851. return lhs.as_i32() < rhs.as_i32();
  852. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  853. if (relation == TriState::Unknown)
  854. return Value(false);
  855. return Value(relation == TriState::True);
  856. }
  857. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  858. ThrowCompletionOr<Value> less_than_equals(VM& vm, Value lhs, Value rhs)
  859. {
  860. if (lhs.is_int32() && rhs.is_int32())
  861. return lhs.as_i32() <= rhs.as_i32();
  862. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  863. if (relation == TriState::Unknown || relation == TriState::True)
  864. return Value(false);
  865. return Value(true);
  866. }
  867. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  868. ThrowCompletionOr<Value> bitwise_and(VM& vm, Value lhs, Value rhs)
  869. {
  870. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  871. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  872. if (both_number(lhs_numeric, rhs_numeric)) {
  873. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  874. return Value(0);
  875. return Value(TRY(lhs_numeric.to_i32(vm)) & TRY(rhs_numeric.to_i32(vm)));
  876. }
  877. if (both_bigint(lhs_numeric, rhs_numeric))
  878. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer())));
  879. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  880. }
  881. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  882. ThrowCompletionOr<Value> bitwise_or(VM& vm, Value lhs, Value rhs)
  883. {
  884. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  885. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  886. if (both_number(lhs_numeric, rhs_numeric)) {
  887. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  888. return Value(0);
  889. if (!lhs_numeric.is_finite_number())
  890. return rhs_numeric;
  891. if (!rhs_numeric.is_finite_number())
  892. return lhs_numeric;
  893. return Value(TRY(lhs_numeric.to_i32(vm)) | TRY(rhs_numeric.to_i32(vm)));
  894. }
  895. if (both_bigint(lhs_numeric, rhs_numeric))
  896. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer())));
  897. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  898. }
  899. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  900. ThrowCompletionOr<Value> bitwise_xor(VM& vm, Value lhs, Value rhs)
  901. {
  902. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  903. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  904. if (both_number(lhs_numeric, rhs_numeric)) {
  905. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  906. return Value(0);
  907. if (!lhs_numeric.is_finite_number())
  908. return rhs_numeric;
  909. if (!rhs_numeric.is_finite_number())
  910. return lhs_numeric;
  911. return Value(TRY(lhs_numeric.to_i32(vm)) ^ TRY(rhs_numeric.to_i32(vm)));
  912. }
  913. if (both_bigint(lhs_numeric, rhs_numeric))
  914. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer())));
  915. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  916. }
  917. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  918. ThrowCompletionOr<Value> bitwise_not(VM& vm, Value lhs)
  919. {
  920. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  921. if (lhs_numeric.is_number())
  922. return Value(~TRY(lhs_numeric.to_i32(vm)));
  923. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().bitwise_not()));
  924. }
  925. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  926. ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
  927. {
  928. return TRY(lhs.to_number(vm));
  929. }
  930. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  931. ThrowCompletionOr<Value> unary_minus(VM& vm, Value lhs)
  932. {
  933. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  934. if (lhs_numeric.is_number()) {
  935. if (lhs_numeric.is_nan())
  936. return js_nan();
  937. return Value(-lhs_numeric.as_double());
  938. }
  939. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  940. return Value(js_bigint(vm, BIGINT_ZERO));
  941. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  942. big_integer_negated.negate();
  943. return Value(js_bigint(vm, big_integer_negated));
  944. }
  945. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  946. ThrowCompletionOr<Value> left_shift(VM& vm, Value lhs, Value rhs)
  947. {
  948. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  949. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  950. if (both_number(lhs_numeric, rhs_numeric)) {
  951. if (!lhs_numeric.is_finite_number())
  952. return Value(0);
  953. if (!rhs_numeric.is_finite_number())
  954. return lhs_numeric;
  955. // Ok, so this performs toNumber() again but that "can't" throw
  956. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  957. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  958. return Value(lhs_i32 << rhs_u32);
  959. }
  960. if (both_bigint(lhs_numeric, rhs_numeric)) {
  961. // 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
  962. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  963. // 1. If y < 0ℤ, then
  964. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  965. // a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
  966. // NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
  967. auto const& big_integer = lhs_numeric.as_bigint().big_integer();
  968. auto division_result = big_integer.divided_by(multiplier_divisor);
  969. // For positive initial values and no remainder just return quotient
  970. if (division_result.remainder.is_zero() || !big_integer.is_negative())
  971. return js_bigint(vm, division_result.quotient);
  972. // For negative round "down" to the next negative number
  973. return js_bigint(vm, division_result.quotient.minus(Crypto::SignedBigInteger { 1 }));
  974. }
  975. // 2. Return the BigInt value that represents ℝ(x) × 2^y.
  976. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor)));
  977. }
  978. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "left-shift");
  979. }
  980. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  981. ThrowCompletionOr<Value> right_shift(VM& vm, Value lhs, Value rhs)
  982. {
  983. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  984. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  985. if (both_number(lhs_numeric, rhs_numeric)) {
  986. if (!lhs_numeric.is_finite_number())
  987. return Value(0);
  988. if (!rhs_numeric.is_finite_number())
  989. return lhs_numeric;
  990. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  991. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  992. return Value(lhs_i32 >> rhs_u32);
  993. }
  994. if (both_bigint(lhs_numeric, rhs_numeric)) {
  995. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  996. rhs_negated.negate();
  997. return left_shift(vm, lhs, js_bigint(vm, rhs_negated));
  998. }
  999. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "right-shift");
  1000. }
  1001. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  1002. ThrowCompletionOr<Value> unsigned_right_shift(VM& vm, Value lhs, Value rhs)
  1003. {
  1004. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1005. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1006. if (both_number(lhs_numeric, rhs_numeric)) {
  1007. if (!lhs_numeric.is_finite_number())
  1008. return Value(0);
  1009. if (!rhs_numeric.is_finite_number())
  1010. return lhs_numeric;
  1011. // Ok, so this performs toNumber() again but that "can't" throw
  1012. auto lhs_u32 = MUST(lhs_numeric.to_u32(vm));
  1013. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1014. return Value(lhs_u32 >> rhs_u32);
  1015. }
  1016. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperator, "unsigned right-shift");
  1017. }
  1018. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  1019. ThrowCompletionOr<Value> add(VM& vm, Value lhs, Value rhs)
  1020. {
  1021. if (both_number(lhs, rhs)) {
  1022. if (lhs.is_int32() && rhs.is_int32()) {
  1023. Checked<i32> result;
  1024. result = MUST(lhs.to_i32(vm));
  1025. result += MUST(rhs.to_i32(vm));
  1026. if (!result.has_overflow())
  1027. return Value(result.value());
  1028. }
  1029. return Value(lhs.as_double() + rhs.as_double());
  1030. }
  1031. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1032. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1033. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  1034. auto lhs_string = TRY(lhs_primitive.to_primitive_string(vm));
  1035. auto rhs_string = TRY(rhs_primitive.to_primitive_string(vm));
  1036. return js_rope_string(vm, *lhs_string, *rhs_string);
  1037. }
  1038. auto lhs_numeric = TRY(lhs_primitive.to_numeric(vm));
  1039. auto rhs_numeric = TRY(rhs_primitive.to_numeric(vm));
  1040. if (both_number(lhs_numeric, rhs_numeric))
  1041. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  1042. if (both_bigint(lhs_numeric, rhs_numeric))
  1043. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer())));
  1044. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "addition");
  1045. }
  1046. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1047. ThrowCompletionOr<Value> sub(VM& vm, Value lhs, Value rhs)
  1048. {
  1049. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1050. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1051. if (both_number(lhs_numeric, rhs_numeric)) {
  1052. double lhsd = lhs_numeric.as_double();
  1053. double rhsd = rhs_numeric.as_double();
  1054. double interm = lhsd - rhsd;
  1055. return Value(interm);
  1056. }
  1057. if (both_bigint(lhs_numeric, rhs_numeric))
  1058. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer())));
  1059. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1060. }
  1061. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1062. ThrowCompletionOr<Value> mul(VM& vm, Value lhs, Value rhs)
  1063. {
  1064. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1065. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1066. if (both_number(lhs_numeric, rhs_numeric))
  1067. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  1068. if (both_bigint(lhs_numeric, rhs_numeric))
  1069. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer())));
  1070. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1071. }
  1072. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1073. ThrowCompletionOr<Value> div(VM& vm, Value lhs, Value rhs)
  1074. {
  1075. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1076. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1077. if (both_number(lhs_numeric, rhs_numeric))
  1078. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1079. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1080. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1081. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1082. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient));
  1083. }
  1084. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "division");
  1085. }
  1086. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1087. ThrowCompletionOr<Value> mod(VM& vm, Value lhs, Value rhs)
  1088. {
  1089. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1090. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1091. if (both_number(lhs_numeric, rhs_numeric)) {
  1092. // 6.1.6.1.6 Number::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-number-remainder
  1093. // The ECMA specification is describing the mathematical definition of modulus
  1094. // implemented by fmod.
  1095. auto n = lhs_numeric.as_double();
  1096. auto d = rhs_numeric.as_double();
  1097. return Value(fmod(n, d));
  1098. }
  1099. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1100. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1101. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1102. return Value(js_bigint(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder));
  1103. }
  1104. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "modulo");
  1105. }
  1106. static Value exp_double(Value base, Value exponent)
  1107. {
  1108. VERIFY(both_number(base, exponent));
  1109. if (exponent.is_nan())
  1110. return js_nan();
  1111. if (exponent.is_positive_zero() || exponent.is_negative_zero())
  1112. return Value(1);
  1113. if (base.is_nan())
  1114. return js_nan();
  1115. if (base.is_positive_infinity())
  1116. return exponent.as_double() > 0 ? js_infinity() : Value(0);
  1117. if (base.is_negative_infinity()) {
  1118. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1119. if (exponent.as_double() > 0)
  1120. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1121. else
  1122. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1123. }
  1124. if (base.is_positive_zero())
  1125. return exponent.as_double() > 0 ? Value(0) : js_infinity();
  1126. if (base.is_negative_zero()) {
  1127. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1128. if (exponent.as_double() > 0)
  1129. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1130. else
  1131. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1132. }
  1133. VERIFY(base.is_finite_number() && !base.is_positive_zero() && !base.is_negative_zero());
  1134. if (exponent.is_positive_infinity()) {
  1135. auto absolute_base = fabs(base.as_double());
  1136. if (absolute_base > 1)
  1137. return js_infinity();
  1138. else if (absolute_base == 1)
  1139. return js_nan();
  1140. else if (absolute_base < 1)
  1141. return Value(0);
  1142. }
  1143. if (exponent.is_negative_infinity()) {
  1144. auto absolute_base = fabs(base.as_double());
  1145. if (absolute_base > 1)
  1146. return Value(0);
  1147. else if (absolute_base == 1)
  1148. return js_nan();
  1149. else if (absolute_base < 1)
  1150. return js_infinity();
  1151. }
  1152. VERIFY(exponent.is_finite_number() && !exponent.is_positive_zero() && !exponent.is_negative_zero());
  1153. if (base.as_double() < 0 && !exponent.is_integral_number())
  1154. return js_nan();
  1155. return Value(::pow(base.as_double(), exponent.as_double()));
  1156. }
  1157. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1158. ThrowCompletionOr<Value> exp(VM& vm, Value lhs, Value rhs)
  1159. {
  1160. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1161. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1162. if (both_number(lhs_numeric, rhs_numeric))
  1163. return exp_double(lhs_numeric, rhs_numeric);
  1164. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1165. if (rhs_numeric.as_bigint().big_integer().is_negative())
  1166. return vm.throw_completion<RangeError>(ErrorType::NegativeExponent);
  1167. return Value(js_bigint(vm, Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer())));
  1168. }
  1169. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1170. }
  1171. ThrowCompletionOr<Value> in(VM& vm, Value lhs, Value rhs)
  1172. {
  1173. if (!rhs.is_object())
  1174. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  1175. auto lhs_property_key = TRY(lhs.to_property_key(vm));
  1176. return Value(TRY(rhs.as_object().has_property(lhs_property_key)));
  1177. }
  1178. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1179. ThrowCompletionOr<Value> instance_of(VM& vm, Value lhs, Value rhs)
  1180. {
  1181. if (!rhs.is_object())
  1182. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  1183. auto has_instance_method = TRY(rhs.get_method(vm, *vm.well_known_symbol_has_instance()));
  1184. if (has_instance_method) {
  1185. auto has_instance_result = TRY(call(vm, *has_instance_method, rhs, lhs));
  1186. return Value(has_instance_result.to_boolean());
  1187. }
  1188. if (!rhs.is_function())
  1189. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  1190. return TRY(ordinary_has_instance(vm, lhs, rhs));
  1191. }
  1192. // 7.3.22 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1193. ThrowCompletionOr<Value> ordinary_has_instance(VM& vm, Value lhs, Value rhs)
  1194. {
  1195. if (!rhs.is_function())
  1196. return Value(false);
  1197. auto& rhs_function = rhs.as_function();
  1198. if (is<BoundFunction>(rhs_function)) {
  1199. auto& bound_target = static_cast<BoundFunction const&>(rhs_function);
  1200. return instance_of(vm, lhs, Value(&bound_target.bound_target_function()));
  1201. }
  1202. if (!lhs.is_object())
  1203. return Value(false);
  1204. Object* lhs_object = &lhs.as_object();
  1205. auto rhs_prototype = TRY(rhs_function.get(vm.names.prototype));
  1206. if (!rhs_prototype.is_object())
  1207. return vm.throw_completion<TypeError>(ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1208. while (true) {
  1209. lhs_object = TRY(lhs_object->internal_get_prototype_of());
  1210. if (!lhs_object)
  1211. return Value(false);
  1212. if (same_value(rhs_prototype, lhs_object))
  1213. return Value(true);
  1214. }
  1215. }
  1216. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1217. bool same_value(Value lhs, Value rhs)
  1218. {
  1219. if (!same_type_for_equality(lhs, rhs))
  1220. return false;
  1221. if (lhs.is_number()) {
  1222. if (lhs.is_nan() && rhs.is_nan())
  1223. return true;
  1224. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1225. return false;
  1226. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1227. return false;
  1228. return lhs.as_double() == rhs.as_double();
  1229. }
  1230. if (lhs.is_bigint()) {
  1231. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1232. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1233. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1234. return false;
  1235. return lhs_big_integer == rhs_big_integer;
  1236. }
  1237. return same_value_non_numeric(lhs, rhs);
  1238. }
  1239. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1240. bool same_value_zero(Value lhs, Value rhs)
  1241. {
  1242. if (!same_type_for_equality(lhs, rhs))
  1243. return false;
  1244. if (lhs.is_number()) {
  1245. if (lhs.is_nan() && rhs.is_nan())
  1246. return true;
  1247. return lhs.as_double() == rhs.as_double();
  1248. }
  1249. if (lhs.is_bigint())
  1250. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1251. return same_value_non_numeric(lhs, rhs);
  1252. }
  1253. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1254. bool same_value_non_numeric(Value lhs, Value rhs)
  1255. {
  1256. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1257. VERIFY(same_type_for_equality(lhs, rhs));
  1258. if (lhs.is_string())
  1259. return lhs.as_string().string() == rhs.as_string().string();
  1260. return lhs.m_value.encoded == rhs.m_value.encoded;
  1261. }
  1262. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1263. bool is_strictly_equal(Value lhs, Value rhs)
  1264. {
  1265. if (!same_type_for_equality(lhs, rhs))
  1266. return false;
  1267. if (lhs.is_number()) {
  1268. if (lhs.is_nan() || rhs.is_nan())
  1269. return false;
  1270. if (lhs.as_double() == rhs.as_double())
  1271. return true;
  1272. return false;
  1273. }
  1274. if (lhs.is_bigint())
  1275. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1276. return same_value_non_numeric(lhs, rhs);
  1277. }
  1278. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1279. ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs)
  1280. {
  1281. // 1. If Type(x) is the same as Type(y), then
  1282. if (same_type_for_equality(lhs, rhs)) {
  1283. // a. Return IsStrictlyEqual(x, y).
  1284. return is_strictly_equal(lhs, rhs);
  1285. }
  1286. // 2. If x is null and y is undefined, return true.
  1287. // 3. If x is undefined and y is null, return true.
  1288. if (lhs.is_nullish() && rhs.is_nullish())
  1289. return true;
  1290. // 4. NOTE: This step is replaced in section B.3.6.2.
  1291. // B.3.6.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1292. // 4. Perform the following steps:
  1293. // a. If Type(x) is Object and x has an [[IsHTMLDDA]] internal slot and y is either null or undefined, return true.
  1294. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1295. return true;
  1296. // b. If x is either null or undefined and Type(y) is Object and y has an [[IsHTMLDDA]] internal slot, return true.
  1297. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1298. return true;
  1299. // == End of B.3.6.2 ==
  1300. // 5. If Type(x) is Number and Type(y) is String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1301. if (lhs.is_number() && rhs.is_string())
  1302. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1303. // 6. If Type(x) is String and Type(y) is Number, return ! IsLooselyEqual(! ToNumber(x), y).
  1304. if (lhs.is_string() && rhs.is_number())
  1305. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1306. // 7. If Type(x) is BigInt and Type(y) is String, then
  1307. if (lhs.is_bigint() && rhs.is_string()) {
  1308. // a. Let n be StringToBigInt(y).
  1309. auto bigint = rhs.string_to_bigint(vm);
  1310. // b. If n is undefined, return false.
  1311. if (!bigint.has_value())
  1312. return false;
  1313. // c. Return ! IsLooselyEqual(x, n).
  1314. return is_loosely_equal(vm, lhs, *bigint);
  1315. }
  1316. // 8. If Type(x) is String and Type(y) is BigInt, return ! IsLooselyEqual(y, x).
  1317. if (lhs.is_string() && rhs.is_bigint())
  1318. return is_loosely_equal(vm, rhs, lhs);
  1319. // 9. If Type(x) is Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  1320. if (lhs.is_boolean())
  1321. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1322. // 10. If Type(y) is Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1323. if (rhs.is_boolean())
  1324. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1325. // 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  1326. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1327. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1328. return is_loosely_equal(vm, lhs, rhs_primitive);
  1329. }
  1330. // 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  1331. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || rhs.is_bigint() || rhs.is_symbol())) {
  1332. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1333. return is_loosely_equal(vm, lhs_primitive, rhs);
  1334. }
  1335. // 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
  1336. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1337. // a. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false.
  1338. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1339. return false;
  1340. // b. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1341. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1342. return false;
  1343. VERIFY(!lhs.is_nan() && !rhs.is_nan());
  1344. auto& number_side = lhs.is_number() ? lhs : rhs;
  1345. auto& bigint_side = lhs.is_number() ? rhs : lhs;
  1346. return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::SignedBigInteger::CompareResult::DoubleEqualsBigInt;
  1347. }
  1348. // 14. Return false.
  1349. return false;
  1350. }
  1351. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1352. ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left_first)
  1353. {
  1354. Value x_primitive;
  1355. Value y_primitive;
  1356. if (left_first) {
  1357. x_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1358. y_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1359. } else {
  1360. y_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1361. x_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1362. }
  1363. if (x_primitive.is_string() && y_primitive.is_string()) {
  1364. auto x_string = x_primitive.as_string().string();
  1365. auto y_string = y_primitive.as_string().string();
  1366. Utf8View x_code_points { x_string };
  1367. Utf8View y_code_points { y_string };
  1368. if (x_code_points.starts_with(y_code_points))
  1369. return TriState::False;
  1370. if (y_code_points.starts_with(x_code_points))
  1371. return TriState::True;
  1372. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1373. k != x_code_points.end() && l != y_code_points.end();
  1374. ++k, ++l) {
  1375. if (*k != *l) {
  1376. if (*k < *l) {
  1377. return TriState::True;
  1378. } else {
  1379. return TriState::False;
  1380. }
  1381. }
  1382. }
  1383. VERIFY_NOT_REACHED();
  1384. }
  1385. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1386. auto y_bigint = y_primitive.string_to_bigint(vm);
  1387. if (!y_bigint.has_value())
  1388. return TriState::Unknown;
  1389. if (x_primitive.as_bigint().big_integer() < (*y_bigint)->big_integer())
  1390. return TriState::True;
  1391. return TriState::False;
  1392. }
  1393. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1394. auto x_bigint = x_primitive.string_to_bigint(vm);
  1395. if (!x_bigint.has_value())
  1396. return TriState::Unknown;
  1397. if ((*x_bigint)->big_integer() < y_primitive.as_bigint().big_integer())
  1398. return TriState::True;
  1399. return TriState::False;
  1400. }
  1401. auto x_numeric = TRY(x_primitive.to_numeric(vm));
  1402. auto y_numeric = TRY(y_primitive.to_numeric(vm));
  1403. if (x_numeric.is_nan() || y_numeric.is_nan())
  1404. return TriState::Unknown;
  1405. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1406. return TriState::False;
  1407. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1408. return TriState::True;
  1409. if (x_numeric.is_number() && y_numeric.is_number()) {
  1410. if (x_numeric.as_double() < y_numeric.as_double())
  1411. return TriState::True;
  1412. else
  1413. return TriState::False;
  1414. }
  1415. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1416. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1417. return TriState::True;
  1418. else
  1419. return TriState::False;
  1420. }
  1421. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1422. bool x_lower_than_y;
  1423. VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan());
  1424. if (x_numeric.is_number()) {
  1425. x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double())
  1426. == Crypto::SignedBigInteger::CompareResult::DoubleLessThanBigInt;
  1427. } else {
  1428. x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double())
  1429. == Crypto::SignedBigInteger::CompareResult::DoubleGreaterThanBigInt;
  1430. }
  1431. if (x_lower_than_y)
  1432. return TriState::True;
  1433. else
  1434. return TriState::False;
  1435. }
  1436. // 7.3.21 Invoke ( V, P [ , argumentsList ] ), https://tc39.es/ecma262/#sec-invoke
  1437. ThrowCompletionOr<Value> Value::invoke_internal(VM& vm, PropertyKey const& property_key, Optional<MarkedVector<Value>> arguments)
  1438. {
  1439. auto property = TRY(get(vm, property_key));
  1440. if (!property.is_function())
  1441. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, property.to_string_without_side_effects());
  1442. return call(vm, property.as_function(), *this, move(arguments));
  1443. }
  1444. }