Value.cpp 95 KB

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