Value.cpp 61 KB

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