Value.cpp 95 KB

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