Value.cpp 94 KB

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