Value.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.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/CharacterTypes.h>
  11. #include <AK/DeprecatedString.h>
  12. #include <AK/FloatingPointStringConversions.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/StringFloatingPointConversions.h>
  15. #include <AK/Utf8View.h>
  16. #include <LibCrypto/BigInt/SignedBigInteger.h>
  17. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  18. #include <LibJS/Runtime/AbstractOperations.h>
  19. #include <LibJS/Runtime/Accessor.h>
  20. #include <LibJS/Runtime/Array.h>
  21. #include <LibJS/Runtime/BigInt.h>
  22. #include <LibJS/Runtime/BigIntObject.h>
  23. #include <LibJS/Runtime/BooleanObject.h>
  24. #include <LibJS/Runtime/BoundFunction.h>
  25. #include <LibJS/Runtime/Completion.h>
  26. #include <LibJS/Runtime/Error.h>
  27. #include <LibJS/Runtime/FunctionObject.h>
  28. #include <LibJS/Runtime/GlobalObject.h>
  29. #include <LibJS/Runtime/NativeFunction.h>
  30. #include <LibJS/Runtime/NumberObject.h>
  31. #include <LibJS/Runtime/Object.h>
  32. #include <LibJS/Runtime/PrimitiveString.h>
  33. #include <LibJS/Runtime/ProxyObject.h>
  34. #include <LibJS/Runtime/RegExpObject.h>
  35. #include <LibJS/Runtime/StringObject.h>
  36. #include <LibJS/Runtime/StringPrototype.h>
  37. #include <LibJS/Runtime/SymbolObject.h>
  38. #include <LibJS/Runtime/Utf16String.h>
  39. #include <LibJS/Runtime/VM.h>
  40. #include <LibJS/Runtime/Value.h>
  41. #include <math.h>
  42. namespace JS {
  43. static inline bool same_type_for_equality(Value const& lhs, Value const& rhs)
  44. {
  45. // If the top two bytes are identical then either:
  46. // both are NaN boxed Values with the same type
  47. // or they are doubles which happen to have the same top bytes.
  48. if ((lhs.encoded() & TAG_EXTRACTION) == (rhs.encoded() & TAG_EXTRACTION))
  49. return true;
  50. if (lhs.is_number() && rhs.is_number())
  51. return true;
  52. // One of the Values is not a number and they do not have the same tag
  53. return false;
  54. }
  55. static const Crypto::SignedBigInteger BIGINT_ZERO { 0 };
  56. ALWAYS_INLINE bool both_number(Value const& lhs, Value const& rhs)
  57. {
  58. return lhs.is_number() && rhs.is_number();
  59. }
  60. ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs)
  61. {
  62. return lhs.is_bigint() && rhs.is_bigint();
  63. }
  64. // 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring
  65. // Implementation for radix = 10
  66. static ErrorOr<void> number_to_string_impl(StringBuilder& builder, double d, NumberToStringMode mode)
  67. {
  68. auto convert_to_decimal_digits_array = [](auto x, auto& digits, auto& length) {
  69. for (; x; x /= 10)
  70. digits[length++] = x % 10 | '0';
  71. for (i32 i = 0; 2 * i + 1 < length; ++i)
  72. swap(digits[i], digits[length - i - 1]);
  73. };
  74. // 1. If x is NaN, return "NaN".
  75. if (isnan(d)) {
  76. TRY(builder.try_append("NaN"sv));
  77. return {};
  78. }
  79. // 2. If x is +0𝔽 or -0𝔽, return "0".
  80. if (d == +0.0 || d == -0.0) {
  81. TRY(builder.try_append("0"sv));
  82. return {};
  83. }
  84. // 4. If x is +∞𝔽, return "Infinity".
  85. if (isinf(d)) {
  86. if (d > 0) {
  87. TRY(builder.try_append("Infinity"sv));
  88. return {};
  89. }
  90. TRY(builder.try_append("-Infinity"sv));
  91. return {};
  92. }
  93. // 5. Let n, k, and s be integers such that k ≥ 1, radix ^ (k - 1) ≤ s < radix ^ k,
  94. // 𝔽(s × radix ^ (n - k)) is x, and k is as small as possible. Note that k is the number of
  95. // digits in the representation of s using radix radix, that s is not divisible by radix, and
  96. // that the least significant digit of s is not necessarily uniquely determined by these criteria.
  97. //
  98. // Note: guarantees provided by convert_floating_point_to_decimal_exponential_form satisfy
  99. // requirements of NOTE 2.
  100. auto [sign, mantissa, exponent] = convert_floating_point_to_decimal_exponential_form(d);
  101. i32 k = 0;
  102. AK::Array<char, 20> mantissa_digits;
  103. convert_to_decimal_digits_array(mantissa, mantissa_digits, k);
  104. i32 n = exponent + k; // s = mantissa
  105. // 3. If x < -0𝔽, return the string-concatenation of "-" and Number::toString(-x, radix).
  106. if (sign)
  107. TRY(builder.try_append('-'));
  108. // Non-standard: Intl needs number-to-string conversions for extremely large numbers without any
  109. // exponential formatting, as it will handle such formatting itself in a locale-aware way.
  110. bool force_no_exponent = mode == NumberToStringMode::WithoutExponent;
  111. // 6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then
  112. if ((n >= -5 && n <= 21) || force_no_exponent) {
  113. // a. If n ≥ k, then
  114. if (n >= k) {
  115. // i. Return the string-concatenation of:
  116. // the code units of the k digits of the representation of s using radix radix
  117. TRY(builder.try_append(mantissa_digits.data(), k));
  118. // n - k occurrences of the code unit 0x0030 (DIGIT ZERO)
  119. TRY(builder.try_append_repeated('0', n - k));
  120. // b. Else if n > 0, then
  121. } else if (n > 0) {
  122. // i. Return the string-concatenation of:
  123. // the code units of the most significant n digits of the representation of s using radix radix
  124. TRY(builder.try_append(mantissa_digits.data(), n));
  125. // the code unit 0x002E (FULL STOP)
  126. TRY(builder.try_append('.'));
  127. // the code units of the remaining k - n digits of the representation of s using radix radix
  128. TRY(builder.try_append(mantissa_digits.data() + n, k - n));
  129. // c. Else,
  130. } else {
  131. // i. Assert: n ≤ 0.
  132. VERIFY(n <= 0);
  133. // ii. Return the string-concatenation of:
  134. // the code unit 0x0030 (DIGIT ZERO)
  135. TRY(builder.try_append('0'));
  136. // the code unit 0x002E (FULL STOP)
  137. TRY(builder.try_append('.'));
  138. // -n occurrences of the code unit 0x0030 (DIGIT ZERO)
  139. TRY(builder.try_append_repeated('0', -n));
  140. // the code units of the k digits of the representation of s using radix radix
  141. TRY(builder.try_append(mantissa_digits.data(), k));
  142. }
  143. return {};
  144. }
  145. // 7. NOTE: In this case, the input will be represented using scientific E notation, such as 1.2e+3.
  146. // 9. If n < 0, then
  147. // a. Let exponentSign be the code unit 0x002D (HYPHEN-MINUS).
  148. // 10. Else,
  149. // a. Let exponentSign be the code unit 0x002B (PLUS SIGN).
  150. char exponent_sign = n < 0 ? '-' : '+';
  151. AK::Array<char, 5> exponent_digits;
  152. i32 exponent_length = 0;
  153. convert_to_decimal_digits_array(abs(n - 1), exponent_digits, exponent_length);
  154. // 11. If k is 1, then
  155. if (k == 1) {
  156. // a. Return the string-concatenation of:
  157. // the code unit of the single digit of s
  158. TRY(builder.try_append(mantissa_digits[0]));
  159. // the code unit 0x0065 (LATIN SMALL LETTER E)
  160. TRY(builder.try_append('e'));
  161. // exponentSign
  162. TRY(builder.try_append(exponent_sign));
  163. // the code units of the decimal representation of abs(n - 1)
  164. TRY(builder.try_append(exponent_digits.data(), exponent_length));
  165. return {};
  166. }
  167. // 12. Return the string-concatenation of:
  168. // the code unit of the most significant digit of the decimal representation of s
  169. TRY(builder.try_append(mantissa_digits[0]));
  170. // the code unit 0x002E (FULL STOP)
  171. TRY(builder.try_append('.'));
  172. // the code units of the remaining k - 1 digits of the decimal representation of s
  173. TRY(builder.try_append(mantissa_digits.data() + 1, k - 1));
  174. // the code unit 0x0065 (LATIN SMALL LETTER E)
  175. TRY(builder.try_append('e'));
  176. // exponentSign
  177. TRY(builder.try_append(exponent_sign));
  178. // the code units of the decimal representation of abs(n - 1)
  179. TRY(builder.try_append(exponent_digits.data(), exponent_length));
  180. return {};
  181. }
  182. ErrorOr<String> number_to_string(double d, NumberToStringMode mode)
  183. {
  184. StringBuilder builder;
  185. TRY(number_to_string_impl(builder, d, mode));
  186. return builder.to_string();
  187. }
  188. DeprecatedString number_to_deprecated_string(double d, NumberToStringMode mode)
  189. {
  190. StringBuilder builder;
  191. MUST(number_to_string_impl(builder, d, mode));
  192. return builder.to_deprecated_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. StringView Value::typeof() const
  270. {
  271. // 9. If val is a Number, return "number".
  272. if (is_number())
  273. return "number"sv;
  274. switch (m_value.tag) {
  275. // 4. If val is undefined, return "undefined".
  276. case UNDEFINED_TAG:
  277. return "undefined"sv;
  278. // 5. If val is null, return "object".
  279. case NULL_TAG:
  280. return "object"sv;
  281. // 6. If val is a String, return "string".
  282. case STRING_TAG:
  283. return "string"sv;
  284. // 7. If val is a Symbol, return "symbol".
  285. case SYMBOL_TAG:
  286. return "symbol"sv;
  287. // 8. If val is a Boolean, return "boolean".
  288. case BOOLEAN_TAG:
  289. return "boolean"sv;
  290. // 10. If val is a BigInt, return "bigint".
  291. case BIGINT_TAG:
  292. return "bigint"sv;
  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 "undefined"sv;
  299. // 13. If val has a [[Call]] internal slot, return "function".
  300. if (is_function())
  301. return "function"sv;
  302. // 14. Return "object".
  303. return "object"sv;
  304. default:
  305. VERIFY_NOT_REACHED();
  306. }
  307. }
  308. ErrorOr<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 String::from_utf8("undefined"sv);
  315. case NULL_TAG:
  316. return String::from_utf8("null"sv);
  317. case BOOLEAN_TAG:
  318. return String::from_utf8(as_bool() ? "true"sv : "false"sv);
  319. case INT32_TAG:
  320. return String::number(as_i32());
  321. case STRING_TAG:
  322. if (auto string = as_string().utf8_string(); string.is_throw_completion()) {
  323. auto completion = string.release_error();
  324. // We can't explicitly check for OOM because InternalError does not store the ErrorType
  325. VERIFY(completion.value().has_value());
  326. VERIFY(completion.value()->is_object());
  327. VERIFY(is<InternalError>(completion.value()->as_object()));
  328. return AK::Error::from_errno(ENOMEM);
  329. } else {
  330. return string.release_value();
  331. }
  332. case SYMBOL_TAG:
  333. return as_symbol().descriptive_string();
  334. case BIGINT_TAG:
  335. return as_bigint().to_string();
  336. case OBJECT_TAG:
  337. return String::formatted("[object {}]", as_object().class_name());
  338. case ACCESSOR_TAG:
  339. return String::from_utf8("<accessor>"sv);
  340. default:
  341. VERIFY_NOT_REACHED();
  342. }
  343. }
  344. ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm)
  345. {
  346. if (is_string())
  347. return &as_string();
  348. auto string = TRY(to_string(vm));
  349. return PrimitiveString::create(vm, move(string)).ptr();
  350. }
  351. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  352. ThrowCompletionOr<String> Value::to_string(VM& vm) const
  353. {
  354. if (is_double())
  355. return TRY_OR_THROW_OOM(vm, number_to_string(m_value.as_double));
  356. switch (m_value.tag) {
  357. // 1. If argument is a String, return argument.
  358. case STRING_TAG:
  359. return TRY(as_string().utf8_string());
  360. // 2. If argument is a Symbol, throw a TypeError exception.
  361. case SYMBOL_TAG:
  362. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "string");
  363. // 3. If argument is undefined, return "undefined".
  364. case UNDEFINED_TAG:
  365. return TRY_OR_THROW_OOM(vm, String::from_utf8("undefined"sv));
  366. // 4. If argument is null, return "null".
  367. case NULL_TAG:
  368. return TRY_OR_THROW_OOM(vm, String::from_utf8("null"sv));
  369. // 5. If argument is true, return "true".
  370. // 6. If argument is false, return "false".
  371. case BOOLEAN_TAG:
  372. return TRY_OR_THROW_OOM(vm, String::from_utf8(as_bool() ? "true"sv : "false"sv));
  373. // 7. If argument is a Number, return Number::toString(argument, 10).
  374. case INT32_TAG:
  375. return TRY_OR_THROW_OOM(vm, String::number(as_i32()));
  376. // 8. If argument is a BigInt, return BigInt::toString(argument, 10).
  377. case BIGINT_TAG:
  378. return TRY_OR_THROW_OOM(vm, as_bigint().big_integer().to_base(10));
  379. // 9. Assert: argument is an Object.
  380. case OBJECT_TAG: {
  381. // 10. Let primValue be ? ToPrimitive(argument, string).
  382. auto primitive_value = TRY(to_primitive(vm, PreferredType::String));
  383. // 11. Assert: primValue is not an Object.
  384. VERIFY(!primitive_value.is_object());
  385. // 12. Return ? ToString(primValue).
  386. return primitive_value.to_string(vm);
  387. }
  388. default:
  389. VERIFY_NOT_REACHED();
  390. }
  391. }
  392. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  393. ThrowCompletionOr<DeprecatedString> Value::to_deprecated_string(VM& vm) const
  394. {
  395. return TRY(to_string(vm)).to_deprecated_string();
  396. }
  397. ThrowCompletionOr<Utf16String> Value::to_utf16_string(VM& vm) const
  398. {
  399. if (is_string())
  400. return TRY(as_string().utf16_string());
  401. auto utf8_string = TRY(to_string(vm));
  402. return Utf16String::create(vm, utf8_string.bytes_as_string_view());
  403. }
  404. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  405. bool Value::to_boolean() const
  406. {
  407. if (is_double()) {
  408. if (is_nan())
  409. return false;
  410. return m_value.as_double != 0;
  411. }
  412. switch (m_value.tag) {
  413. // 1. If argument is a Boolean, return argument.
  414. case BOOLEAN_TAG:
  415. return as_bool();
  416. // 2. If argument is any of undefined, null, +0𝔽, -0𝔽, NaN, 0ℤ, or the empty String, return false.
  417. case UNDEFINED_TAG:
  418. case NULL_TAG:
  419. return false;
  420. case INT32_TAG:
  421. return as_i32() != 0;
  422. case STRING_TAG:
  423. return !as_string().is_empty();
  424. case BIGINT_TAG:
  425. return as_bigint().big_integer() != BIGINT_ZERO;
  426. case OBJECT_TAG:
  427. // B.3.6.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  428. // 3. If argument is an Object and argument has an [[IsHTMLDDA]] internal slot, return false.
  429. if (as_object().is_htmldda())
  430. return false;
  431. // 4. Return true.
  432. return true;
  433. case SYMBOL_TAG:
  434. return true;
  435. default:
  436. VERIFY_NOT_REACHED();
  437. }
  438. }
  439. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  440. ThrowCompletionOr<Value> Value::to_primitive(VM& vm, PreferredType preferred_type) const
  441. {
  442. // 1. If input is an Object, then
  443. if (is_object()) {
  444. // a. Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
  445. auto* exotic_to_primitive = TRY(get_method(vm, *vm.well_known_symbol_to_primitive()));
  446. // b. If exoticToPrim is not undefined, then
  447. if (exotic_to_primitive) {
  448. auto hint = [&]() -> DeprecatedString {
  449. switch (preferred_type) {
  450. // i. If preferredType is not present, let hint be "default".
  451. case PreferredType::Default:
  452. return "default";
  453. // ii. Else if preferredType is string, let hint be "string".
  454. case PreferredType::String:
  455. return "string";
  456. // iii. Else,
  457. // 1. Assert: preferredType is number.
  458. // 2. Let hint be "number".
  459. case PreferredType::Number:
  460. return "number";
  461. default:
  462. VERIFY_NOT_REACHED();
  463. }
  464. }();
  465. // iv. Let result be ? Call(exoticToPrim, input, « hint »).
  466. auto result = TRY(call(vm, *exotic_to_primitive, *this, PrimitiveString::create(vm, hint)));
  467. // v. If result is not an Object, return result.
  468. if (!result.is_object())
  469. return result;
  470. // vi. Throw a TypeError exception.
  471. return vm.throw_completion<TypeError>(ErrorType::ToPrimitiveReturnedObject, TRY_OR_THROW_OOM(vm, to_string_without_side_effects()), hint);
  472. }
  473. // c. If preferredType is not present, let preferredType be number.
  474. if (preferred_type == PreferredType::Default)
  475. preferred_type = PreferredType::Number;
  476. // d. Return ? OrdinaryToPrimitive(input, preferredType).
  477. return as_object().ordinary_to_primitive(preferred_type);
  478. }
  479. // 2. Return input.
  480. return *this;
  481. }
  482. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  483. ThrowCompletionOr<Object*> Value::to_object(VM& vm) const
  484. {
  485. auto& realm = *vm.current_realm();
  486. VERIFY(!is_empty());
  487. // Number
  488. if (is_number()) {
  489. // Return a new Number object whose [[NumberData]] internal slot is set to argument. See 21.1 for a description of Number objects.
  490. return NumberObject::create(realm, as_double()).ptr();
  491. }
  492. switch (m_value.tag) {
  493. // Undefined
  494. // Null
  495. case UNDEFINED_TAG:
  496. case NULL_TAG:
  497. // Throw a TypeError exception.
  498. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  499. // Boolean
  500. case BOOLEAN_TAG:
  501. // Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 20.3 for a description of Boolean objects.
  502. return BooleanObject::create(realm, as_bool()).ptr();
  503. // String
  504. case STRING_TAG:
  505. // Return a new String object whose [[StringData]] internal slot is set to argument. See 22.1 for a description of String objects.
  506. return MUST_OR_THROW_OOM(StringObject::create(realm, const_cast<JS::PrimitiveString&>(as_string()), *realm.intrinsics().string_prototype())).ptr();
  507. // Symbol
  508. case SYMBOL_TAG:
  509. // Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 20.4 for a description of Symbol objects.
  510. return SymbolObject::create(realm, const_cast<JS::Symbol&>(as_symbol())).ptr();
  511. // BigInt
  512. case BIGINT_TAG:
  513. // Return a new BigInt object whose [[BigIntData]] internal slot is set to argument. See 21.2 for a description of BigInt objects.
  514. return BigIntObject::create(realm, const_cast<JS::BigInt&>(as_bigint())).ptr();
  515. // Object
  516. case OBJECT_TAG:
  517. // Return argument.
  518. return &const_cast<Object&>(as_object());
  519. default:
  520. VERIFY_NOT_REACHED();
  521. }
  522. }
  523. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  524. FLATTEN ThrowCompletionOr<Value> Value::to_numeric(VM& vm) const
  525. {
  526. // 1. Let primValue be ? ToPrimitive(value, number).
  527. auto primitive_value = TRY(to_primitive(vm, Value::PreferredType::Number));
  528. // 2. If primValue is a BigInt, return primValue.
  529. if (primitive_value.is_bigint())
  530. return primitive_value;
  531. // 3. Return ? ToNumber(primValue).
  532. return primitive_value.to_number(vm);
  533. }
  534. constexpr bool is_ascii_number(u32 code_point)
  535. {
  536. return is_ascii_digit(code_point) || code_point == '.' || (code_point == 'e' || code_point == 'E') || code_point == '+' || code_point == '-';
  537. }
  538. struct NumberParseResult {
  539. StringView literal;
  540. u8 base;
  541. };
  542. static Optional<NumberParseResult> parse_number_text(StringView text)
  543. {
  544. NumberParseResult result {};
  545. auto check_prefix = [&](auto lower_prefix, auto upper_prefix) {
  546. if (text.length() <= 2)
  547. return false;
  548. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  549. return false;
  550. return true;
  551. };
  552. // https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
  553. if (check_prefix("0b"sv, "0B"sv)) {
  554. if (!all_of(text.substring_view(2), is_ascii_binary_digit))
  555. return {};
  556. result.literal = text.substring_view(2);
  557. result.base = 2;
  558. } else if (check_prefix("0o"sv, "0O"sv)) {
  559. if (!all_of(text.substring_view(2), is_ascii_octal_digit))
  560. return {};
  561. result.literal = text.substring_view(2);
  562. result.base = 8;
  563. } else if (check_prefix("0x"sv, "0X"sv)) {
  564. if (!all_of(text.substring_view(2), is_ascii_hex_digit))
  565. return {};
  566. result.literal = text.substring_view(2);
  567. result.base = 16;
  568. } else {
  569. if (!all_of(text, is_ascii_number))
  570. return {};
  571. result.literal = text;
  572. result.base = 10;
  573. }
  574. return result;
  575. }
  576. // 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber
  577. Optional<Value> string_to_number(StringView string)
  578. {
  579. // 1. Let text be StringToCodePoints(str).
  580. DeprecatedString text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  581. // 2. Let literal be ParseText(text, StringNumericLiteral).
  582. if (text.is_empty())
  583. return Value(0);
  584. if (text == "Infinity" || text == "+Infinity")
  585. return js_infinity();
  586. if (text == "-Infinity")
  587. return js_negative_infinity();
  588. auto result = parse_number_text(text);
  589. // 3. If literal is a List of errors, return NaN.
  590. if (!result.has_value())
  591. return js_nan();
  592. // 4. Return StringNumericValue of literal.
  593. if (result->base != 10) {
  594. auto bigint = Crypto::UnsignedBigInteger::from_base(result->base, result->literal);
  595. return Value(bigint.to_double());
  596. }
  597. auto maybe_double = text.to_double(AK::TrimWhitespace::No);
  598. if (!maybe_double.has_value())
  599. return js_nan();
  600. return Value(*maybe_double);
  601. }
  602. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  603. ThrowCompletionOr<Value> Value::to_number(VM& vm) const
  604. {
  605. VERIFY(!is_empty());
  606. // 1. If argument is a Number, return argument.
  607. if (is_number())
  608. return *this;
  609. switch (m_value.tag) {
  610. // 2. If argument is either a Symbol or a BigInt, throw a TypeError exception.
  611. case SYMBOL_TAG:
  612. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "number");
  613. case BIGINT_TAG:
  614. return vm.throw_completion<TypeError>(ErrorType::Convert, "BigInt", "number");
  615. // 3. If argument is undefined, return NaN.
  616. case UNDEFINED_TAG:
  617. return js_nan();
  618. // 4. If argument is either null or false, return +0𝔽.
  619. case NULL_TAG:
  620. return Value(0);
  621. // 5. If argument is true, return 1𝔽.
  622. case BOOLEAN_TAG:
  623. return Value(as_bool() ? 1 : 0);
  624. // 6. If argument is a String, return StringToNumber(argument).
  625. case STRING_TAG:
  626. return string_to_number(TRY(as_string().deprecated_string()));
  627. // 7. Assert: argument is an Object.
  628. case OBJECT_TAG: {
  629. // 8. Let primValue be ? ToPrimitive(argument, number).
  630. auto primitive_value = TRY(to_primitive(vm, PreferredType::Number));
  631. // 9. Assert: primValue is not an Object.
  632. VERIFY(!primitive_value.is_object());
  633. // 10. Return ? ToNumber(primValue).
  634. return primitive_value.to_number(vm);
  635. }
  636. default:
  637. VERIFY_NOT_REACHED();
  638. }
  639. }
  640. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string);
  641. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  642. ThrowCompletionOr<BigInt*> Value::to_bigint(VM& vm) const
  643. {
  644. // 1. Let prim be ? ToPrimitive(argument, number).
  645. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  646. // 2. Return the value that prim corresponds to in Table 12.
  647. // Number
  648. if (primitive.is_number()) {
  649. // Throw a TypeError exception.
  650. return vm.throw_completion<TypeError>(ErrorType::Convert, "number", "BigInt");
  651. }
  652. switch (primitive.m_value.tag) {
  653. // Undefined
  654. case UNDEFINED_TAG:
  655. // Throw a TypeError exception.
  656. return vm.throw_completion<TypeError>(ErrorType::Convert, "undefined", "BigInt");
  657. // Null
  658. case NULL_TAG:
  659. // Throw a TypeError exception.
  660. return vm.throw_completion<TypeError>(ErrorType::Convert, "null", "BigInt");
  661. // Boolean
  662. case BOOLEAN_TAG: {
  663. // Return 1n if prim is true and 0n if prim is false.
  664. auto value = primitive.as_bool() ? 1 : 0;
  665. return BigInt::create(vm, Crypto::SignedBigInteger { value }).ptr();
  666. }
  667. // BigInt
  668. case BIGINT_TAG:
  669. // Return prim.
  670. return &primitive.as_bigint();
  671. case STRING_TAG: {
  672. // 1. Let n be ! StringToBigInt(prim).
  673. auto bigint = string_to_bigint(vm, TRY(primitive.as_string().deprecated_string()));
  674. // 2. If n is undefined, throw a SyntaxError exception.
  675. if (!bigint.has_value())
  676. return vm.throw_completion<SyntaxError>(ErrorType::BigIntInvalidValue, primitive);
  677. // 3. Return n.
  678. return bigint.release_value();
  679. }
  680. // Symbol
  681. case SYMBOL_TAG:
  682. // Throw a TypeError exception.
  683. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "BigInt");
  684. default:
  685. VERIFY_NOT_REACHED();
  686. }
  687. }
  688. struct BigIntParseResult {
  689. StringView literal;
  690. u8 base { 10 };
  691. bool is_negative { false };
  692. };
  693. static Optional<BigIntParseResult> parse_bigint_text(StringView text)
  694. {
  695. BigIntParseResult result {};
  696. auto parse_for_prefixed_base = [&](auto lower_prefix, auto upper_prefix, auto validator) {
  697. if (text.length() <= 2)
  698. return false;
  699. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  700. return false;
  701. return all_of(text.substring_view(2), validator);
  702. };
  703. if (parse_for_prefixed_base("0b"sv, "0B"sv, is_ascii_binary_digit)) {
  704. result.literal = text.substring_view(2);
  705. result.base = 2;
  706. } else if (parse_for_prefixed_base("0o"sv, "0O"sv, is_ascii_octal_digit)) {
  707. result.literal = text.substring_view(2);
  708. result.base = 8;
  709. } else if (parse_for_prefixed_base("0x"sv, "0X"sv, is_ascii_hex_digit)) {
  710. result.literal = text.substring_view(2);
  711. result.base = 16;
  712. } else {
  713. if (text.starts_with('-')) {
  714. text = text.substring_view(1);
  715. result.is_negative = true;
  716. } else if (text.starts_with('+')) {
  717. text = text.substring_view(1);
  718. }
  719. if (!all_of(text, is_ascii_digit))
  720. return {};
  721. result.literal = text;
  722. result.base = 10;
  723. }
  724. return result;
  725. }
  726. // 7.1.14 StringToBigInt ( str ), https://tc39.es/ecma262/#sec-stringtobigint
  727. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string)
  728. {
  729. // 1. Let text be StringToCodePoints(str).
  730. auto text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  731. // 2. Let literal be ParseText(text, StringIntegerLiteral).
  732. auto result = parse_bigint_text(text);
  733. // 3. If literal is a List of errors, return undefined.
  734. if (!result.has_value())
  735. return {};
  736. // 4. Let mv be the MV of literal.
  737. // 5. Assert: mv is an integer.
  738. auto bigint = Crypto::SignedBigInteger::from_base(result->base, result->literal);
  739. if (result->is_negative && (bigint != BIGINT_ZERO))
  740. bigint.negate();
  741. // 6. Return ℤ(mv).
  742. return BigInt::create(vm, move(bigint));
  743. }
  744. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/#sec-tobigint64
  745. ThrowCompletionOr<i64> Value::to_bigint_int64(VM& vm) const
  746. {
  747. // 1. Let n be ? ToBigInt(argument).
  748. auto* bigint = TRY(to_bigint(vm));
  749. // 2. Let int64bit be ℝ(n) modulo 2^64.
  750. // 3. If int64bit ≥ 2^63, return ℤ(int64bit - 2^64); otherwise return ℤ(int64bit).
  751. return static_cast<i64>(bigint->big_integer().to_u64());
  752. }
  753. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/#sec-tobiguint64
  754. ThrowCompletionOr<u64> Value::to_bigint_uint64(VM& vm) const
  755. {
  756. // 1. Let n be ? ToBigInt(argument).
  757. auto* bigint = TRY(to_bigint(vm));
  758. // 2. Let int64bit be ℝ(n) modulo 2^64.
  759. // 3. Return ℤ(int64bit).
  760. return bigint->big_integer().to_u64();
  761. }
  762. ThrowCompletionOr<double> Value::to_double(VM& vm) const
  763. {
  764. return TRY(to_number(vm)).as_double();
  765. }
  766. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  767. ThrowCompletionOr<PropertyKey> Value::to_property_key(VM& vm) const
  768. {
  769. // OPTIMIZATION: Return the value as a numeric PropertyKey, if possible.
  770. if (is_int32() && as_i32() >= 0)
  771. return PropertyKey { as_i32() };
  772. // 1. Let key be ? ToPrimitive(argument, string).
  773. auto key = TRY(to_primitive(vm, PreferredType::String));
  774. // 2. If key is a Symbol, then
  775. if (key.is_symbol()) {
  776. // a. Return key.
  777. return &key.as_symbol();
  778. }
  779. // 3. Return ! ToString(key).
  780. return MUST(key.to_deprecated_string(vm));
  781. }
  782. // 7.1.6 ToInt32 ( argument ), https://tc39.es/ecma262/#sec-toint32
  783. ThrowCompletionOr<i32> Value::to_i32_slow_case(VM& vm) const
  784. {
  785. VERIFY(!is_int32());
  786. // 1. Let number be ? ToNumber(argument).
  787. double number = TRY(to_number(vm)).as_double();
  788. // 2. If number is not finite or number is either +0𝔽 or -0𝔽, return +0𝔽.
  789. if (!isfinite(number) || number == 0)
  790. return 0;
  791. // 3. Let int be the mathematical value whose sign is the sign of number and whose magnitude is floor(abs(ℝ(number))).
  792. auto abs = fabs(number);
  793. auto int_val = floor(abs);
  794. if (signbit(number))
  795. int_val = -int_val;
  796. // 4. Let int32bit be int modulo 2^32.
  797. auto int32bit = modulo(int_val, NumericLimits<u32>::max() + 1.0);
  798. // 5. If int32bit ≥ 2^31, return 𝔽(int32bit - 2^32); otherwise return 𝔽(int32bit).
  799. if (int32bit >= 2147483648.0)
  800. int32bit -= 4294967296.0;
  801. return static_cast<i32>(int32bit);
  802. }
  803. // 7.1.6 ToInt32 ( argument ), https://tc39.es/ecma262/#sec-toint32
  804. ThrowCompletionOr<i32> Value::to_i32(VM& vm) const
  805. {
  806. if (is_int32())
  807. return as_i32();
  808. return to_i32_slow_case(vm);
  809. }
  810. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  811. ThrowCompletionOr<u32> Value::to_u32(VM& vm) const
  812. {
  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<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, TRY_OR_THROW_OOM(vm, 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. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1124. // 1-2, 6. N/A.
  1125. // 3. Let lnum be ? ToNumeric(lval).
  1126. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1127. // 4. Let rnum be ? ToNumeric(rval).
  1128. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1129. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1130. // [...]
  1131. // 8. Return operation(lnum, rnum).
  1132. if (both_number(lhs_numeric, rhs_numeric)) {
  1133. // 6.1.6.1.17 Number::bitwiseAND ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseAND
  1134. // 1. Return NumberBitwiseOp(&, x, y).
  1135. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  1136. return Value(0);
  1137. return Value(TRY(lhs_numeric.to_i32(vm)) & TRY(rhs_numeric.to_i32(vm)));
  1138. }
  1139. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1140. // 6.1.6.2.18 BigInt::bitwiseAND ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseAND
  1141. // 1. Return BigIntBitwiseOp(&, x, y).
  1142. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  1143. }
  1144. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1145. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  1146. }
  1147. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  1148. // BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression
  1149. ThrowCompletionOr<Value> bitwise_or(VM& vm, Value lhs, Value rhs)
  1150. {
  1151. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1152. // 1-2, 6. N/A.
  1153. // 3. Let lnum be ? ToNumeric(lval).
  1154. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1155. // 4. Let rnum be ? ToNumeric(rval).
  1156. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1157. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1158. // [...]
  1159. // 8. Return operation(lnum, rnum).
  1160. if (both_number(lhs_numeric, rhs_numeric)) {
  1161. // 6.1.6.1.19 Number::bitwiseOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseOR
  1162. // 1. Return NumberBitwiseOp(|, x, y).
  1163. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  1164. return Value(0);
  1165. if (!lhs_numeric.is_finite_number())
  1166. return rhs_numeric;
  1167. if (!rhs_numeric.is_finite_number())
  1168. return lhs_numeric;
  1169. return Value(TRY(lhs_numeric.to_i32(vm)) | TRY(rhs_numeric.to_i32(vm)));
  1170. }
  1171. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1172. // 6.1.6.2.20 BigInt::bitwiseOR ( x, y )
  1173. // 1. Return BigIntBitwiseOp(|, x, y).
  1174. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  1175. }
  1176. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1177. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  1178. }
  1179. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  1180. // BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
  1181. ThrowCompletionOr<Value> bitwise_xor(VM& vm, Value lhs, Value rhs)
  1182. {
  1183. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1184. // 1-2, 6. N/A.
  1185. // 3. Let lnum be ? ToNumeric(lval).
  1186. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1187. // 4. Let rnum be ? ToNumeric(rval).
  1188. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1189. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1190. // [...]
  1191. // 8. Return operation(lnum, rnum).
  1192. if (both_number(lhs_numeric, rhs_numeric)) {
  1193. // 6.1.6.1.18 Number::bitwiseXOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseXOR
  1194. // 1. Return NumberBitwiseOp(^, x, y).
  1195. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  1196. return Value(0);
  1197. if (!lhs_numeric.is_finite_number())
  1198. return rhs_numeric;
  1199. if (!rhs_numeric.is_finite_number())
  1200. return lhs_numeric;
  1201. return Value(TRY(lhs_numeric.to_i32(vm)) ^ TRY(rhs_numeric.to_i32(vm)));
  1202. }
  1203. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1204. // 6.1.6.2.19 BigInt::bitwiseXOR ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseXOR
  1205. // 1. Return BigIntBitwiseOp(^, x, y).
  1206. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  1207. }
  1208. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1209. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  1210. }
  1211. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  1212. // UnaryExpression : ~ UnaryExpression
  1213. ThrowCompletionOr<Value> bitwise_not(VM& vm, Value lhs)
  1214. {
  1215. // 1. Let expr be ? Evaluation of UnaryExpression.
  1216. // NOTE: This is handled in the AST or Bytecode interpreter.
  1217. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  1218. auto old_value = TRY(lhs.to_numeric(vm));
  1219. // 3. If oldValue is a Number, then
  1220. if (old_value.is_number()) {
  1221. // a. Return Number::bitwiseNOT(oldValue).
  1222. // 6.1.6.1.2 Number::bitwiseNOT ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-bitwiseNOT
  1223. // 1. Let oldValue be ! ToInt32(x).
  1224. // 2. Return the result of applying bitwise complement to oldValue. The mathematical value of the result is
  1225. // exactly representable as a 32-bit two's complement bit string.
  1226. return Value(~TRY(old_value.to_i32(vm)));
  1227. }
  1228. // 4. Else,
  1229. // a. Assert: oldValue is a BigInt.
  1230. VERIFY(old_value.is_bigint());
  1231. // b. Return BigInt::bitwiseNOT(oldValue).
  1232. // 6.1.6.2.2 BigInt::bitwiseNOT ( x ), https://tc39.es/ecma262/#sec-numeric-types-bigint-bitwiseNOT
  1233. // 1. Return -x - 1ℤ.
  1234. return BigInt::create(vm, old_value.as_bigint().big_integer().bitwise_not());
  1235. }
  1236. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  1237. // UnaryExpression : + UnaryExpression
  1238. ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
  1239. {
  1240. // 1. Let expr be ? Evaluation of UnaryExpression.
  1241. // NOTE: This is handled in the AST or Bytecode interpreter.
  1242. // 2. Return ? ToNumber(? GetValue(expr)).
  1243. return TRY(lhs.to_number(vm));
  1244. }
  1245. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  1246. // UnaryExpression : - UnaryExpression
  1247. ThrowCompletionOr<Value> unary_minus(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. Let oldValue be ? ToNumeric(? GetValue(expr)).
  1252. auto old_value = TRY(lhs.to_numeric(vm));
  1253. // 3. If oldValue is a Number, then
  1254. if (old_value.is_number()) {
  1255. // a. Return Number::unaryMinus(oldValue).
  1256. // 6.1.6.1.1 Number::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-unaryMinus
  1257. // 1. If x is NaN, return NaN.
  1258. if (old_value.is_nan())
  1259. return js_nan();
  1260. // 2. Return the result of negating x; that is, compute a Number with the same magnitude but opposite sign.
  1261. return Value(-old_value.as_double());
  1262. }
  1263. // 4. Else,
  1264. // a. Assert: oldValue is a BigInt.
  1265. VERIFY(old_value.is_bigint());
  1266. // b. Return BigInt::unaryMinus(oldValue).
  1267. // 6.1.6.2.1 BigInt::unaryMinus ( x ), https://tc39.es/ecma262/#sec-numeric-types-bigint-unaryMinus
  1268. // 1. If x is 0ℤ, return 0ℤ.
  1269. if (old_value.as_bigint().big_integer() == BIGINT_ZERO)
  1270. return BigInt::create(vm, BIGINT_ZERO);
  1271. // 2. Return the BigInt value that represents the negation of ℝ(x).
  1272. auto big_integer_negated = old_value.as_bigint().big_integer();
  1273. big_integer_negated.negate();
  1274. return BigInt::create(vm, big_integer_negated);
  1275. }
  1276. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  1277. // ShiftExpression : ShiftExpression << AdditiveExpression
  1278. ThrowCompletionOr<Value> left_shift(VM& vm, Value lhs, Value rhs)
  1279. {
  1280. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1281. // 1-2, 6. N/A.
  1282. // 3. Let lnum be ? ToNumeric(lval).
  1283. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1284. // 4. Let rnum be ? ToNumeric(rval).
  1285. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1286. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1287. // [...]
  1288. // 8. Return operation(lnum, rnum).
  1289. if (both_number(lhs_numeric, rhs_numeric)) {
  1290. // 6.1.6.1.9 Number::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-leftShift
  1291. // OPTIMIZATION: Handle infinite values according to the results returned by ToInt32/ToUint32.
  1292. if (!lhs_numeric.is_finite_number())
  1293. return Value(0);
  1294. if (!rhs_numeric.is_finite_number())
  1295. return lhs_numeric;
  1296. // 1. Let lnum be ! ToInt32(x).
  1297. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1298. // 2. Let rnum be ! ToUint32(y).
  1299. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1300. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1301. auto shift_count = rhs_u32 % 32;
  1302. // 4. Return the result of left shifting lnum by shiftCount bits. The mathematical value of the result is
  1303. // exactly representable as a 32-bit two's complement bit string.
  1304. return Value(lhs_i32 << shift_count);
  1305. }
  1306. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1307. // 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
  1308. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  1309. // 1. If y < 0ℤ, then
  1310. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  1311. // a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
  1312. // NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
  1313. auto const& big_integer = lhs_numeric.as_bigint().big_integer();
  1314. auto division_result = big_integer.divided_by(multiplier_divisor);
  1315. // For positive initial values and no remainder just return quotient
  1316. if (division_result.remainder.is_zero() || !big_integer.is_negative())
  1317. return BigInt::create(vm, division_result.quotient);
  1318. // For negative round "down" to the next negative number
  1319. return BigInt::create(vm, division_result.quotient.minus(Crypto::SignedBigInteger { 1 }));
  1320. }
  1321. // 2. Return the BigInt value that represents ℝ(x) × 2^y.
  1322. return Value(BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor)));
  1323. }
  1324. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1325. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "left-shift");
  1326. }
  1327. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  1328. // ShiftExpression : ShiftExpression >> AdditiveExpression
  1329. ThrowCompletionOr<Value> right_shift(VM& vm, Value lhs, Value rhs)
  1330. {
  1331. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1332. // 1-2, 6. N/A.
  1333. // 3. Let lnum be ? ToNumeric(lval).
  1334. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1335. // 4. Let rnum be ? ToNumeric(rval).
  1336. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1337. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1338. // [...]
  1339. // 8. Return operation(lnum, rnum).
  1340. if (both_number(lhs_numeric, rhs_numeric)) {
  1341. // 6.1.6.1.10 Number::signedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-signedRightShift
  1342. // OPTIMIZATION: Handle infinite values according to the results returned by ToInt32/ToUint32.
  1343. if (!lhs_numeric.is_finite_number())
  1344. return Value(0);
  1345. if (!rhs_numeric.is_finite_number())
  1346. return lhs_numeric;
  1347. // 1. Let lnum be ! ToInt32(x).
  1348. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1349. // 2. Let rnum be ! ToUint32(y).
  1350. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1351. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1352. auto shift_count = rhs_u32 % 32;
  1353. // 4. Return the result of performing a sign-extending right shift of lnum by shiftCount bits.
  1354. // The most significant bit is propagated. The mathematical value of the result is exactly representable
  1355. // as a 32-bit two's complement bit string.
  1356. return Value(lhs_i32 >> shift_count);
  1357. }
  1358. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1359. // 6.1.6.2.10 BigInt::signedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-signedRightShift
  1360. // 1. Return BigInt::leftShift(x, -y).
  1361. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  1362. rhs_negated.negate();
  1363. return left_shift(vm, lhs, BigInt::create(vm, rhs_negated));
  1364. }
  1365. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1366. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "right-shift");
  1367. }
  1368. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  1369. // ShiftExpression : ShiftExpression >>> AdditiveExpression
  1370. ThrowCompletionOr<Value> unsigned_right_shift(VM& vm, Value lhs, Value rhs)
  1371. {
  1372. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1373. // 1-2, 5-6. N/A.
  1374. // 3. Let lnum be ? ToNumeric(lval).
  1375. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1376. // 4. Let rnum be ? ToNumeric(rval).
  1377. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1378. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1379. // [...]
  1380. // 8. Return operation(lnum, rnum).
  1381. if (both_number(lhs_numeric, rhs_numeric)) {
  1382. // 6.1.6.1.11 Number::unsignedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-unsignedRightShift
  1383. // OPTIMIZATION: Handle infinite values according to the results returned by ToUint32.
  1384. if (!lhs_numeric.is_finite_number())
  1385. return Value(0);
  1386. if (!rhs_numeric.is_finite_number())
  1387. return lhs_numeric;
  1388. // 1. Let lnum be ! ToUint32(x).
  1389. auto lhs_u32 = MUST(lhs_numeric.to_u32(vm));
  1390. // 2. Let rnum be ! ToUint32(y).
  1391. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm));
  1392. // 3. Let shiftCount be ℝ(rnum) modulo 32.
  1393. auto shift_count = rhs_u32 % 32;
  1394. // 4. Return the result of performing a zero-filling right shift of lnum by shiftCount bits.
  1395. // Vacated bits are filled with zero. The mathematical value of the result is exactly representable
  1396. // as a 32-bit unsigned bit string.
  1397. return Value(lhs_u32 >> shift_count);
  1398. }
  1399. // 6. If lnum is a BigInt, then
  1400. // d. If opText is >>>, return ? BigInt::unsignedRightShift(lnum, rnum).
  1401. // 6.1.6.2.11 BigInt::unsignedRightShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-unsignedRightShift
  1402. // 1. Throw a TypeError exception.
  1403. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperator, "unsigned right-shift");
  1404. }
  1405. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  1406. // AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1407. ThrowCompletionOr<Value> add(VM& vm, Value lhs, Value rhs)
  1408. {
  1409. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1410. // 1. If opText is +, then
  1411. // OPTIMIZATION: If both values are i32 or double, we can do a direct addition without the type conversions below.
  1412. if (both_number(lhs, rhs)) {
  1413. if (lhs.is_int32() && rhs.is_int32()) {
  1414. Checked<i32> result;
  1415. result = MUST(lhs.to_i32(vm));
  1416. result += MUST(rhs.to_i32(vm));
  1417. if (!result.has_overflow())
  1418. return Value(result.value());
  1419. }
  1420. return Value(lhs.as_double() + rhs.as_double());
  1421. }
  1422. // a. Let lprim be ? ToPrimitive(lval).
  1423. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1424. // b. Let rprim be ? ToPrimitive(rval).
  1425. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1426. // c. If lprim is a String or rprim is a String, then
  1427. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  1428. // i. Let lstr be ? ToString(lprim).
  1429. auto lhs_string = TRY(lhs_primitive.to_primitive_string(vm));
  1430. // ii. Let rstr be ? ToString(rprim).
  1431. auto rhs_string = TRY(rhs_primitive.to_primitive_string(vm));
  1432. // iii. Return the string-concatenation of lstr and rstr.
  1433. return PrimitiveString::create(vm, *lhs_string, *rhs_string);
  1434. }
  1435. // d. Set lval to lprim.
  1436. // e. Set rval to rprim.
  1437. // 2. NOTE: At this point, it must be a numeric operation.
  1438. // 3. Let lnum be ? ToNumeric(lval).
  1439. auto lhs_numeric = TRY(lhs_primitive.to_numeric(vm));
  1440. // 4. Let rnum be ? ToNumeric(rval).
  1441. auto rhs_numeric = TRY(rhs_primitive.to_numeric(vm));
  1442. // 6. N/A.
  1443. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1444. // [...]
  1445. // 8. Return operation(lnum, rnum).
  1446. if (both_number(lhs_numeric, rhs_numeric)) {
  1447. // 6.1.6.1.7 Number::add ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-add
  1448. auto x = lhs_numeric.as_double();
  1449. auto y = rhs_numeric.as_double();
  1450. return Value(x + y);
  1451. }
  1452. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1453. // 6.1.6.2.7 BigInt::add ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-add
  1454. auto x = lhs_numeric.as_bigint().big_integer();
  1455. auto y = rhs_numeric.as_bigint().big_integer();
  1456. return BigInt::create(vm, x.plus(y));
  1457. }
  1458. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1459. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "addition");
  1460. }
  1461. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1462. // AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1463. ThrowCompletionOr<Value> sub(VM& vm, Value lhs, Value rhs)
  1464. {
  1465. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1466. // 1-2, 6. N/A.
  1467. // 3. Let lnum be ? ToNumeric(lval).
  1468. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1469. // 4. Let rnum be ? ToNumeric(rval).
  1470. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1471. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1472. // [...]
  1473. // 8. Return operation(lnum, rnum).
  1474. if (both_number(lhs_numeric, rhs_numeric)) {
  1475. // 6.1.6.1.8 Number::subtract ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-subtract
  1476. auto x = lhs_numeric.as_double();
  1477. auto y = rhs_numeric.as_double();
  1478. // 1. Return Number::add(x, Number::unaryMinus(y)).
  1479. return Value(x - y);
  1480. }
  1481. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1482. // 6.1.6.2.8 BigInt::subtract ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-subtract
  1483. auto x = lhs_numeric.as_bigint().big_integer();
  1484. auto y = rhs_numeric.as_bigint().big_integer();
  1485. // 1. Return the BigInt value that represents the difference x minus y.
  1486. return BigInt::create(vm, x.minus(y));
  1487. }
  1488. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1489. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1490. }
  1491. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1492. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1493. ThrowCompletionOr<Value> mul(VM& vm, Value lhs, Value rhs)
  1494. {
  1495. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1496. // 1-2, 6. N/A.
  1497. // 3. Let lnum be ? ToNumeric(lval).
  1498. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1499. // 4. Let rnum be ? ToNumeric(rval).
  1500. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1501. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1502. // [...]
  1503. // 8. Return operation(lnum, rnum).
  1504. if (both_number(lhs_numeric, rhs_numeric)) {
  1505. // 6.1.6.1.4 Number::multiply ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-multiply
  1506. auto x = lhs_numeric.as_double();
  1507. auto y = rhs_numeric.as_double();
  1508. return Value(x * y);
  1509. }
  1510. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1511. // 6.1.6.2.4 BigInt::multiply ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-multiply
  1512. auto x = lhs_numeric.as_bigint().big_integer();
  1513. auto y = rhs_numeric.as_bigint().big_integer();
  1514. // 1. Return the BigInt value that represents the product of x and y.
  1515. return BigInt::create(vm, x.multiplied_by(y));
  1516. }
  1517. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1518. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1519. }
  1520. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1521. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1522. ThrowCompletionOr<Value> div(VM& vm, Value lhs, Value rhs)
  1523. {
  1524. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1525. // 1-2, 6. N/A.
  1526. // 3. Let lnum be ? ToNumeric(lval).
  1527. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1528. // 4. Let rnum be ? ToNumeric(rval).
  1529. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1530. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1531. // [...]
  1532. // 8. Return operation(lnum, rnum).
  1533. if (both_number(lhs_numeric, rhs_numeric)) {
  1534. // 6.1.6.1.5 Number::divide ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-divide
  1535. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1536. }
  1537. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1538. // 6.1.6.2.5 BigInt::divide ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-divide
  1539. auto x = lhs_numeric.as_bigint().big_integer();
  1540. auto y = rhs_numeric.as_bigint().big_integer();
  1541. // 1. If y is 0ℤ, throw a RangeError exception.
  1542. if (y == BIGINT_ZERO)
  1543. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1544. // 2. Let quotient be ℝ(x) / ℝ(y).
  1545. // 3. Return the BigInt value that represents quotient rounded towards 0 to the next integer value.
  1546. return BigInt::create(vm, x.divided_by(y).quotient);
  1547. }
  1548. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1549. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "division");
  1550. }
  1551. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1552. // MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1553. ThrowCompletionOr<Value> mod(VM& vm, Value lhs, Value rhs)
  1554. {
  1555. // 13.15.3 ApplyStringOrNumericBinaryOperator ( lval, opText, rval ), https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator
  1556. // 1-2, 6. N/A.
  1557. // 3. Let lnum be ? ToNumeric(lval).
  1558. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1559. // 4. Let rnum be ? ToNumeric(rval).
  1560. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1561. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1562. // [...]
  1563. // 8. Return operation(lnum, rnum).
  1564. if (both_number(lhs_numeric, rhs_numeric)) {
  1565. // 6.1.6.1.6 Number::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-number-remainder
  1566. // The ECMA specification is describing the mathematical definition of modulus
  1567. // implemented by fmod.
  1568. auto n = lhs_numeric.as_double();
  1569. auto d = rhs_numeric.as_double();
  1570. return Value(fmod(n, d));
  1571. }
  1572. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1573. // 6.1.6.2.6 BigInt::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-bigint-remainder
  1574. auto n = lhs_numeric.as_bigint().big_integer();
  1575. auto d = rhs_numeric.as_bigint().big_integer();
  1576. // 1. If d is 0ℤ, throw a RangeError exception.
  1577. if (d == BIGINT_ZERO)
  1578. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1579. // 2. If n is 0ℤ, return 0ℤ.
  1580. // 3. Let quotient be ℝ(n) / ℝ(d).
  1581. // 4. Let q be the BigInt whose sign is the sign of quotient and whose magnitude is floor(abs(quotient)).
  1582. // 5. Return n - (d × q).
  1583. return BigInt::create(vm, n.divided_by(d).remainder);
  1584. }
  1585. // 5. If Type(lnum) is different from Type(rnum), throw a TypeError exception.
  1586. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "modulo");
  1587. }
  1588. // 6.1.6.1.3 Number::exponentiate ( base, exponent ), https://tc39.es/ecma262/#sec-numeric-types-number-exponentiate
  1589. static Value exp_double(Value base, Value exponent)
  1590. {
  1591. VERIFY(both_number(base, exponent));
  1592. // 1. If exponent is NaN, return NaN.
  1593. if (exponent.is_nan())
  1594. return js_nan();
  1595. // 2. If exponent is +0𝔽 or exponent is -0𝔽, return 1𝔽.
  1596. if (exponent.is_positive_zero() || exponent.is_negative_zero())
  1597. return Value(1);
  1598. // 3. If base is NaN, return NaN.
  1599. if (base.is_nan())
  1600. return js_nan();
  1601. // 4. If base is +∞𝔽, then
  1602. if (base.is_positive_infinity()) {
  1603. // a. If exponent > +0𝔽, return +∞𝔽. Otherwise, return +0𝔽.
  1604. return exponent.as_double() > 0 ? js_infinity() : Value(0);
  1605. }
  1606. // 5. If base is -∞𝔽, then
  1607. if (base.is_negative_infinity()) {
  1608. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1609. // a. If exponent > +0𝔽, then
  1610. if (exponent.as_double() > 0) {
  1611. // i. If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
  1612. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1613. }
  1614. // b. Else,
  1615. else {
  1616. // i. If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
  1617. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1618. }
  1619. }
  1620. // 6. If base is +0𝔽, then
  1621. if (base.is_positive_zero()) {
  1622. // a. If exponent > +0𝔽, return +0𝔽. Otherwise, return +∞𝔽.
  1623. return exponent.as_double() > 0 ? Value(0) : js_infinity();
  1624. }
  1625. // 7. If base is -0𝔽, then
  1626. if (base.is_negative_zero()) {
  1627. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1628. // a. If exponent > +0𝔽, then
  1629. if (exponent.as_double() > 0) {
  1630. // i. If exponent is an odd integral Number, return -0𝔽. Otherwise, return +0𝔽.
  1631. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1632. }
  1633. // b. Else,
  1634. else {
  1635. // i. If exponent is an odd integral Number, return -∞𝔽. Otherwise, return +∞𝔽.
  1636. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1637. }
  1638. }
  1639. // 8. Assert: base is finite and is neither +0𝔽 nor -0𝔽.
  1640. VERIFY(base.is_finite_number() && !base.is_positive_zero() && !base.is_negative_zero());
  1641. // 9. If exponent is +∞𝔽, then
  1642. if (exponent.is_positive_infinity()) {
  1643. auto absolute_base = fabs(base.as_double());
  1644. // a. If abs(ℝ(base)) > 1, return +∞𝔽.
  1645. if (absolute_base > 1)
  1646. return js_infinity();
  1647. // b. If abs(ℝ(base)) is 1, return NaN.
  1648. else if (absolute_base == 1)
  1649. return js_nan();
  1650. // c. If abs(ℝ(base)) < 1, return +0𝔽.
  1651. else if (absolute_base < 1)
  1652. return Value(0);
  1653. }
  1654. // 10. If exponent is -∞𝔽, then
  1655. if (exponent.is_negative_infinity()) {
  1656. auto absolute_base = fabs(base.as_double());
  1657. // a. If abs(ℝ(base)) > 1, return +0𝔽.
  1658. if (absolute_base > 1)
  1659. return Value(0);
  1660. // b. If abs(ℝ(base)) is 1, return NaN.
  1661. else if (absolute_base == 1)
  1662. return js_nan();
  1663. // a. If abs(ℝ(base)) > 1, return +0𝔽.
  1664. else if (absolute_base < 1)
  1665. return js_infinity();
  1666. }
  1667. // 11. Assert: exponent is finite and is neither +0𝔽 nor -0𝔽.
  1668. VERIFY(exponent.is_finite_number() && !exponent.is_positive_zero() && !exponent.is_negative_zero());
  1669. // 12. If base < -0𝔽 and exponent is not an integral Number, return NaN.
  1670. if (base.as_double() < 0 && !exponent.is_integral_number())
  1671. return js_nan();
  1672. // 13. Return an implementation-approximated Number value representing the result of raising ℝ(base) to the ℝ(exponent) power.
  1673. return Value(::pow(base.as_double(), exponent.as_double()));
  1674. }
  1675. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1676. // ExponentiationExpression : UpdateExpression ** ExponentiationExpression
  1677. ThrowCompletionOr<Value> exp(VM& vm, Value lhs, Value rhs)
  1678. {
  1679. // 3. Let lnum be ? ToNumeric(lval).
  1680. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1681. // 4. Let rnum be ? ToNumeric(rval).
  1682. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1683. // 7. Let operation be the abstract operation associated with opText and Type(lnum) in the following table:
  1684. // [...]
  1685. // 8. Return operation(lnum, rnum).
  1686. if (both_number(lhs_numeric, rhs_numeric)) {
  1687. return exp_double(lhs_numeric, rhs_numeric);
  1688. }
  1689. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1690. // 6.1.6.2.3 BigInt::exponentiate ( base, exponent ), https://tc39.es/ecma262/#sec-numeric-types-bigint-exponentiate
  1691. auto base = lhs_numeric.as_bigint().big_integer();
  1692. auto exponent = rhs_numeric.as_bigint().big_integer();
  1693. // 1. If exponent < 0ℤ, throw a RangeError exception.
  1694. if (exponent.is_negative())
  1695. return vm.throw_completion<RangeError>(ErrorType::NegativeExponent);
  1696. // 2. If base is 0ℤ and exponent is 0ℤ, return 1ℤ.
  1697. // 3. Return the BigInt value that represents ℝ(base) raised to the power ℝ(exponent).
  1698. return BigInt::create(vm, Crypto::NumberTheory::Power(base, exponent));
  1699. }
  1700. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1701. }
  1702. ThrowCompletionOr<Value> in(VM& vm, Value lhs, Value rhs)
  1703. {
  1704. if (!rhs.is_object())
  1705. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  1706. auto lhs_property_key = TRY(lhs.to_property_key(vm));
  1707. return Value(TRY(rhs.as_object().has_property(lhs_property_key)));
  1708. }
  1709. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1710. ThrowCompletionOr<Value> instance_of(VM& vm, Value value, Value target)
  1711. {
  1712. // 1. If target is not an Object, throw a TypeError exception.
  1713. if (!target.is_object())
  1714. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, TRY_OR_THROW_OOM(vm, target.to_string_without_side_effects()));
  1715. // 2. Let instOfHandler be ? GetMethod(target, @@hasInstance).
  1716. auto* instance_of_handler = TRY(target.get_method(vm, *vm.well_known_symbol_has_instance()));
  1717. // 3. If instOfHandler is not undefined, then
  1718. if (instance_of_handler) {
  1719. // a. Return ToBoolean(? Call(instOfHandler, target, « V »)).
  1720. return Value(TRY(call(vm, *instance_of_handler, target, value)).to_boolean());
  1721. }
  1722. // 4. If IsCallable(target) is false, throw a TypeError exception.
  1723. if (!target.is_function())
  1724. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, TRY_OR_THROW_OOM(vm, target.to_string_without_side_effects()));
  1725. // 5. Return ? OrdinaryHasInstance(target, V).
  1726. return ordinary_has_instance(vm, target, value);
  1727. }
  1728. // 7.3.22 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1729. ThrowCompletionOr<Value> ordinary_has_instance(VM& vm, Value lhs, Value rhs)
  1730. {
  1731. // 1. If IsCallable(C) is false, return false.
  1732. if (!rhs.is_function())
  1733. return Value(false);
  1734. auto& rhs_function = rhs.as_function();
  1735. // 2. If C has a [[BoundTargetFunction]] internal slot, then
  1736. if (is<BoundFunction>(rhs_function)) {
  1737. auto const& bound_target = static_cast<BoundFunction const&>(rhs_function);
  1738. // a. Let BC be C.[[BoundTargetFunction]].
  1739. // b. Return ? InstanceofOperator(O, BC).
  1740. return instance_of(vm, lhs, Value(&bound_target.bound_target_function()));
  1741. }
  1742. // 3. If O is not an Object, return false.
  1743. if (!lhs.is_object())
  1744. return Value(false);
  1745. auto* lhs_object = &lhs.as_object();
  1746. // 4. Let P be ? Get(C, "prototype").
  1747. auto rhs_prototype = TRY(rhs_function.get(vm.names.prototype));
  1748. // 5. If P is not an Object, throw a TypeError exception.
  1749. if (!rhs_prototype.is_object())
  1750. return vm.throw_completion<TypeError>(ErrorType::InstanceOfOperatorBadPrototype, TRY_OR_THROW_OOM(vm, rhs.to_string_without_side_effects()));
  1751. // 6. Repeat,
  1752. while (true) {
  1753. // a. Set O to ? O.[[GetPrototypeOf]]().
  1754. lhs_object = TRY(lhs_object->internal_get_prototype_of());
  1755. // b. If O is null, return false.
  1756. if (!lhs_object)
  1757. return Value(false);
  1758. // c. If SameValue(P, O) is true, return true.
  1759. if (same_value(rhs_prototype, lhs_object))
  1760. return Value(true);
  1761. }
  1762. }
  1763. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1764. bool same_value(Value lhs, Value rhs)
  1765. {
  1766. // 1. If Type(x) is different from Type(y), return false.
  1767. if (!same_type_for_equality(lhs, rhs))
  1768. return false;
  1769. // 2. If x is a Number, then
  1770. if (lhs.is_number()) {
  1771. // a. Return Number::sameValue(x, y).
  1772. // 6.1.6.1.14 Number::sameValue ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-sameValue
  1773. // 1. If x is NaN and y is NaN, return true.
  1774. if (lhs.is_nan() && rhs.is_nan())
  1775. return true;
  1776. // 2. If x is +0𝔽 and y is -0𝔽, return false.
  1777. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1778. return false;
  1779. // 3. If x is -0𝔽 and y is +0𝔽, return false.
  1780. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1781. return false;
  1782. // 4. If x is the same Number value as y, return true.
  1783. // 5. Return false.
  1784. return lhs.as_double() == rhs.as_double();
  1785. }
  1786. // 3. Return SameValueNonNumber(x, y).
  1787. return same_value_non_number(lhs, rhs);
  1788. }
  1789. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1790. bool same_value_zero(Value lhs, Value rhs)
  1791. {
  1792. // 1. If Type(x) is different from Type(y), return false.
  1793. if (!same_type_for_equality(lhs, rhs))
  1794. return false;
  1795. // 2. If x is a Number, then
  1796. if (lhs.is_number()) {
  1797. // a. Return Number::sameValueZero(x, y).
  1798. if (lhs.is_nan() && rhs.is_nan())
  1799. return true;
  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.12 SameValueNonNumber ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1806. bool same_value_non_number(Value lhs, Value rhs)
  1807. {
  1808. // 1. Assert: Type(x) is the same as Type(y).
  1809. VERIFY(same_type_for_equality(lhs, rhs));
  1810. VERIFY(!lhs.is_number());
  1811. // 2. If x is a BigInt, then
  1812. if (lhs.is_bigint()) {
  1813. // a. Return BigInt::equal(x, y).
  1814. // 6.1.6.2.13 BigInt::equal ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-equal
  1815. // 1. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1816. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1817. }
  1818. // 5. If x is a String, then
  1819. if (lhs.is_string()) {
  1820. // 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.
  1821. // FIXME: Propagate this error.
  1822. return MUST(lhs.as_string().deprecated_string()) == MUST(rhs.as_string().deprecated_string());
  1823. }
  1824. // 3. If x is undefined, return true.
  1825. // 4. If x is null, return true.
  1826. // 6. If x is a Boolean, then
  1827. // a. If x and y are both true or both false, return true; otherwise, return false.
  1828. // 7. If x is a Symbol, then
  1829. // a. If x and y are both the same Symbol value, return true; otherwise, return false.
  1830. // 8. If x and y are the same Object value, return true. Otherwise, return false.
  1831. // NOTE: All the options above will have the exact same bit representation in Value, so we can directly compare the bits.
  1832. return lhs.m_value.encoded == rhs.m_value.encoded;
  1833. }
  1834. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1835. bool is_strictly_equal(Value lhs, Value rhs)
  1836. {
  1837. // 1. If Type(x) is different from Type(y), return false.
  1838. if (!same_type_for_equality(lhs, rhs))
  1839. return false;
  1840. // 2. If x is a Number, then
  1841. if (lhs.is_number()) {
  1842. // a. Return Number::equal(x, y).
  1843. // 6.1.6.1.13 Number::equal ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-number-equal
  1844. // 1. If x is NaN, return false.
  1845. // 2. If y is NaN, return false.
  1846. if (lhs.is_nan() || rhs.is_nan())
  1847. return false;
  1848. // 3. If x is the same Number value as y, return true.
  1849. // 4. If x is +0𝔽 and y is -0𝔽, return true.
  1850. // 5. If x is -0𝔽 and y is +0𝔽, return true.
  1851. if (lhs.as_double() == rhs.as_double())
  1852. return true;
  1853. // 6. Return false.
  1854. return false;
  1855. }
  1856. // 3. Return SameValueNonNumber(x, y).
  1857. return same_value_non_number(lhs, rhs);
  1858. }
  1859. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1860. ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs)
  1861. {
  1862. // 1. If Type(x) is the same as Type(y), then
  1863. if (same_type_for_equality(lhs, rhs)) {
  1864. // a. Return IsStrictlyEqual(x, y).
  1865. return is_strictly_equal(lhs, rhs);
  1866. }
  1867. // 2. If x is null and y is undefined, return true.
  1868. // 3. If x is undefined and y is null, return true.
  1869. if (lhs.is_nullish() && rhs.is_nullish())
  1870. return true;
  1871. // 4. NOTE: This step is replaced in section B.3.6.2.
  1872. // B.3.6.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1873. // 4. Perform the following steps:
  1874. // a. If Type(x) is Object and x has an [[IsHTMLDDA]] internal slot and y is either null or undefined, return true.
  1875. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1876. return true;
  1877. // b. If x is either null or undefined and Type(y) is Object and y has an [[IsHTMLDDA]] internal slot, return true.
  1878. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1879. return true;
  1880. // == End of B.3.6.2 ==
  1881. // 5. If Type(x) is Number and Type(y) is String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1882. if (lhs.is_number() && rhs.is_string())
  1883. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1884. // 6. If Type(x) is String and Type(y) is Number, return ! IsLooselyEqual(! ToNumber(x), y).
  1885. if (lhs.is_string() && rhs.is_number())
  1886. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1887. // 7. If Type(x) is BigInt and Type(y) is String, then
  1888. if (lhs.is_bigint() && rhs.is_string()) {
  1889. // a. Let n be StringToBigInt(y).
  1890. auto bigint = string_to_bigint(vm, TRY(rhs.as_string().deprecated_string()));
  1891. // b. If n is undefined, return false.
  1892. if (!bigint.has_value())
  1893. return false;
  1894. // c. Return ! IsLooselyEqual(x, n).
  1895. return is_loosely_equal(vm, lhs, *bigint);
  1896. }
  1897. // 8. If Type(x) is String and Type(y) is BigInt, return ! IsLooselyEqual(y, x).
  1898. if (lhs.is_string() && rhs.is_bigint())
  1899. return is_loosely_equal(vm, rhs, lhs);
  1900. // 9. If Type(x) is Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  1901. if (lhs.is_boolean())
  1902. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1903. // 10. If Type(y) is Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1904. if (rhs.is_boolean())
  1905. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1906. // 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  1907. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1908. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1909. return is_loosely_equal(vm, lhs, rhs_primitive);
  1910. }
  1911. // 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  1912. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || rhs.is_bigint() || rhs.is_symbol())) {
  1913. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1914. return is_loosely_equal(vm, lhs_primitive, rhs);
  1915. }
  1916. // 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
  1917. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1918. // a. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false.
  1919. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1920. return false;
  1921. // b. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1922. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1923. return false;
  1924. VERIFY(!lhs.is_nan() && !rhs.is_nan());
  1925. auto& number_side = lhs.is_number() ? lhs : rhs;
  1926. auto& bigint_side = lhs.is_number() ? rhs : lhs;
  1927. return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt;
  1928. }
  1929. // 14. Return false.
  1930. return false;
  1931. }
  1932. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1933. ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left_first)
  1934. {
  1935. Value x_primitive;
  1936. Value y_primitive;
  1937. // 1. If the LeftFirst flag is true, then
  1938. if (left_first) {
  1939. // a. Let px be ? ToPrimitive(x, number).
  1940. x_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1941. // b. Let py be ? ToPrimitive(y, number).
  1942. y_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1943. } else {
  1944. // a. NOTE: The order of evaluation needs to be reversed to preserve left to right evaluation.
  1945. // b. Let py be ? ToPrimitive(y, number).
  1946. y_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1947. // c. Let px be ? ToPrimitive(x, number).
  1948. x_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1949. }
  1950. // 3. If px is a String and py is a String, then
  1951. if (x_primitive.is_string() && y_primitive.is_string()) {
  1952. auto x_string = TRY(x_primitive.as_string().deprecated_string());
  1953. auto y_string = TRY(y_primitive.as_string().deprecated_string());
  1954. Utf8View x_code_points { x_string };
  1955. Utf8View y_code_points { y_string };
  1956. // a. Let lx be the length of px.
  1957. // b. Let ly be the length of py.
  1958. // c. For each integer i such that 0 ≤ i < min(lx, ly), in ascending order, do
  1959. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1960. k != x_code_points.end() && l != y_code_points.end();
  1961. ++k, ++l) {
  1962. // i. Let cx be the integer that is the numeric value of the code unit at index i within px.
  1963. // ii. Let cy be the integer that is the numeric value of the code unit at index i within py.
  1964. if (*k != *l) {
  1965. // iii. If cx < cy, return true.
  1966. if (*k < *l) {
  1967. return TriState::True;
  1968. }
  1969. // iv. If cx > cy, return false.
  1970. else {
  1971. return TriState::False;
  1972. }
  1973. }
  1974. }
  1975. // d. If lx < ly, return true. Otherwise, return false.
  1976. return x_code_points.length() < y_code_points.length()
  1977. ? TriState::True
  1978. : TriState::False;
  1979. }
  1980. // 4. Else,
  1981. // a. If px is a BigInt and py is a String, then
  1982. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1983. // i. Let ny be StringToBigInt(py).
  1984. auto y_bigint = string_to_bigint(vm, TRY(y_primitive.as_string().deprecated_string()));
  1985. // ii. If ny is undefined, return undefined.
  1986. if (!y_bigint.has_value())
  1987. return TriState::Unknown;
  1988. // iii. Return BigInt::lessThan(px, ny).
  1989. if (x_primitive.as_bigint().big_integer() < (*y_bigint)->big_integer())
  1990. return TriState::True;
  1991. return TriState::False;
  1992. }
  1993. // b. If px is a String and py is a BigInt, then
  1994. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1995. // i. Let nx be StringToBigInt(px).
  1996. auto x_bigint = string_to_bigint(vm, TRY(x_primitive.as_string().deprecated_string()));
  1997. // ii. If nx is undefined, return undefined.
  1998. if (!x_bigint.has_value())
  1999. return TriState::Unknown;
  2000. // iii. Return BigInt::lessThan(nx, py).
  2001. if ((*x_bigint)->big_integer() < y_primitive.as_bigint().big_integer())
  2002. return TriState::True;
  2003. return TriState::False;
  2004. }
  2005. // c. NOTE: Because px and py are primitive values, evaluation order is not important.
  2006. // d. Let nx be ? ToNumeric(px).
  2007. auto x_numeric = TRY(x_primitive.to_numeric(vm));
  2008. // e. Let ny be ? ToNumeric(py).
  2009. auto y_numeric = TRY(y_primitive.to_numeric(vm));
  2010. // h. If nx or ny is NaN, return undefined.
  2011. if (x_numeric.is_nan() || y_numeric.is_nan())
  2012. return TriState::Unknown;
  2013. // i. If nx is -∞𝔽 or ny is +∞𝔽, return true.
  2014. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  2015. return TriState::False;
  2016. // j. If nx is +∞𝔽 or ny is -∞𝔽, return false.
  2017. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  2018. return TriState::True;
  2019. // f. If Type(nx) is the same as Type(ny), then
  2020. // i. If nx is a Number, then
  2021. if (x_numeric.is_number() && y_numeric.is_number()) {
  2022. // 1. Return Number::lessThan(nx, ny).
  2023. if (x_numeric.as_double() < y_numeric.as_double())
  2024. return TriState::True;
  2025. else
  2026. return TriState::False;
  2027. }
  2028. // ii. Else,
  2029. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  2030. // 1. Assert: nx is a BigInt.
  2031. // 2. Return BigInt::lessThan(nx, ny).
  2032. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  2033. return TriState::True;
  2034. else
  2035. return TriState::False;
  2036. }
  2037. // g. Assert: nx is a BigInt and ny is a Number, or nx is a Number and ny is a BigInt.
  2038. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  2039. // k. If ℝ(nx) < ℝ(ny), return true; otherwise return false.
  2040. bool x_lower_than_y;
  2041. VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan());
  2042. if (x_numeric.is_number()) {
  2043. x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double())
  2044. == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt;
  2045. } else {
  2046. x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double())
  2047. == Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt;
  2048. }
  2049. if (x_lower_than_y)
  2050. return TriState::True;
  2051. else
  2052. return TriState::False;
  2053. }
  2054. // 7.3.21 Invoke ( V, P [ , argumentsList ] ), https://tc39.es/ecma262/#sec-invoke
  2055. ThrowCompletionOr<Value> Value::invoke_internal(VM& vm, PropertyKey const& property_key, Optional<MarkedVector<Value>> arguments)
  2056. {
  2057. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  2058. // 2. Let func be ? GetV(V, P).
  2059. auto function = TRY(get(vm, property_key));
  2060. // 3. Return ? Call(func, V, argumentsList).
  2061. return call(vm, function, *this, move(arguments));
  2062. }
  2063. }