Value.cpp 95 KB

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