Value.cpp 63 KB

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