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