Value.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  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. // 9. If val is a Number, return "number".
  254. if (is_number())
  255. return "number";
  256. switch (m_value.tag) {
  257. // 4. If val is undefined, return "undefined".
  258. case UNDEFINED_TAG:
  259. return "undefined";
  260. // 5. If val is null, return "object".
  261. case NULL_TAG:
  262. return "object";
  263. // 6. If val is a String, return "string".
  264. case STRING_TAG:
  265. return "string";
  266. // 7. If val is a Symbol, return "symbol".
  267. case SYMBOL_TAG:
  268. return "symbol";
  269. // 8. If val is a Boolean, return "boolean".
  270. case BOOLEAN_TAG:
  271. return "boolean";
  272. // 10. If val is a BigInt, return "bigint".
  273. case BIGINT_TAG:
  274. return "bigint";
  275. // 11. Assert: val is an Object.
  276. case OBJECT_TAG:
  277. // B.3.6.3 Changes to the typeof Operator, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-typeof
  278. // 12. If val has an [[IsHTMLDDA]] internal slot, return "undefined".
  279. if (as_object().is_htmldda())
  280. return "undefined";
  281. // 13. If val has a [[Call]] internal slot, return "function".
  282. if (is_function())
  283. return "function";
  284. // 14. Return "object".
  285. return "object";
  286. default:
  287. VERIFY_NOT_REACHED();
  288. }
  289. }
  290. DeprecatedString Value::to_string_without_side_effects() const
  291. {
  292. if (is_double())
  293. return number_to_string(m_value.as_double);
  294. switch (m_value.tag) {
  295. case UNDEFINED_TAG:
  296. return "undefined";
  297. case NULL_TAG:
  298. return "null";
  299. case BOOLEAN_TAG:
  300. return as_bool() ? "true" : "false";
  301. case INT32_TAG:
  302. return DeprecatedString::number(as_i32());
  303. case STRING_TAG:
  304. return as_string().deprecated_string();
  305. case SYMBOL_TAG:
  306. return as_symbol().to_deprecated_string();
  307. case BIGINT_TAG:
  308. return as_bigint().to_deprecated_string();
  309. case OBJECT_TAG:
  310. return DeprecatedString::formatted("[object {}]", as_object().class_name());
  311. case ACCESSOR_TAG:
  312. return "<accessor>";
  313. default:
  314. VERIFY_NOT_REACHED();
  315. }
  316. }
  317. ThrowCompletionOr<PrimitiveString*> Value::to_primitive_string(VM& vm)
  318. {
  319. if (is_string())
  320. return &as_string();
  321. auto string = TRY(to_string(vm));
  322. return PrimitiveString::create(vm, string).ptr();
  323. }
  324. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  325. ThrowCompletionOr<DeprecatedString> Value::to_string(VM& vm) const
  326. {
  327. if (is_double())
  328. return number_to_string(m_value.as_double);
  329. switch (m_value.tag) {
  330. // 1. If argument is a String, return argument.
  331. case STRING_TAG:
  332. return as_string().deprecated_string();
  333. // 2. If argument is a Symbol, throw a TypeError exception.
  334. case SYMBOL_TAG:
  335. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "string");
  336. // 3. If argument is undefined, return "undefined".
  337. case UNDEFINED_TAG:
  338. return "undefined"sv;
  339. // 4. If argument is null, return "null".
  340. case NULL_TAG:
  341. return "null"sv;
  342. // 5. If argument is true, return "true".
  343. // 6. If argument is false, return "false".
  344. case BOOLEAN_TAG:
  345. return as_bool() ? "true"sv : "false"sv;
  346. // 7. If argument is a Number, return Number::toString(argument, 10).
  347. case INT32_TAG:
  348. return DeprecatedString::number(as_i32());
  349. // 8. If argument is a BigInt, return BigInt::toString(argument, 10).
  350. case BIGINT_TAG:
  351. return as_bigint().big_integer().to_base(10);
  352. // 9. Assert: argument is an Object.
  353. case OBJECT_TAG: {
  354. // 10. Let primValue be ? ToPrimitive(argument, string).
  355. auto primitive_value = TRY(to_primitive(vm, PreferredType::String));
  356. // 11. Assert: primValue is not an Object.
  357. VERIFY(!primitive_value.is_object());
  358. // 12. Return ? ToString(primValue).
  359. return primitive_value.to_string(vm);
  360. }
  361. default:
  362. VERIFY_NOT_REACHED();
  363. }
  364. }
  365. ThrowCompletionOr<Utf16String> Value::to_utf16_string(VM& vm) const
  366. {
  367. if (is_string())
  368. return as_string().utf16_string();
  369. auto utf8_string = TRY(to_string(vm));
  370. return Utf16String(utf8_string);
  371. }
  372. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  373. bool Value::to_boolean() const
  374. {
  375. if (is_double()) {
  376. if (is_nan())
  377. return false;
  378. return m_value.as_double != 0;
  379. }
  380. switch (m_value.tag) {
  381. // 1. If argument is a Boolean, return argument.
  382. case BOOLEAN_TAG:
  383. return as_bool();
  384. // 2. If argument is any of undefined, null, +0𝔽, -0𝔽, NaN, 0ℤ, or the empty String, return false.
  385. case UNDEFINED_TAG:
  386. case NULL_TAG:
  387. return false;
  388. case INT32_TAG:
  389. return as_i32() != 0;
  390. case STRING_TAG:
  391. return !as_string().is_empty();
  392. case BIGINT_TAG:
  393. return as_bigint().big_integer() != BIGINT_ZERO;
  394. case OBJECT_TAG:
  395. // B.3.6.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  396. // 3. If argument is an Object and argument has an [[IsHTMLDDA]] internal slot, return false.
  397. if (as_object().is_htmldda())
  398. return false;
  399. // 4. Return true.
  400. return true;
  401. case SYMBOL_TAG:
  402. return true;
  403. default:
  404. VERIFY_NOT_REACHED();
  405. }
  406. }
  407. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  408. ThrowCompletionOr<Value> Value::to_primitive(VM& vm, PreferredType preferred_type) const
  409. {
  410. // 1. If input is an Object, then
  411. if (is_object()) {
  412. // a. Let exoticToPrim be ? GetMethod(input, @@toPrimitive).
  413. auto* exotic_to_primitive = TRY(get_method(vm, *vm.well_known_symbol_to_primitive()));
  414. // b. If exoticToPrim is not undefined, then
  415. if (exotic_to_primitive) {
  416. auto hint = [&]() -> DeprecatedString {
  417. switch (preferred_type) {
  418. // i. If preferredType is not present, let hint be "default".
  419. case PreferredType::Default:
  420. return "default";
  421. // ii. Else if preferredType is string, let hint be "string".
  422. case PreferredType::String:
  423. return "string";
  424. // iii. Else,
  425. // 1. Assert: preferredType is number.
  426. // 2. Let hint be "number".
  427. case PreferredType::Number:
  428. return "number";
  429. default:
  430. VERIFY_NOT_REACHED();
  431. }
  432. }();
  433. // iv. Let result be ? Call(exoticToPrim, input, « hint »).
  434. auto result = TRY(call(vm, *exotic_to_primitive, *this, PrimitiveString::create(vm, hint)));
  435. // v. If result is not an Object, return result.
  436. if (!result.is_object())
  437. return result;
  438. // vi. Throw a TypeError exception.
  439. return vm.throw_completion<TypeError>(ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  440. }
  441. // c. If preferredType is not present, let preferredType be number.
  442. if (preferred_type == PreferredType::Default)
  443. preferred_type = PreferredType::Number;
  444. // d. Return ? OrdinaryToPrimitive(input, preferredType).
  445. return as_object().ordinary_to_primitive(preferred_type);
  446. }
  447. // 2. Return input.
  448. return *this;
  449. }
  450. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  451. ThrowCompletionOr<Object*> Value::to_object(VM& vm) const
  452. {
  453. auto& realm = *vm.current_realm();
  454. VERIFY(!is_empty());
  455. // Number
  456. if (is_number()) {
  457. // Return a new Number object whose [[NumberData]] internal slot is set to argument. See 21.1 for a description of Number objects.
  458. return NumberObject::create(realm, as_double());
  459. }
  460. switch (m_value.tag) {
  461. // Undefined
  462. // Null
  463. case UNDEFINED_TAG:
  464. case NULL_TAG:
  465. // Throw a TypeError exception.
  466. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  467. // Boolean
  468. case BOOLEAN_TAG:
  469. // Return a new Boolean object whose [[BooleanData]] internal slot is set to argument. See 20.3 for a description of Boolean objects.
  470. return BooleanObject::create(realm, as_bool());
  471. // String
  472. case STRING_TAG:
  473. // Return a new String object whose [[StringData]] internal slot is set to argument. See 22.1 for a description of String objects.
  474. return StringObject::create(realm, const_cast<JS::PrimitiveString&>(as_string()), *realm.intrinsics().string_prototype());
  475. // Symbol
  476. case SYMBOL_TAG:
  477. // Return a new Symbol object whose [[SymbolData]] internal slot is set to argument. See 20.4 for a description of Symbol objects.
  478. return SymbolObject::create(realm, const_cast<JS::Symbol&>(as_symbol()));
  479. // BigInt
  480. case BIGINT_TAG:
  481. // Return a new BigInt object whose [[BigIntData]] internal slot is set to argument. See 21.2 for a description of BigInt objects.
  482. return BigIntObject::create(realm, const_cast<JS::BigInt&>(as_bigint()));
  483. // Object
  484. case OBJECT_TAG:
  485. // Return argument.
  486. return &const_cast<Object&>(as_object());
  487. default:
  488. VERIFY_NOT_REACHED();
  489. }
  490. }
  491. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  492. FLATTEN ThrowCompletionOr<Value> Value::to_numeric(VM& vm) const
  493. {
  494. // 1. Let primValue be ? ToPrimitive(value, number).
  495. auto primitive_value = TRY(to_primitive(vm, Value::PreferredType::Number));
  496. // 2. If primValue is a BigInt, return primValue.
  497. if (primitive_value.is_bigint())
  498. return primitive_value;
  499. // 3. Return ? ToNumber(primValue).
  500. return primitive_value.to_number(vm);
  501. }
  502. constexpr bool is_ascii_number(u32 code_point)
  503. {
  504. return is_ascii_digit(code_point) || code_point == '.' || (code_point == 'e' || code_point == 'E') || code_point == '+' || code_point == '-';
  505. }
  506. struct NumberParseResult {
  507. StringView literal;
  508. u8 base;
  509. };
  510. static Optional<NumberParseResult> parse_number_text(StringView text)
  511. {
  512. NumberParseResult result {};
  513. auto check_prefix = [&](auto lower_prefix, auto upper_prefix) {
  514. if (text.length() <= 2)
  515. return false;
  516. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  517. return false;
  518. return true;
  519. };
  520. // https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
  521. if (check_prefix("0b"sv, "0B"sv)) {
  522. if (!all_of(text.substring_view(2), is_ascii_binary_digit))
  523. return {};
  524. result.literal = text.substring_view(2);
  525. result.base = 2;
  526. } else if (check_prefix("0o"sv, "0O"sv)) {
  527. if (!all_of(text.substring_view(2), is_ascii_octal_digit))
  528. return {};
  529. result.literal = text.substring_view(2);
  530. result.base = 8;
  531. } else if (check_prefix("0x"sv, "0X"sv)) {
  532. if (!all_of(text.substring_view(2), is_ascii_hex_digit))
  533. return {};
  534. result.literal = text.substring_view(2);
  535. result.base = 16;
  536. } else {
  537. if (!all_of(text, is_ascii_number))
  538. return {};
  539. result.literal = text;
  540. result.base = 10;
  541. }
  542. return result;
  543. }
  544. // 7.1.4.1.1 StringToNumber ( str ), https://tc39.es/ecma262/#sec-stringtonumber
  545. Optional<Value> string_to_number(StringView string)
  546. {
  547. // 1. Let text be StringToCodePoints(str).
  548. DeprecatedString text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  549. // 2. Let literal be ParseText(text, StringNumericLiteral).
  550. if (text.is_empty())
  551. return Value(0);
  552. if (text == "Infinity" || text == "+Infinity")
  553. return js_infinity();
  554. if (text == "-Infinity")
  555. return js_negative_infinity();
  556. auto result = parse_number_text(text);
  557. // 3. If literal is a List of errors, return NaN.
  558. if (!result.has_value())
  559. return js_nan();
  560. // 4. Return StringNumericValue of literal.
  561. if (result->base != 10) {
  562. auto bigint = Crypto::UnsignedBigInteger::from_base(result->base, result->literal);
  563. return Value(bigint.to_double());
  564. }
  565. auto maybe_double = text.to_double(AK::TrimWhitespace::No);
  566. if (!maybe_double.has_value())
  567. return js_nan();
  568. return Value(*maybe_double);
  569. }
  570. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  571. ThrowCompletionOr<Value> Value::to_number(VM& vm) const
  572. {
  573. VERIFY(!is_empty());
  574. if (is_number())
  575. return *this;
  576. switch (m_value.tag) {
  577. case UNDEFINED_TAG:
  578. return js_nan();
  579. case NULL_TAG:
  580. return Value(0);
  581. case BOOLEAN_TAG:
  582. return Value(as_bool() ? 1 : 0);
  583. case STRING_TAG:
  584. return string_to_number(as_string().deprecated_string().view());
  585. case SYMBOL_TAG:
  586. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "number");
  587. case BIGINT_TAG:
  588. return vm.throw_completion<TypeError>(ErrorType::Convert, "BigInt", "number");
  589. case OBJECT_TAG: {
  590. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  591. return primitive.to_number(vm);
  592. }
  593. default:
  594. VERIFY_NOT_REACHED();
  595. }
  596. }
  597. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string);
  598. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  599. ThrowCompletionOr<BigInt*> Value::to_bigint(VM& vm) const
  600. {
  601. auto primitive = TRY(to_primitive(vm, PreferredType::Number));
  602. VERIFY(!primitive.is_empty());
  603. if (primitive.is_number())
  604. return vm.throw_completion<TypeError>(ErrorType::Convert, "number", "BigInt");
  605. switch (primitive.m_value.tag) {
  606. case UNDEFINED_TAG:
  607. return vm.throw_completion<TypeError>(ErrorType::Convert, "undefined", "BigInt");
  608. case NULL_TAG:
  609. return vm.throw_completion<TypeError>(ErrorType::Convert, "null", "BigInt");
  610. case BOOLEAN_TAG: {
  611. auto value = primitive.as_bool() ? 1 : 0;
  612. return BigInt::create(vm, Crypto::SignedBigInteger { value }).ptr();
  613. }
  614. case BIGINT_TAG:
  615. return &primitive.as_bigint();
  616. case STRING_TAG: {
  617. // 1. Let n be ! StringToBigInt(prim).
  618. auto bigint = string_to_bigint(vm, primitive.as_string().deprecated_string());
  619. // 2. If n is undefined, throw a SyntaxError exception.
  620. if (!bigint.has_value())
  621. return vm.throw_completion<SyntaxError>(ErrorType::BigIntInvalidValue, primitive);
  622. // 3. Return n.
  623. return bigint.release_value();
  624. }
  625. case SYMBOL_TAG:
  626. return vm.throw_completion<TypeError>(ErrorType::Convert, "symbol", "BigInt");
  627. default:
  628. VERIFY_NOT_REACHED();
  629. }
  630. }
  631. struct BigIntParseResult {
  632. StringView literal;
  633. u8 base { 10 };
  634. bool is_negative { false };
  635. };
  636. static Optional<BigIntParseResult> parse_bigint_text(StringView text)
  637. {
  638. BigIntParseResult result {};
  639. auto parse_for_prefixed_base = [&](auto lower_prefix, auto upper_prefix, auto validator) {
  640. if (text.length() <= 2)
  641. return false;
  642. if (!text.starts_with(lower_prefix) && !text.starts_with(upper_prefix))
  643. return false;
  644. return all_of(text.substring_view(2), validator);
  645. };
  646. if (parse_for_prefixed_base("0b"sv, "0B"sv, is_ascii_binary_digit)) {
  647. result.literal = text.substring_view(2);
  648. result.base = 2;
  649. } else if (parse_for_prefixed_base("0o"sv, "0O"sv, is_ascii_octal_digit)) {
  650. result.literal = text.substring_view(2);
  651. result.base = 8;
  652. } else if (parse_for_prefixed_base("0x"sv, "0X"sv, is_ascii_hex_digit)) {
  653. result.literal = text.substring_view(2);
  654. result.base = 16;
  655. } else {
  656. if (text.starts_with('-')) {
  657. text = text.substring_view(1);
  658. result.is_negative = true;
  659. } else if (text.starts_with('+')) {
  660. text = text.substring_view(1);
  661. }
  662. if (!all_of(text, is_ascii_digit))
  663. return {};
  664. result.literal = text;
  665. result.base = 10;
  666. }
  667. return result;
  668. }
  669. // 7.1.14 StringToBigInt ( str ), https://tc39.es/ecma262/#sec-stringtobigint
  670. static Optional<BigInt*> string_to_bigint(VM& vm, StringView string)
  671. {
  672. // 1. Let text be StringToCodePoints(str).
  673. auto text = Utf8View(string).trim(whitespace_characters, AK::TrimMode::Both).as_string();
  674. // 2. Let literal be ParseText(text, StringIntegerLiteral).
  675. auto result = parse_bigint_text(text);
  676. // 3. If literal is a List of errors, return undefined.
  677. if (!result.has_value())
  678. return {};
  679. // 4. Let mv be the MV of literal.
  680. // 5. Assert: mv is an integer.
  681. auto bigint = Crypto::SignedBigInteger::from_base(result->base, result->literal);
  682. if (result->is_negative && (bigint != BIGINT_ZERO))
  683. bigint.negate();
  684. // 6. Return ℤ(mv).
  685. return BigInt::create(vm, move(bigint));
  686. }
  687. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/#sec-tobigint64
  688. ThrowCompletionOr<i64> Value::to_bigint_int64(VM& vm) const
  689. {
  690. auto* bigint = TRY(to_bigint(vm));
  691. return static_cast<i64>(bigint->big_integer().to_u64());
  692. }
  693. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/#sec-tobiguint64
  694. ThrowCompletionOr<u64> Value::to_bigint_uint64(VM& vm) const
  695. {
  696. auto* bigint = TRY(to_bigint(vm));
  697. return bigint->big_integer().to_u64();
  698. }
  699. ThrowCompletionOr<double> Value::to_double(VM& vm) const
  700. {
  701. return TRY(to_number(vm)).as_double();
  702. }
  703. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  704. ThrowCompletionOr<PropertyKey> Value::to_property_key(VM& vm) const
  705. {
  706. if (is_int32() && as_i32() >= 0)
  707. return PropertyKey { as_i32() };
  708. auto key = TRY(to_primitive(vm, PreferredType::String));
  709. if (key.is_symbol())
  710. return &key.as_symbol();
  711. return TRY(key.to_string(vm));
  712. }
  713. ThrowCompletionOr<i32> Value::to_i32_slow_case(VM& vm) const
  714. {
  715. VERIFY(!is_int32());
  716. double value = TRY(to_number(vm)).as_double();
  717. if (!isfinite(value) || value == 0)
  718. return 0;
  719. auto abs = fabs(value);
  720. auto int_val = floor(abs);
  721. if (signbit(value))
  722. int_val = -int_val;
  723. auto remainder = fmod(int_val, 4294967296.0);
  724. auto int32bit = remainder >= 0.0 ? remainder : remainder + 4294967296.0; // The notation “x modulo y” computes a value k of the same sign as y
  725. if (int32bit >= 2147483648.0)
  726. int32bit -= 4294967296.0;
  727. return static_cast<i32>(int32bit);
  728. }
  729. ThrowCompletionOr<i32> Value::to_i32(VM& vm) const
  730. {
  731. if (is_int32())
  732. return as_i32();
  733. return to_i32_slow_case(vm);
  734. }
  735. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  736. ThrowCompletionOr<u32> Value::to_u32(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 int32bit = fmod(int_val, NumericLimits<u32>::max() + 1.0);
  745. // Cast to i64 here to ensure that the double --> u32 cast doesn't invoke undefined behavior
  746. // Otherwise, negative numbers cause a UBSAN warning.
  747. return static_cast<u32>(static_cast<i64>(int32bit));
  748. }
  749. // 7.1.8 ToInt16 ( argument ), https://tc39.es/ecma262/#sec-toint16
  750. ThrowCompletionOr<i16> Value::to_i16(VM& vm) const
  751. {
  752. double value = TRY(to_number(vm)).as_double();
  753. if (!isfinite(value) || value == 0)
  754. return 0;
  755. auto abs = fabs(value);
  756. auto int_val = floor(abs);
  757. if (signbit(value))
  758. int_val = -int_val;
  759. auto remainder = fmod(int_val, 65536.0);
  760. auto int16bit = remainder >= 0.0 ? remainder : remainder + 65536.0; // The notation “x modulo y” computes a value k of the same sign as y
  761. if (int16bit >= 32768.0)
  762. int16bit -= 65536.0;
  763. return static_cast<i16>(int16bit);
  764. }
  765. // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16
  766. ThrowCompletionOr<u16> Value::to_u16(VM& vm) const
  767. {
  768. double value = TRY(to_number(vm)).as_double();
  769. if (!isfinite(value) || value == 0)
  770. return 0;
  771. auto int_val = floor(fabs(value));
  772. if (signbit(value))
  773. int_val = -int_val;
  774. auto int16bit = fmod(int_val, NumericLimits<u16>::max() + 1.0);
  775. if (int16bit < 0)
  776. int16bit += NumericLimits<u16>::max() + 1.0;
  777. return static_cast<u16>(int16bit);
  778. }
  779. // 7.1.10 ToInt8 ( argument ), https://tc39.es/ecma262/#sec-toint8
  780. ThrowCompletionOr<i8> Value::to_i8(VM& vm) const
  781. {
  782. double value = TRY(to_number(vm)).as_double();
  783. if (!isfinite(value) || value == 0)
  784. return 0;
  785. auto abs = fabs(value);
  786. auto int_val = floor(abs);
  787. if (signbit(value))
  788. int_val = -int_val;
  789. auto remainder = fmod(int_val, 256.0);
  790. auto int8bit = remainder >= 0.0 ? remainder : remainder + 256.0; // The notation “x modulo y” computes a value k of the same sign as y
  791. if (int8bit >= 128.0)
  792. int8bit -= 256.0;
  793. return static_cast<i8>(int8bit);
  794. }
  795. // 7.1.11 ToUint8 ( argument ), https://tc39.es/ecma262/#sec-touint8
  796. ThrowCompletionOr<u8> Value::to_u8(VM& vm) const
  797. {
  798. double value = TRY(to_number(vm)).as_double();
  799. if (!isfinite(value) || value == 0)
  800. return 0;
  801. auto int_val = floor(fabs(value));
  802. if (signbit(value))
  803. int_val = -int_val;
  804. auto int8bit = fmod(int_val, NumericLimits<u8>::max() + 1.0);
  805. if (int8bit < 0)
  806. int8bit += NumericLimits<u8>::max() + 1.0;
  807. return static_cast<u8>(int8bit);
  808. }
  809. // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp
  810. ThrowCompletionOr<u8> Value::to_u8_clamp(VM& vm) const
  811. {
  812. auto number = TRY(to_number(vm));
  813. if (number.is_nan())
  814. return 0;
  815. double value = number.as_double();
  816. if (value <= 0.0)
  817. return 0;
  818. if (value >= 255.0)
  819. return 255;
  820. auto int_val = floor(value);
  821. if (int_val + 0.5 < value)
  822. return static_cast<u8>(int_val + 1.0);
  823. if (value < int_val + 0.5)
  824. return static_cast<u8>(int_val);
  825. if (fmod(int_val, 2.0) == 1.0)
  826. return static_cast<u8>(int_val + 1.0);
  827. return static_cast<u8>(int_val);
  828. }
  829. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  830. ThrowCompletionOr<size_t> Value::to_length(VM& vm) const
  831. {
  832. auto len = TRY(to_integer_or_infinity(vm));
  833. if (len <= 0)
  834. return 0;
  835. // 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.
  836. constexpr double length_limit = sizeof(void*) == 4 ? NumericLimits<size_t>::max() : MAX_ARRAY_LIKE_INDEX;
  837. return min(len, length_limit);
  838. }
  839. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  840. ThrowCompletionOr<size_t> Value::to_index(VM& vm) const
  841. {
  842. if (is_undefined())
  843. return 0;
  844. auto integer_index = TRY(to_integer_or_infinity(vm));
  845. if (integer_index < 0)
  846. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  847. auto index = MUST(Value(integer_index).to_length(vm));
  848. if (integer_index != index)
  849. return vm.throw_completion<RangeError>(ErrorType::InvalidIndex);
  850. return index;
  851. }
  852. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  853. ThrowCompletionOr<double> Value::to_integer_or_infinity(VM& vm) const
  854. {
  855. auto number = TRY(to_number(vm));
  856. if (number.is_nan() || number.as_double() == 0)
  857. return 0;
  858. if (number.is_infinity())
  859. return number.as_double();
  860. auto integer = floor(fabs(number.as_double()));
  861. if (number.as_double() < 0 && integer != 0)
  862. integer = -integer;
  863. return integer;
  864. }
  865. // Standalone variant using plain doubles for cases where we already got numbers and know the AO won't throw.
  866. double to_integer_or_infinity(double number)
  867. {
  868. // 1. Let number be ? ToNumber(argument).
  869. // 2. If number is NaN, +0𝔽, or -0𝔽, return 0.
  870. if (isnan(number) || number == 0)
  871. return 0;
  872. // 3. If number is +∞𝔽, return +∞.
  873. if (__builtin_isinf_sign(number) > 0)
  874. return static_cast<double>(INFINITY);
  875. // 4. If number is -∞𝔽, return -∞.
  876. if (__builtin_isinf_sign(number) < 0)
  877. return static_cast<double>(-INFINITY);
  878. // 5. Let integer be floor(abs(ℝ(number))).
  879. auto integer = floor(fabs(number));
  880. // 6. If number < -0𝔽, set integer to -integer.
  881. if (number < 0 && integer != 0)
  882. integer = -integer;
  883. // 7. Return integer.
  884. return integer;
  885. }
  886. // 7.3.3 GetV ( V, P ), https://tc39.es/ecma262/#sec-getv
  887. ThrowCompletionOr<Value> Value::get(VM& vm, PropertyKey const& property_key) const
  888. {
  889. // 1. Assert: IsPropertyKey(P) is true.
  890. VERIFY(property_key.is_valid());
  891. // 2. Let O be ? ToObject(V).
  892. auto* object = TRY(to_object(vm));
  893. // 3. Return ? O.[[Get]](P, V).
  894. return TRY(object->internal_get(property_key, *this));
  895. }
  896. // 7.3.11 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  897. ThrowCompletionOr<FunctionObject*> Value::get_method(VM& vm, PropertyKey const& property_key) const
  898. {
  899. // 1. Assert: IsPropertyKey(P) is true.
  900. VERIFY(property_key.is_valid());
  901. // 2. Let func be ? GetV(V, P).
  902. auto function = TRY(get(vm, property_key));
  903. // 3. If func is either undefined or null, return undefined.
  904. if (function.is_nullish())
  905. return nullptr;
  906. // 4. If IsCallable(func) is false, throw a TypeError exception.
  907. if (!function.is_function())
  908. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, function.to_string_without_side_effects());
  909. // 5. Return func.
  910. return &function.as_function();
  911. }
  912. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  913. ThrowCompletionOr<Value> greater_than(VM& vm, Value lhs, Value rhs)
  914. {
  915. if (lhs.is_int32() && rhs.is_int32())
  916. return lhs.as_i32() > rhs.as_i32();
  917. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  918. if (relation == TriState::Unknown)
  919. return Value(false);
  920. return Value(relation == TriState::True);
  921. }
  922. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  923. ThrowCompletionOr<Value> greater_than_equals(VM& vm, Value lhs, Value rhs)
  924. {
  925. if (lhs.is_int32() && rhs.is_int32())
  926. return lhs.as_i32() >= rhs.as_i32();
  927. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  928. if (relation == TriState::Unknown || relation == TriState::True)
  929. return Value(false);
  930. return Value(true);
  931. }
  932. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  933. ThrowCompletionOr<Value> less_than(VM& vm, Value lhs, Value rhs)
  934. {
  935. if (lhs.is_int32() && rhs.is_int32())
  936. return lhs.as_i32() < rhs.as_i32();
  937. TriState relation = TRY(is_less_than(vm, lhs, rhs, true));
  938. if (relation == TriState::Unknown)
  939. return Value(false);
  940. return Value(relation == TriState::True);
  941. }
  942. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  943. ThrowCompletionOr<Value> less_than_equals(VM& vm, Value lhs, Value rhs)
  944. {
  945. if (lhs.is_int32() && rhs.is_int32())
  946. return lhs.as_i32() <= rhs.as_i32();
  947. TriState relation = TRY(is_less_than(vm, lhs, rhs, false));
  948. if (relation == TriState::Unknown || relation == TriState::True)
  949. return Value(false);
  950. return Value(true);
  951. }
  952. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  953. ThrowCompletionOr<Value> bitwise_and(VM& vm, Value lhs, Value rhs)
  954. {
  955. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  956. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  957. if (both_number(lhs_numeric, rhs_numeric)) {
  958. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  959. return Value(0);
  960. return Value(TRY(lhs_numeric.to_i32(vm)) & TRY(rhs_numeric.to_i32(vm)));
  961. }
  962. if (both_bigint(lhs_numeric, rhs_numeric))
  963. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  964. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  965. }
  966. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  967. ThrowCompletionOr<Value> bitwise_or(VM& vm, Value lhs, Value rhs)
  968. {
  969. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  970. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  971. if (both_number(lhs_numeric, rhs_numeric)) {
  972. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  973. return Value(0);
  974. if (!lhs_numeric.is_finite_number())
  975. return rhs_numeric;
  976. if (!rhs_numeric.is_finite_number())
  977. return lhs_numeric;
  978. return Value(TRY(lhs_numeric.to_i32(vm)) | TRY(rhs_numeric.to_i32(vm)));
  979. }
  980. if (both_bigint(lhs_numeric, rhs_numeric))
  981. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  982. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  983. }
  984. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  985. ThrowCompletionOr<Value> bitwise_xor(VM& vm, Value lhs, Value rhs)
  986. {
  987. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  988. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  989. if (both_number(lhs_numeric, rhs_numeric)) {
  990. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  991. return Value(0);
  992. if (!lhs_numeric.is_finite_number())
  993. return rhs_numeric;
  994. if (!rhs_numeric.is_finite_number())
  995. return lhs_numeric;
  996. return Value(TRY(lhs_numeric.to_i32(vm)) ^ TRY(rhs_numeric.to_i32(vm)));
  997. }
  998. if (both_bigint(lhs_numeric, rhs_numeric))
  999. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  1000. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  1001. }
  1002. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  1003. ThrowCompletionOr<Value> bitwise_not(VM& vm, Value lhs)
  1004. {
  1005. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1006. if (lhs_numeric.is_number())
  1007. return Value(~TRY(lhs_numeric.to_i32(vm)));
  1008. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().bitwise_not());
  1009. }
  1010. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  1011. ThrowCompletionOr<Value> unary_plus(VM& vm, Value lhs)
  1012. {
  1013. return TRY(lhs.to_number(vm));
  1014. }
  1015. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  1016. ThrowCompletionOr<Value> unary_minus(VM& vm, Value lhs)
  1017. {
  1018. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1019. if (lhs_numeric.is_number()) {
  1020. if (lhs_numeric.is_nan())
  1021. return js_nan();
  1022. return Value(-lhs_numeric.as_double());
  1023. }
  1024. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1025. return BigInt::create(vm, BIGINT_ZERO);
  1026. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  1027. big_integer_negated.negate();
  1028. return BigInt::create(vm, big_integer_negated);
  1029. }
  1030. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  1031. ThrowCompletionOr<Value> left_shift(VM& vm, Value lhs, Value rhs)
  1032. {
  1033. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1034. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1035. if (both_number(lhs_numeric, rhs_numeric)) {
  1036. if (!lhs_numeric.is_finite_number())
  1037. return Value(0);
  1038. if (!rhs_numeric.is_finite_number())
  1039. return lhs_numeric;
  1040. // Ok, so this performs toNumber() again but that "can't" throw
  1041. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1042. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1043. return Value(lhs_i32 << rhs_u32);
  1044. }
  1045. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1046. // 6.1.6.2.9 BigInt::leftShift ( x, y ), https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
  1047. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  1048. // 1. If y < 0ℤ, then
  1049. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  1050. // a. Return the BigInt value that represents ℝ(x) / 2^-y, rounding down to the nearest integer, including for negative numbers.
  1051. // NOTE: Since y is negative we can just do ℝ(x) / 2^|y|
  1052. auto const& big_integer = lhs_numeric.as_bigint().big_integer();
  1053. auto division_result = big_integer.divided_by(multiplier_divisor);
  1054. // For positive initial values and no remainder just return quotient
  1055. if (division_result.remainder.is_zero() || !big_integer.is_negative())
  1056. return BigInt::create(vm, division_result.quotient);
  1057. // For negative round "down" to the next negative number
  1058. return BigInt::create(vm, division_result.quotient.minus(Crypto::SignedBigInteger { 1 }));
  1059. }
  1060. // 2. Return the BigInt value that represents ℝ(x) × 2^y.
  1061. return Value(BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor)));
  1062. }
  1063. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "left-shift");
  1064. }
  1065. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  1066. ThrowCompletionOr<Value> right_shift(VM& vm, Value lhs, Value rhs)
  1067. {
  1068. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1069. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1070. if (both_number(lhs_numeric, rhs_numeric)) {
  1071. if (!lhs_numeric.is_finite_number())
  1072. return Value(0);
  1073. if (!rhs_numeric.is_finite_number())
  1074. return lhs_numeric;
  1075. auto lhs_i32 = MUST(lhs_numeric.to_i32(vm));
  1076. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1077. return Value(lhs_i32 >> rhs_u32);
  1078. }
  1079. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1080. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  1081. rhs_negated.negate();
  1082. return left_shift(vm, lhs, BigInt::create(vm, rhs_negated));
  1083. }
  1084. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "right-shift");
  1085. }
  1086. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  1087. ThrowCompletionOr<Value> unsigned_right_shift(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. if (!lhs_numeric.is_finite_number())
  1093. return Value(0);
  1094. if (!rhs_numeric.is_finite_number())
  1095. return lhs_numeric;
  1096. // Ok, so this performs toNumber() again but that "can't" throw
  1097. auto lhs_u32 = MUST(lhs_numeric.to_u32(vm));
  1098. auto rhs_u32 = MUST(rhs_numeric.to_u32(vm)) % 32;
  1099. return Value(lhs_u32 >> rhs_u32);
  1100. }
  1101. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperator, "unsigned right-shift");
  1102. }
  1103. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  1104. ThrowCompletionOr<Value> add(VM& vm, Value lhs, Value rhs)
  1105. {
  1106. if (both_number(lhs, rhs)) {
  1107. if (lhs.is_int32() && rhs.is_int32()) {
  1108. Checked<i32> result;
  1109. result = MUST(lhs.to_i32(vm));
  1110. result += MUST(rhs.to_i32(vm));
  1111. if (!result.has_overflow())
  1112. return Value(result.value());
  1113. }
  1114. return Value(lhs.as_double() + rhs.as_double());
  1115. }
  1116. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1117. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1118. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  1119. auto lhs_string = TRY(lhs_primitive.to_primitive_string(vm));
  1120. auto rhs_string = TRY(rhs_primitive.to_primitive_string(vm));
  1121. return PrimitiveString::create(vm, *lhs_string, *rhs_string);
  1122. }
  1123. auto lhs_numeric = TRY(lhs_primitive.to_numeric(vm));
  1124. auto rhs_numeric = TRY(rhs_primitive.to_numeric(vm));
  1125. if (both_number(lhs_numeric, rhs_numeric))
  1126. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  1127. if (both_bigint(lhs_numeric, rhs_numeric))
  1128. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer()));
  1129. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "addition");
  1130. }
  1131. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1132. ThrowCompletionOr<Value> sub(VM& vm, Value lhs, Value rhs)
  1133. {
  1134. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1135. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1136. if (both_number(lhs_numeric, rhs_numeric)) {
  1137. double lhsd = lhs_numeric.as_double();
  1138. double rhsd = rhs_numeric.as_double();
  1139. double interm = lhsd - rhsd;
  1140. return Value(interm);
  1141. }
  1142. if (both_bigint(lhs_numeric, rhs_numeric))
  1143. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer()));
  1144. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1145. }
  1146. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1147. ThrowCompletionOr<Value> mul(VM& vm, Value lhs, Value rhs)
  1148. {
  1149. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1150. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1151. if (both_number(lhs_numeric, rhs_numeric))
  1152. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  1153. if (both_bigint(lhs_numeric, rhs_numeric))
  1154. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer()));
  1155. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1156. }
  1157. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1158. ThrowCompletionOr<Value> div(VM& vm, Value lhs, Value rhs)
  1159. {
  1160. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1161. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1162. if (both_number(lhs_numeric, rhs_numeric))
  1163. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1164. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1165. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1166. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1167. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient);
  1168. }
  1169. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "division");
  1170. }
  1171. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1172. ThrowCompletionOr<Value> mod(VM& vm, Value lhs, Value rhs)
  1173. {
  1174. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1175. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1176. if (both_number(lhs_numeric, rhs_numeric)) {
  1177. // 6.1.6.1.6 Number::remainder ( n, d ), https://tc39.es/ecma262/#sec-numeric-types-number-remainder
  1178. // The ECMA specification is describing the mathematical definition of modulus
  1179. // implemented by fmod.
  1180. auto n = lhs_numeric.as_double();
  1181. auto d = rhs_numeric.as_double();
  1182. return Value(fmod(n, d));
  1183. }
  1184. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1185. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  1186. return vm.throw_completion<RangeError>(ErrorType::DivisionByZero);
  1187. return BigInt::create(vm, lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder);
  1188. }
  1189. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "modulo");
  1190. }
  1191. static Value exp_double(Value base, Value exponent)
  1192. {
  1193. VERIFY(both_number(base, exponent));
  1194. if (exponent.is_nan())
  1195. return js_nan();
  1196. if (exponent.is_positive_zero() || exponent.is_negative_zero())
  1197. return Value(1);
  1198. if (base.is_nan())
  1199. return js_nan();
  1200. if (base.is_positive_infinity())
  1201. return exponent.as_double() > 0 ? js_infinity() : Value(0);
  1202. if (base.is_negative_infinity()) {
  1203. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1204. if (exponent.as_double() > 0)
  1205. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1206. else
  1207. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1208. }
  1209. if (base.is_positive_zero())
  1210. return exponent.as_double() > 0 ? Value(0) : js_infinity();
  1211. if (base.is_negative_zero()) {
  1212. auto is_odd_integral_number = exponent.is_integral_number() && (static_cast<i32>(exponent.as_double()) % 2 != 0);
  1213. if (exponent.as_double() > 0)
  1214. return is_odd_integral_number ? Value(-0.0) : Value(0);
  1215. else
  1216. return is_odd_integral_number ? js_negative_infinity() : js_infinity();
  1217. }
  1218. VERIFY(base.is_finite_number() && !base.is_positive_zero() && !base.is_negative_zero());
  1219. if (exponent.is_positive_infinity()) {
  1220. auto absolute_base = fabs(base.as_double());
  1221. if (absolute_base > 1)
  1222. return js_infinity();
  1223. else if (absolute_base == 1)
  1224. return js_nan();
  1225. else if (absolute_base < 1)
  1226. return Value(0);
  1227. }
  1228. if (exponent.is_negative_infinity()) {
  1229. auto absolute_base = fabs(base.as_double());
  1230. if (absolute_base > 1)
  1231. return Value(0);
  1232. else if (absolute_base == 1)
  1233. return js_nan();
  1234. else if (absolute_base < 1)
  1235. return js_infinity();
  1236. }
  1237. VERIFY(exponent.is_finite_number() && !exponent.is_positive_zero() && !exponent.is_negative_zero());
  1238. if (base.as_double() < 0 && !exponent.is_integral_number())
  1239. return js_nan();
  1240. return Value(::pow(base.as_double(), exponent.as_double()));
  1241. }
  1242. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1243. ThrowCompletionOr<Value> exp(VM& vm, Value lhs, Value rhs)
  1244. {
  1245. auto lhs_numeric = TRY(lhs.to_numeric(vm));
  1246. auto rhs_numeric = TRY(rhs.to_numeric(vm));
  1247. if (both_number(lhs_numeric, rhs_numeric))
  1248. return exp_double(lhs_numeric, rhs_numeric);
  1249. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1250. if (rhs_numeric.as_bigint().big_integer().is_negative())
  1251. return vm.throw_completion<RangeError>(ErrorType::NegativeExponent);
  1252. return BigInt::create(vm, Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
  1253. }
  1254. return vm.throw_completion<TypeError>(ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1255. }
  1256. ThrowCompletionOr<Value> in(VM& vm, Value lhs, Value rhs)
  1257. {
  1258. if (!rhs.is_object())
  1259. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  1260. auto lhs_property_key = TRY(lhs.to_property_key(vm));
  1261. return Value(TRY(rhs.as_object().has_property(lhs_property_key)));
  1262. }
  1263. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1264. ThrowCompletionOr<Value> instance_of(VM& vm, Value lhs, Value rhs)
  1265. {
  1266. if (!rhs.is_object())
  1267. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  1268. auto has_instance_method = TRY(rhs.get_method(vm, *vm.well_known_symbol_has_instance()));
  1269. if (has_instance_method) {
  1270. auto has_instance_result = TRY(call(vm, *has_instance_method, rhs, lhs));
  1271. return Value(has_instance_result.to_boolean());
  1272. }
  1273. if (!rhs.is_function())
  1274. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  1275. return TRY(ordinary_has_instance(vm, lhs, rhs));
  1276. }
  1277. // 7.3.22 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1278. ThrowCompletionOr<Value> ordinary_has_instance(VM& vm, Value lhs, Value rhs)
  1279. {
  1280. if (!rhs.is_function())
  1281. return Value(false);
  1282. auto& rhs_function = rhs.as_function();
  1283. if (is<BoundFunction>(rhs_function)) {
  1284. auto& bound_target = static_cast<BoundFunction const&>(rhs_function);
  1285. return instance_of(vm, lhs, Value(&bound_target.bound_target_function()));
  1286. }
  1287. if (!lhs.is_object())
  1288. return Value(false);
  1289. Object* lhs_object = &lhs.as_object();
  1290. auto rhs_prototype = TRY(rhs_function.get(vm.names.prototype));
  1291. if (!rhs_prototype.is_object())
  1292. return vm.throw_completion<TypeError>(ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1293. while (true) {
  1294. lhs_object = TRY(lhs_object->internal_get_prototype_of());
  1295. if (!lhs_object)
  1296. return Value(false);
  1297. if (same_value(rhs_prototype, lhs_object))
  1298. return Value(true);
  1299. }
  1300. }
  1301. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1302. bool same_value(Value lhs, Value rhs)
  1303. {
  1304. if (!same_type_for_equality(lhs, rhs))
  1305. return false;
  1306. if (lhs.is_number()) {
  1307. if (lhs.is_nan() && rhs.is_nan())
  1308. return true;
  1309. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1310. return false;
  1311. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1312. return false;
  1313. return lhs.as_double() == rhs.as_double();
  1314. }
  1315. if (lhs.is_bigint()) {
  1316. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1317. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1318. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1319. return false;
  1320. return lhs_big_integer == rhs_big_integer;
  1321. }
  1322. return same_value_non_numeric(lhs, rhs);
  1323. }
  1324. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1325. bool same_value_zero(Value lhs, Value rhs)
  1326. {
  1327. if (!same_type_for_equality(lhs, rhs))
  1328. return false;
  1329. if (lhs.is_number()) {
  1330. if (lhs.is_nan() && rhs.is_nan())
  1331. return true;
  1332. return lhs.as_double() == rhs.as_double();
  1333. }
  1334. if (lhs.is_bigint())
  1335. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1336. return same_value_non_numeric(lhs, rhs);
  1337. }
  1338. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1339. bool same_value_non_numeric(Value lhs, Value rhs)
  1340. {
  1341. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1342. VERIFY(same_type_for_equality(lhs, rhs));
  1343. if (lhs.is_string())
  1344. return lhs.as_string().deprecated_string() == rhs.as_string().deprecated_string();
  1345. return lhs.m_value.encoded == rhs.m_value.encoded;
  1346. }
  1347. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1348. bool is_strictly_equal(Value lhs, Value rhs)
  1349. {
  1350. if (!same_type_for_equality(lhs, rhs))
  1351. return false;
  1352. if (lhs.is_number()) {
  1353. if (lhs.is_nan() || rhs.is_nan())
  1354. return false;
  1355. if (lhs.as_double() == rhs.as_double())
  1356. return true;
  1357. return false;
  1358. }
  1359. if (lhs.is_bigint())
  1360. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1361. return same_value_non_numeric(lhs, rhs);
  1362. }
  1363. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1364. ThrowCompletionOr<bool> is_loosely_equal(VM& vm, Value lhs, Value rhs)
  1365. {
  1366. // 1. If Type(x) is the same as Type(y), then
  1367. if (same_type_for_equality(lhs, rhs)) {
  1368. // a. Return IsStrictlyEqual(x, y).
  1369. return is_strictly_equal(lhs, rhs);
  1370. }
  1371. // 2. If x is null and y is undefined, return true.
  1372. // 3. If x is undefined and y is null, return true.
  1373. if (lhs.is_nullish() && rhs.is_nullish())
  1374. return true;
  1375. // 4. NOTE: This step is replaced in section B.3.6.2.
  1376. // B.3.6.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1377. // 4. Perform the following steps:
  1378. // a. If Type(x) is Object and x has an [[IsHTMLDDA]] internal slot and y is either null or undefined, return true.
  1379. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1380. return true;
  1381. // b. If x is either null or undefined and Type(y) is Object and y has an [[IsHTMLDDA]] internal slot, return true.
  1382. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1383. return true;
  1384. // == End of B.3.6.2 ==
  1385. // 5. If Type(x) is Number and Type(y) is String, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1386. if (lhs.is_number() && rhs.is_string())
  1387. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1388. // 6. If Type(x) is String and Type(y) is Number, return ! IsLooselyEqual(! ToNumber(x), y).
  1389. if (lhs.is_string() && rhs.is_number())
  1390. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1391. // 7. If Type(x) is BigInt and Type(y) is String, then
  1392. if (lhs.is_bigint() && rhs.is_string()) {
  1393. // a. Let n be StringToBigInt(y).
  1394. auto bigint = string_to_bigint(vm, rhs.as_string().deprecated_string());
  1395. // b. If n is undefined, return false.
  1396. if (!bigint.has_value())
  1397. return false;
  1398. // c. Return ! IsLooselyEqual(x, n).
  1399. return is_loosely_equal(vm, lhs, *bigint);
  1400. }
  1401. // 8. If Type(x) is String and Type(y) is BigInt, return ! IsLooselyEqual(y, x).
  1402. if (lhs.is_string() && rhs.is_bigint())
  1403. return is_loosely_equal(vm, rhs, lhs);
  1404. // 9. If Type(x) is Boolean, return ! IsLooselyEqual(! ToNumber(x), y).
  1405. if (lhs.is_boolean())
  1406. return is_loosely_equal(vm, MUST(lhs.to_number(vm)), rhs);
  1407. // 10. If Type(y) is Boolean, return ! IsLooselyEqual(x, ! ToNumber(y)).
  1408. if (rhs.is_boolean())
  1409. return is_loosely_equal(vm, lhs, MUST(rhs.to_number(vm)));
  1410. // 11. If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return ! IsLooselyEqual(x, ? ToPrimitive(y)).
  1411. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1412. auto rhs_primitive = TRY(rhs.to_primitive(vm));
  1413. return is_loosely_equal(vm, lhs, rhs_primitive);
  1414. }
  1415. // 12. If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return ! IsLooselyEqual(? ToPrimitive(x), y).
  1416. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || rhs.is_bigint() || rhs.is_symbol())) {
  1417. auto lhs_primitive = TRY(lhs.to_primitive(vm));
  1418. return is_loosely_equal(vm, lhs_primitive, rhs);
  1419. }
  1420. // 13. If Type(x) is BigInt and Type(y) is Number, or if Type(x) is Number and Type(y) is BigInt, then
  1421. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1422. // a. If x or y are any of NaN, +∞𝔽, or -∞𝔽, return false.
  1423. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1424. return false;
  1425. // b. If ℝ(x) = ℝ(y), return true; otherwise return false.
  1426. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1427. return false;
  1428. VERIFY(!lhs.is_nan() && !rhs.is_nan());
  1429. auto& number_side = lhs.is_number() ? lhs : rhs;
  1430. auto& bigint_side = lhs.is_number() ? rhs : lhs;
  1431. return bigint_side.as_bigint().big_integer().compare_to_double(number_side.as_double()) == Crypto::UnsignedBigInteger::CompareResult::DoubleEqualsBigInt;
  1432. }
  1433. // 14. Return false.
  1434. return false;
  1435. }
  1436. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1437. ThrowCompletionOr<TriState> is_less_than(VM& vm, Value lhs, Value rhs, bool left_first)
  1438. {
  1439. Value x_primitive;
  1440. Value y_primitive;
  1441. if (left_first) {
  1442. x_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1443. y_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1444. } else {
  1445. y_primitive = TRY(lhs.to_primitive(vm, Value::PreferredType::Number));
  1446. x_primitive = TRY(rhs.to_primitive(vm, Value::PreferredType::Number));
  1447. }
  1448. if (x_primitive.is_string() && y_primitive.is_string()) {
  1449. auto x_string = x_primitive.as_string().deprecated_string();
  1450. auto y_string = y_primitive.as_string().deprecated_string();
  1451. Utf8View x_code_points { x_string };
  1452. Utf8View y_code_points { y_string };
  1453. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1454. k != x_code_points.end() && l != y_code_points.end();
  1455. ++k, ++l) {
  1456. if (*k != *l) {
  1457. if (*k < *l) {
  1458. return TriState::True;
  1459. } else {
  1460. return TriState::False;
  1461. }
  1462. }
  1463. }
  1464. return x_code_points.length() < y_code_points.length()
  1465. ? TriState::True
  1466. : TriState::False;
  1467. }
  1468. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1469. auto y_bigint = string_to_bigint(vm, y_primitive.as_string().deprecated_string());
  1470. if (!y_bigint.has_value())
  1471. return TriState::Unknown;
  1472. if (x_primitive.as_bigint().big_integer() < (*y_bigint)->big_integer())
  1473. return TriState::True;
  1474. return TriState::False;
  1475. }
  1476. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1477. auto x_bigint = string_to_bigint(vm, x_primitive.as_string().deprecated_string());
  1478. if (!x_bigint.has_value())
  1479. return TriState::Unknown;
  1480. if ((*x_bigint)->big_integer() < y_primitive.as_bigint().big_integer())
  1481. return TriState::True;
  1482. return TriState::False;
  1483. }
  1484. auto x_numeric = TRY(x_primitive.to_numeric(vm));
  1485. auto y_numeric = TRY(y_primitive.to_numeric(vm));
  1486. if (x_numeric.is_nan() || y_numeric.is_nan())
  1487. return TriState::Unknown;
  1488. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1489. return TriState::False;
  1490. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1491. return TriState::True;
  1492. if (x_numeric.is_number() && y_numeric.is_number()) {
  1493. if (x_numeric.as_double() < y_numeric.as_double())
  1494. return TriState::True;
  1495. else
  1496. return TriState::False;
  1497. }
  1498. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1499. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1500. return TriState::True;
  1501. else
  1502. return TriState::False;
  1503. }
  1504. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1505. bool x_lower_than_y;
  1506. VERIFY(!x_numeric.is_nan() && !y_numeric.is_nan());
  1507. if (x_numeric.is_number()) {
  1508. x_lower_than_y = y_numeric.as_bigint().big_integer().compare_to_double(x_numeric.as_double())
  1509. == Crypto::UnsignedBigInteger::CompareResult::DoubleLessThanBigInt;
  1510. } else {
  1511. x_lower_than_y = x_numeric.as_bigint().big_integer().compare_to_double(y_numeric.as_double())
  1512. == Crypto::UnsignedBigInteger::CompareResult::DoubleGreaterThanBigInt;
  1513. }
  1514. if (x_lower_than_y)
  1515. return TriState::True;
  1516. else
  1517. return TriState::False;
  1518. }
  1519. // 7.3.21 Invoke ( V, P [ , argumentsList ] ), https://tc39.es/ecma262/#sec-invoke
  1520. ThrowCompletionOr<Value> Value::invoke_internal(VM& vm, PropertyKey const& property_key, Optional<MarkedVector<Value>> arguments)
  1521. {
  1522. auto property = TRY(get(vm, property_key));
  1523. if (!property.is_function())
  1524. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, property.to_string_without_side_effects());
  1525. return call(vm, property.as_function(), *this, move(arguments));
  1526. }
  1527. }