Value.cpp 95 KB

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