Value.cpp 94 KB

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