Value.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/AllOf.h>
  9. #include <AK/Assertions.h>
  10. #include <AK/CharacterTypes.h>
  11. #include <AK/DeprecatedString.h>
  12. #include <AK/FloatingPointStringConversions.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/StringFloatingPointConversions.h>
  15. #include <AK/Utf8View.h>
  16. #include <LibCrypto/BigInt/SignedBigInteger.h>
  17. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  18. #include <LibJS/Runtime/AbstractOperations.h>
  19. #include <LibJS/Runtime/Accessor.h>
  20. #include <LibJS/Runtime/Array.h>
  21. #include <LibJS/Runtime/BigInt.h>
  22. #include <LibJS/Runtime/BigIntObject.h>
  23. #include <LibJS/Runtime/BooleanObject.h>
  24. #include <LibJS/Runtime/BoundFunction.h>
  25. #include <LibJS/Runtime/Completion.h>
  26. #include <LibJS/Runtime/Error.h>
  27. #include <LibJS/Runtime/FunctionObject.h>
  28. #include <LibJS/Runtime/GlobalObject.h>
  29. #include <LibJS/Runtime/NativeFunction.h>
  30. #include <LibJS/Runtime/NumberObject.h>
  31. #include <LibJS/Runtime/Object.h>
  32. #include <LibJS/Runtime/PrimitiveString.h>
  33. #include <LibJS/Runtime/ProxyObject.h>
  34. #include <LibJS/Runtime/RegExpObject.h>
  35. #include <LibJS/Runtime/StringObject.h>
  36. #include <LibJS/Runtime/StringPrototype.h>
  37. #include <LibJS/Runtime/SymbolObject.h>
  38. #include <LibJS/Runtime/VM.h>
  39. #include <LibJS/Runtime/Value.h>
  40. #include <math.h>
  41. namespace JS {
  42. static inline bool same_type_for_equality(Value const& lhs, Value const& rhs)
  43. {
  44. // If the top two bytes are identical then either:
  45. // both are NaN boxed Values with the same type
  46. // or they are doubles which happen to have the same top bytes.
  47. if ((lhs.encoded() & TAG_EXTRACTION) == (rhs.encoded() & TAG_EXTRACTION))
  48. return true;
  49. if (lhs.is_number() && rhs.is_number())
  50. return true;
  51. // One of the Values is not a number and they do not have the same tag
  52. return false;
  53. }
  54. static const Crypto::SignedBigInteger BIGINT_ZERO { 0 };
  55. ALWAYS_INLINE bool both_number(Value const& lhs, Value const& rhs)
  56. {
  57. return lhs.is_number() && rhs.is_number();
  58. }
  59. ALWAYS_INLINE bool both_bigint(Value const& lhs, Value const& rhs)
  60. {
  61. return lhs.is_bigint() && rhs.is_bigint();
  62. }
  63. // 6.1.6.1.20 Number::toString ( x ), https://tc39.es/ecma262/#sec-numeric-types-number-tostring
  64. // Implementation for radix = 10
  65. DeprecatedString number_to_string(double d, NumberToStringMode mode)
  66. {
  67. auto convert_to_decimal_digits_array = [](auto x, auto& digits, auto& length) {
  68. for (; x; x /= 10)
  69. digits[length++] = x % 10 | '0';
  70. for (i32 i = 0; 2 * i + 1 < length; ++i)
  71. swap(digits[i], digits[length - i - 1]);
  72. };
  73. // 1. If x is NaN, return "NaN".
  74. if (isnan(d))
  75. return "NaN";
  76. // 2. If x is +0𝔽 or -0𝔽, return "0".
  77. if (d == +0.0 || d == -0.0)
  78. return "0";
  79. // 4. If x is +∞𝔽, return "Infinity".
  80. if (isinf(d)) {
  81. if (d > 0)
  82. return "Infinity";
  83. else
  84. return "-Infinity";
  85. }
  86. StringBuilder builder;
  87. // 5. Let n, k, and s be integers such that k ≥ 1, radix ^ (k - 1) ≤ s < radix ^ k,
  88. // 𝔽(s × radix ^ (n - k)) is x, and k is as small as possible. Note that k is the number of
  89. // digits in the representation of s using radix radix, that s is not divisible by radix, and
  90. // that the least significant digit of s is not necessarily uniquely determined by these criteria.
  91. //
  92. // Note: guarantees provided by convert_floating_point_to_decimal_exponential_form satisfy
  93. // requirements of NOTE 2.
  94. auto [sign, mantissa, exponent] = convert_floating_point_to_decimal_exponential_form(d);
  95. i32 k = 0;
  96. AK::Array<char, 20> mantissa_digits;
  97. convert_to_decimal_digits_array(mantissa, mantissa_digits, k);
  98. i32 n = exponent + k; // s = mantissa
  99. // 3. If x < -0𝔽, return the string-concatenation of "-" and Number::toString(-x, radix).
  100. if (sign)
  101. builder.append('-');
  102. // Non-standard: Intl needs number-to-string conversions for extremely large numbers without any
  103. // exponential formatting, as it will handle such formatting itself in a locale-aware way.
  104. bool force_no_exponent = mode == NumberToStringMode::WithoutExponent;
  105. // 6. If radix ≠ 10 or n is in the inclusive interval from -5 to 21, then
  106. if ((n >= -5 && n <= 21) || force_no_exponent) {
  107. // a. If n ≥ k, then
  108. if (n >= k) {
  109. // i. Return the string-concatenation of:
  110. // the code units of the k digits of the representation of s using radix radix
  111. builder.append(mantissa_digits.data(), k);
  112. // n - k occurrences of the code unit 0x0030 (DIGIT ZERO)
  113. builder.append_repeated('0', n - k);
  114. // b. Else if n > 0, then
  115. } else if (n > 0) {
  116. // i. Return the string-concatenation of:
  117. // the code units of the most significant n digits of the representation of s using radix radix
  118. builder.append(mantissa_digits.data(), n);
  119. // the code unit 0x002E (FULL STOP)
  120. builder.append('.');
  121. // the code units of the remaining k - n digits of the representation of s using radix radix
  122. builder.append(mantissa_digits.data() + n, k - n);
  123. // c. Else,
  124. } else {
  125. // i. Assert: n ≤ 0.
  126. VERIFY(n <= 0);
  127. // ii. Return the string-concatenation of:
  128. // the code unit 0x0030 (DIGIT ZERO)
  129. builder.append('0');
  130. // the code unit 0x002E (FULL STOP)
  131. builder.append('.');
  132. // -n occurrences of the code unit 0x0030 (DIGIT ZERO)
  133. builder.append_repeated('0', -n);
  134. // the code units of the k digits of the representation of s using radix radix
  135. builder.append(mantissa_digits.data(), k);
  136. }
  137. return builder.to_deprecated_string();
  138. }
  139. // 7. NOTE: In this case, the input will be represented using scientific E notation, such as 1.2e+3.
  140. // 9. If n < 0, then
  141. // a. Let exponentSign be the code unit 0x002D (HYPHEN-MINUS).
  142. // 10. Else,
  143. // a. Let exponentSign be the code unit 0x002B (PLUS SIGN).
  144. char exponent_sign = n < 0 ? '-' : '+';
  145. AK::Array<char, 5> exponent_digits;
  146. i32 exponent_length = 0;
  147. convert_to_decimal_digits_array(abs(n - 1), exponent_digits, exponent_length);
  148. // 11. If k is 1, then
  149. if (k == 1) {
  150. // a. Return the string-concatenation of:
  151. // the code unit of the single digit of s
  152. builder.append(mantissa_digits[0]);
  153. // the code unit 0x0065 (LATIN SMALL LETTER E)
  154. builder.append('e');
  155. // exponentSign
  156. builder.append(exponent_sign);
  157. // the code units of the decimal representation of abs(n - 1)
  158. builder.append(exponent_digits.data(), exponent_length);
  159. return builder.to_deprecated_string();
  160. }
  161. // 12. Return the string-concatenation of:
  162. // the code unit of the most significant digit of the decimal representation of s
  163. builder.append(mantissa_digits[0]);
  164. // the code unit 0x002E (FULL STOP)
  165. builder.append('.');
  166. // the code units of the remaining k - 1 digits of the decimal representation of s
  167. builder.append(mantissa_digits.data() + 1, k - 1);
  168. // the code unit 0x0065 (LATIN SMALL LETTER E)
  169. builder.append('e');
  170. // exponentSign
  171. builder.append(exponent_sign);
  172. // the code units of the decimal representation of abs(n - 1)
  173. builder.append(exponent_digits.data(), exponent_length);
  174. return builder.to_deprecated_string();
  175. }
  176. // 7.2.2 IsArray ( argument ), https://tc39.es/ecma262/#sec-isarray
  177. ThrowCompletionOr<bool> Value::is_array(VM& vm) const
  178. {
  179. // 1. If argument is not an Object, return false.
  180. if (!is_object())
  181. return false;
  182. auto const& object = as_object();
  183. // 2. If argument is an Array exotic object, return true.
  184. if (is<Array>(object))
  185. return true;
  186. // 3. If argument is a Proxy exotic object, then
  187. if (is<ProxyObject>(object)) {
  188. auto const& proxy = static_cast<ProxyObject const&>(object);
  189. // a. If argument.[[ProxyHandler]] is null, throw a TypeError exception.
  190. if (proxy.is_revoked())
  191. return vm.throw_completion<TypeError>(ErrorType::ProxyRevoked);
  192. // b. Let target be argument.[[ProxyTarget]].
  193. auto const& target = proxy.target();
  194. // c. Return ? IsArray(target).
  195. return Value(&target).is_array(vm);
  196. }
  197. // 4. Return false.
  198. return false;
  199. }
  200. Array& Value::as_array()
  201. {
  202. VERIFY(is_object() && is<Array>(as_object()));
  203. return static_cast<Array&>(as_object());
  204. }
  205. // 7.2.3 IsCallable ( argument ), https://tc39.es/ecma262/#sec-iscallable
  206. bool Value::is_function() const
  207. {
  208. return is_object() && as_object().is_function();
  209. }
  210. FunctionObject& Value::as_function()
  211. {
  212. VERIFY(is_function());
  213. return static_cast<FunctionObject&>(as_object());
  214. }
  215. FunctionObject const& Value::as_function() const
  216. {
  217. VERIFY(is_function());
  218. return static_cast<FunctionObject const&>(as_object());
  219. }
  220. // 7.2.4 IsConstructor ( argument ), https://tc39.es/ecma262/#sec-isconstructor
  221. bool Value::is_constructor() const
  222. {
  223. // 1. If Type(argument) is not Object, return false.
  224. if (!is_function())
  225. return false;
  226. // 2. If argument has a [[Construct]] internal method, return true.
  227. if (as_function().has_constructor())
  228. return true;
  229. // 3. Return false.
  230. return false;
  231. }
  232. // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
  233. ThrowCompletionOr<bool> Value::is_regexp(VM& vm) const
  234. {
  235. if (!is_object())
  236. return false;
  237. auto matcher = TRY(as_object().get(*vm.well_known_symbol_match()));
  238. if (!matcher.is_undefined())
  239. return matcher.to_boolean();
  240. return is<RegExpObject>(as_object());
  241. }
  242. // 13.5.3 The typeof Operator, https://tc39.es/ecma262/#sec-typeof-operator
  243. DeprecatedString Value::typeof() const
  244. {
  245. if (is_number())
  246. return "number";
  247. switch (m_value.tag) {
  248. case UNDEFINED_TAG:
  249. return "undefined";
  250. case NULL_TAG:
  251. return "object";
  252. case STRING_TAG:
  253. return "string";
  254. case OBJECT_TAG:
  255. // B.3.7.3 Changes to the typeof Operator, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-typeof
  256. if (as_object().is_htmldda())
  257. return "undefined";
  258. if (is_function())
  259. return "function";
  260. return "object";
  261. case BOOLEAN_TAG:
  262. return "boolean";
  263. case SYMBOL_TAG:
  264. return "symbol";
  265. case BIGINT_TAG:
  266. return "bigint";
  267. default:
  268. VERIFY_NOT_REACHED();
  269. }
  270. }
  271. DeprecatedString Value::to_string_without_side_effects() const
  272. {
  273. if (is_double())
  274. return number_to_string(m_value.as_double);
  275. switch (m_value.tag) {
  276. case UNDEFINED_TAG:
  277. return "undefined";
  278. case NULL_TAG:
  279. return "null";
  280. case BOOLEAN_TAG:
  281. return as_bool() ? "true" : "false";
  282. case INT32_TAG:
  283. return DeprecatedString::number(as_i32());
  284. case STRING_TAG:
  285. return as_string().deprecated_string();
  286. case SYMBOL_TAG:
  287. return as_symbol().to_deprecated_string();
  288. case BIGINT_TAG:
  289. return as_bigint().to_deprecated_string();
  290. case OBJECT_TAG:
  291. return DeprecatedString::formatted("[object {}]", as_object().class_name());
  292. case ACCESSOR_TAG:
  293. return "<accessor>";
  294. default:
  295. VERIFY_NOT_REACHED();
  296. }
  297. }
  298. ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm)
  299. {
  300. if (is_string())
  301. return &as_string();
  302. auto string = TRY(to_string(vm));
  303. return PrimitiveString::create(vm, string).ptr();
  304. }
  305. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  306. ThrowCompletionOr<DeprecatedString> Value::to_string(VM& vm) const
  307. {
  308. if (is_double())
  309. return number_to_string(m_value.as_double);
  310. switch (m_value.tag) {
  311. case UNDEFINED_TAG:
  312. return "undefined"sv;
  313. case NULL_TAG:
  314. return "null"sv;
  315. case BOOLEAN_TAG:
  316. return as_bool() ? "true"sv : "false"sv;
  317. case INT32_TAG:
  318. return DeprecatedString::number(as_i32());
  319. case STRING_TAG:
  320. return as_string().deprecated_string();
  321. case SYMBOL_TAG:
  322. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "string");
  323. case BIGINT_TAG:
  324. return as_bigint().big_integer().to_base(10);
  325. case OBJECT_TAG: {
  326. auto primitive_value = TRY(to_primitive(vm, PreferredType::String));
  327. return primitive_value.to_string(vm);
  328. }
  329. default:
  330. VERIFY_NOT_REACHED();
  331. }
  332. }
  333. ThrowCompletionOr<Utf16String> Value::to_utf16_string(VM& vm) const
  334. {
  335. if (is_string())
  336. return as_string().utf16_string();
  337. auto utf8_string = TRY(to_string(vm));
  338. return Utf16String(utf8_string);
  339. }
  340. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  341. bool Value::to_boolean() const
  342. {
  343. if (is_double()) {
  344. if (is_nan())
  345. return false;
  346. return m_value.as_double != 0;
  347. }
  348. switch (m_value.tag) {
  349. case UNDEFINED_TAG:
  350. case NULL_TAG:
  351. return false;
  352. case BOOLEAN_TAG:
  353. return as_bool();
  354. case INT32_TAG:
  355. return as_i32() != 0;
  356. case STRING_TAG:
  357. return !as_string().is_empty();
  358. case SYMBOL_TAG:
  359. return true;
  360. case BIGINT_TAG:
  361. return as_bigint().big_integer() != BIGINT_ZERO;
  362. case OBJECT_TAG:
  363. // B.3.7.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  364. if (as_object().is_htmldda())
  365. return false;
  366. return true;
  367. default:
  368. VERIFY_NOT_REACHED();
  369. }
  370. }
  371. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  372. ThrowCompletionOr<Value> Value::to_primitive(VM& vm, PreferredType preferred_type) const
  373. {
  374. auto get_hint_for_preferred_type = [&]() -> DeprecatedString {
  375. switch (preferred_type) {
  376. case PreferredType::Default:
  377. return "default";
  378. case PreferredType::String:
  379. return "string";
  380. case PreferredType::Number:
  381. return "number";
  382. default:
  383. VERIFY_NOT_REACHED();
  384. }
  385. };
  386. if (is_object()) {
  387. auto to_primitive_method = TRY(get_method(vm, *vm.well_known_symbol_to_primitive()));
  388. if (to_primitive_method) {
  389. auto hint = get_hint_for_preferred_type();
  390. auto result = TRY(call(vm, *to_primitive_method, *this, PrimitiveString::create(vm, hint)));
  391. if (!result.is_object())
  392. return result;
  393. return vm.throw_completion<TypeError>(ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  394. }
  395. if (preferred_type == PreferredType::Default)
  396. preferred_type = PreferredType::Number;
  397. return as_object().ordinary_to_primitive(preferred_type);
  398. }
  399. return *this;
  400. }
  401. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  402. ThrowCompletionOr<Object*> Value::to_object(VM& vm) const
  403. {
  404. auto& realm = *vm.current_realm();
  405. VERIFY(!is_empty());
  406. if (is_number())
  407. return NumberObject::create(realm, as_double());
  408. switch (m_value.tag) {
  409. case UNDEFINED_TAG:
  410. case NULL_TAG:
  411. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  412. case BOOLEAN_TAG:
  413. return BooleanObject::create(realm, as_bool());
  414. case STRING_TAG:
  415. return StringObject::create(realm, const_cast<JS::PrimitiveString&>(as_string()), *realm.intrinsics().string_prototype());
  416. case SYMBOL_TAG:
  417. return SymbolObject::create(realm, const_cast<JS::Symbol&>(as_symbol()));
  418. case BIGINT_TAG:
  419. return BigIntObject::create(realm, const_cast<JS::BigInt&>(as_bigint()));
  420. case OBJECT_TAG:
  421. return &const_cast<Object&>(as_object());
  422. default:
  423. VERIFY_NOT_REACHED();
  424. }
  425. }
  426. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  427. FLATTEN ThrowCompletionOr<Value> Value::to_numeric(VM& vm) const
  428. {
  429. auto primitive = TRY(to_primitive(vm, Value::PreferredType::Number));
  430. if (primitive.is_bigint())
  431. return primitive;
  432. return primitive.to_number(vm);
  433. }
  434. constexpr bool is_ascii_number(u32 code_point)
  435. {
  436. return is_ascii_digit(code_point) || code_point == '.' || (code_point == 'e' || code_point == 'E') || code_point == '+' || code_point == '-';
  437. }
  438. struct NumberParseResult {
  439. StringView literal;
  440. u8 base;
  441. };
  442. static Optional<NumberParseResult> parse_number_text(StringView text)
  443. {
  444. NumberParseResult result {};
  445. auto check_prefix = [&](auto lower_prefix, auto upper_prefix) {
  446. if (text.length() <= 2)
  447. return false;
  448. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  449. return false;
  450. return true;
  451. };
  452. // https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
  453. if (check_prefix("0b"sv, "0B"sv)) {
  454. if (!all_of(text.substring_view(2), is_ascii_binary_digit))
  455. return {};
  456. result.literal = text.substring_view(2);
  457. result.base = 2;
  458. } else if (check_prefix("0o"sv, "0O"sv)) {
  459. if (!all_of(text.substring_view(2), is_ascii_octal_digit))
  460. return {};
  461. result.literal = text.substring_view(2);
  462. result.base = 8;
  463. } else if (check_prefix("0x"sv, "0X"sv)) {
  464. if (!all_of(text.substring_view(2), is_ascii_hex_digit))
  465. return {};
  466. result.literal = text.substring_view(2);
  467. result.base = 16;
  468. } else {
  469. if (!all_of(text, is_ascii_number))
  470. return {};
  471. result.literal = text;
  472. result.base = 10;
  473. }
  474. return result;
  475. }
  476. // 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber
  477. Optional<Value> string_to_number(StringView string)
  478. {
  479. // 1. Let text be StringToCodePoints(str).
  480. DeprecatedString text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  481. // 2. Let literal be ParseText(text, StringNumericLiteral).
  482. if (text.is_empty())
  483. return Value(0);
  484. if (text == "Infinity" || text == "+Infinity")
  485. return js_infinity();
  486. if (text == "-Infinity")
  487. return js_negative_infinity();
  488. auto result = parse_number_text(text);
  489. // 3. If literal is a List of errors, return NaN.
  490. if (!result.has_value())
  491. return js_nan();
  492. // 4. Return StringNumericValue of literal.
  493. if (result->base != 10) {
  494. auto bigint = Crypto::UnsignedBigInteger::from_base(result->base, result->literal);
  495. return Value(bigint.to_double());
  496. }
  497. auto maybe_double = text.to_double(AK::TrimWhitespace::No);
  498. if (!maybe_double.has_value())
  499. return js_nan();
  500. return Value(*maybe_double);
  501. }
  502. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  503. ThrowCompletionOr<Value> Value::to_number(VM& vm) const
  504. {
  505. VERIFY(!is_empty());
  506. if (is_number())
  507. return *this;
  508. switch (m_value.tag) {
  509. case UNDEFINED_TAG:
  510. return js_nan();
  511. case NULL_TAG:
  512. return Value(0);
  513. case BOOLEAN_TAG:
  514. return Value(as_bool() ? 1 : 0);
  515. case STRING_TAG:
  516. return string_to_number(as_string().deprecated_string().view());
  517. case SYMBOL_TAG:
  518. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "number");
  519. case BIGINT_TAG:
  520. return vm.throw_completion<TypeError>(ErrorType::Convert, "BigInt", "number");
  521. case OBJECT_TAG: {
  522. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  523. return primitive.to_number(vm);
  524. }
  525. default:
  526. VERIFY_NOT_REACHED();
  527. }
  528. }
  529. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string);
  530. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  531. ThrowCompletionOr<BigInt*> Value::to_bigint(VM& vm) const
  532. {
  533. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  534. VERIFY(!primitive.is_empty());
  535. if (primitive.is_number())
  536. return vm.throw_completion<TypeError>(ErrorType::Convert, "number", "BigInt");
  537. switch (primitive.m_value.tag) {
  538. case UNDEFINED_TAG:
  539. return vm.throw_completion<TypeError>(ErrorType::Convert, "undefined", "BigInt");
  540. case NULL_TAG:
  541. return vm.throw_completion<TypeError>(ErrorType::Convert, "null", "BigInt");
  542. case BOOLEAN_TAG: {
  543. auto value = primitive.as_bool() ? 1 : 0;
  544. return BigInt::create(vm, Crypto::SignedBigInteger { value }).ptr();
  545. }
  546. case BIGINT_TAG:
  547. return &primitive.as_bigint();
  548. case STRING_TAG: {
  549. // 1. Let n be ! StringToBigInt(prim).
  550. auto bigint = string_to_bigint(vm, primitive.as_string().deprecated_string());
  551. // 2. If n is undefined, throw a SyntaxError exception.
  552. if (!bigint.has_value())
  553. return vm.throw_completion<SyntaxError>(ErrorType::BigIntInvalidValue, primitive);
  554. // 3. Return n.
  555. return bigint.release_value();
  556. }
  557. case SYMBOL_TAG:
  558. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "BigInt");
  559. default:
  560. VERIFY_NOT_REACHED();
  561. }
  562. }
  563. struct BigIntParseResult {
  564. StringView literal;
  565. u8 base { 10 };
  566. bool is_negative { false };
  567. };
  568. static Optional<BigIntParseResult> parse_bigint_text(StringView text)
  569. {
  570. BigIntParseResult result {};
  571. auto parse_for_prefixed_base = [&](auto lower_prefix, auto upper_prefix, auto validator) {
  572. if (text.length() <= 2)
  573. return false;
  574. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  575. return false;
  576. return all_of(text.substring_view(2), validator);
  577. };
  578. if (parse_for_prefixed_base("0b"sv, "0B"sv, is_ascii_binary_digit)) {
  579. result.literal = text.substring_view(2);
  580. result.base = 2;
  581. } else if (parse_for_prefixed_base("0o"sv, "0O"sv, is_ascii_octal_digit)) {
  582. result.literal = text.substring_view(2);
  583. result.base = 8;
  584. } else if (parse_for_prefixed_base("0x"sv, "0X"sv, is_ascii_hex_digit)) {
  585. result.literal = text.substring_view(2);
  586. result.base = 16;
  587. } else {
  588. if (text.starts_with('-')) {
  589. text = text.substring_view(1);
  590. result.is_negative = true;
  591. } else if (text.starts_with('+')) {
  592. text = text.substring_view(1);
  593. }
  594. if (!all_of(text, is_ascii_digit))
  595. return {};
  596. result.literal = text;
  597. result.base = 10;
  598. }
  599. return result;
  600. }
  601. // 7.1.14 StringToBigInt ( str ), https://tc39.es/ecma262/#sec-stringtobigint
  602. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string)
  603. {
  604. // 1. Let text be StringToCodePoints(str).
  605. auto text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  606. // 2. Let literal be ParseText(text, StringIntegerLiteral).
  607. auto result = parse_bigint_text(text);
  608. // 3. If literal is a List of errors, return undefined.
  609. if (!result.has_value())
  610. return {};
  611. // 4. Let mv be the MV of literal.
  612. // 5. Assert: mv is an integer.
  613. auto bigint = Crypto::SignedBigInteger::from_base(result->base, result->literal);
  614. if (result->is_negative && (bigint != BIGINT_ZERO))
  615. bigint.negate();
  616. // 6. Return ℤ(mv).
  617. return BigInt::create(vm, move(bigint));
  618. }
  619. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/#sec-tobigint64
  620. ThrowCompletionOr<i64> Value::to_bigint_int64(VM& vm) const
  621. {
  622. auto* bigint = TRY(to_bigint(vm));
  623. return static_cast<i64>(bigint->big_integer().to_u64());
  624. }
  625. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/#sec-tobiguint64
  626. ThrowCompletionOr<u64> Value::to_bigint_uint64(VM& vm) const
  627. {
  628. auto* bigint = TRY(to_bigint(vm));
  629. return bigint->big_integer().to_u64();
  630. }
  631. ThrowCompletionOr<double> Value::to_double(VM& vm) const
  632. {
  633. return TRY(to_number(vm)).as_double();
  634. }
  635. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  636. ThrowCompletionOr<PropertyKey> Value::to_property_key(VM& vm) const
  637. {
  638. if (is_int32() && as_i32() >= 0)
  639. return PropertyKey { as_i32() };
  640. auto key = TRY(to_primitive(vm, PreferredType::String));
  641. if (key.is_symbol())
  642. return &key.as_symbol();
  643. return TRY(key.to_string(vm));
  644. }
  645. ThrowCompletionOr<i32> Value::to_i32_slow_case(VM& vm) const
  646. {
  647. VERIFY(!is_int32());
  648. double value = TRY(to_number(vm)).as_double();
  649. if (!isfinite(value) || value == 0)
  650. return 0;
  651. auto abs = fabs(value);
  652. auto int_val = floor(abs);
  653. if (signbit(value))
  654. int_val = -int_val;
  655. auto remainder = fmod(int_val, 4294967296.0);
  656. auto int32bit = remainder >= 0.0 ? remainder : remainder + 4294967296.0; // The notation “x modulo y” computes a value k of the same sign as y
  657. if (int32bit >= 2147483648.0)
  658. int32bit -= 4294967296.0;
  659. return static_cast<i32>(int32bit);
  660. }
  661. ThrowCompletionOr<i32> Value::to_i32(VM& vm) const
  662. {
  663. if (is_int32())
  664. return as_i32();
  665. return to_i32_slow_case(vm);
  666. }
  667. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  668. ThrowCompletionOr<u32> Value::to_u32(VM& vm) const
  669. {
  670. double value = TRY(to_number(vm)).as_double();
  671. if (!isfinite(value) || value == 0)
  672. return 0;
  673. auto int_val = floor(fabs(value));
  674. if (signbit(value))
  675. int_val = -int_val;
  676. auto int32bit = fmod(int_val, NumericLimits<u32>::max() + 1.0);
  677. // Cast to i64 here to ensure that the double --> u32 cast doesn't invoke undefined behavior
  678. // Otherwise, negative numbers cause a UBSAN warning.
  679. return static_cast<u32>(static_cast<i64>(int32bit));
  680. }
  681. // 7.1.8 ToInt16 ( argument ), https://tc39.es/ecma262/#sec-toint16
  682. ThrowCompletionOr<i16> Value::to_i16(VM& vm) const
  683. {
  684. double value = TRY(to_number(vm)).as_double();
  685. if (!isfinite(value) || value == 0)
  686. return 0;
  687. auto abs = fabs(value);
  688. auto int_val = floor(abs);
  689. if (signbit(value))
  690. int_val = -int_val;
  691. auto remainder = fmod(int_val, 65536.0);
  692. auto int16bit = remainder >= 0.0 ? remainder : remainder + 65536.0; // The notation “x modulo y” computes a value k of the same sign as y
  693. if (int16bit >= 32768.0)
  694. int16bit -= 65536.0;
  695. return static_cast<i16>(int16bit);
  696. }
  697. // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16
  698. ThrowCompletionOr<u16> Value::to_u16(VM& vm) const
  699. {
  700. double value = TRY(to_number(vm)).as_double();
  701. if (!isfinite(value) || value == 0)
  702. return 0;
  703. auto int_val = floor(fabs(value));
  704. if (signbit(value))
  705. int_val = -int_val;
  706. auto int16bit = fmod(int_val, NumericLimits<u16>::max() + 1.0);
  707. if (int16bit < 0)
  708. int16bit += NumericLimits<u16>::max() + 1.0;
  709. return static_cast<u16>(int16bit);
  710. }
  711. // 7.1.10 ToInt8 ( argument ), https://tc39.es/ecma262/#sec-toint8
  712. ThrowCompletionOr<i8> Value::to_i8(VM& vm) const
  713. {
  714. double value = TRY(to_number(vm)).as_double();
  715. if (!isfinite(value) || value == 0)
  716. return 0;
  717. auto abs = fabs(value);
  718. auto int_val = floor(abs);
  719. if (signbit(value))
  720. int_val = -int_val;
  721. auto remainder = fmod(int_val, 256.0);
  722. auto int8bit = remainder >= 0.0 ? remainder : remainder + 256.0; // The notation “x modulo y” computes a value k of the same sign as y
  723. if (int8bit >= 128.0)
  724. int8bit -= 256.0;
  725. return static_cast<i8>(int8bit);
  726. }
  727. // 7.1.11 ToUint8 ( argument ), https://tc39.es/ecma262/#sec-touint8
  728. ThrowCompletionOr<u8> Value::to_u8(VM& vm) const
  729. {
  730. double value = TRY(to_number(vm)).as_double();
  731. if (!isfinite(value) || value == 0)
  732. return 0;
  733. auto int_val = floor(fabs(value));
  734. if (signbit(value))
  735. int_val = -int_val;
  736. auto int8bit = fmod(int_val, NumericLimits<u8>::max() + 1.0);
  737. if (int8bit < 0)
  738. int8bit += NumericLimits<u8>::max() + 1.0;
  739. return static_cast<u8>(int8bit);
  740. }
  741. // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp
  742. ThrowCompletionOr<u8> Value::to_u8_clamp(VM& vm) const
  743. {
  744. auto number = TRY(to_number(vm));
  745. if (number.is_nan())
  746. return 0;
  747. double value = number.as_double();
  748. if (value <= 0.0)
  749. return 0;
  750. if (value >= 255.0)
  751. return 255;
  752. auto int_val = floor(value);
  753. if (int_val + 0.5 < value)
  754. return static_cast<u8>(int_val + 1.0);
  755. if (value < int_val + 0.5)
  756. return static_cast<u8>(int_val);
  757. if (fmod(int_val, 2.0) == 1.0)
  758. return static_cast<u8>(int_val + 1.0);
  759. return static_cast<u8>(int_val);
  760. }
  761. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  762. ThrowCompletionOr<size_t> Value::to_length(VM& vm) const
  763. {
  764. auto len = TRY(to_integer_or_infinity(vm));
  765. if (len <= 0)
  766. return 0;
  767. // FIXME: The spec says that this function's output range is 0 - 2^53-1. But we don't want to overflow the size_t.
  768. constexpr double length_limit = sizeof(void*) == 4 ? NumericLimits<size_t>::max() : MAX_ARRAY_LIKE_INDEX;
  769. return min(len, length_limit);
  770. }
  771. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  772. ThrowCompletionOr<size_t> Value::to_index(VM& vm) const
  773. {
  774. if (is_undefined())
  775. return 0;
  776. auto integer_index = TRY(to_integer_or_infinity(vm));
  777. if (integer_index < 0)
  778. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  779. auto index = MUST(Value(integer_index).to_length(vm));
  780. if (integer_index != index)
  781. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  782. return index;
  783. }
  784. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  785. ThrowCompletionOr<double> Value::to_integer_or_infinity(VM& vm) const
  786. {
  787. auto number = TRY(to_number(vm));
  788. if (number.is_nan() || number.as_double() == 0)
  789. return 0;
  790. if (number.is_infinity())
  791. return number.as_double();
  792. auto integer = floor(fabs(number.as_double()));
  793. if (number.as_double() < 0 && integer != 0)
  794. integer = -integer;
  795. return integer;
  796. }
  797. // Standalone variant using plain doubles for cases where we already got numbers and know the AO won't throw.
  798. double to_integer_or_infinity(double number)
  799. {
  800. // 1. Let number be ? ToNumber(argument).
  801. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
  802. if (isnan(number) || number == 0)
  803. return 0;
  804. // 3. If number is +∞𝔽, return +∞.
  805. if (__builtin_isinf_sign(number) > 0)
  806. return static_cast<double>(INFINITY);
  807. // 4. If number is -∞𝔽, return -∞.
  808. if (__builtin_isinf_sign(number) < 0)
  809. return static_cast<double>(-INFINITY);
  810. // 5. Let integer be floor(abs(ℝ(number))).
  811. auto integer = floor(fabs(number));
  812. // 6. If number < -0𝔽, set integer to -integer.
  813. if (number < 0 && integer != 0)
  814. integer = -integer;
  815. // 7. Return integer.
  816. return integer;
  817. }
  818. // 7.3.3 GetV ( V, P ), https://tc39.es/ecma262/#sec-getv
  819. ThrowCompletionOr<Value> Value::get(VM& vm, PropertyKey const& property_key) const
  820. {
  821. // 1. Assert: IsPropertyKey(P) is true.
  822. VERIFY(property_key.is_valid());
  823. // 2. Let O be ? ToObject(V).
  824. auto* object = TRY(to_object(vm));
  825. // 3. Return ? O.[[Get]](P, V).
  826. return TRY(object->internal_get(property_key, *this));
  827. }
  828. // 7.3.11 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  829. ThrowCompletionOr<FunctionObject*> Value::get_method(VM& vm, PropertyKey const& property_key) const
  830. {
  831. // 1. Assert: IsPropertyKey(P) is true.
  832. VERIFY(property_key.is_valid());
  833. // 2. Let func be ? GetV(V, P).
  834. auto function = TRY(get(vm, property_key));
  835. // 3. If func is either undefined or null, return undefined.
  836. if (function.is_nullish())
  837. return nullptr;
  838. // 4. If IsCallable(func) is false, throw a TypeError exception.
  839. if (!function.is_function())
  840. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, function.to_string_without_side_effects());
  841. // 5. Return func.
  842. return &function.as_function();
  843. }
  844. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  845. ThrowCompletionOr<Value> greater_than(VM& vm, Value lhs, Value rhs)
  846. {
  847. if (lhs.is_int32() && rhs.is_int32())
  848. return lhs.as_i32() > rhs.as_i32();
  849. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  850. if (relation == TriState::Unknown)
  851. return Value(false);
  852. return Value(relation == TriState::True);
  853. }
  854. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  855. ThrowCompletionOr<Value> greater_than_equals(VM& vm, Value lhs, Value rhs)
  856. {
  857. if (lhs.is_int32() && rhs.is_int32())
  858. return lhs.as_i32() >= rhs.as_i32();
  859. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  860. if (relation == TriState::Unknown || relation == TriState::True)
  861. return Value(false);
  862. return Value(true);
  863. }
  864. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  865. ThrowCompletionOr<Value> less_than(VM& vm, Value lhs, Value rhs)
  866. {
  867. if (lhs.is_int32() && rhs.is_int32())
  868. return lhs.as_i32() < rhs.as_i32();
  869. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  870. if (relation == TriState::Unknown)
  871. return Value(false);
  872. return Value(relation == TriState::True);
  873. }
  874. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  875. ThrowCompletionOr<Value> less_than_equals(VM& vm, Value lhs, Value rhs)
  876. {
  877. if (lhs.is_int32() && rhs.is_int32())
  878. return lhs.as_i32() <= rhs.as_i32();
  879. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  880. if (relation == TriState::Unknown || relation == TriState::True)
  881. return Value(false);
  882. return Value(true);
  883. }
  884. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  885. ThrowCompletionOr<Value> bitwise_and(VM& vm, Value lhs, Value rhs)
  886. {
  887. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  888. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  889. if (both_number(lhs_numeric, rhs_numeric)) {
  890. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  891. return Value(0);
  892. return Value(TRY(lhs_numeric.to_i32(vm)) & TRY(rhs_numeric.to_i32(vm)));
  893. }
  894. if (both_bigint(lhs_numeric, rhs_numeric))
  895. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  896. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  897. }
  898. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  899. ThrowCompletionOr<Value> bitwise_or(VM& vm, Value lhs, Value rhs)
  900. {
  901. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  902. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  903. if (both_number(lhs_numeric, rhs_numeric)) {
  904. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  905. return Value(0);
  906. if (!lhs_numeric.is_finite_number())
  907. return rhs_numeric;
  908. if (!rhs_numeric.is_finite_number())
  909. return lhs_numeric;
  910. return Value(TRY(lhs_numeric.to_i32(vm)) | TRY(rhs_numeric.to_i32(vm)));
  911. }
  912. if (both_bigint(lhs_numeric, rhs_numeric))
  913. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  914. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  915. }
  916. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  917. ThrowCompletionOr<Value> bitwise_xor(VM& vm, Value lhs, Value rhs)
  918. {
  919. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  920. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  921. if (both_number(lhs_numeric, rhs_numeric)) {
  922. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  923. return Value(0);
  924. if (!lhs_numeric.is_finite_number())
  925. return rhs_numeric;
  926. if (!rhs_numeric.is_finite_number())
  927. return lhs_numeric;
  928. return Value(TRY(lhs_numeric.to_i32(vm)) ^ TRY(rhs_numeric.to_i32(vm)));
  929. }
  930. if (both_bigint(lhs_numeric, rhs_numeric))
  931. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  932. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  933. }
  934. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  935. ThrowCompletionOr<Value> bitwise_not(VM& vm, Value lhs)
  936. {
  937. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  938. if (lhs_numeric.is_number())
  939. return Value(~TRY(lhs_numeric.to_i32(vm)));
  940. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_not());
  941. }
  942. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  943. ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
  944. {
  945. return TRY(lhs.to_number(vm));
  946. }
  947. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  948. ThrowCompletionOr<Value> unary_minus(VM& vm, Value lhs)
  949. {
  950. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  951. if (lhs_numeric.is_number()) {
  952. if (lhs_numeric.is_nan())
  953. return js_nan();
  954. return Value(-lhs_numeric.as_double());
  955. }
  956. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  957. return BigInt::create(vm, BIGINT_ZERO);
  958. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  959. big_integer_negated.negate();
  960. return BigInt::create(vm, big_integer_negated);
  961. }
  962. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  963. ThrowCompletionOr<Value> left_shift(VM& vm, Value lhs, Value rhs)
  964. {
  965. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  966. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  967. if (both_number(lhs_numeric, rhs_numeric)) {
  968. if (!lhs_numeric.is_finite_number())
  969. return Value(0);
  970. if (!rhs_numeric.is_finite_number())
  971. return lhs_numeric;
  972. // Ok, so this performs toNumber() again but that "can't" throw
  973. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  974. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  975. return Value(lhs_i32 << rhs_u32);
  976. }
  977. if (both_bigint(lhs_numeric, rhs_numeric)) {
  978. // 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
  979. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  980. // 1. If y < 0ℤ, then
  981. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  982. // a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
  983. // NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
  984. auto const& big_integer = lhs_numeric.as_bigint().big_integer();
  985. auto division_result = big_integer.divided_by(multiplier_divisor);
  986. // For positive initial values and no remainder just return quotient
  987. if (division_result.remainder.is_zero() || !big_integer.is_negative())
  988. return BigInt::create(vm, division_result.quotient);
  989. // For negative round "down" to the next negative number
  990. return BigInt::create(vm, division_result.quotient.minus(Crypto::SignedBigInteger { 1 }));
  991. }
  992. // 2. Return the BigInt value that represents ℝ(x) × 2^y.
  993. return Value(BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor)));
  994. }
  995. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "left-shift");
  996. }
  997. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  998. ThrowCompletionOr<Value> right_shift(VM& vm, Value lhs, Value rhs)
  999. {
  1000. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1001. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1002. if (both_number(lhs_numeric, rhs_numeric)) {
  1003. if (!lhs_numeric.is_finite_number())
  1004. return Value(0);
  1005. if (!rhs_numeric.is_finite_number())
  1006. return lhs_numeric;
  1007. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1008. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1009. return Value(lhs_i32 >> rhs_u32);
  1010. }
  1011. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1012. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  1013. rhs_negated.negate();
  1014. return left_shift(vm, lhs, BigInt::create(vm, rhs_negated));
  1015. }
  1016. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "right-shift");
  1017. }
  1018. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  1019. ThrowCompletionOr<Value> unsigned_right_shift(VM& vm, Value lhs, Value rhs)
  1020. {
  1021. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1022. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1023. if (both_number(lhs_numeric, rhs_numeric)) {
  1024. if (!lhs_numeric.is_finite_number())
  1025. return Value(0);
  1026. if (!rhs_numeric.is_finite_number())
  1027. return lhs_numeric;
  1028. // Ok, so this performs toNumber() again but that "can't" throw
  1029. auto lhs_u32 = MUST(lhs_numeric.to_u32(vm));
  1030. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1031. return Value(lhs_u32 >> rhs_u32);
  1032. }
  1033. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperator, "unsigned right-shift");
  1034. }
  1035. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  1036. ThrowCompletionOr<Value> add(VM& vm, Value lhs, Value rhs)
  1037. {
  1038. if (both_number(lhs, rhs)) {
  1039. if (lhs.is_int32() && rhs.is_int32()) {
  1040. Checked<i32> result;
  1041. result = MUST(lhs.to_i32(vm));
  1042. result += MUST(rhs.to_i32(vm));
  1043. if (!result.has_overflow())
  1044. return Value(result.value());
  1045. }
  1046. return Value(lhs.as_double() + rhs.as_double());
  1047. }
  1048. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1049. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1050. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  1051. auto lhs_string = TRY(lhs_primitive.to_primitive_string(vm));
  1052. auto rhs_string = TRY(rhs_primitive.to_primitive_string(vm));
  1053. return PrimitiveString::create(vm, *lhs_string, *rhs_string);
  1054. }
  1055. auto lhs_numeric = TRY(lhs_primitive.to_numeric(vm));
  1056. auto rhs_numeric = TRY(rhs_primitive.to_numeric(vm));
  1057. if (both_number(lhs_numeric, rhs_numeric))
  1058. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  1059. if (both_bigint(lhs_numeric, rhs_numeric))
  1060. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer()));
  1061. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "addition");
  1062. }
  1063. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1064. ThrowCompletionOr<Value> sub(VM& vm, Value lhs, Value rhs)
  1065. {
  1066. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1067. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1068. if (both_number(lhs_numeric, rhs_numeric)) {
  1069. double lhsd = lhs_numeric.as_double();
  1070. double rhsd = rhs_numeric.as_double();
  1071. double interm = lhsd - rhsd;
  1072. return Value(interm);
  1073. }
  1074. if (both_bigint(lhs_numeric, rhs_numeric))
  1075. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer()));
  1076. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1077. }
  1078. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1079. ThrowCompletionOr<Value> mul(VM& vm, Value lhs, Value rhs)
  1080. {
  1081. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1082. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1083. if (both_number(lhs_numeric, rhs_numeric))
  1084. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  1085. if (both_bigint(lhs_numeric, rhs_numeric))
  1086. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer()));
  1087. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1088. }
  1089. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1090. ThrowCompletionOr<Value> div(VM& vm, Value lhs, Value rhs)
  1091. {
  1092. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1093. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1094. if (both_number(lhs_numeric, rhs_numeric))
  1095. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1096. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1097. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1098. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1099. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient);
  1100. }
  1101. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "division");
  1102. }
  1103. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1104. ThrowCompletionOr<Value> mod(VM& vm, Value lhs, Value rhs)
  1105. {
  1106. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1107. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1108. if (both_number(lhs_numeric, rhs_numeric)) {
  1109. // 6.1.6.1.6 Number::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-number-remainder
  1110. // The ECMA specification is describing the mathematical definition of modulus
  1111. // implemented by fmod.
  1112. auto n = lhs_numeric.as_double();
  1113. auto d = rhs_numeric.as_double();
  1114. return Value(fmod(n, d));
  1115. }
  1116. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1117. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1118. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1119. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder);
  1120. }
  1121. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "modulo");
  1122. }
  1123. static Value exp_double(Value base, Value exponent)
  1124. {
  1125. VERIFY(both_number(base, exponent));
  1126. if (exponent.is_nan())
  1127. return js_nan();
  1128. if (exponent.is_positive_zero() || exponent.is_negative_zero())
  1129. return Value(1);
  1130. if (base.is_nan())
  1131. return js_nan();
  1132. if (base.is_positive_infinity())
  1133. return exponent.as_double() > 0 ? js_infinity() : Value(0);
  1134. if (base.is_negative_infinity()) {
  1135. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1136. if (exponent.as_double() > 0)
  1137. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1138. else
  1139. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1140. }
  1141. if (base.is_positive_zero())
  1142. return exponent.as_double() > 0 ? Value(0) : js_infinity();
  1143. if (base.is_negative_zero()) {
  1144. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1145. if (exponent.as_double() > 0)
  1146. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1147. else
  1148. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1149. }
  1150. VERIFY(base.is_finite_number() && !base.is_positive_zero() && !base.is_negative_zero());
  1151. if (exponent.is_positive_infinity()) {
  1152. auto absolute_base = fabs(base.as_double());
  1153. if (absolute_base > 1)
  1154. return js_infinity();
  1155. else if (absolute_base == 1)
  1156. return js_nan();
  1157. else if (absolute_base < 1)
  1158. return Value(0);
  1159. }
  1160. if (exponent.is_negative_infinity()) {
  1161. auto absolute_base = fabs(base.as_double());
  1162. if (absolute_base > 1)
  1163. return Value(0);
  1164. else if (absolute_base == 1)
  1165. return js_nan();
  1166. else if (absolute_base < 1)
  1167. return js_infinity();
  1168. }
  1169. VERIFY(exponent.is_finite_number() && !exponent.is_positive_zero() && !exponent.is_negative_zero());
  1170. if (base.as_double() < 0 && !exponent.is_integral_number())
  1171. return js_nan();
  1172. return Value(::pow(base.as_double(), exponent.as_double()));
  1173. }
  1174. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1175. ThrowCompletionOr<Value> exp(VM& vm, Value lhs, Value rhs)
  1176. {
  1177. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1178. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1179. if (both_number(lhs_numeric, rhs_numeric))
  1180. return exp_double(lhs_numeric, rhs_numeric);
  1181. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1182. if (rhs_numeric.as_bigint().big_integer().is_negative())
  1183. return vm.throw_completion<RangeError>(ErrorType::NegativeExponent);
  1184. return BigInt::create(vm, Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
  1185. }
  1186. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1187. }
  1188. ThrowCompletionOr<Value> in(VM& vm, Value lhs, Value rhs)
  1189. {
  1190. if (!rhs.is_object())
  1191. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  1192. auto lhs_property_key = TRY(lhs.to_property_key(vm));
  1193. return Value(TRY(rhs.as_object().has_property(lhs_property_key)));
  1194. }
  1195. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1196. ThrowCompletionOr<Value> instance_of(VM& vm, Value lhs, Value rhs)
  1197. {
  1198. if (!rhs.is_object())
  1199. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  1200. auto has_instance_method = TRY(rhs.get_method(vm, *vm.well_known_symbol_has_instance()));
  1201. if (has_instance_method) {
  1202. auto has_instance_result = TRY(call(vm, *has_instance_method, rhs, lhs));
  1203. return Value(has_instance_result.to_boolean());
  1204. }
  1205. if (!rhs.is_function())
  1206. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  1207. return TRY(ordinary_has_instance(vm, lhs, rhs));
  1208. }
  1209. // 7.3.22 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1210. ThrowCompletionOr<Value> ordinary_has_instance(VM& vm, Value lhs, Value rhs)
  1211. {
  1212. if (!rhs.is_function())
  1213. return Value(false);
  1214. auto& rhs_function = rhs.as_function();
  1215. if (is<BoundFunction>(rhs_function)) {
  1216. auto& bound_target = static_cast<BoundFunction const&>(rhs_function);
  1217. return instance_of(vm, lhs, Value(&bound_target.bound_target_function()));
  1218. }
  1219. if (!lhs.is_object())
  1220. return Value(false);
  1221. Object* lhs_object = &lhs.as_object();
  1222. auto rhs_prototype = TRY(rhs_function.get(vm.names.prototype));
  1223. if (!rhs_prototype.is_object())
  1224. return vm.throw_completion<TypeError>(ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1225. while (true) {
  1226. lhs_object = TRY(lhs_object->internal_get_prototype_of());
  1227. if (!lhs_object)
  1228. return Value(false);
  1229. if (same_value(rhs_prototype, lhs_object))
  1230. return Value(true);
  1231. }
  1232. }
  1233. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1234. bool same_value(Value lhs, Value rhs)
  1235. {
  1236. if (!same_type_for_equality(lhs, rhs))
  1237. return false;
  1238. if (lhs.is_number()) {
  1239. if (lhs.is_nan() && rhs.is_nan())
  1240. return true;
  1241. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1242. return false;
  1243. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1244. return false;
  1245. return lhs.as_double() == rhs.as_double();
  1246. }
  1247. if (lhs.is_bigint()) {
  1248. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1249. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1250. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1251. return false;
  1252. return lhs_big_integer == rhs_big_integer;
  1253. }
  1254. return same_value_non_numeric(lhs, rhs);
  1255. }
  1256. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1257. bool same_value_zero(Value lhs, Value rhs)
  1258. {
  1259. if (!same_type_for_equality(lhs, rhs))
  1260. return false;
  1261. if (lhs.is_number()) {
  1262. if (lhs.is_nan() && rhs.is_nan())
  1263. return true;
  1264. return lhs.as_double() == rhs.as_double();
  1265. }
  1266. if (lhs.is_bigint())
  1267. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1268. return same_value_non_numeric(lhs, rhs);
  1269. }
  1270. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1271. bool same_value_non_numeric(Value lhs, Value rhs)
  1272. {
  1273. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1274. VERIFY(same_type_for_equality(lhs, rhs));
  1275. if (lhs.is_string())
  1276. return lhs.as_string().deprecated_string() == rhs.as_string().deprecated_string();
  1277. return lhs.m_value.encoded == rhs.m_value.encoded;
  1278. }
  1279. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1280. bool is_strictly_equal(Value lhs, Value rhs)
  1281. {
  1282. if (!same_type_for_equality(lhs, rhs))
  1283. return false;
  1284. if (lhs.is_number()) {
  1285. if (lhs.is_nan() || rhs.is_nan())
  1286. return false;
  1287. if (lhs.as_double() == rhs.as_double())
  1288. return true;
  1289. return false;
  1290. }
  1291. if (lhs.is_bigint())
  1292. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1293. return same_value_non_numeric(lhs, rhs);
  1294. }
  1295. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1296. ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs)
  1297. {
  1298. // 1. If Type(x) is the same as Type(y), then
  1299. if (same_type_for_equality(lhs, rhs)) {
  1300. // a. Return IsStrictlyEqual(x, y).
  1301. return is_strictly_equal(lhs, rhs);
  1302. }
  1303. // 2. If x is null and y is undefined, return true.
  1304. // 3. If x is undefined and y is null, return true.
  1305. if (lhs.is_nullish() && rhs.is_nullish())
  1306. return true;
  1307. // 4. NOTE: This step is replaced in section B.3.6.2.
  1308. // B.3.6.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1309. // 4. Perform the following steps:
  1310. // a. If Type(x) is Object and x has an [[IsHTMLDDA]] internal slot and y is either null or undefined, return true.
  1311. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1312. return true;
  1313. // b. If x is either null or undefined and Type(y) is Object and y has an [[IsHTMLDDA]] internal slot, return true.
  1314. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1315. return true;
  1316. // == End of B.3.6.2 ==
  1317. // 5. If Type(x) is Number and Type(y) is String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1318. if (lhs.is_number() && rhs.is_string())
  1319. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1320. // 6. If Type(x) is String and Type(y) is Number, return ! IsLooselyEqual(! ToNumber(x), y).
  1321. if (lhs.is_string() && rhs.is_number())
  1322. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1323. // 7. If Type(x) is BigInt and Type(y) is String, then
  1324. if (lhs.is_bigint() && rhs.is_string()) {
  1325. // a. Let n be StringToBigInt(y).
  1326. auto bigint = string_to_bigint(vm, rhs.as_string().deprecated_string());
  1327. // b. If n is undefined, return false.
  1328. if (!bigint.has_value())
  1329. return false;
  1330. // c. Return ! IsLooselyEqual(x, n).
  1331. return is_loosely_equal(vm, lhs, *bigint);
  1332. }
  1333. // 8. If Type(x) is String and Type(y) is BigInt, return ! IsLooselyEqual(y, x).
  1334. if (lhs.is_string() && rhs.is_bigint())
  1335. return is_loosely_equal(vm, rhs, lhs);
  1336. // 9. If Type(x) is Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  1337. if (lhs.is_boolean())
  1338. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1339. // 10. If Type(y) is Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1340. if (rhs.is_boolean())
  1341. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1342. // 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  1343. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1344. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1345. return is_loosely_equal(vm, lhs, rhs_primitive);
  1346. }
  1347. // 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  1348. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || rhs.is_bigint() || rhs.is_symbol())) {
  1349. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1350. return is_loosely_equal(vm, lhs_primitive, rhs);
  1351. }
  1352. // 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
  1353. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1354. // a. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false.
  1355. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1356. return false;
  1357. // b. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1358. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1359. return false;
  1360. VERIFY(!lhs.is_nan() && !rhs.is_nan());
  1361. auto& number_side = lhs.is_number() ? lhs : rhs;
  1362. auto& bigint_side = lhs.is_number() ? rhs : lhs;
  1363. return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt;
  1364. }
  1365. // 14. Return false.
  1366. return false;
  1367. }
  1368. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1369. ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left_first)
  1370. {
  1371. Value x_primitive;
  1372. Value y_primitive;
  1373. if (left_first) {
  1374. x_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1375. y_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1376. } else {
  1377. y_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1378. x_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1379. }
  1380. if (x_primitive.is_string() && y_primitive.is_string()) {
  1381. auto x_string = x_primitive.as_string().deprecated_string();
  1382. auto y_string = y_primitive.as_string().deprecated_string();
  1383. Utf8View x_code_points { x_string };
  1384. Utf8View y_code_points { y_string };
  1385. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1386. k != x_code_points.end() && l != y_code_points.end();
  1387. ++k, ++l) {
  1388. if (*k != *l) {
  1389. if (*k < *l) {
  1390. return TriState::True;
  1391. } else {
  1392. return TriState::False;
  1393. }
  1394. }
  1395. }
  1396. return x_code_points.length() < y_code_points.length()
  1397. ? TriState::True
  1398. : TriState::False;
  1399. }
  1400. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1401. auto y_bigint = string_to_bigint(vm, y_primitive.as_string().deprecated_string());
  1402. if (!y_bigint.has_value())
  1403. return TriState::Unknown;
  1404. if (x_primitive.as_bigint().big_integer() < (*y_bigint)->big_integer())
  1405. return TriState::True;
  1406. return TriState::False;
  1407. }
  1408. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1409. auto x_bigint = string_to_bigint(vm, x_primitive.as_string().deprecated_string());
  1410. if (!x_bigint.has_value())
  1411. return TriState::Unknown;
  1412. if ((*x_bigint)->big_integer() < y_primitive.as_bigint().big_integer())
  1413. return TriState::True;
  1414. return TriState::False;
  1415. }
  1416. auto x_numeric = TRY(x_primitive.to_numeric(vm));
  1417. auto y_numeric = TRY(y_primitive.to_numeric(vm));
  1418. if (x_numeric.is_nan() || y_numeric.is_nan())
  1419. return TriState::Unknown;
  1420. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1421. return TriState::False;
  1422. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1423. return TriState::True;
  1424. if (x_numeric.is_number() && y_numeric.is_number()) {
  1425. if (x_numeric.as_double() < y_numeric.as_double())
  1426. return TriState::True;
  1427. else
  1428. return TriState::False;
  1429. }
  1430. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1431. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1432. return TriState::True;
  1433. else
  1434. return TriState::False;
  1435. }
  1436. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1437. bool x_lower_than_y;
  1438. VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan());
  1439. if (x_numeric.is_number()) {
  1440. x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double())
  1441. == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt;
  1442. } else {
  1443. x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double())
  1444. == Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt;
  1445. }
  1446. if (x_lower_than_y)
  1447. return TriState::True;
  1448. else
  1449. return TriState::False;
  1450. }
  1451. // 7.3.21 Invoke ( V, P [ , argumentsList ] ), https://tc39.es/ecma262/#sec-invoke
  1452. ThrowCompletionOr<Value> Value::invoke_internal(VM& vm, PropertyKey const& property_key, Optional<MarkedVector<Value>> arguments)
  1453. {
  1454. auto property = TRY(get(vm, property_key));
  1455. if (!property.is_function())
  1456. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, property.to_string_without_side_effects());
  1457. return call(vm, property.as_function(), *this, move(arguments));
  1458. }
  1459. }