Value.cpp 60 KB

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