Value.cpp 93 KB

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