Value.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2020-2023, 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/ByteString.h>
  11. #include <AK/CharacterTypes.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/Utf16String.h>
  39. #include <LibJS/Runtime/VM.h>
  40. #include <LibJS/Runtime/Value.h>
  41. #include <LibJS/Runtime/ValueInlines.h>
  42. #include <math.h>
  43. namespace JS {
  44. static inline bool same_type_for_equality(Value const& lhs, Value const& rhs)
  45. {
  46. // If the top two bytes are identical then either:
  47. // both are NaN boxed Values with the same type
  48. // or they are doubles which happen to have the same top bytes.
  49. if ((lhs.encoded() & GC::TAG_EXTRACTION) == (rhs.encoded() & GC::TAG_EXTRACTION))
  50. return true;
  51. if (lhs.is_number() && rhs.is_number())
  52. return true;
  53. // One of the Values is not a number and they do not have the same tag
  54. return false;
  55. }
  56. static Crypto::SignedBigInteger const BIGINT_ZERO { 0 };
  57. ALWAYS_INLINE bool both_number(Value const& lhs, Value const& rhs)
  58. {
  59. return lhs.is_number() && rhs.is_number();
  60. }
  61. ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs)
  62. {
  63. return lhs.is_bigint() && rhs.is_bigint();
  64. }
  65. // 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring
  66. // Implementation for radix = 10
  67. static void number_to_string_impl(StringBuilder& builder, double d, NumberToStringMode mode)
  68. {
  69. auto convert_to_decimal_digits_array = [](auto x, auto& digits, auto& length) {
  70. for (; x; x /= 10)
  71. digits[length++] = x % 10 | '0';
  72. for (i32 i = 0; 2 * i + 1 < length; ++i)
  73. swap(digits[i], digits[length - i - 1]);
  74. };
  75. // 1. If x is NaN, return "NaN".
  76. if (isnan(d)) {
  77. builder.append("NaN"sv);
  78. return;
  79. }
  80. // 2. If x is +0𝔽 or -0𝔽, return "0".
  81. if (d == +0.0 || d == -0.0) {
  82. builder.append("0"sv);
  83. return;
  84. }
  85. // 4. If x is +∞𝔽, return "Infinity".
  86. if (isinf(d)) {
  87. if (d > 0) {
  88. builder.append("Infinity"sv);
  89. return;
  90. }
  91. builder.append("-Infinity"sv);
  92. return;
  93. }
  94. // 5. Let n, k, and s be integers such that k ≥ 1, radix ^ (k - 1) ≤ s < radix ^ k,
  95. // 𝔽(s × radix ^ (n - k)) is x, and k is as small as possible. Note that k is the number of
  96. // digits in the representation of s using radix radix, that s is not divisible by radix, and
  97. // that the least significant digit of s is not necessarily uniquely determined by these criteria.
  98. //
  99. // Note: guarantees provided by convert_floating_point_to_decimal_exponential_form satisfy
  100. // requirements of NOTE 2.
  101. auto [sign, mantissa, exponent] = convert_floating_point_to_decimal_exponential_form(d);
  102. i32 k = 0;
  103. AK::Array<char, 20> mantissa_digits;
  104. convert_to_decimal_digits_array(mantissa, mantissa_digits, k);
  105. i32 n = exponent + k; // s = mantissa
  106. // 3. If x < -0𝔽, return the string-concatenation of "-" and Number::toString(-x, radix).
  107. if (sign)
  108. builder.append('-');
  109. // Non-standard: Intl needs number-to-string conversions for extremely large numbers without any
  110. // exponential formatting, as it will handle such formatting itself in a locale-aware way.
  111. bool force_no_exponent = mode == NumberToStringMode::WithoutExponent;
  112. // 6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then
  113. if ((n >= -5 && n <= 21) || force_no_exponent) {
  114. // a. If n ≥ k, then
  115. if (n >= k) {
  116. // i. Return the string-concatenation of:
  117. // the code units of the k digits of the representation of s using radix radix
  118. builder.append(mantissa_digits.data(), k);
  119. // n - k occurrences of the code unit 0x0030 (DIGIT ZERO)
  120. builder.append_repeated('0', n - k);
  121. // b. Else if n > 0, then
  122. } else if (n > 0) {
  123. // i. Return the string-concatenation of:
  124. // the code units of the most significant n digits of the representation of s using radix radix
  125. builder.append(mantissa_digits.data(), n);
  126. // the code unit 0x002E (FULL STOP)
  127. builder.append('.');
  128. // the code units of the remaining k - n digits of the representation of s using radix radix
  129. builder.append(mantissa_digits.data() + n, k - n);
  130. // c. Else,
  131. } else {
  132. // i. Assert: n ≤ 0.
  133. VERIFY(n <= 0);
  134. // ii. Return the string-concatenation of:
  135. // the code unit 0x0030 (DIGIT ZERO)
  136. builder.append('0');
  137. // the code unit 0x002E (FULL STOP)
  138. builder.append('.');
  139. // -n occurrences of the code unit 0x0030 (DIGIT ZERO)
  140. builder.append_repeated('0', -n);
  141. // the code units of the k digits of the representation of s using radix radix
  142. builder.append(mantissa_digits.data(), k);
  143. }
  144. return;
  145. }
  146. // 7. NOTE: In this case, the input will be represented using scientific E notation, such as 1.2e+3.
  147. // 9. If n < 0, then
  148. // a. Let exponentSign be the code unit 0x002D (HYPHEN-MINUS).
  149. // 10. Else,
  150. // a. Let exponentSign be the code unit 0x002B (PLUS SIGN).
  151. char exponent_sign = n < 0 ? '-' : '+';
  152. AK::Array<char, 5> exponent_digits;
  153. i32 exponent_length = 0;
  154. convert_to_decimal_digits_array(abs(n - 1), exponent_digits, exponent_length);
  155. // 11. If k is 1, then
  156. if (k == 1) {
  157. // a. Return the string-concatenation of:
  158. // the code unit of the single digit of s
  159. builder.append(mantissa_digits[0]);
  160. // the code unit 0x0065 (LATIN SMALL LETTER E)
  161. builder.append('e');
  162. // exponentSign
  163. builder.append(exponent_sign);
  164. // the code units of the decimal representation of abs(n - 1)
  165. builder.append(exponent_digits.data(), exponent_length);
  166. return;
  167. }
  168. // 12. Return the string-concatenation of:
  169. // the code unit of the most significant digit of the decimal representation of s
  170. builder.append(mantissa_digits[0]);
  171. // the code unit 0x002E (FULL STOP)
  172. builder.append('.');
  173. // the code units of the remaining k - 1 digits of the decimal representation of s
  174. builder.append(mantissa_digits.data() + 1, k - 1);
  175. // the code unit 0x0065 (LATIN SMALL LETTER E)
  176. builder.append('e');
  177. // exponentSign
  178. builder.append(exponent_sign);
  179. // the code units of the decimal representation of abs(n - 1)
  180. builder.append(exponent_digits.data(), exponent_length);
  181. }
  182. String number_to_string(double d, NumberToStringMode mode)
  183. {
  184. StringBuilder builder;
  185. number_to_string_impl(builder, d, mode);
  186. return builder.to_string().release_value();
  187. }
  188. ByteString number_to_byte_string(double d, NumberToStringMode mode)
  189. {
  190. StringBuilder builder;
  191. number_to_string_impl(builder, d, mode);
  192. return builder.to_byte_string();
  193. }
  194. // 7.2.2 IsArray ( argument ), https://tc39.es/ecma262/#sec-isarray
  195. ThrowCompletionOr<bool> Value::is_array(VM& vm) const
  196. {
  197. // 1. If argument is not an Object, return false.
  198. if (!is_object())
  199. return false;
  200. auto const& object = as_object();
  201. // 2. If argument is an Array exotic object, return true.
  202. if (is<Array>(object))
  203. return true;
  204. // 3. If argument is a Proxy exotic object, then
  205. if (is<ProxyObject>(object)) {
  206. auto const& proxy = static_cast<ProxyObject const&>(object);
  207. // a. If argument.[[ProxyHandler]] is null, throw a TypeError exception.
  208. if (proxy.is_revoked())
  209. return vm.throw_completion<TypeError>(ErrorType::ProxyRevoked);
  210. // b. Let target be argument.[[ProxyTarget]].
  211. auto const& target = proxy.target();
  212. // c. Return ? IsArray(target).
  213. return Value(&target).is_array(vm);
  214. }
  215. // 4. Return false.
  216. return false;
  217. }
  218. Array& Value::as_array()
  219. {
  220. VERIFY(is_object() && is<Array>(as_object()));
  221. return static_cast<Array&>(as_object());
  222. }
  223. // 20.5.8.2 IsError ( argument ), https://tc39.es/proposal-is-error/#sec-iserror
  224. bool Value::is_error() const
  225. {
  226. // 1. If argument is not an Object, return false.
  227. // 2. If argument has an [[ErrorData]] internal slot, return true.
  228. // 3. Return false.
  229. return is_object() && is<Error>(as_object());
  230. }
  231. // 7.2.3 IsCallable ( argument ), https://tc39.es/ecma262/#sec-iscallable
  232. bool Value::is_function() const
  233. {
  234. // 1. If argument is not an Object, return false.
  235. // 2. If argument has a [[Call]] internal method, return true.
  236. // 3. Return false.
  237. return is_object() && as_object().is_function();
  238. }
  239. FunctionObject& Value::as_function()
  240. {
  241. VERIFY(is_function());
  242. return static_cast<FunctionObject&>(as_object());
  243. }
  244. FunctionObject const& Value::as_function() const
  245. {
  246. VERIFY(is_function());
  247. return static_cast<FunctionObject const&>(as_object());
  248. }
  249. // 7.2.4 IsConstructor ( argument ), https://tc39.es/ecma262/#sec-isconstructor
  250. bool Value::is_constructor() const
  251. {
  252. // 1. If Type(argument) is not Object, return false.
  253. if (!is_function())
  254. return false;
  255. // 2. If argument has a [[Construct]] internal method, return true.
  256. if (as_function().has_constructor())
  257. return true;
  258. // 3. Return false.
  259. return false;
  260. }
  261. // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
  262. ThrowCompletionOr<bool> Value::is_regexp(VM& vm) const
  263. {
  264. // 1. If argument is not an Object, return false.
  265. if (!is_object())
  266. return false;
  267. // 2. Let matcher be ? Get(argument, @@match).
  268. auto matcher = TRY(as_object().get(vm.well_known_symbol_match()));
  269. // 3. If matcher is not undefined, return ToBoolean(matcher).
  270. if (!matcher.is_undefined())
  271. return matcher.to_boolean();
  272. // 4. If argument has a [[RegExpMatcher]] internal slot, return true.
  273. // 5. Return false.
  274. return is<RegExpObject>(as_object());
  275. }
  276. // 13.5.3 The typeof Operator, https://tc39.es/ecma262/#sec-typeof-operator
  277. GC::Ref<PrimitiveString> Value::typeof_(VM& vm) const
  278. {
  279. // 9. If val is a Number, return "number".
  280. if (is_number())
  281. return *vm.typeof_strings.number;
  282. switch (m_value.tag) {
  283. // 4. If val is undefined, return "undefined".
  284. case UNDEFINED_TAG:
  285. return *vm.typeof_strings.undefined;
  286. // 5. If val is null, return "object".
  287. case NULL_TAG:
  288. return *vm.typeof_strings.object;
  289. // 6. If val is a String, return "string".
  290. case STRING_TAG:
  291. return *vm.typeof_strings.string;
  292. // 7. If val is a Symbol, return "symbol".
  293. case SYMBOL_TAG:
  294. return *vm.typeof_strings.symbol;
  295. // 8. If val is a Boolean, return "boolean".
  296. case BOOLEAN_TAG:
  297. return *vm.typeof_strings.boolean;
  298. // 10. If val is a BigInt, return "bigint".
  299. case BIGINT_TAG:
  300. return *vm.typeof_strings.bigint;
  301. // 11. Assert: val is an Object.
  302. case OBJECT_TAG:
  303. // B.3.6.3 Changes to the typeof Operator, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-typeof
  304. // 12. If val has an [[IsHTMLDDA]] internal slot, return "undefined".
  305. if (as_object().is_htmldda())
  306. return *vm.typeof_strings.undefined;
  307. // 13. If val has a [[Call]] internal slot, return "function".
  308. if (is_function())
  309. return *vm.typeof_strings.function;
  310. // 14. Return "object".
  311. return *vm.typeof_strings.object;
  312. default:
  313. VERIFY_NOT_REACHED();
  314. }
  315. }
  316. String Value::to_string_without_side_effects() const
  317. {
  318. if (is_double())
  319. return number_to_string(m_value.as_double);
  320. switch (m_value.tag) {
  321. case UNDEFINED_TAG:
  322. return "undefined"_string;
  323. case NULL_TAG:
  324. return "null"_string;
  325. case BOOLEAN_TAG:
  326. return as_bool() ? "true"_string : "false"_string;
  327. case INT32_TAG:
  328. return String::number(as_i32());
  329. case STRING_TAG:
  330. return as_string().utf8_string();
  331. case SYMBOL_TAG:
  332. return as_symbol().descriptive_string().release_value();
  333. case BIGINT_TAG:
  334. return as_bigint().to_string().release_value();
  335. case OBJECT_TAG:
  336. return String::formatted("[object {}]", as_object().class_name()).release_value();
  337. case ACCESSOR_TAG:
  338. return "<accessor>"_string;
  339. case EMPTY_TAG:
  340. return "<empty>"_string;
  341. default:
  342. VERIFY_NOT_REACHED();
  343. }
  344. }
  345. ThrowCompletionOr<GC::Ref<PrimitiveString>> Value::to_primitive_string(VM& vm)
  346. {
  347. if (is_string())
  348. return as_string();
  349. auto string = TRY(to_string(vm));
  350. return PrimitiveString::create(vm, move(string));
  351. }
  352. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  353. ThrowCompletionOr<String> Value::to_string(VM& vm) const
  354. {
  355. if (is_double())
  356. return number_to_string(m_value.as_double);
  357. switch (m_value.tag) {
  358. // 1. If argument is a String, return argument.
  359. case STRING_TAG:
  360. return as_string().utf8_string();
  361. // 2. If argument is a Symbol, throw a TypeError exception.
  362. case SYMBOL_TAG:
  363. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "string");
  364. // 3. If argument is undefined, return "undefined".
  365. case UNDEFINED_TAG:
  366. return "undefined"_string;
  367. // 4. If argument is null, return "null".
  368. case NULL_TAG:
  369. return "null"_string;
  370. // 5. If argument is true, return "true".
  371. // 6. If argument is false, return "false".
  372. case BOOLEAN_TAG:
  373. return as_bool() ? "true"_string : "false"_string;
  374. // 7. If argument is a Number, return Number::toString(argument, 10).
  375. case INT32_TAG:
  376. return String::number(as_i32());
  377. // 8. If argument is a BigInt, return BigInt::toString(argument, 10).
  378. case BIGINT_TAG:
  379. return TRY_OR_THROW_OOM(vm, as_bigint().big_integer().to_base(10));
  380. // 9. Assert: argument is an Object.
  381. case OBJECT_TAG: {
  382. // 10. Let primValue be ? ToPrimitive(argument, string).
  383. auto primitive_value = TRY(to_primitive(vm, PreferredType::String));
  384. // 11. Assert: primValue is not an Object.
  385. VERIFY(!primitive_value.is_object());
  386. // 12. Return ? ToString(primValue).
  387. return primitive_value.to_string(vm);
  388. }
  389. default:
  390. VERIFY_NOT_REACHED();
  391. }
  392. }
  393. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  394. ThrowCompletionOr<ByteString> Value::to_byte_string(VM& vm) const
  395. {
  396. return TRY(to_string(vm)).to_byte_string();
  397. }
  398. ThrowCompletionOr<Utf16String> Value::to_utf16_string(VM& vm) const
  399. {
  400. if (is_string())
  401. return as_string().utf16_string();
  402. auto utf8_string = TRY(to_string(vm));
  403. return Utf16String::create(utf8_string.bytes_as_string_view());
  404. }
  405. ThrowCompletionOr<String> Value::to_well_formed_string(VM& vm) const
  406. {
  407. return ::JS::to_well_formed_string(TRY(to_utf16_string(vm)));
  408. }
  409. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  410. bool Value::to_boolean_slow_case() const
  411. {
  412. if (is_double()) {
  413. if (is_nan())
  414. return false;
  415. return m_value.as_double != 0;
  416. }
  417. switch (m_value.tag) {
  418. // 1. If argument is a Boolean, return argument.
  419. case BOOLEAN_TAG:
  420. return as_bool();
  421. // 2. If argument is any of undefined, null, +0𝔽, -0𝔽, NaN, 0ℤ, or the empty String, return false.
  422. case UNDEFINED_TAG:
  423. case NULL_TAG:
  424. return false;
  425. case INT32_TAG:
  426. return as_i32() != 0;
  427. case STRING_TAG:
  428. return !as_string().is_empty();
  429. case BIGINT_TAG:
  430. return as_bigint().big_integer() != BIGINT_ZERO;
  431. case OBJECT_TAG:
  432. // B.3.6.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  433. // 3. If argument is an Object and argument has an [[IsHTMLDDA]] internal slot, return false.
  434. if (as_object().is_htmldda())
  435. return false;
  436. // 4. Return true.
  437. return true;
  438. case SYMBOL_TAG:
  439. return true;
  440. default:
  441. VERIFY_NOT_REACHED();
  442. }
  443. }
  444. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  445. ThrowCompletionOr<Value> Value::to_primitive_slow_case(VM& vm, PreferredType preferred_type) const
  446. {
  447. // 1. If input is an Object, then
  448. if (is_object()) {
  449. // a. Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
  450. auto exotic_to_primitive = TRY(get_method(vm, vm.well_known_symbol_to_primitive()));
  451. // b. If exoticToPrim is not undefined, then
  452. if (exotic_to_primitive) {
  453. auto hint = [&]() -> ByteString {
  454. switch (preferred_type) {
  455. // i. If preferredType is not present, let hint be "default".
  456. case PreferredType::Default:
  457. return "default";
  458. // ii. Else if preferredType is string, let hint be "string".
  459. case PreferredType::String:
  460. return "string";
  461. // iii. Else,
  462. // 1. Assert: preferredType is number.
  463. // 2. Let hint be "number".
  464. case PreferredType::Number:
  465. return "number";
  466. default:
  467. VERIFY_NOT_REACHED();
  468. }
  469. }();
  470. // iv. Let result be ? Call(exoticToPrim, input, « hint »).
  471. auto result = TRY(call(vm, *exotic_to_primitive, *this, PrimitiveString::create(vm, hint)));
  472. // v. If result is not an Object, return result.
  473. if (!result.is_object())
  474. return result;
  475. // vi. Throw a TypeError exception.
  476. return vm.throw_completion<TypeError>(ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  477. }
  478. // c. If preferredType is not present, let preferredType be number.
  479. if (preferred_type == PreferredType::Default)
  480. preferred_type = PreferredType::Number;
  481. // d. Return ? OrdinaryToPrimitive(input, preferredType).
  482. return as_object().ordinary_to_primitive(preferred_type);
  483. }
  484. // 2. Return input.
  485. return *this;
  486. }
  487. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  488. ThrowCompletionOr<GC::Ref<Object>> Value::to_object(VM& vm) const
  489. {
  490. auto& realm = *vm.current_realm();
  491. VERIFY(!is_empty());
  492. // Number
  493. if (is_number()) {
  494. // Return a new Number object whose [[NumberData]] internal slot is set to argument. See 21.1 for a description of Number objects.
  495. return NumberObject::create(realm, as_double());
  496. }
  497. switch (m_value.tag) {
  498. // Undefined
  499. // Null
  500. case UNDEFINED_TAG:
  501. case NULL_TAG:
  502. // Throw a TypeError exception.
  503. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  504. // Boolean
  505. case BOOLEAN_TAG:
  506. // Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 20.3 for a description of Boolean objects.
  507. return BooleanObject::create(realm, as_bool());
  508. // String
  509. case STRING_TAG:
  510. // Return a new String object whose [[StringData]] internal slot is set to argument. See 22.1 for a description of String objects.
  511. return StringObject::create(realm, const_cast<JS::PrimitiveString&>(as_string()), realm.intrinsics().string_prototype());
  512. // Symbol
  513. case SYMBOL_TAG:
  514. // Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 20.4 for a description of Symbol objects.
  515. return SymbolObject::create(realm, const_cast<JS::Symbol&>(as_symbol()));
  516. // BigInt
  517. case BIGINT_TAG:
  518. // Return a new BigInt object whose [[BigIntData]] internal slot is set to argument. See 21.2 for a description of BigInt objects.
  519. return BigIntObject::create(realm, const_cast<JS::BigInt&>(as_bigint()));
  520. // Object
  521. case OBJECT_TAG:
  522. // Return argument.
  523. return const_cast<Object&>(as_object());
  524. default:
  525. VERIFY_NOT_REACHED();
  526. }
  527. }
  528. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  529. FLATTEN ThrowCompletionOr<Value> Value::to_numeric_slow_case(VM& vm) const
  530. {
  531. // 1. Let primValue be ? ToPrimitive(value, number).
  532. auto primitive_value = TRY(to_primitive(vm, Value::PreferredType::Number));
  533. // 2. If primValue is a BigInt, return primValue.
  534. if (primitive_value.is_bigint())
  535. return primitive_value;
  536. // 3. Return ? ToNumber(primValue).
  537. return primitive_value.to_number(vm);
  538. }
  539. constexpr bool is_ascii_number(u32 code_point)
  540. {
  541. return is_ascii_digit(code_point) || code_point == '.' || (code_point == 'e' || code_point == 'E') || code_point == '+' || code_point == '-';
  542. }
  543. struct NumberParseResult {
  544. StringView literal;
  545. u8 base;
  546. };
  547. static Optional<NumberParseResult> parse_number_text(StringView text)
  548. {
  549. NumberParseResult result {};
  550. auto check_prefix = [&](auto lower_prefix, auto upper_prefix) {
  551. if (text.length() <= 2)
  552. return false;
  553. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  554. return false;
  555. return true;
  556. };
  557. // https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
  558. if (check_prefix("0b"sv, "0B"sv)) {
  559. if (!all_of(text.substring_view(2), is_ascii_binary_digit))
  560. return {};
  561. result.literal = text.substring_view(2);
  562. result.base = 2;
  563. } else if (check_prefix("0o"sv, "0O"sv)) {
  564. if (!all_of(text.substring_view(2), is_ascii_octal_digit))
  565. return {};
  566. result.literal = text.substring_view(2);
  567. result.base = 8;
  568. } else if (check_prefix("0x"sv, "0X"sv)) {
  569. if (!all_of(text.substring_view(2), is_ascii_hex_digit))
  570. return {};
  571. result.literal = text.substring_view(2);
  572. result.base = 16;
  573. } else {
  574. if (!all_of(text, is_ascii_number))
  575. return {};
  576. result.literal = text;
  577. result.base = 10;
  578. }
  579. return result;
  580. }
  581. // 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber
  582. double string_to_number(StringView string)
  583. {
  584. // 1. Let text be StringToCodePoints(str).
  585. auto text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  586. // 2. Let literal be ParseText(text, StringNumericLiteral).
  587. if (text.is_empty())
  588. return 0;
  589. if (text == "Infinity"sv || text == "+Infinity"sv)
  590. return INFINITY;
  591. if (text == "-Infinity"sv)
  592. return -INFINITY;
  593. auto result = parse_number_text(text);
  594. // 3. If literal is a List of errors, return NaN.
  595. if (!result.has_value())
  596. return NAN;
  597. // 4. Return StringNumericValue of literal.
  598. if (result->base != 10) {
  599. auto bigint = MUST(Crypto::UnsignedBigInteger::from_base(result->base, result->literal));
  600. return bigint.to_double();
  601. }
  602. auto maybe_double = text.to_number<double>(AK::TrimWhitespace::No);
  603. if (!maybe_double.has_value())
  604. return NAN;
  605. return *maybe_double;
  606. }
  607. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  608. ThrowCompletionOr<Value> Value::to_number_slow_case(VM& vm) const
  609. {
  610. VERIFY(!is_empty());
  611. // 1. If argument is a Number, return argument.
  612. if (is_number())
  613. return *this;
  614. switch (m_value.tag) {
  615. // 2. If argument is either a Symbol or a BigInt, throw a TypeError exception.
  616. case SYMBOL_TAG:
  617. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "number");
  618. case BIGINT_TAG:
  619. return vm.throw_completion<TypeError>(ErrorType::Convert, "BigInt", "number");
  620. // 3. If argument is undefined, return NaN.
  621. case UNDEFINED_TAG:
  622. return js_nan();
  623. // 4. If argument is either null or false, return +0𝔽.
  624. case NULL_TAG:
  625. return Value(0);
  626. // 5. If argument is true, return 1𝔽.
  627. case BOOLEAN_TAG:
  628. return Value(as_bool() ? 1 : 0);
  629. // 6. If argument is a String, return StringToNumber(argument).
  630. case STRING_TAG:
  631. return string_to_number(as_string().byte_string());
  632. // 7. Assert: argument is an Object.
  633. case OBJECT_TAG: {
  634. // 8. Let primValue be ? ToPrimitive(argument, number).
  635. auto primitive_value = TRY(to_primitive(vm, PreferredType::Number));
  636. // 9. Assert: primValue is not an Object.
  637. VERIFY(!primitive_value.is_object());
  638. // 10. Return ? ToNumber(primValue).
  639. return primitive_value.to_number(vm);
  640. }
  641. default:
  642. VERIFY_NOT_REACHED();
  643. }
  644. }
  645. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string);
  646. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  647. ThrowCompletionOr<GC::Ref<BigInt>> Value::to_bigint(VM& vm) const
  648. {
  649. // 1. Let prim be ? ToPrimitive(argument, number).
  650. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  651. // 2. Return the value that prim corresponds to in Table 12.
  652. // Number
  653. if (primitive.is_number()) {
  654. // Throw a TypeError exception.
  655. return vm.throw_completion<TypeError>(ErrorType::Convert, "number", "BigInt");
  656. }
  657. switch (primitive.m_value.tag) {
  658. // Undefined
  659. case UNDEFINED_TAG:
  660. // Throw a TypeError exception.
  661. return vm.throw_completion<TypeError>(ErrorType::Convert, "undefined", "BigInt");
  662. // Null
  663. case NULL_TAG:
  664. // Throw a TypeError exception.
  665. return vm.throw_completion<TypeError>(ErrorType::Convert, "null", "BigInt");
  666. // Boolean
  667. case BOOLEAN_TAG: {
  668. // Return 1n if prim is true and 0n if prim is false.
  669. auto value = primitive.as_bool() ? 1 : 0;
  670. return BigInt::create(vm, Crypto::SignedBigInteger { value });
  671. }
  672. // BigInt
  673. case BIGINT_TAG:
  674. // Return prim.
  675. return primitive.as_bigint();
  676. case STRING_TAG: {
  677. // 1. Let n be ! StringToBigInt(prim).
  678. auto bigint = string_to_bigint(vm, primitive.as_string().byte_string());
  679. // 2. If n is undefined, throw a SyntaxError exception.
  680. if (!bigint.has_value())
  681. return vm.throw_completion<SyntaxError>(ErrorType::BigIntInvalidValue, primitive);
  682. // 3. Return n.
  683. return *bigint.release_value();
  684. }
  685. // Symbol
  686. case SYMBOL_TAG:
  687. // Throw a TypeError exception.
  688. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "BigInt");
  689. default:
  690. VERIFY_NOT_REACHED();
  691. }
  692. }
  693. struct BigIntParseResult {
  694. StringView literal;
  695. u8 base { 10 };
  696. bool is_negative { false };
  697. };
  698. static Optional<BigIntParseResult> parse_bigint_text(StringView text)
  699. {
  700. BigIntParseResult result {};
  701. auto parse_for_prefixed_base = [&](auto lower_prefix, auto upper_prefix, auto validator) {
  702. if (text.length() <= 2)
  703. return false;
  704. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  705. return false;
  706. return all_of(text.substring_view(2), validator);
  707. };
  708. if (parse_for_prefixed_base("0b"sv, "0B"sv, is_ascii_binary_digit)) {
  709. result.literal = text.substring_view(2);
  710. result.base = 2;
  711. } else if (parse_for_prefixed_base("0o"sv, "0O"sv, is_ascii_octal_digit)) {
  712. result.literal = text.substring_view(2);
  713. result.base = 8;
  714. } else if (parse_for_prefixed_base("0x"sv, "0X"sv, is_ascii_hex_digit)) {
  715. result.literal = text.substring_view(2);
  716. result.base = 16;
  717. } else {
  718. if (text.starts_with('-')) {
  719. text = text.substring_view(1);
  720. result.is_negative = true;
  721. } else if (text.starts_with('+')) {
  722. text = text.substring_view(1);
  723. }
  724. if (!all_of(text, is_ascii_digit))
  725. return {};
  726. result.literal = text;
  727. result.base = 10;
  728. }
  729. return result;
  730. }
  731. // 7.1.14 StringToBigInt ( str ), https://tc39.es/ecma262/#sec-stringtobigint
  732. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string)
  733. {
  734. // 1. Let text be StringToCodePoints(str).
  735. auto text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  736. // 2. Let literal be ParseText(text, StringIntegerLiteral).
  737. auto result = parse_bigint_text(text);
  738. // 3. If literal is a List of errors, return undefined.
  739. if (!result.has_value())
  740. return {};
  741. // 4. Let mv be the MV of literal.
  742. // 5. Assert: mv is an integer.
  743. auto bigint = MUST(Crypto::SignedBigInteger::from_base(result->base, result->literal));
  744. if (result->is_negative && (bigint != BIGINT_ZERO))
  745. bigint.negate();
  746. // 6. Return ℤ(mv).
  747. return BigInt::create(vm, move(bigint));
  748. }
  749. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/#sec-tobigint64
  750. ThrowCompletionOr<i64> Value::to_bigint_int64(VM& vm) const
  751. {
  752. // 1. Let n be ? ToBigInt(argument).
  753. auto bigint = TRY(to_bigint(vm));
  754. // 2. Let int64bit be ℝ(n) modulo 2^64.
  755. // 3. If int64bit ≥ 2^63, return ℤ(int64bit - 2^64); otherwise return ℤ(int64bit).
  756. return static_cast<i64>(bigint->big_integer().to_u64());
  757. }
  758. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/#sec-tobiguint64
  759. ThrowCompletionOr<u64> Value::to_bigint_uint64(VM& vm) const
  760. {
  761. // 1. Let n be ? ToBigInt(argument).
  762. auto bigint = TRY(to_bigint(vm));
  763. // 2. Let int64bit be ℝ(n) modulo 2^64.
  764. // 3. Return ℤ(int64bit).
  765. return bigint->big_integer().to_u64();
  766. }
  767. ThrowCompletionOr<double> Value::to_double(VM& vm) const
  768. {
  769. return TRY(to_number(vm)).as_double();
  770. }
  771. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  772. ThrowCompletionOr<PropertyKey> Value::to_property_key(VM& vm) const
  773. {
  774. // OPTIMIZATION: Return the value as a numeric PropertyKey, if possible.
  775. if (is_int32() && as_i32() >= 0)
  776. return PropertyKey { as_i32() };
  777. // 1. Let key be ? ToPrimitive(argument, string).
  778. auto key = TRY(to_primitive(vm, PreferredType::String));
  779. // 2. If key is a Symbol, then
  780. if (key.is_symbol()) {
  781. // a. Return key.
  782. return &key.as_symbol();
  783. }
  784. // 3. Return ! ToString(key).
  785. return MUST(key.to_byte_string(vm));
  786. }
  787. // 7.1.6 ToInt32 ( argument ), https://tc39.es/ecma262/#sec-toint32
  788. ThrowCompletionOr<i32> Value::to_i32_slow_case(VM& vm) const
  789. {
  790. VERIFY(!is_int32());
  791. // 1. Let number be ? ToNumber(argument).
  792. double number = TRY(to_number(vm)).as_double();
  793. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  794. if (!isfinite(number) || number == 0)
  795. return 0;
  796. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  797. auto abs = fabs(number);
  798. auto int_val = floor(abs);
  799. if (signbit(number))
  800. int_val = -int_val;
  801. // 4. Let int32bit be int modulo 2^32.
  802. auto int32bit = modulo(int_val, NumericLimits<u32>::max() + 1.0);
  803. // 5. If int32bit ≥ 2^31, return 𝔽(int32bit - 2^32); otherwise return 𝔽(int32bit).
  804. if (int32bit >= 2147483648.0)
  805. int32bit -= 4294967296.0;
  806. return static_cast<i32>(int32bit);
  807. }
  808. // 7.1.6 ToInt32 ( argument ), https://tc39.es/ecma262/#sec-toint32
  809. ThrowCompletionOr<i32> Value::to_i32(VM& vm) const
  810. {
  811. if (is_int32())
  812. return as_i32();
  813. return to_i32_slow_case(vm);
  814. }
  815. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  816. ThrowCompletionOr<u32> Value::to_u32(VM& vm) const
  817. {
  818. // OPTIMIZATION: If this value is encoded as a positive i32, return it directly.
  819. if (is_int32() && as_i32() >= 0)
  820. return as_i32();
  821. // 1. Let number be ? ToNumber(argument).
  822. double number = TRY(to_number(vm)).as_double();
  823. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  824. if (!isfinite(number) || number == 0)
  825. return 0;
  826. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  827. auto int_val = floor(fabs(number));
  828. if (signbit(number))
  829. int_val = -int_val;
  830. // 4. Let int32bit be int modulo 2^32.
  831. auto int32bit = modulo(int_val, NumericLimits<u32>::max() + 1.0);
  832. // 5. Return 𝔽(int32bit).
  833. // Cast to i64 here to ensure that the double --> u32 cast doesn't invoke undefined behavior
  834. // Otherwise, negative numbers cause a UBSAN warning.
  835. return static_cast<u32>(static_cast<i64>(int32bit));
  836. }
  837. // 7.1.8 ToInt16 ( argument ), https://tc39.es/ecma262/#sec-toint16
  838. ThrowCompletionOr<i16> Value::to_i16(VM& vm) const
  839. {
  840. // 1. Let number be ? ToNumber(argument).
  841. double number = TRY(to_number(vm)).as_double();
  842. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  843. if (!isfinite(number) || number == 0)
  844. return 0;
  845. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  846. auto abs = fabs(number);
  847. auto int_val = floor(abs);
  848. if (signbit(number))
  849. int_val = -int_val;
  850. // 4. Let int16bit be int modulo 2^16.
  851. auto int16bit = modulo(int_val, NumericLimits<u16>::max() + 1.0);
  852. // 5. If int16bit ≥ 2^15, return 𝔽(int16bit - 2^16); otherwise return 𝔽(int16bit).
  853. if (int16bit >= 32768.0)
  854. int16bit -= 65536.0;
  855. return static_cast<i16>(int16bit);
  856. }
  857. // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16
  858. ThrowCompletionOr<u16> Value::to_u16(VM& vm) const
  859. {
  860. // 1. Let number be ? ToNumber(argument).
  861. double number = TRY(to_number(vm)).as_double();
  862. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  863. if (!isfinite(number) || number == 0)
  864. return 0;
  865. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  866. auto int_val = floor(fabs(number));
  867. if (signbit(number))
  868. int_val = -int_val;
  869. // 4. Let int16bit be int modulo 2^16.
  870. auto int16bit = modulo(int_val, NumericLimits<u16>::max() + 1.0);
  871. // 5. Return 𝔽(int16bit).
  872. return static_cast<u16>(int16bit);
  873. }
  874. // 7.1.10 ToInt8 ( argument ), https://tc39.es/ecma262/#sec-toint8
  875. ThrowCompletionOr<i8> Value::to_i8(VM& vm) const
  876. {
  877. // 1. Let number be ? ToNumber(argument).
  878. double number = TRY(to_number(vm)).as_double();
  879. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  880. if (!isfinite(number) || number == 0)
  881. return 0;
  882. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  883. auto abs = fabs(number);
  884. auto int_val = floor(abs);
  885. if (signbit(number))
  886. int_val = -int_val;
  887. // 4. Let int8bit be int modulo 2^8.
  888. auto int8bit = modulo(int_val, NumericLimits<u8>::max() + 1.0);
  889. // 5. If int8bit ≥ 2^7, return 𝔽(int8bit - 2^8); otherwise return 𝔽(int8bit).
  890. if (int8bit >= 128.0)
  891. int8bit -= 256.0;
  892. return static_cast<i8>(int8bit);
  893. }
  894. // 7.1.11 ToUint8 ( argument ), https://tc39.es/ecma262/#sec-touint8
  895. ThrowCompletionOr<u8> Value::to_u8(VM& vm) const
  896. {
  897. // 1. Let number be ? ToNumber(argument).
  898. double number = TRY(to_number(vm)).as_double();
  899. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  900. if (!isfinite(number) || number == 0)
  901. return 0;
  902. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  903. auto int_val = floor(fabs(number));
  904. if (signbit(number))
  905. int_val = -int_val;
  906. // 4. Let int8bit be int modulo 2^8.
  907. auto int8bit = modulo(int_val, NumericLimits<u8>::max() + 1.0);
  908. // 5. Return 𝔽(int8bit).
  909. return static_cast<u8>(int8bit);
  910. }
  911. // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp
  912. ThrowCompletionOr<u8> Value::to_u8_clamp(VM& vm) const
  913. {
  914. // 1. Let number be ? ToNumber(argument).
  915. auto number = TRY(to_number(vm));
  916. // 2. If number is NaN, return +0𝔽.
  917. if (number.is_nan())
  918. return 0;
  919. double value = number.as_double();
  920. // 3. If ℝ(number) ≤ 0, return +0𝔽.
  921. if (value <= 0.0)
  922. return 0;
  923. // 4. If ℝ(number) ≥ 255, return 255𝔽.
  924. if (value >= 255.0)
  925. return 255;
  926. // 5. Let f be floor(ℝ(number)).
  927. auto int_val = floor(value);
  928. // 6. If f + 0.5 < ℝ(number), return 𝔽(f + 1).
  929. if (int_val + 0.5 < value)
  930. return static_cast<u8>(int_val + 1.0);
  931. // 7. If ℝ(number) < f + 0.5, return 𝔽(f).
  932. if (value < int_val + 0.5)
  933. return static_cast<u8>(int_val);
  934. // 8. If f is odd, return 𝔽(f + 1).
  935. if (fmod(int_val, 2.0) == 1.0)
  936. return static_cast<u8>(int_val + 1.0);
  937. // 9. Return 𝔽(f).
  938. return static_cast<u8>(int_val);
  939. }
  940. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  941. ThrowCompletionOr<size_t> Value::to_length(VM& vm) const
  942. {
  943. // 1. Let len be ? ToIntegerOrInfinity(argument).
  944. auto len = TRY(to_integer_or_infinity(vm));
  945. // 2. If len ≤ 0, return +0𝔽.
  946. if (len <= 0)
  947. return 0;
  948. // FIXME: The expected output range is 0 - 2^53-1, but we don't want to overflow the size_t on 32-bit platforms.
  949. // Convert this to u64 so it works everywhere.
  950. constexpr double length_limit = sizeof(void*) == 4 ? NumericLimits<size_t>::max() : MAX_ARRAY_LIKE_INDEX;
  951. // 3. Return 𝔽(min(len, 2^53 - 1)).
  952. return min(len, length_limit);
  953. }
  954. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  955. ThrowCompletionOr<size_t> Value::to_index(VM& vm) const
  956. {
  957. // 1. If value is undefined, then
  958. if (is_undefined()) {
  959. // a. Return 0.
  960. return 0;
  961. }
  962. // 2. Else,
  963. // a. Let integer be ? ToIntegerOrInfinity(value).
  964. auto integer = TRY(to_integer_or_infinity(vm));
  965. // OPTIMIZATION: If the value is negative, ToLength normalizes it to 0, and we fail the SameValue comparison below.
  966. // Bail out early instead.
  967. if (integer < 0)
  968. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  969. // b. Let clamped be ! ToLength(𝔽(integer)).
  970. auto clamped = MUST(Value(integer).to_length(vm));
  971. // c. If SameValue(𝔽(integer), clamped) is false, throw a RangeError exception.
  972. if (integer != clamped)
  973. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  974. // d. Assert: 0 ≤ integer ≤ 2^53 - 1.
  975. VERIFY(0 <= integer && integer <= MAX_ARRAY_LIKE_INDEX);
  976. // e. Return integer.
  977. // NOTE: We return the clamped value here, which already has the right type.
  978. return clamped;
  979. }
  980. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  981. ThrowCompletionOr<double> Value::to_integer_or_infinity(VM& vm) const
  982. {
  983. // 1. Let number be ? ToNumber(argument).
  984. auto number = TRY(to_number(vm));
  985. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
  986. if (number.is_nan() || number.as_double() == 0)
  987. return 0;
  988. // 3. If number is +∞𝔽, return +∞.
  989. // 4. If number is -∞𝔽, return -∞.
  990. if (number.is_infinity())
  991. return number.as_double();
  992. // 5. Let integer be floor(abs(ℝ(number))).
  993. auto integer = floor(fabs(number.as_double()));
  994. // 6. If number < -0𝔽, set integer to -integer.
  995. // NOTE: The zero check is required as 'integer' is a double here but an MV in the spec,
  996. // which doesn't have negative zero.
  997. if (number.as_double() < 0 && integer != 0)
  998. integer = -integer;
  999. // 7. Return integer.
  1000. return integer;
  1001. }
  1002. // Standalone variant using plain doubles for cases where we already got numbers and know the AO won't throw.
  1003. double to_integer_or_infinity(double number)
  1004. {
  1005. // 1. Let number be ? ToNumber(argument).
  1006. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
  1007. if (isnan(number) || number == 0)
  1008. return 0;
  1009. // 3. If number is +∞𝔽, return +∞.
  1010. if (__builtin_isinf_sign(number) > 0)
  1011. return static_cast<double>(INFINITY);
  1012. // 4. If number is -∞𝔽, return -∞.
  1013. if (__builtin_isinf_sign(number) < 0)
  1014. return static_cast<double>(-INFINITY);
  1015. // 5. Let integer be floor(abs(ℝ(number))).
  1016. auto integer = floor(fabs(number));
  1017. // 6. If number < -0𝔽, set integer to -integer.
  1018. // NOTE: The zero check is required as 'integer' is a double here but an MV in the spec,
  1019. // which doesn't have negative zero.
  1020. if (number < 0 && integer != 0)
  1021. integer = -integer;
  1022. // 7. Return integer.
  1023. return integer;
  1024. }
  1025. // 7.3.3 GetV ( V, P ), https://tc39.es/ecma262/#sec-getv
  1026. ThrowCompletionOr<Value> Value::get(VM& vm, PropertyKey const& property_key) const
  1027. {
  1028. // 1. Let O be ? ToObject(V).
  1029. auto object = TRY(to_object(vm));
  1030. // 2. Return ? O.[[Get]](P, V).
  1031. return TRY(object->internal_get(property_key, *this));
  1032. }
  1033. // 7.3.11 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  1034. ThrowCompletionOr<GC::Ptr<FunctionObject>> Value::get_method(VM& vm, PropertyKey const& property_key) const
  1035. {
  1036. // 1. Let func be ? GetV(V, P).
  1037. auto function = TRY(get(vm, property_key));
  1038. // 2. If func is either undefined or null, return undefined.
  1039. if (function.is_nullish())
  1040. return nullptr;
  1041. // 3. If IsCallable(func) is false, throw a TypeError exception.
  1042. if (!function.is_function())
  1043. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, function.to_string_without_side_effects());
  1044. // 4. Return func.
  1045. return function.as_function();
  1046. }
  1047. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  1048. // RelationalExpression : RelationalExpression > ShiftExpression
  1049. ThrowCompletionOr<Value> greater_than(VM& vm, Value lhs, Value rhs)
  1050. {
  1051. // 1. Let lref be ? Evaluation of RelationalExpression.
  1052. // 2. Let lval be ? GetValue(lref).
  1053. // 3. Let rref be ? Evaluation of ShiftExpression.
  1054. // 4. Let rval be ? GetValue(rref).
  1055. // NOTE: This is handled in the AST or Bytecode interpreter.
  1056. // OPTIMIZATION: If both values are i32, we can do a direct comparison without calling into IsLessThan.
  1057. if (lhs.is_int32() && rhs.is_int32())
  1058. return lhs.as_i32() > rhs.as_i32();
  1059. // 5. Let r be ? IsLessThan(rval, lval, false).
  1060. auto relation = TRY(is_less_than(vm, lhs, rhs, false));
  1061. // 6. If r is undefined, return false. Otherwise, return r.
  1062. if (relation == TriState::Unknown)
  1063. return Value(false);
  1064. return Value(relation == TriState::True);
  1065. }
  1066. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  1067. // RelationalExpression : RelationalExpression >= ShiftExpression
  1068. ThrowCompletionOr<Value> greater_than_equals(VM& vm, Value lhs, Value rhs)
  1069. {
  1070. // 1. Let lref be ? Evaluation of RelationalExpression.
  1071. // 2. Let lval be ? GetValue(lref).
  1072. // 3. Let rref be ? Evaluation of ShiftExpression.
  1073. // 4. Let rval be ? GetValue(rref).
  1074. // NOTE: This is handled in the AST or Bytecode interpreter.
  1075. // OPTIMIZATION: If both values are i32, we can do a direct comparison without calling into IsLessThan.
  1076. if (lhs.is_int32() && rhs.is_int32())
  1077. return lhs.as_i32() >= rhs.as_i32();
  1078. // 5. Let r be ? IsLessThan(lval, rval, true).
  1079. auto relation = TRY(is_less_than(vm, lhs, rhs, true));
  1080. // 6. If r is true or undefined, return false. Otherwise, return true.
  1081. if (relation == TriState::Unknown || relation == TriState::True)
  1082. return Value(false);
  1083. return Value(true);
  1084. }
  1085. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  1086. // RelationalExpression : RelationalExpression < ShiftExpression
  1087. ThrowCompletionOr<Value> less_than(VM& vm, Value lhs, Value rhs)
  1088. {
  1089. // 1. Let lref be ? Evaluation of RelationalExpression.
  1090. // 2. Let lval be ? GetValue(lref).
  1091. // 3. Let rref be ? Evaluation of ShiftExpression.
  1092. // 4. Let rval be ? GetValue(rref).
  1093. // NOTE: This is handled in the AST or Bytecode interpreter.
  1094. // OPTIMIZATION: If both values are i32, we can do a direct comparison without calling into IsLessThan.
  1095. if (lhs.is_int32() && rhs.is_int32())
  1096. return lhs.as_i32() < rhs.as_i32();
  1097. // 5. Let r be ? IsLessThan(lval, rval, true).
  1098. auto relation = TRY(is_less_than(vm, lhs, rhs, true));
  1099. // 6. If r is undefined, return false. Otherwise, return r.
  1100. if (relation == TriState::Unknown)
  1101. return Value(false);
  1102. return Value(relation == TriState::True);
  1103. }
  1104. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  1105. // RelationalExpression : RelationalExpression <= ShiftExpression
  1106. ThrowCompletionOr<Value> less_than_equals(VM& vm, Value lhs, Value rhs)
  1107. {
  1108. // 1. Let lref be ? Evaluation of RelationalExpression.
  1109. // 2. Let lval be ? GetValue(lref).
  1110. // 3. Let rref be ? Evaluation of ShiftExpression.
  1111. // 4. Let rval be ? GetValue(rref).
  1112. // NOTE: This is handled in the AST or Bytecode interpreter.
  1113. // OPTIMIZATION: If both values are i32, we can do a direct comparison without calling into IsLessThan.
  1114. if (lhs.is_int32() && rhs.is_int32())
  1115. return lhs.as_i32() <= rhs.as_i32();
  1116. // 5. Let r be ? IsLessThan(rval, lval, false).
  1117. auto relation = TRY(is_less_than(vm, lhs, rhs, false));
  1118. // 6. If r is true or undefined, return false. Otherwise, return true.
  1119. if (relation == TriState::True || relation == TriState::Unknown)
  1120. return Value(false);
  1121. return Value(true);
  1122. }
  1123. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  1124. // BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
  1125. ThrowCompletionOr<Value> bitwise_and(VM& vm, Value lhs, Value rhs)
  1126. {
  1127. // OPTIMIZATION: Fast path when both values are Int32.
  1128. if (lhs.is_int32() && rhs.is_int32())
  1129. return Value(lhs.as_i32() & rhs.as_i32());
  1130. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1131. // 1-2, 6. N/A.
  1132. // 3. Let lnum be ? ToNumeric(lval).
  1133. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1134. // 4. Let rnum be ? ToNumeric(rval).
  1135. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1136. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1137. // [...]
  1138. // 8. Return operation(lnum, rnum).
  1139. if (both_number(lhs_numeric, rhs_numeric)) {
  1140. // 6.1.6.1.17 Number::bitwiseAND ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseAND
  1141. // 1. Return NumberBitwiseOp(&, x, y).
  1142. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  1143. return Value(0);
  1144. return Value(TRY(lhs_numeric.to_i32(vm)) & TRY(rhs_numeric.to_i32(vm)));
  1145. }
  1146. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1147. // 6.1.6.2.18 BigInt::bitwiseAND ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseAND
  1148. // 1. Return BigIntBitwiseOp(&, x, y).
  1149. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  1150. }
  1151. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1152. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  1153. }
  1154. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  1155. // BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression
  1156. ThrowCompletionOr<Value> bitwise_or(VM& vm, Value lhs, Value rhs)
  1157. {
  1158. // OPTIMIZATION: Fast path when both values are Int32.
  1159. if (lhs.is_int32() && rhs.is_int32())
  1160. return Value(lhs.as_i32() | rhs.as_i32());
  1161. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1162. // 1-2, 6. N/A.
  1163. // 3. Let lnum be ? ToNumeric(lval).
  1164. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1165. // 4. Let rnum be ? ToNumeric(rval).
  1166. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1167. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1168. // [...]
  1169. // 8. Return operation(lnum, rnum).
  1170. if (both_number(lhs_numeric, rhs_numeric)) {
  1171. // 6.1.6.1.19 Number::bitwiseOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseOR
  1172. // 1. Return NumberBitwiseOp(|, x, y).
  1173. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  1174. return Value(0);
  1175. if (!lhs_numeric.is_finite_number())
  1176. return rhs_numeric;
  1177. if (!rhs_numeric.is_finite_number())
  1178. return lhs_numeric;
  1179. return Value(TRY(lhs_numeric.to_i32(vm)) | TRY(rhs_numeric.to_i32(vm)));
  1180. }
  1181. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1182. // 6.1.6.2.20 BigInt::bitwiseOR ( x, y )
  1183. // 1. Return BigIntBitwiseOp(|, x, y).
  1184. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  1185. }
  1186. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1187. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  1188. }
  1189. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  1190. // BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
  1191. ThrowCompletionOr<Value> bitwise_xor(VM& vm, Value lhs, Value rhs)
  1192. {
  1193. // OPTIMIZATION: Fast path when both values are Int32.
  1194. if (lhs.is_int32() && rhs.is_int32())
  1195. return Value(lhs.as_i32() ^ rhs.as_i32());
  1196. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1197. // 1-2, 6. N/A.
  1198. // 3. Let lnum be ? ToNumeric(lval).
  1199. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1200. // 4. Let rnum be ? ToNumeric(rval).
  1201. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1202. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1203. // [...]
  1204. // 8. Return operation(lnum, rnum).
  1205. if (both_number(lhs_numeric, rhs_numeric)) {
  1206. // 6.1.6.1.18 Number::bitwiseXOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseXOR
  1207. // 1. Return NumberBitwiseOp(^, x, y).
  1208. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  1209. return Value(0);
  1210. if (!lhs_numeric.is_finite_number())
  1211. return rhs_numeric;
  1212. if (!rhs_numeric.is_finite_number())
  1213. return lhs_numeric;
  1214. return Value(TRY(lhs_numeric.to_i32(vm)) ^ TRY(rhs_numeric.to_i32(vm)));
  1215. }
  1216. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1217. // 6.1.6.2.19 BigInt::bitwiseXOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseXOR
  1218. // 1. Return BigIntBitwiseOp(^, x, y).
  1219. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  1220. }
  1221. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1222. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  1223. }
  1224. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  1225. // UnaryExpression : ~ UnaryExpression
  1226. ThrowCompletionOr<Value> bitwise_not(VM& vm, Value lhs)
  1227. {
  1228. // 1. Let expr be ? Evaluation of UnaryExpression.
  1229. // NOTE: This is handled in the AST or Bytecode interpreter.
  1230. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  1231. auto old_value = TRY(lhs.to_numeric(vm));
  1232. // 3. If oldValue is a Number, then
  1233. if (old_value.is_number()) {
  1234. // a. Return Number::bitwiseNOT(oldValue).
  1235. // 6.1.6.1.2 Number::bitwiseNOT ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseNOT
  1236. // 1. Let oldValue be ! ToInt32(x).
  1237. // 2. Return the result of applying bitwise complement to oldValue. The mathematical value of the result is
  1238. // exactly representable as a 32-bit two's complement bit string.
  1239. return Value(~TRY(old_value.to_i32(vm)));
  1240. }
  1241. // 4. Else,
  1242. // a. Assert: oldValue is a BigInt.
  1243. VERIFY(old_value.is_bigint());
  1244. // b. Return BigInt::bitwiseNOT(oldValue).
  1245. // 6.1.6.2.2 BigInt::bitwiseNOT ( x ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseNOT
  1246. // 1. Return -x - 1ℤ.
  1247. return BigInt::create(vm, old_value.as_bigint().big_integer().bitwise_not());
  1248. }
  1249. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  1250. // UnaryExpression : + UnaryExpression
  1251. ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
  1252. {
  1253. // 1. Let expr be ? Evaluation of UnaryExpression.
  1254. // NOTE: This is handled in the AST or Bytecode interpreter.
  1255. // 2. Return ? ToNumber(? GetValue(expr)).
  1256. return TRY(lhs.to_number(vm));
  1257. }
  1258. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  1259. // UnaryExpression : - UnaryExpression
  1260. ThrowCompletionOr<Value> unary_minus(VM& vm, Value lhs)
  1261. {
  1262. // 1. Let expr be ? Evaluation of UnaryExpression.
  1263. // NOTE: This is handled in the AST or Bytecode interpreter.
  1264. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  1265. auto old_value = TRY(lhs.to_numeric(vm));
  1266. // 3. If oldValue is a Number, then
  1267. if (old_value.is_number()) {
  1268. // a. Return Number::unaryMinus(oldValue).
  1269. // 6.1.6.1.1 Number::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-unaryMinus
  1270. // 1. If x is NaN, return NaN.
  1271. if (old_value.is_nan())
  1272. return js_nan();
  1273. // 2. Return the result of negating x; that is, compute a Number with the same magnitude but opposite sign.
  1274. return Value(-old_value.as_double());
  1275. }
  1276. // 4. Else,
  1277. // a. Assert: oldValue is a BigInt.
  1278. VERIFY(old_value.is_bigint());
  1279. // b. Return BigInt::unaryMinus(oldValue).
  1280. // 6.1.6.2.1 BigInt::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-bigint-unaryMinus
  1281. // 1. If x is 0ℤ, return 0ℤ.
  1282. if (old_value.as_bigint().big_integer() == BIGINT_ZERO)
  1283. return BigInt::create(vm, BIGINT_ZERO);
  1284. // 2. Return the BigInt value that represents the negation of ℝ(x).
  1285. auto big_integer_negated = old_value.as_bigint().big_integer();
  1286. big_integer_negated.negate();
  1287. return BigInt::create(vm, big_integer_negated);
  1288. }
  1289. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  1290. // ShiftExpression : ShiftExpression << AdditiveExpression
  1291. ThrowCompletionOr<Value> left_shift(VM& vm, Value lhs, Value rhs)
  1292. {
  1293. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1294. // 1-2, 6. N/A.
  1295. // 3. Let lnum be ? ToNumeric(lval).
  1296. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1297. // 4. Let rnum be ? ToNumeric(rval).
  1298. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1299. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1300. // [...]
  1301. // 8. Return operation(lnum, rnum).
  1302. if (both_number(lhs_numeric, rhs_numeric)) {
  1303. // 6.1.6.1.9 Number::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-leftShift
  1304. // OPTIMIZATION: Handle infinite values according to the results returned by ToInt32/ToUint32.
  1305. if (!lhs_numeric.is_finite_number())
  1306. return Value(0);
  1307. if (!rhs_numeric.is_finite_number())
  1308. return lhs_numeric;
  1309. // 1. Let lnum be ! ToInt32(x).
  1310. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1311. // 2. Let rnum be ! ToUint32(y).
  1312. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1313. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1314. auto shift_count = rhs_u32 % 32;
  1315. // 4. Return the result of left shifting lnum by shiftCount bits. The mathematical value of the result is
  1316. // exactly representable as a 32-bit two's complement bit string.
  1317. return Value(lhs_i32 << shift_count);
  1318. }
  1319. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1320. // 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
  1321. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  1322. // 1. If y < 0ℤ, then
  1323. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  1324. // a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
  1325. // NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
  1326. auto const& big_integer = lhs_numeric.as_bigint().big_integer();
  1327. auto division_result = big_integer.divided_by(multiplier_divisor);
  1328. // For positive initial values and no remainder just return quotient
  1329. if (division_result.remainder.is_zero() || !big_integer.is_negative())
  1330. return BigInt::create(vm, division_result.quotient);
  1331. // For negative round "down" to the next negative number
  1332. return BigInt::create(vm, division_result.quotient.minus(Crypto::SignedBigInteger { 1 }));
  1333. }
  1334. // 2. Return the BigInt value that represents ℝ(x) × 2^y.
  1335. return Value(BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor)));
  1336. }
  1337. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1338. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "left-shift");
  1339. }
  1340. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  1341. // ShiftExpression : ShiftExpression >> AdditiveExpression
  1342. ThrowCompletionOr<Value> right_shift(VM& vm, Value lhs, Value rhs)
  1343. {
  1344. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1345. // 1-2, 6. N/A.
  1346. // 3. Let lnum be ? ToNumeric(lval).
  1347. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1348. // 4. Let rnum be ? ToNumeric(rval).
  1349. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1350. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1351. // [...]
  1352. // 8. Return operation(lnum, rnum).
  1353. if (both_number(lhs_numeric, rhs_numeric)) {
  1354. // 6.1.6.1.10 Number::signedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-signedRightShift
  1355. // OPTIMIZATION: Handle infinite values according to the results returned by ToInt32/ToUint32.
  1356. if (!lhs_numeric.is_finite_number())
  1357. return Value(0);
  1358. if (!rhs_numeric.is_finite_number())
  1359. return lhs_numeric;
  1360. // 1. Let lnum be ! ToInt32(x).
  1361. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1362. // 2. Let rnum be ! ToUint32(y).
  1363. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1364. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1365. auto shift_count = rhs_u32 % 32;
  1366. // 4. Return the result of performing a sign-extending right shift of lnum by shiftCount bits.
  1367. // The most significant bit is propagated. The mathematical value of the result is exactly representable
  1368. // as a 32-bit two's complement bit string.
  1369. return Value(lhs_i32 >> shift_count);
  1370. }
  1371. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1372. // 6.1.6.2.10 BigInt::signedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-signedRightShift
  1373. // 1. Return BigInt::leftShift(x, -y).
  1374. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  1375. rhs_negated.negate();
  1376. return left_shift(vm, lhs, BigInt::create(vm, rhs_negated));
  1377. }
  1378. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1379. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "right-shift");
  1380. }
  1381. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  1382. // ShiftExpression : ShiftExpression >>> AdditiveExpression
  1383. ThrowCompletionOr<Value> unsigned_right_shift(VM& vm, Value lhs, Value rhs)
  1384. {
  1385. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1386. // 1-2, 5-6. N/A.
  1387. // 3. Let lnum be ? ToNumeric(lval).
  1388. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1389. // 4. Let rnum be ? ToNumeric(rval).
  1390. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1391. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1392. // [...]
  1393. // 8. Return operation(lnum, rnum).
  1394. if (both_number(lhs_numeric, rhs_numeric)) {
  1395. // 6.1.6.1.11 Number::unsignedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-unsignedRightShift
  1396. // OPTIMIZATION: Handle infinite values according to the results returned by ToUint32.
  1397. if (!lhs_numeric.is_finite_number())
  1398. return Value(0);
  1399. if (!rhs_numeric.is_finite_number())
  1400. return lhs_numeric;
  1401. // 1. Let lnum be ! ToUint32(x).
  1402. auto lhs_u32 = MUST(lhs_numeric.to_u32(vm));
  1403. // 2. Let rnum be ! ToUint32(y).
  1404. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1405. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1406. auto shift_count = rhs_u32 % 32;
  1407. // 4. Return the result of performing a zero-filling right shift of lnum by shiftCount bits.
  1408. // Vacated bits are filled with zero. The mathematical value of the result is exactly representable
  1409. // as a 32-bit unsigned bit string.
  1410. return Value(lhs_u32 >> shift_count);
  1411. }
  1412. // 6. If lnum is a BigInt, then
  1413. // d. If opText is >>>, return ? BigInt::unsignedRightShift(lnum, rnum).
  1414. // 6.1.6.2.11 BigInt::unsignedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-unsignedRightShift
  1415. // 1. Throw a TypeError exception.
  1416. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperator, "unsigned right-shift");
  1417. }
  1418. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  1419. // AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1420. ThrowCompletionOr<Value> add(VM& vm, Value lhs, Value rhs)
  1421. {
  1422. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1423. // 1. If opText is +, then
  1424. // OPTIMIZATION: If both values are i32 or double, we can do a direct addition without the type conversions below.
  1425. if (both_number(lhs, rhs)) {
  1426. if (lhs.is_int32() && rhs.is_int32()) {
  1427. Checked<i32> result;
  1428. result = MUST(lhs.to_i32(vm));
  1429. result += MUST(rhs.to_i32(vm));
  1430. if (!result.has_overflow())
  1431. return Value(result.value());
  1432. }
  1433. return Value(lhs.as_double() + rhs.as_double());
  1434. }
  1435. // a. Let lprim be ? ToPrimitive(lval).
  1436. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1437. // b. Let rprim be ? ToPrimitive(rval).
  1438. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1439. // c. If lprim is a String or rprim is a String, then
  1440. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  1441. // i. Let lstr be ? ToString(lprim).
  1442. auto lhs_string = TRY(lhs_primitive.to_primitive_string(vm));
  1443. // ii. Let rstr be ? ToString(rprim).
  1444. auto rhs_string = TRY(rhs_primitive.to_primitive_string(vm));
  1445. // iii. Return the string-concatenation of lstr and rstr.
  1446. return PrimitiveString::create(vm, lhs_string, rhs_string);
  1447. }
  1448. // d. Set lval to lprim.
  1449. // e. Set rval to rprim.
  1450. // 2. NOTE: At this point, it must be a numeric operation.
  1451. // 3. Let lnum be ? ToNumeric(lval).
  1452. auto lhs_numeric = TRY(lhs_primitive.to_numeric(vm));
  1453. // 4. Let rnum be ? ToNumeric(rval).
  1454. auto rhs_numeric = TRY(rhs_primitive.to_numeric(vm));
  1455. // 6. N/A.
  1456. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1457. // [...]
  1458. // 8. Return operation(lnum, rnum).
  1459. if (both_number(lhs_numeric, rhs_numeric)) {
  1460. // 6.1.6.1.7 Number::add ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-add
  1461. auto x = lhs_numeric.as_double();
  1462. auto y = rhs_numeric.as_double();
  1463. return Value(x + y);
  1464. }
  1465. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1466. // 6.1.6.2.7 BigInt::add ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-add
  1467. auto x = lhs_numeric.as_bigint().big_integer();
  1468. auto y = rhs_numeric.as_bigint().big_integer();
  1469. return BigInt::create(vm, x.plus(y));
  1470. }
  1471. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1472. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "addition");
  1473. }
  1474. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1475. // AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1476. ThrowCompletionOr<Value> sub(VM& vm, Value lhs, Value rhs)
  1477. {
  1478. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1479. // 1-2, 6. N/A.
  1480. // 3. Let lnum be ? ToNumeric(lval).
  1481. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1482. // 4. Let rnum be ? ToNumeric(rval).
  1483. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1484. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1485. // [...]
  1486. // 8. Return operation(lnum, rnum).
  1487. if (both_number(lhs_numeric, rhs_numeric)) {
  1488. // 6.1.6.1.8 Number::subtract ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-subtract
  1489. auto x = lhs_numeric.as_double();
  1490. auto y = rhs_numeric.as_double();
  1491. // 1. Return Number::add(x, Number::unaryMinus(y)).
  1492. return Value(x - y);
  1493. }
  1494. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1495. // 6.1.6.2.8 BigInt::subtract ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-subtract
  1496. auto x = lhs_numeric.as_bigint().big_integer();
  1497. auto y = rhs_numeric.as_bigint().big_integer();
  1498. // 1. Return the BigInt value that represents the difference x minus y.
  1499. return BigInt::create(vm, x.minus(y));
  1500. }
  1501. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1502. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1503. }
  1504. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1505. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1506. ThrowCompletionOr<Value> mul(VM& vm, Value lhs, Value rhs)
  1507. {
  1508. // OPTIMIZATION: Fast path for multiplication of two Int32 values.
  1509. if (lhs.is_int32() && rhs.is_int32()) {
  1510. Checked<i32> result = lhs.as_i32();
  1511. result *= rhs.as_i32();
  1512. if (!result.has_overflow())
  1513. return result.value();
  1514. }
  1515. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1516. // 1-2, 6. N/A.
  1517. // 3. Let lnum be ? ToNumeric(lval).
  1518. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1519. // 4. Let rnum be ? ToNumeric(rval).
  1520. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1521. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1522. // [...]
  1523. // 8. Return operation(lnum, rnum).
  1524. if (both_number(lhs_numeric, rhs_numeric)) {
  1525. // 6.1.6.1.4 Number::multiply ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-multiply
  1526. auto x = lhs_numeric.as_double();
  1527. auto y = rhs_numeric.as_double();
  1528. return Value(x * y);
  1529. }
  1530. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1531. // 6.1.6.2.4 BigInt::multiply ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-multiply
  1532. auto x = lhs_numeric.as_bigint().big_integer();
  1533. auto y = rhs_numeric.as_bigint().big_integer();
  1534. // 1. Return the BigInt value that represents the product of x and y.
  1535. return BigInt::create(vm, x.multiplied_by(y));
  1536. }
  1537. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1538. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1539. }
  1540. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1541. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1542. ThrowCompletionOr<Value> div(VM& vm, Value lhs, Value rhs)
  1543. {
  1544. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1545. // 1-2, 6. N/A.
  1546. // 3. Let lnum be ? ToNumeric(lval).
  1547. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1548. // 4. Let rnum be ? ToNumeric(rval).
  1549. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1550. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1551. // [...]
  1552. // 8. Return operation(lnum, rnum).
  1553. if (both_number(lhs_numeric, rhs_numeric)) {
  1554. // 6.1.6.1.5 Number::divide ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-divide
  1555. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1556. }
  1557. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1558. // 6.1.6.2.5 BigInt::divide ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-divide
  1559. auto x = lhs_numeric.as_bigint().big_integer();
  1560. auto y = rhs_numeric.as_bigint().big_integer();
  1561. // 1. If y is 0ℤ, throw a RangeError exception.
  1562. if (y == BIGINT_ZERO)
  1563. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1564. // 2. Let quotient be ℝ(x) / ℝ(y).
  1565. // 3. Return the BigInt value that represents quotient rounded towards 0 to the next integer value.
  1566. return BigInt::create(vm, x.divided_by(y).quotient);
  1567. }
  1568. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1569. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "division");
  1570. }
  1571. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1572. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1573. ThrowCompletionOr<Value> mod(VM& vm, Value lhs, Value rhs)
  1574. {
  1575. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1576. // 1-2, 6. N/A.
  1577. // 3. Let lnum be ? ToNumeric(lval).
  1578. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1579. // 4. Let rnum be ? ToNumeric(rval).
  1580. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1581. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1582. // [...]
  1583. // 8. Return operation(lnum, rnum).
  1584. if (both_number(lhs_numeric, rhs_numeric)) {
  1585. // 6.1.6.1.6 Number::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-number-remainder
  1586. // The ECMA specification is describing the mathematical definition of modulus
  1587. // implemented by fmod.
  1588. auto n = lhs_numeric.as_double();
  1589. auto d = rhs_numeric.as_double();
  1590. return Value(fmod(n, d));
  1591. }
  1592. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1593. // 6.1.6.2.6 BigInt::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-bigint-remainder
  1594. auto n = lhs_numeric.as_bigint().big_integer();
  1595. auto d = rhs_numeric.as_bigint().big_integer();
  1596. // 1. If d is 0ℤ, throw a RangeError exception.
  1597. if (d == BIGINT_ZERO)
  1598. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1599. // 2. If n is 0ℤ, return 0ℤ.
  1600. // 3. Let quotient be ℝ(n) / ℝ(d).
  1601. // 4. Let q be the BigInt whose sign is the sign of quotient and whose magnitude is floor(abs(quotient)).
  1602. // 5. Return n - (d × q).
  1603. return BigInt::create(vm, n.divided_by(d).remainder);
  1604. }
  1605. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1606. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "modulo");
  1607. }
  1608. // 6.1.6.1.3 Number::exponentiate ( base, exponent ), https://tc39.es/ecma262/#sec-numeric-types-number-exponentiate
  1609. static Value exp_double(Value base, Value exponent)
  1610. {
  1611. VERIFY(both_number(base, exponent));
  1612. // 1. If exponent is NaN, return NaN.
  1613. if (exponent.is_nan())
  1614. return js_nan();
  1615. // 2. If exponent is +0𝔽 or exponent is -0𝔽, return 1𝔽.
  1616. if (exponent.is_positive_zero() || exponent.is_negative_zero())
  1617. return Value(1);
  1618. // 3. If base is NaN, return NaN.
  1619. if (base.is_nan())
  1620. return js_nan();
  1621. // 4. If base is +∞𝔽, then
  1622. if (base.is_positive_infinity()) {
  1623. // a. If exponent > +0𝔽, return +∞𝔽. Otherwise, return +0𝔽.
  1624. return exponent.as_double() > 0 ? js_infinity() : Value(0);
  1625. }
  1626. // 5. If base is -∞𝔽, then
  1627. if (base.is_negative_infinity()) {
  1628. auto is_odd_integral_number = exponent.is_integral_number() && (fmod(exponent.as_double(), 2.0) != 0);
  1629. // a. If exponent > +0𝔽, then
  1630. if (exponent.as_double() > 0) {
  1631. // i. If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
  1632. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1633. }
  1634. // b. Else,
  1635. else {
  1636. // i. If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
  1637. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1638. }
  1639. }
  1640. // 6. If base is +0𝔽, then
  1641. if (base.is_positive_zero()) {
  1642. // a. If exponent > +0𝔽, return +0𝔽. Otherwise, return +∞𝔽.
  1643. return exponent.as_double() > 0 ? Value(0) : js_infinity();
  1644. }
  1645. // 7. If base is -0𝔽, then
  1646. if (base.is_negative_zero()) {
  1647. auto is_odd_integral_number = exponent.is_integral_number() && (fmod(exponent.as_double(), 2.0) != 0);
  1648. // a. If exponent > +0𝔽, then
  1649. if (exponent.as_double() > 0) {
  1650. // i. If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
  1651. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1652. }
  1653. // b. Else,
  1654. else {
  1655. // i. If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
  1656. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1657. }
  1658. }
  1659. // 8. Assert: base is finite and is neither +0𝔽 nor -0𝔽.
  1660. VERIFY(base.is_finite_number() && !base.is_positive_zero() && !base.is_negative_zero());
  1661. // 9. If exponent is +∞𝔽, then
  1662. if (exponent.is_positive_infinity()) {
  1663. auto absolute_base = fabs(base.as_double());
  1664. // a. If abs(ℝ(base)) > 1, return +∞𝔽.
  1665. if (absolute_base > 1)
  1666. return js_infinity();
  1667. // b. If abs(ℝ(base)) is 1, return NaN.
  1668. else if (absolute_base == 1)
  1669. return js_nan();
  1670. // c. If abs(ℝ(base)) < 1, return +0𝔽.
  1671. else if (absolute_base < 1)
  1672. return Value(0);
  1673. }
  1674. // 10. If exponent is -∞𝔽, then
  1675. if (exponent.is_negative_infinity()) {
  1676. auto absolute_base = fabs(base.as_double());
  1677. // a. If abs(ℝ(base)) > 1, return +0𝔽.
  1678. if (absolute_base > 1)
  1679. return Value(0);
  1680. // b. If abs(ℝ(base)) is 1, return NaN.
  1681. else if (absolute_base == 1)
  1682. return js_nan();
  1683. // a. If abs(ℝ(base)) > 1, return +0𝔽.
  1684. else if (absolute_base < 1)
  1685. return js_infinity();
  1686. }
  1687. // 11. Assert: exponent is finite and is neither +0𝔽 nor -0𝔽.
  1688. VERIFY(exponent.is_finite_number() && !exponent.is_positive_zero() && !exponent.is_negative_zero());
  1689. // 12. If base < -0𝔽 and exponent is not an integral Number, return NaN.
  1690. if (base.as_double() < 0 && !exponent.is_integral_number())
  1691. return js_nan();
  1692. // 13. Return an implementation-approximated Number value representing the result of raising ℝ(base) to the ℝ(exponent) power.
  1693. return Value(::pow(base.as_double(), exponent.as_double()));
  1694. }
  1695. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1696. // ExponentiationExpression : UpdateExpression ** ExponentiationExpression
  1697. ThrowCompletionOr<Value> exp(VM& vm, Value lhs, Value rhs)
  1698. {
  1699. // 3. Let lnum be ? ToNumeric(lval).
  1700. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1701. // 4. Let rnum be ? ToNumeric(rval).
  1702. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1703. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1704. // [...]
  1705. // 8. Return operation(lnum, rnum).
  1706. if (both_number(lhs_numeric, rhs_numeric)) {
  1707. return exp_double(lhs_numeric, rhs_numeric);
  1708. }
  1709. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1710. // 6.1.6.2.3 BigInt::exponentiate ( base, exponent ), https://tc39.es/ecma262/#sec-numeric-types-bigint-exponentiate
  1711. auto base = lhs_numeric.as_bigint().big_integer();
  1712. auto exponent = rhs_numeric.as_bigint().big_integer();
  1713. // 1. If exponent < 0ℤ, throw a RangeError exception.
  1714. if (exponent.is_negative())
  1715. return vm.throw_completion<RangeError>(ErrorType::NegativeExponent);
  1716. // 2. If base is 0ℤ and exponent is 0ℤ, return 1ℤ.
  1717. // 3. Return the BigInt value that represents ℝ(base) raised to the power ℝ(exponent).
  1718. return BigInt::create(vm, Crypto::NumberTheory::Power(base, exponent));
  1719. }
  1720. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1721. }
  1722. ThrowCompletionOr<Value> in(VM& vm, Value lhs, Value rhs)
  1723. {
  1724. if (!rhs.is_object())
  1725. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  1726. auto lhs_property_key = TRY(lhs.to_property_key(vm));
  1727. return Value(TRY(rhs.as_object().has_property(lhs_property_key)));
  1728. }
  1729. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1730. ThrowCompletionOr<Value> instance_of(VM& vm, Value value, Value target)
  1731. {
  1732. // 1. If target is not an Object, throw a TypeError exception.
  1733. if (!target.is_object())
  1734. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, target.to_string_without_side_effects());
  1735. // 2. Let instOfHandler be ? GetMethod(target, @@hasInstance).
  1736. auto instance_of_handler = TRY(target.get_method(vm, vm.well_known_symbol_has_instance()));
  1737. // 3. If instOfHandler is not undefined, then
  1738. if (instance_of_handler) {
  1739. // a. Return ToBoolean(? Call(instOfHandler, target, « V »)).
  1740. return Value(TRY(call(vm, *instance_of_handler, target, value)).to_boolean());
  1741. }
  1742. // 4. If IsCallable(target) is false, throw a TypeError exception.
  1743. if (!target.is_function())
  1744. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, target.to_string_without_side_effects());
  1745. // 5. Return ? OrdinaryHasInstance(target, V).
  1746. return ordinary_has_instance(vm, target, value);
  1747. }
  1748. // 7.3.22 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1749. ThrowCompletionOr<Value> ordinary_has_instance(VM& vm, Value lhs, Value rhs)
  1750. {
  1751. // 1. If IsCallable(C) is false, return false.
  1752. if (!rhs.is_function())
  1753. return Value(false);
  1754. auto& rhs_function = rhs.as_function();
  1755. // 2. If C has a [[BoundTargetFunction]] internal slot, then
  1756. if (is<BoundFunction>(rhs_function)) {
  1757. auto const& bound_target = static_cast<BoundFunction const&>(rhs_function);
  1758. // a. Let BC be C.[[BoundTargetFunction]].
  1759. // b. Return ? InstanceofOperator(O, BC).
  1760. return instance_of(vm, lhs, Value(&bound_target.bound_target_function()));
  1761. }
  1762. // 3. If O is not an Object, return false.
  1763. if (!lhs.is_object())
  1764. return Value(false);
  1765. auto* lhs_object = &lhs.as_object();
  1766. // 4. Let P be ? Get(C, "prototype").
  1767. auto rhs_prototype = TRY(rhs_function.get(vm.names.prototype));
  1768. // 5. If P is not an Object, throw a TypeError exception.
  1769. if (!rhs_prototype.is_object())
  1770. return vm.throw_completion<TypeError>(ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1771. // 6. Repeat,
  1772. while (true) {
  1773. // a. Set O to ? O.[[GetPrototypeOf]]().
  1774. lhs_object = TRY(lhs_object->internal_get_prototype_of());
  1775. // b. If O is null, return false.
  1776. if (!lhs_object)
  1777. return Value(false);
  1778. // c. If SameValue(P, O) is true, return true.
  1779. if (same_value(rhs_prototype, lhs_object))
  1780. return Value(true);
  1781. }
  1782. }
  1783. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1784. bool same_value(Value lhs, Value rhs)
  1785. {
  1786. // 1. If Type(x) is different from Type(y), return false.
  1787. if (!same_type_for_equality(lhs, rhs))
  1788. return false;
  1789. // 2. If x is a Number, then
  1790. if (lhs.is_number()) {
  1791. // a. Return Number::sameValue(x, y).
  1792. // 6.1.6.1.14 Number::sameValue ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-sameValue
  1793. // 1. If x is NaN and y is NaN, return true.
  1794. if (lhs.is_nan() && rhs.is_nan())
  1795. return true;
  1796. // 2. If x is +0𝔽 and y is -0𝔽, return false.
  1797. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1798. return false;
  1799. // 3. If x is -0𝔽 and y is +0𝔽, return false.
  1800. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1801. return false;
  1802. // 4. If x is the same Number value as y, return true.
  1803. // 5. Return false.
  1804. return lhs.as_double() == rhs.as_double();
  1805. }
  1806. // 3. Return SameValueNonNumber(x, y).
  1807. return same_value_non_number(lhs, rhs);
  1808. }
  1809. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1810. bool same_value_zero(Value lhs, Value rhs)
  1811. {
  1812. // 1. If Type(x) is different from Type(y), return false.
  1813. if (!same_type_for_equality(lhs, rhs))
  1814. return false;
  1815. // 2. If x is a Number, then
  1816. if (lhs.is_number()) {
  1817. // a. Return Number::sameValueZero(x, y).
  1818. if (lhs.is_nan() && rhs.is_nan())
  1819. return true;
  1820. return lhs.as_double() == rhs.as_double();
  1821. }
  1822. // 3. Return SameValueNonNumber(x, y).
  1823. return same_value_non_number(lhs, rhs);
  1824. }
  1825. // 7.2.12 SameValueNonNumber ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1826. bool same_value_non_number(Value lhs, Value rhs)
  1827. {
  1828. // 1. Assert: Type(x) is the same as Type(y).
  1829. VERIFY(same_type_for_equality(lhs, rhs));
  1830. VERIFY(!lhs.is_number());
  1831. // 2. If x is a BigInt, then
  1832. if (lhs.is_bigint()) {
  1833. // a. Return BigInt::equal(x, y).
  1834. // 6.1.6.2.13 BigInt::equal ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-equal
  1835. // 1. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1836. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1837. }
  1838. // 5. If x is a String, then
  1839. if (lhs.is_string()) {
  1840. // a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices), return true; otherwise, return false.
  1841. return lhs.as_string().byte_string() == rhs.as_string().byte_string();
  1842. }
  1843. // 3. If x is undefined, return true.
  1844. // 4. If x is null, return true.
  1845. // 6. If x is a Boolean, then
  1846. // a. If x and y are both true or both false, return true; otherwise, return false.
  1847. // 7. If x is a Symbol, then
  1848. // a. If x and y are both the same Symbol value, return true; otherwise, return false.
  1849. // 8. If x and y are the same Object value, return true. Otherwise, return false.
  1850. // NOTE: All the options above will have the exact same bit representation in Value, so we can directly compare the bits.
  1851. return lhs.m_value.encoded == rhs.m_value.encoded;
  1852. }
  1853. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1854. bool is_strictly_equal(Value lhs, Value rhs)
  1855. {
  1856. // 1. If Type(x) is different from Type(y), return false.
  1857. if (!same_type_for_equality(lhs, rhs))
  1858. return false;
  1859. // 2. If x is a Number, then
  1860. if (lhs.is_number()) {
  1861. // a. Return Number::equal(x, y).
  1862. // 6.1.6.1.13 Number::equal ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-equal
  1863. // 1. If x is NaN, return false.
  1864. // 2. If y is NaN, return false.
  1865. if (lhs.is_nan() || rhs.is_nan())
  1866. return false;
  1867. // 3. If x is the same Number value as y, return true.
  1868. // 4. If x is +0𝔽 and y is -0𝔽, return true.
  1869. // 5. If x is -0𝔽 and y is +0𝔽, return true.
  1870. if (lhs.as_double() == rhs.as_double())
  1871. return true;
  1872. // 6. Return false.
  1873. return false;
  1874. }
  1875. // 3. Return SameValueNonNumber(x, y).
  1876. return same_value_non_number(lhs, rhs);
  1877. }
  1878. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1879. ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs)
  1880. {
  1881. // 1. If Type(x) is the same as Type(y), then
  1882. if (same_type_for_equality(lhs, rhs)) {
  1883. // a. Return IsStrictlyEqual(x, y).
  1884. return is_strictly_equal(lhs, rhs);
  1885. }
  1886. // 2. If x is null and y is undefined, return true.
  1887. // 3. If x is undefined and y is null, return true.
  1888. if (lhs.is_nullish() && rhs.is_nullish())
  1889. return true;
  1890. // 4. NOTE: This step is replaced in section B.3.6.2.
  1891. // B.3.6.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1892. // 4. Perform the following steps:
  1893. // a. If Type(x) is Object and x has an [[IsHTMLDDA]] internal slot and y is either null or undefined, return true.
  1894. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1895. return true;
  1896. // b. If x is either null or undefined and Type(y) is Object and y has an [[IsHTMLDDA]] internal slot, return true.
  1897. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1898. return true;
  1899. // == End of B.3.6.2 ==
  1900. // 5. If Type(x) is Number and Type(y) is String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1901. if (lhs.is_number() && rhs.is_string())
  1902. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1903. // 6. If Type(x) is String and Type(y) is Number, return ! IsLooselyEqual(! ToNumber(x), y).
  1904. if (lhs.is_string() && rhs.is_number())
  1905. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1906. // 7. If Type(x) is BigInt and Type(y) is String, then
  1907. if (lhs.is_bigint() && rhs.is_string()) {
  1908. // a. Let n be StringToBigInt(y).
  1909. auto bigint = string_to_bigint(vm, rhs.as_string().byte_string());
  1910. // b. If n is undefined, return false.
  1911. if (!bigint.has_value())
  1912. return false;
  1913. // c. Return ! IsLooselyEqual(x, n).
  1914. return is_loosely_equal(vm, lhs, *bigint);
  1915. }
  1916. // 8. If Type(x) is String and Type(y) is BigInt, return ! IsLooselyEqual(y, x).
  1917. if (lhs.is_string() && rhs.is_bigint())
  1918. return is_loosely_equal(vm, rhs, lhs);
  1919. // 9. If Type(x) is Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  1920. if (lhs.is_boolean())
  1921. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1922. // 10. If Type(y) is Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1923. if (rhs.is_boolean())
  1924. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1925. // 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  1926. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1927. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1928. return is_loosely_equal(vm, lhs, rhs_primitive);
  1929. }
  1930. // 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  1931. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || rhs.is_bigint() || rhs.is_symbol())) {
  1932. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1933. return is_loosely_equal(vm, lhs_primitive, rhs);
  1934. }
  1935. // 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
  1936. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1937. // a. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false.
  1938. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1939. return false;
  1940. // b. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1941. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1942. return false;
  1943. VERIFY(!lhs.is_nan() && !rhs.is_nan());
  1944. auto& number_side = lhs.is_number() ? lhs : rhs;
  1945. auto& bigint_side = lhs.is_number() ? rhs : lhs;
  1946. return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt;
  1947. }
  1948. // 14. Return false.
  1949. return false;
  1950. }
  1951. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1952. ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left_first)
  1953. {
  1954. Value x_primitive;
  1955. Value y_primitive;
  1956. // 1. If the LeftFirst flag is true, then
  1957. if (left_first) {
  1958. // a. Let px be ? ToPrimitive(x, number).
  1959. x_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1960. // b. Let py be ? ToPrimitive(y, number).
  1961. y_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1962. } else {
  1963. // a. NOTE: The order of evaluation needs to be reversed to preserve left to right evaluation.
  1964. // b. Let py be ? ToPrimitive(y, number).
  1965. y_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1966. // c. Let px be ? ToPrimitive(x, number).
  1967. x_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1968. }
  1969. // 3. If px is a String and py is a String, then
  1970. if (x_primitive.is_string() && y_primitive.is_string()) {
  1971. auto x_string = x_primitive.as_string().byte_string();
  1972. auto y_string = y_primitive.as_string().byte_string();
  1973. Utf8View x_code_points { x_string };
  1974. Utf8View y_code_points { y_string };
  1975. // a. Let lx be the length of px.
  1976. // b. Let ly be the length of py.
  1977. // c. For each integer i such that 0 ≤ i < min(lx, ly), in ascending order, do
  1978. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1979. k != x_code_points.end() && l != y_code_points.end();
  1980. ++k, ++l) {
  1981. // i. Let cx be the integer that is the numeric value of the code unit at index i within px.
  1982. // ii. Let cy be the integer that is the numeric value of the code unit at index i within py.
  1983. if (*k != *l) {
  1984. // iii. If cx < cy, return true.
  1985. if (*k < *l) {
  1986. return TriState::True;
  1987. }
  1988. // iv. If cx > cy, return false.
  1989. else {
  1990. return TriState::False;
  1991. }
  1992. }
  1993. }
  1994. // d. If lx < ly, return true. Otherwise, return false.
  1995. return x_code_points.length() < y_code_points.length()
  1996. ? TriState::True
  1997. : TriState::False;
  1998. }
  1999. // 4. Else,
  2000. // a. If px is a BigInt and py is a String, then
  2001. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  2002. // i. Let ny be StringToBigInt(py).
  2003. auto y_bigint = string_to_bigint(vm, y_primitive.as_string().byte_string());
  2004. // ii. If ny is undefined, return undefined.
  2005. if (!y_bigint.has_value())
  2006. return TriState::Unknown;
  2007. // iii. Return BigInt::lessThan(px, ny).
  2008. if (x_primitive.as_bigint().big_integer() < (*y_bigint)->big_integer())
  2009. return TriState::True;
  2010. return TriState::False;
  2011. }
  2012. // b. If px is a String and py is a BigInt, then
  2013. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  2014. // i. Let nx be StringToBigInt(px).
  2015. auto x_bigint = string_to_bigint(vm, x_primitive.as_string().byte_string());
  2016. // ii. If nx is undefined, return undefined.
  2017. if (!x_bigint.has_value())
  2018. return TriState::Unknown;
  2019. // iii. Return BigInt::lessThan(nx, py).
  2020. if ((*x_bigint)->big_integer() < y_primitive.as_bigint().big_integer())
  2021. return TriState::True;
  2022. return TriState::False;
  2023. }
  2024. // c. NOTE: Because px and py are primitive values, evaluation order is not important.
  2025. // d. Let nx be ? ToNumeric(px).
  2026. auto x_numeric = TRY(x_primitive.to_numeric(vm));
  2027. // e. Let ny be ? ToNumeric(py).
  2028. auto y_numeric = TRY(y_primitive.to_numeric(vm));
  2029. // h. If nx or ny is NaN, return undefined.
  2030. if (x_numeric.is_nan() || y_numeric.is_nan())
  2031. return TriState::Unknown;
  2032. // i. If nx is -∞𝔽 or ny is +∞𝔽, return true.
  2033. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  2034. return TriState::False;
  2035. // j. If nx is +∞𝔽 or ny is -∞𝔽, return false.
  2036. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  2037. return TriState::True;
  2038. // f. If Type(nx) is the same as Type(ny), then
  2039. // i. If nx is a Number, then
  2040. if (x_numeric.is_number() && y_numeric.is_number()) {
  2041. // 1. Return Number::lessThan(nx, ny).
  2042. if (x_numeric.as_double() < y_numeric.as_double())
  2043. return TriState::True;
  2044. else
  2045. return TriState::False;
  2046. }
  2047. // ii. Else,
  2048. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  2049. // 1. Assert: nx is a BigInt.
  2050. // 2. Return BigInt::lessThan(nx, ny).
  2051. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  2052. return TriState::True;
  2053. else
  2054. return TriState::False;
  2055. }
  2056. // g. Assert: nx is a BigInt and ny is a Number, or nx is a Number and ny is a BigInt.
  2057. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  2058. // k. If ℝ(nx) < ℝ(ny), return true; otherwise return false.
  2059. bool x_lower_than_y;
  2060. VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan());
  2061. if (x_numeric.is_number()) {
  2062. x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double())
  2063. == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt;
  2064. } else {
  2065. x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double())
  2066. == Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt;
  2067. }
  2068. if (x_lower_than_y)
  2069. return TriState::True;
  2070. else
  2071. return TriState::False;
  2072. }
  2073. // 7.3.21 Invoke ( V, P [ , argumentsList ] ), https://tc39.es/ecma262/#sec-invoke
  2074. ThrowCompletionOr<Value> Value::invoke_internal(VM& vm, PropertyKey const& property_key, Optional<GC::RootVector<Value>> arguments)
  2075. {
  2076. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  2077. // 2. Let func be ? GetV(V, P).
  2078. auto function = TRY(get(vm, property_key));
  2079. // 3. Return ? Call(func, V, argumentsList).
  2080. ReadonlySpan<Value> argument_list;
  2081. if (arguments.has_value())
  2082. argument_list = arguments.value().span();
  2083. return call(vm, function, *this, argument_list);
  2084. }
  2085. }