Value.cpp 93 KB

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