Value.cpp 95 KB

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