Value.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/AllOf.h>
  8. #include <AK/FlyString.h>
  9. #include <AK/Result.h>
  10. #include <AK/String.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Utf8View.h>
  13. #include <LibCrypto/BigInt/SignedBigInteger.h>
  14. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  15. #include <LibJS/Heap/Heap.h>
  16. #include <LibJS/Runtime/Accessor.h>
  17. #include <LibJS/Runtime/Array.h>
  18. #include <LibJS/Runtime/BigInt.h>
  19. #include <LibJS/Runtime/BigIntObject.h>
  20. #include <LibJS/Runtime/BooleanObject.h>
  21. #include <LibJS/Runtime/BoundFunction.h>
  22. #include <LibJS/Runtime/Error.h>
  23. #include <LibJS/Runtime/Function.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/NativeFunction.h>
  26. #include <LibJS/Runtime/NumberObject.h>
  27. #include <LibJS/Runtime/Object.h>
  28. #include <LibJS/Runtime/PrimitiveString.h>
  29. #include <LibJS/Runtime/ProxyObject.h>
  30. #include <LibJS/Runtime/RegExpObject.h>
  31. #include <LibJS/Runtime/StringObject.h>
  32. #include <LibJS/Runtime/Symbol.h>
  33. #include <LibJS/Runtime/SymbolObject.h>
  34. #include <LibJS/Runtime/Value.h>
  35. #include <math.h>
  36. namespace JS {
  37. // Used in various abstract operations to make it obvious when a non-optional return value must be discarded.
  38. static const double INVALID { 0 };
  39. static inline bool same_type_for_equality(const Value& lhs, const Value& rhs)
  40. {
  41. if (lhs.type() == rhs.type())
  42. return true;
  43. if (lhs.is_number() && rhs.is_number())
  44. return true;
  45. return false;
  46. }
  47. static const Crypto::SignedBigInteger BIGINT_ZERO { 0 };
  48. static bool is_valid_bigint_value(StringView string)
  49. {
  50. string = string.trim_whitespace();
  51. if (string.length() > 1 && (string[0] == '-' || string[0] == '+'))
  52. string = string.substring_view(1, string.length() - 1);
  53. return all_of(string.begin(), string.end(), [](auto ch) { return isdigit(ch); });
  54. }
  55. ALWAYS_INLINE bool both_number(const Value& lhs, const Value& rhs)
  56. {
  57. return lhs.is_number() && rhs.is_number();
  58. }
  59. ALWAYS_INLINE bool both_bigint(const Value& lhs, const Value& 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. static String double_to_string(double d)
  65. {
  66. if (isnan(d))
  67. return "NaN";
  68. if (d == +0.0 || d == -0.0)
  69. return "0";
  70. if (d < +0.0) {
  71. StringBuilder builder;
  72. builder.append('-');
  73. builder.append(double_to_string(-d));
  74. return builder.to_string();
  75. }
  76. if (d == static_cast<double>(INFINITY))
  77. return "Infinity";
  78. StringBuilder number_string_builder;
  79. size_t start_index = 0;
  80. size_t end_index = 0;
  81. size_t int_part_end = 0;
  82. // generate integer part (reversed)
  83. double int_part;
  84. double frac_part;
  85. frac_part = modf(d, &int_part);
  86. while (int_part > 0) {
  87. number_string_builder.append('0' + (int)fmod(int_part, 10));
  88. end_index++;
  89. int_part = floor(int_part / 10);
  90. }
  91. auto reversed_integer_part = number_string_builder.to_string().reverse();
  92. number_string_builder.clear();
  93. number_string_builder.append(reversed_integer_part);
  94. int_part_end = end_index;
  95. int exponent = 0;
  96. // generate fractional part
  97. while (frac_part > 0) {
  98. double old_frac_part = frac_part;
  99. frac_part *= 10;
  100. frac_part = modf(frac_part, &int_part);
  101. if (old_frac_part == frac_part)
  102. break;
  103. number_string_builder.append('0' + (int)int_part);
  104. end_index++;
  105. exponent--;
  106. }
  107. auto number_string = number_string_builder.to_string();
  108. // FIXME: Remove this hack.
  109. // FIXME: Instead find the shortest round-trippable representation.
  110. // Remove decimals after the 15th position
  111. if (end_index > int_part_end + 15) {
  112. exponent += end_index - int_part_end - 15;
  113. end_index = int_part_end + 15;
  114. }
  115. // remove leading zeroes
  116. while (start_index < end_index && number_string[start_index] == '0') {
  117. start_index++;
  118. }
  119. // remove trailing zeroes
  120. while (end_index > 0 && number_string[end_index - 1] == '0') {
  121. end_index--;
  122. exponent++;
  123. }
  124. if (end_index <= start_index)
  125. return "0";
  126. auto digits = number_string.substring_view(start_index, end_index - start_index);
  127. int number_of_digits = end_index - start_index;
  128. exponent += number_of_digits;
  129. StringBuilder builder;
  130. if (number_of_digits <= exponent && exponent <= 21) {
  131. builder.append(digits);
  132. builder.append(String::repeated('0', exponent - number_of_digits));
  133. return builder.to_string();
  134. }
  135. if (0 < exponent && exponent <= 21) {
  136. builder.append(digits.substring_view(0, exponent));
  137. builder.append('.');
  138. builder.append(digits.substring_view(exponent));
  139. return builder.to_string();
  140. }
  141. if (-6 < exponent && exponent <= 0) {
  142. builder.append("0.");
  143. builder.append(String::repeated('0', -exponent));
  144. builder.append(digits);
  145. return builder.to_string();
  146. }
  147. if (number_of_digits == 1) {
  148. builder.append(digits);
  149. builder.append('e');
  150. if (exponent - 1 > 0)
  151. builder.append('+');
  152. else
  153. builder.append('-');
  154. builder.append(String::number(fabs(exponent - 1)));
  155. return builder.to_string();
  156. }
  157. builder.append(digits[0]);
  158. builder.append('.');
  159. builder.append(digits.substring_view(1));
  160. builder.append('e');
  161. if (exponent - 1 > 0)
  162. builder.append('+');
  163. else
  164. builder.append('-');
  165. builder.append(String::number(fabs(exponent - 1)));
  166. return builder.to_string();
  167. }
  168. // 7.2.2 IsArray ( argument ), https://tc39.es/ecma262/#sec-isarray
  169. bool Value::is_array(GlobalObject& global_object) const
  170. {
  171. if (!is_object())
  172. return false;
  173. auto& object = as_object();
  174. if (object.is_array())
  175. return true;
  176. if (is<ProxyObject>(object)) {
  177. auto& proxy = static_cast<ProxyObject const&>(object);
  178. if (proxy.is_revoked()) {
  179. auto& vm = global_object.vm();
  180. vm.throw_exception<TypeError>(global_object, ErrorType::ProxyRevoked);
  181. return false;
  182. }
  183. return Value(&proxy.target()).is_array(global_object);
  184. }
  185. return false;
  186. }
  187. Array& Value::as_array()
  188. {
  189. VERIFY(is_object() && as_object().is_array());
  190. return static_cast<Array&>(*m_value.as_object);
  191. }
  192. // 7.2.3 IsCallable ( argument ), https://tc39.es/ecma262/#sec-iscallable
  193. bool Value::is_function() const
  194. {
  195. return is_object() && as_object().is_function();
  196. }
  197. Function& Value::as_function()
  198. {
  199. VERIFY(is_function());
  200. return static_cast<Function&>(as_object());
  201. }
  202. // 7.2.4 IsConstructor ( argument ), https://tc39.es/ecma262/#sec-isconstructor
  203. bool Value::is_constructor() const
  204. {
  205. if (!is_function())
  206. return false;
  207. if (is<NativeFunction>(as_object()))
  208. return static_cast<const NativeFunction&>(as_object()).has_constructor();
  209. // ScriptFunction or BoundFunction
  210. return true;
  211. }
  212. // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
  213. bool Value::is_regexp(GlobalObject& global_object) const
  214. {
  215. if (!is_object())
  216. return false;
  217. auto matcher = as_object().get(global_object.vm().well_known_symbol_match());
  218. if (global_object.vm().exception())
  219. return false;
  220. if (!matcher.is_empty() && !matcher.is_undefined())
  221. return matcher.to_boolean();
  222. return is<RegExpObject>(as_object());
  223. }
  224. // 13.5.3 The typeof Operator, https://tc39.es/ecma262/#sec-typeof-operator
  225. String Value::typeof() const
  226. {
  227. switch (m_type) {
  228. case Value::Type::Undefined:
  229. return "undefined";
  230. case Value::Type::Null:
  231. return "object";
  232. case Value::Type::Int32:
  233. case Value::Type::Double:
  234. return "number";
  235. case Value::Type::String:
  236. return "string";
  237. case Value::Type::Object:
  238. if (is_function())
  239. return "function";
  240. return "object";
  241. case Value::Type::Boolean:
  242. return "boolean";
  243. case Value::Type::Symbol:
  244. return "symbol";
  245. case Value::Type::BigInt:
  246. return "bigint";
  247. default:
  248. VERIFY_NOT_REACHED();
  249. }
  250. }
  251. String Value::to_string_without_side_effects() const
  252. {
  253. switch (m_type) {
  254. case Type::Undefined:
  255. return "undefined";
  256. case Type::Null:
  257. return "null";
  258. case Type::Boolean:
  259. return m_value.as_bool ? "true" : "false";
  260. case Type::Int32:
  261. return String::number(m_value.as_i32);
  262. case Type::Double:
  263. return double_to_string(m_value.as_double);
  264. case Type::String:
  265. return m_value.as_string->string();
  266. case Type::Symbol:
  267. return m_value.as_symbol->to_string();
  268. case Type::BigInt:
  269. return m_value.as_bigint->to_string();
  270. case Type::Object:
  271. return String::formatted("[object {}]", as_object().class_name());
  272. case Type::Accessor:
  273. return "<accessor>";
  274. case Type::NativeProperty:
  275. return "<native-property>";
  276. default:
  277. VERIFY_NOT_REACHED();
  278. }
  279. }
  280. PrimitiveString* Value::to_primitive_string(GlobalObject& global_object)
  281. {
  282. if (is_string())
  283. return &as_string();
  284. auto string = to_string(global_object);
  285. if (global_object.vm().exception())
  286. return nullptr;
  287. return js_string(global_object.heap(), string);
  288. }
  289. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  290. String Value::to_string(GlobalObject& global_object, bool legacy_null_to_empty_string) const
  291. {
  292. switch (m_type) {
  293. case Type::Undefined:
  294. return "undefined";
  295. case Type::Null:
  296. return !legacy_null_to_empty_string ? "null" : String::empty();
  297. case Type::Boolean:
  298. return m_value.as_bool ? "true" : "false";
  299. case Type::Int32:
  300. return String::number(m_value.as_i32);
  301. case Type::Double:
  302. return double_to_string(m_value.as_double);
  303. case Type::String:
  304. return m_value.as_string->string();
  305. case Type::Symbol:
  306. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "string");
  307. return {};
  308. case Type::BigInt:
  309. return m_value.as_bigint->big_integer().to_base10();
  310. case Type::Object: {
  311. auto primitive_value = to_primitive(global_object, PreferredType::String);
  312. if (global_object.vm().exception())
  313. return {};
  314. return primitive_value.to_string(global_object);
  315. }
  316. default:
  317. VERIFY_NOT_REACHED();
  318. }
  319. }
  320. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  321. bool Value::to_boolean() const
  322. {
  323. switch (m_type) {
  324. case Type::Undefined:
  325. case Type::Null:
  326. return false;
  327. case Type::Boolean:
  328. return m_value.as_bool;
  329. case Type::Int32:
  330. return m_value.as_i32 != 0;
  331. case Type::Double:
  332. if (is_nan())
  333. return false;
  334. return m_value.as_double != 0;
  335. case Type::String:
  336. return !m_value.as_string->string().is_empty();
  337. case Type::Symbol:
  338. return true;
  339. case Type::BigInt:
  340. return m_value.as_bigint->big_integer() != BIGINT_ZERO;
  341. case Type::Object:
  342. return true;
  343. default:
  344. VERIFY_NOT_REACHED();
  345. }
  346. }
  347. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  348. Value Value::to_primitive(GlobalObject& global_object, PreferredType preferred_type) const
  349. {
  350. auto get_hint_for_preferred_type = [&]() -> String {
  351. switch (preferred_type) {
  352. case PreferredType::Default:
  353. return "default";
  354. case PreferredType::String:
  355. return "string";
  356. case PreferredType::Number:
  357. return "number";
  358. default:
  359. VERIFY_NOT_REACHED();
  360. }
  361. };
  362. if (is_object()) {
  363. auto& vm = global_object.vm();
  364. auto to_primitive_method = get_method(global_object, *this, vm.well_known_symbol_to_primitive());
  365. if (vm.exception())
  366. return {};
  367. if (to_primitive_method) {
  368. auto hint = get_hint_for_preferred_type();
  369. auto result = vm.call(*to_primitive_method, *this, js_string(vm, hint));
  370. if (vm.exception())
  371. return {};
  372. if (!result.is_object())
  373. return result;
  374. vm.throw_exception<TypeError>(global_object, ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  375. return {};
  376. }
  377. if (preferred_type == PreferredType::Default)
  378. preferred_type = PreferredType::Number;
  379. return as_object().ordinary_to_primitive(preferred_type);
  380. }
  381. return *this;
  382. }
  383. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  384. Object* Value::to_object(GlobalObject& global_object) const
  385. {
  386. switch (m_type) {
  387. case Type::Undefined:
  388. case Type::Null:
  389. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::ToObjectNullOrUndefined);
  390. return nullptr;
  391. case Type::Boolean:
  392. return BooleanObject::create(global_object, m_value.as_bool);
  393. case Type::Int32:
  394. case Type::Double:
  395. return NumberObject::create(global_object, as_double());
  396. case Type::String:
  397. return StringObject::create(global_object, *m_value.as_string);
  398. case Type::Symbol:
  399. return SymbolObject::create(global_object, *m_value.as_symbol);
  400. case Type::BigInt:
  401. return BigIntObject::create(global_object, *m_value.as_bigint);
  402. case Type::Object:
  403. return &const_cast<Object&>(as_object());
  404. default:
  405. dbgln("Dying because I can't to_object() on {}", *this);
  406. VERIFY_NOT_REACHED();
  407. }
  408. }
  409. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  410. FLATTEN Value Value::to_numeric(GlobalObject& global_object) const
  411. {
  412. auto primitive = to_primitive(global_object, Value::PreferredType::Number);
  413. if (global_object.vm().exception())
  414. return {};
  415. if (primitive.is_bigint())
  416. return primitive;
  417. return primitive.to_number(global_object);
  418. }
  419. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  420. Value Value::to_number(GlobalObject& global_object) const
  421. {
  422. switch (m_type) {
  423. case Type::Undefined:
  424. return js_nan();
  425. case Type::Null:
  426. return Value(0);
  427. case Type::Boolean:
  428. return Value(m_value.as_bool ? 1 : 0);
  429. case Type::Int32:
  430. case Type::Double:
  431. return *this;
  432. case Type::String: {
  433. auto string = as_string().string().trim_whitespace();
  434. if (string.is_empty())
  435. return Value(0);
  436. if (string == "Infinity" || string == "+Infinity")
  437. return js_infinity();
  438. if (string == "-Infinity")
  439. return js_negative_infinity();
  440. char* endptr;
  441. auto parsed_double = strtod(string.characters(), &endptr);
  442. if (*endptr)
  443. return js_nan();
  444. return Value(parsed_double);
  445. }
  446. case Type::Symbol:
  447. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "number");
  448. return {};
  449. case Type::BigInt:
  450. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "BigInt", "number");
  451. return {};
  452. case Type::Object: {
  453. auto primitive = to_primitive(global_object, PreferredType::Number);
  454. if (global_object.vm().exception())
  455. return {};
  456. return primitive.to_number(global_object);
  457. }
  458. default:
  459. VERIFY_NOT_REACHED();
  460. }
  461. }
  462. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  463. BigInt* Value::to_bigint(GlobalObject& global_object) const
  464. {
  465. auto& vm = global_object.vm();
  466. auto primitive = to_primitive(global_object, PreferredType::Number);
  467. if (vm.exception())
  468. return nullptr;
  469. switch (primitive.type()) {
  470. case Type::Undefined:
  471. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "undefined", "BigInt");
  472. return nullptr;
  473. case Type::Null:
  474. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "null", "BigInt");
  475. return nullptr;
  476. case Type::Boolean: {
  477. auto value = primitive.as_bool() ? 1 : 0;
  478. return js_bigint(vm.heap(), Crypto::SignedBigInteger { value });
  479. }
  480. case Type::BigInt:
  481. return &primitive.as_bigint();
  482. case Type::Int32:
  483. case Type::Double:
  484. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "number", "BigInt");
  485. return {};
  486. case Type::String: {
  487. auto& string = primitive.as_string().string();
  488. if (!is_valid_bigint_value(string)) {
  489. vm.throw_exception<SyntaxError>(global_object, ErrorType::BigIntInvalidValue, string);
  490. return {};
  491. }
  492. return js_bigint(vm.heap(), Crypto::SignedBigInteger::from_base10(string.trim_whitespace()));
  493. }
  494. case Type::Symbol:
  495. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "BigInt");
  496. return {};
  497. default:
  498. VERIFY_NOT_REACHED();
  499. }
  500. }
  501. // FIXME: These two conversions are wrong for JS, and seem likely to be footguns
  502. i32 Value::as_i32() const
  503. {
  504. return static_cast<i32>(as_double());
  505. }
  506. u32 Value::as_u32() const
  507. {
  508. VERIFY(as_double() >= 0);
  509. return min((u32)as_i32(), NumericLimits<u32>::max());
  510. }
  511. double Value::to_double(GlobalObject& global_object) const
  512. {
  513. auto number = to_number(global_object);
  514. if (global_object.vm().exception())
  515. return INVALID;
  516. return number.as_double();
  517. }
  518. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  519. StringOrSymbol Value::to_property_key(GlobalObject& global_object) const
  520. {
  521. auto key = to_primitive(global_object, PreferredType::String);
  522. if (global_object.vm().exception())
  523. return {};
  524. if (key.is_symbol())
  525. return &key.as_symbol();
  526. return key.to_string(global_object);
  527. }
  528. i32 Value::to_i32_slow_case(GlobalObject& global_object) const
  529. {
  530. VERIFY(type() != Type::Int32);
  531. auto number = to_number(global_object);
  532. if (global_object.vm().exception())
  533. return INVALID;
  534. double value = number.as_double();
  535. if (!isfinite(value) || value == 0)
  536. return 0;
  537. auto abs = fabs(value);
  538. auto int_val = floor(abs);
  539. if (signbit(value))
  540. int_val = -int_val;
  541. auto remainder = fmod(int_val, 4294967296.0);
  542. auto int32bit = remainder >= 0.0 ? remainder : remainder + 4294967296.0; // The notation “x modulo y” computes a value k of the same sign as y
  543. if (int32bit >= 2147483648.0)
  544. int32bit -= 4294967296.0;
  545. return static_cast<i32>(int32bit);
  546. }
  547. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  548. u32 Value::to_u32(GlobalObject& global_object) const
  549. {
  550. auto number = to_number(global_object);
  551. if (global_object.vm().exception())
  552. return INVALID;
  553. double value = number.as_double();
  554. if (!isfinite(value) || value == 0)
  555. return 0;
  556. auto int_val = floor(fabs(value));
  557. if (signbit(value))
  558. int_val = -int_val;
  559. auto int32bit = fmod(int_val, NumericLimits<u32>::max() + 1.0);
  560. return static_cast<u32>(int32bit);
  561. }
  562. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  563. size_t Value::to_length(GlobalObject& global_object) const
  564. {
  565. auto& vm = global_object.vm();
  566. auto len = to_integer_or_infinity(global_object);
  567. if (vm.exception())
  568. return INVALID;
  569. if (len <= 0)
  570. return 0;
  571. return min(len, MAX_ARRAY_LIKE_INDEX);
  572. }
  573. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  574. size_t Value::to_index(GlobalObject& global_object) const
  575. {
  576. auto& vm = global_object.vm();
  577. if (is_undefined())
  578. return 0;
  579. auto integer_index = to_integer_or_infinity(global_object);
  580. if (vm.exception())
  581. return INVALID;
  582. if (integer_index < 0) {
  583. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidIndex);
  584. return INVALID;
  585. }
  586. auto index = Value(integer_index).to_length(global_object);
  587. VERIFY(!vm.exception());
  588. if (integer_index != index) {
  589. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidIndex);
  590. return INVALID;
  591. }
  592. return index;
  593. }
  594. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  595. double Value::to_integer_or_infinity(GlobalObject& global_object) const
  596. {
  597. auto& vm = global_object.vm();
  598. auto number = to_number(global_object);
  599. if (vm.exception())
  600. return INVALID;
  601. if (number.is_nan() || number.as_double() == 0)
  602. return 0;
  603. if (number.is_infinity())
  604. return number.as_double();
  605. auto integer = floor(fabs(number.as_double()));
  606. if (number.as_double() < 0)
  607. integer = -integer;
  608. return integer;
  609. }
  610. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  611. Value greater_than(GlobalObject& global_object, Value lhs, Value rhs)
  612. {
  613. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  614. if (relation == TriState::Unknown)
  615. return Value(false);
  616. return Value(relation == TriState::True);
  617. }
  618. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  619. Value greater_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  620. {
  621. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  622. if (relation == TriState::Unknown || relation == TriState::True)
  623. return Value(false);
  624. return Value(true);
  625. }
  626. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  627. Value less_than(GlobalObject& global_object, Value lhs, Value rhs)
  628. {
  629. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  630. if (relation == TriState::Unknown)
  631. return Value(false);
  632. return Value(relation == TriState::True);
  633. }
  634. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  635. Value less_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  636. {
  637. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  638. if (relation == TriState::Unknown || relation == TriState::True)
  639. return Value(false);
  640. return Value(true);
  641. }
  642. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  643. Value bitwise_and(GlobalObject& global_object, Value lhs, Value rhs)
  644. {
  645. auto lhs_numeric = lhs.to_numeric(global_object);
  646. if (global_object.vm().exception())
  647. return {};
  648. auto rhs_numeric = rhs.to_numeric(global_object);
  649. if (global_object.vm().exception())
  650. return {};
  651. if (both_number(lhs_numeric, rhs_numeric)) {
  652. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  653. return Value(0);
  654. return Value(lhs_numeric.to_i32(global_object) & rhs_numeric.to_i32(global_object));
  655. }
  656. if (both_bigint(lhs_numeric, rhs_numeric))
  657. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  658. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  659. return {};
  660. }
  661. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  662. Value bitwise_or(GlobalObject& global_object, Value lhs, Value rhs)
  663. {
  664. auto lhs_numeric = lhs.to_numeric(global_object);
  665. if (global_object.vm().exception())
  666. return {};
  667. auto rhs_numeric = rhs.to_numeric(global_object);
  668. if (global_object.vm().exception())
  669. return {};
  670. if (both_number(lhs_numeric, rhs_numeric)) {
  671. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  672. return Value(0);
  673. if (!lhs_numeric.is_finite_number())
  674. return rhs_numeric;
  675. if (!rhs_numeric.is_finite_number())
  676. return lhs_numeric;
  677. return Value(lhs_numeric.to_i32(global_object) | rhs_numeric.to_i32(global_object));
  678. }
  679. if (both_bigint(lhs_numeric, rhs_numeric))
  680. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  681. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  682. return {};
  683. }
  684. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  685. Value bitwise_xor(GlobalObject& global_object, Value lhs, Value rhs)
  686. {
  687. auto lhs_numeric = lhs.to_numeric(global_object);
  688. if (global_object.vm().exception())
  689. return {};
  690. auto rhs_numeric = rhs.to_numeric(global_object);
  691. if (global_object.vm().exception())
  692. return {};
  693. if (both_number(lhs_numeric, rhs_numeric)) {
  694. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  695. return Value(0);
  696. if (!lhs_numeric.is_finite_number())
  697. return rhs_numeric;
  698. if (!rhs_numeric.is_finite_number())
  699. return lhs_numeric;
  700. return Value(lhs_numeric.to_i32(global_object) ^ rhs_numeric.to_i32(global_object));
  701. }
  702. if (both_bigint(lhs_numeric, rhs_numeric))
  703. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  704. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  705. return {};
  706. }
  707. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  708. Value bitwise_not(GlobalObject& global_object, Value lhs)
  709. {
  710. auto lhs_numeric = lhs.to_numeric(global_object);
  711. if (global_object.vm().exception())
  712. return {};
  713. if (lhs_numeric.is_number())
  714. return Value(~lhs_numeric.to_i32(global_object));
  715. auto big_integer_bitwise_not = lhs_numeric.as_bigint().big_integer();
  716. big_integer_bitwise_not = big_integer_bitwise_not.plus(Crypto::SignedBigInteger { 1 });
  717. big_integer_bitwise_not.negate();
  718. return js_bigint(global_object.heap(), big_integer_bitwise_not);
  719. }
  720. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  721. Value unary_plus(GlobalObject& global_object, Value lhs)
  722. {
  723. return lhs.to_number(global_object);
  724. }
  725. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  726. Value unary_minus(GlobalObject& global_object, Value lhs)
  727. {
  728. auto lhs_numeric = lhs.to_numeric(global_object);
  729. if (global_object.vm().exception())
  730. return {};
  731. if (lhs_numeric.is_number()) {
  732. if (lhs_numeric.is_nan())
  733. return js_nan();
  734. return Value(-lhs_numeric.as_double());
  735. }
  736. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  737. return js_bigint(global_object.heap(), BIGINT_ZERO);
  738. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  739. big_integer_negated.negate();
  740. return js_bigint(global_object.heap(), big_integer_negated);
  741. }
  742. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  743. Value left_shift(GlobalObject& global_object, Value lhs, Value rhs)
  744. {
  745. auto lhs_numeric = lhs.to_numeric(global_object);
  746. if (global_object.vm().exception())
  747. return {};
  748. auto rhs_numeric = rhs.to_numeric(global_object);
  749. if (global_object.vm().exception())
  750. return {};
  751. if (both_number(lhs_numeric, rhs_numeric)) {
  752. if (!lhs_numeric.is_finite_number())
  753. return Value(0);
  754. if (!rhs_numeric.is_finite_number())
  755. return lhs_numeric;
  756. // Ok, so this performs toNumber() again but that "can't" throw
  757. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  758. auto rhs_u32 = rhs_numeric.to_u32(global_object);
  759. return Value(lhs_i32 << rhs_u32);
  760. }
  761. if (both_bigint(lhs_numeric, rhs_numeric)) {
  762. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  763. if (rhs_numeric.as_bigint().big_integer().is_negative())
  764. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(multiplier_divisor).quotient);
  765. else
  766. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor));
  767. }
  768. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "left-shift");
  769. return {};
  770. }
  771. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  772. Value right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  773. {
  774. auto lhs_numeric = lhs.to_numeric(global_object);
  775. if (global_object.vm().exception())
  776. return {};
  777. auto rhs_numeric = rhs.to_numeric(global_object);
  778. if (global_object.vm().exception())
  779. return {};
  780. if (both_number(lhs_numeric, rhs_numeric)) {
  781. if (!lhs_numeric.is_finite_number())
  782. return Value(0);
  783. if (!rhs_numeric.is_finite_number())
  784. return lhs_numeric;
  785. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  786. auto rhs_u32 = rhs_numeric.to_u32(global_object);
  787. return Value(lhs_i32 >> rhs_u32);
  788. }
  789. if (both_bigint(lhs_numeric, rhs_numeric)) {
  790. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  791. rhs_negated.negate();
  792. return left_shift(global_object, lhs, js_bigint(global_object.heap(), rhs_negated));
  793. }
  794. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "right-shift");
  795. return {};
  796. }
  797. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  798. Value unsigned_right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  799. {
  800. auto lhs_numeric = lhs.to_numeric(global_object);
  801. if (global_object.vm().exception())
  802. return {};
  803. auto rhs_numeric = rhs.to_numeric(global_object);
  804. if (global_object.vm().exception())
  805. return {};
  806. if (both_number(lhs_numeric, rhs_numeric)) {
  807. if (!lhs_numeric.is_finite_number())
  808. return Value(0);
  809. if (!rhs_numeric.is_finite_number())
  810. return lhs_numeric;
  811. // Ok, so this performs toNumber() again but that "can't" throw
  812. auto lhs_u32 = lhs_numeric.to_u32(global_object);
  813. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  814. return Value(lhs_u32 >> rhs_u32);
  815. }
  816. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperator, "unsigned right-shift");
  817. return {};
  818. }
  819. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  820. Value add(GlobalObject& global_object, Value lhs, Value rhs)
  821. {
  822. if (both_number(lhs, rhs)) {
  823. if (lhs.type() == Value::Type::Int32 && rhs.type() == Value::Type::Int32) {
  824. Checked<i32> result;
  825. result = lhs.to_i32(global_object);
  826. result += rhs.to_i32(global_object);
  827. if (!result.has_overflow())
  828. return Value(result.value());
  829. }
  830. return Value(lhs.as_double() + rhs.as_double());
  831. }
  832. auto& vm = global_object.vm();
  833. auto lhs_primitive = lhs.to_primitive(global_object);
  834. if (vm.exception())
  835. return {};
  836. auto rhs_primitive = rhs.to_primitive(global_object);
  837. if (vm.exception())
  838. return {};
  839. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  840. auto lhs_string = lhs_primitive.to_string(global_object);
  841. if (vm.exception())
  842. return {};
  843. auto rhs_string = rhs_primitive.to_string(global_object);
  844. if (vm.exception())
  845. return {};
  846. StringBuilder builder(lhs_string.length() + rhs_string.length());
  847. builder.append(lhs_string);
  848. builder.append(rhs_string);
  849. return js_string(vm.heap(), builder.to_string());
  850. }
  851. auto lhs_numeric = lhs_primitive.to_numeric(global_object);
  852. if (vm.exception())
  853. return {};
  854. auto rhs_numeric = rhs_primitive.to_numeric(global_object);
  855. if (vm.exception())
  856. return {};
  857. if (both_number(lhs_numeric, rhs_numeric))
  858. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  859. if (both_bigint(lhs_numeric, rhs_numeric))
  860. return js_bigint(vm.heap(), lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer()));
  861. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "addition");
  862. return {};
  863. }
  864. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  865. Value sub(GlobalObject& global_object, Value lhs, Value rhs)
  866. {
  867. auto lhs_numeric = lhs.to_numeric(global_object);
  868. if (global_object.vm().exception())
  869. return {};
  870. auto rhs_numeric = rhs.to_numeric(global_object);
  871. if (global_object.vm().exception())
  872. return {};
  873. if (both_number(lhs_numeric, rhs_numeric))
  874. return Value(lhs_numeric.as_double() - rhs_numeric.as_double());
  875. if (both_bigint(lhs_numeric, rhs_numeric))
  876. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer()));
  877. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "subtraction");
  878. return {};
  879. }
  880. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  881. Value mul(GlobalObject& global_object, Value lhs, Value rhs)
  882. {
  883. auto lhs_numeric = lhs.to_numeric(global_object);
  884. if (global_object.vm().exception())
  885. return {};
  886. auto rhs_numeric = rhs.to_numeric(global_object);
  887. if (global_object.vm().exception())
  888. return {};
  889. if (both_number(lhs_numeric, rhs_numeric))
  890. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  891. if (both_bigint(lhs_numeric, rhs_numeric))
  892. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer()));
  893. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "multiplication");
  894. return {};
  895. }
  896. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  897. Value div(GlobalObject& global_object, Value lhs, Value rhs)
  898. {
  899. auto& vm = global_object.vm();
  900. auto lhs_numeric = lhs.to_numeric(global_object);
  901. if (vm.exception())
  902. return {};
  903. auto rhs_numeric = rhs.to_numeric(global_object);
  904. if (vm.exception())
  905. return {};
  906. if (both_number(lhs_numeric, rhs_numeric))
  907. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  908. if (both_bigint(lhs_numeric, rhs_numeric)) {
  909. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  910. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  911. return {};
  912. }
  913. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient);
  914. }
  915. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "division");
  916. return {};
  917. }
  918. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  919. Value mod(GlobalObject& global_object, Value lhs, Value rhs)
  920. {
  921. auto& vm = global_object.vm();
  922. auto lhs_numeric = lhs.to_numeric(global_object);
  923. if (vm.exception())
  924. return {};
  925. auto rhs_numeric = rhs.to_numeric(global_object);
  926. if (vm.exception())
  927. return {};
  928. if (both_number(lhs_numeric, rhs_numeric)) {
  929. if (lhs_numeric.is_nan() || rhs_numeric.is_nan())
  930. return js_nan();
  931. auto index = lhs_numeric.as_double();
  932. auto period = rhs_numeric.as_double();
  933. auto trunc = (double)(i32)(index / period);
  934. return Value(index - trunc * period);
  935. }
  936. if (both_bigint(lhs_numeric, rhs_numeric)) {
  937. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  938. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  939. return {};
  940. }
  941. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder);
  942. }
  943. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "modulo");
  944. return {};
  945. }
  946. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  947. Value exp(GlobalObject& global_object, Value lhs, Value rhs)
  948. {
  949. auto& vm = global_object.vm();
  950. auto lhs_numeric = lhs.to_numeric(global_object);
  951. if (vm.exception())
  952. return {};
  953. auto rhs_numeric = rhs.to_numeric(global_object);
  954. if (vm.exception())
  955. return {};
  956. if (both_number(lhs_numeric, rhs_numeric))
  957. return Value(pow(lhs_numeric.as_double(), rhs_numeric.as_double()));
  958. if (both_bigint(lhs_numeric, rhs_numeric)) {
  959. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  960. vm.throw_exception<RangeError>(global_object, ErrorType::NegativeExponent);
  961. return {};
  962. }
  963. return js_bigint(vm.heap(), Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
  964. }
  965. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  966. return {};
  967. }
  968. Value in(GlobalObject& global_object, Value lhs, Value rhs)
  969. {
  970. if (!rhs.is_object()) {
  971. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::InOperatorWithObject);
  972. return {};
  973. }
  974. auto lhs_property_key = lhs.to_property_key(global_object);
  975. if (global_object.vm().exception())
  976. return {};
  977. return Value(rhs.as_object().has_property(lhs_property_key));
  978. }
  979. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  980. Value instance_of(GlobalObject& global_object, Value lhs, Value rhs)
  981. {
  982. auto& vm = global_object.vm();
  983. if (!rhs.is_object()) {
  984. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  985. return {};
  986. }
  987. auto has_instance_method = get_method(global_object, Value(&rhs.as_object()), vm.well_known_symbol_has_instance());
  988. if (vm.exception())
  989. return {};
  990. if (has_instance_method) {
  991. auto has_instance_result = vm.call(*has_instance_method, rhs, lhs);
  992. if (vm.exception())
  993. return {};
  994. return Value(has_instance_result.to_boolean());
  995. }
  996. if (!rhs.is_function()) {
  997. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  998. return {};
  999. }
  1000. return ordinary_has_instance(global_object, lhs, rhs);
  1001. }
  1002. Value ordinary_has_instance(GlobalObject& global_object, Value lhs, Value rhs)
  1003. {
  1004. auto& vm = global_object.vm();
  1005. if (!rhs.is_function())
  1006. return Value(false);
  1007. auto& rhs_function = rhs.as_function();
  1008. if (is<BoundFunction>(rhs_function)) {
  1009. auto& bound_target = static_cast<const BoundFunction&>(rhs_function);
  1010. return instance_of(global_object, lhs, Value(&bound_target.target_function()));
  1011. }
  1012. if (!lhs.is_object())
  1013. return Value(false);
  1014. Object* lhs_object = &lhs.as_object();
  1015. auto rhs_prototype = rhs_function.get(vm.names.prototype);
  1016. if (vm.exception())
  1017. return {};
  1018. if (!rhs_prototype.is_object()) {
  1019. vm.throw_exception<TypeError>(global_object, ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1020. return {};
  1021. }
  1022. while (true) {
  1023. lhs_object = lhs_object->prototype();
  1024. if (vm.exception())
  1025. return {};
  1026. if (!lhs_object)
  1027. return Value(false);
  1028. if (same_value(rhs_prototype, lhs_object))
  1029. return Value(true);
  1030. }
  1031. }
  1032. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1033. bool same_value(Value lhs, Value rhs)
  1034. {
  1035. if (!same_type_for_equality(lhs, rhs))
  1036. return false;
  1037. if (lhs.is_number()) {
  1038. if (lhs.is_nan() && rhs.is_nan())
  1039. return true;
  1040. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1041. return false;
  1042. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1043. return false;
  1044. return lhs.as_double() == rhs.as_double();
  1045. }
  1046. if (lhs.is_bigint()) {
  1047. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1048. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1049. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1050. return false;
  1051. return lhs_big_integer == rhs_big_integer;
  1052. }
  1053. return same_value_non_numeric(lhs, rhs);
  1054. }
  1055. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1056. bool same_value_zero(Value lhs, Value rhs)
  1057. {
  1058. if (!same_type_for_equality(lhs, rhs))
  1059. return false;
  1060. if (lhs.is_number()) {
  1061. if (lhs.is_nan() && rhs.is_nan())
  1062. return true;
  1063. return lhs.as_double() == rhs.as_double();
  1064. }
  1065. if (lhs.is_bigint())
  1066. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1067. return same_value_non_numeric(lhs, rhs);
  1068. }
  1069. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1070. bool same_value_non_numeric(Value lhs, Value rhs)
  1071. {
  1072. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1073. VERIFY(same_type_for_equality(lhs, rhs));
  1074. switch (lhs.type()) {
  1075. case Value::Type::Undefined:
  1076. case Value::Type::Null:
  1077. return true;
  1078. case Value::Type::String:
  1079. return lhs.as_string().string() == rhs.as_string().string();
  1080. case Value::Type::Symbol:
  1081. return &lhs.as_symbol() == &rhs.as_symbol();
  1082. case Value::Type::Boolean:
  1083. return lhs.as_bool() == rhs.as_bool();
  1084. case Value::Type::Object:
  1085. return &lhs.as_object() == &rhs.as_object();
  1086. default:
  1087. VERIFY_NOT_REACHED();
  1088. }
  1089. }
  1090. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1091. bool strict_eq(Value lhs, Value rhs)
  1092. {
  1093. if (!same_type_for_equality(lhs, rhs))
  1094. return false;
  1095. if (lhs.is_number()) {
  1096. if (lhs.is_nan() || rhs.is_nan())
  1097. return false;
  1098. if (lhs.as_double() == rhs.as_double())
  1099. return true;
  1100. return false;
  1101. }
  1102. if (lhs.is_bigint())
  1103. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1104. return same_value_non_numeric(lhs, rhs);
  1105. }
  1106. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1107. bool abstract_eq(GlobalObject& global_object, Value lhs, Value rhs)
  1108. {
  1109. if (same_type_for_equality(lhs, rhs))
  1110. return strict_eq(lhs, rhs);
  1111. if (lhs.is_nullish() && rhs.is_nullish())
  1112. return true;
  1113. if (lhs.is_number() && rhs.is_string())
  1114. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1115. if (lhs.is_string() && rhs.is_number())
  1116. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1117. if (lhs.is_bigint() && rhs.is_string()) {
  1118. auto& rhs_string = rhs.as_string().string();
  1119. if (!is_valid_bigint_value(rhs_string))
  1120. return false;
  1121. return abstract_eq(global_object, lhs, js_bigint(global_object.heap(), Crypto::SignedBigInteger::from_base10(rhs_string)));
  1122. }
  1123. if (lhs.is_string() && rhs.is_bigint())
  1124. return abstract_eq(global_object, rhs, lhs);
  1125. if (lhs.is_boolean())
  1126. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1127. if (rhs.is_boolean())
  1128. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1129. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1130. auto rhs_primitive = rhs.to_primitive(global_object);
  1131. if (global_object.vm().exception())
  1132. return false;
  1133. return abstract_eq(global_object, lhs, rhs_primitive);
  1134. }
  1135. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || lhs.is_bigint() || rhs.is_symbol())) {
  1136. auto lhs_primitive = lhs.to_primitive(global_object);
  1137. if (global_object.vm().exception())
  1138. return false;
  1139. return abstract_eq(global_object, lhs_primitive, rhs);
  1140. }
  1141. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1142. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1143. return false;
  1144. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1145. return false;
  1146. if (lhs.is_number())
  1147. return Crypto::SignedBigInteger { lhs.to_i32(global_object) } == rhs.as_bigint().big_integer();
  1148. else
  1149. return Crypto::SignedBigInteger { rhs.to_i32(global_object) } == lhs.as_bigint().big_integer();
  1150. }
  1151. return false;
  1152. }
  1153. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1154. TriState abstract_relation(GlobalObject& global_object, bool left_first, Value lhs, Value rhs)
  1155. {
  1156. Value x_primitive;
  1157. Value y_primitive;
  1158. if (left_first) {
  1159. x_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1160. if (global_object.vm().exception())
  1161. return {};
  1162. y_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1163. if (global_object.vm().exception())
  1164. return {};
  1165. } else {
  1166. y_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1167. if (global_object.vm().exception())
  1168. return {};
  1169. x_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1170. if (global_object.vm().exception())
  1171. return {};
  1172. }
  1173. if (x_primitive.is_string() && y_primitive.is_string()) {
  1174. auto x_string = x_primitive.as_string().string();
  1175. auto y_string = y_primitive.as_string().string();
  1176. Utf8View x_code_points { x_string };
  1177. Utf8View y_code_points { y_string };
  1178. if (x_code_points.starts_with(y_code_points))
  1179. return TriState::False;
  1180. if (y_code_points.starts_with(x_code_points))
  1181. return TriState::True;
  1182. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1183. k != x_code_points.end() && l != y_code_points.end();
  1184. ++k, ++l) {
  1185. if (*k != *l) {
  1186. if (*k < *l) {
  1187. return TriState::True;
  1188. } else {
  1189. return TriState::False;
  1190. }
  1191. }
  1192. }
  1193. VERIFY_NOT_REACHED();
  1194. }
  1195. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1196. auto& y_string = y_primitive.as_string().string();
  1197. if (!is_valid_bigint_value(y_string))
  1198. return TriState::Unknown;
  1199. if (x_primitive.as_bigint().big_integer() < Crypto::SignedBigInteger::from_base10(y_string))
  1200. return TriState::True;
  1201. else
  1202. return TriState::False;
  1203. }
  1204. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1205. auto& x_string = x_primitive.as_string().string();
  1206. if (!is_valid_bigint_value(x_string))
  1207. return TriState::Unknown;
  1208. if (Crypto::SignedBigInteger::from_base10(x_string) < y_primitive.as_bigint().big_integer())
  1209. return TriState::True;
  1210. else
  1211. return TriState::False;
  1212. }
  1213. auto x_numeric = x_primitive.to_numeric(global_object);
  1214. if (global_object.vm().exception())
  1215. return {};
  1216. auto y_numeric = y_primitive.to_numeric(global_object);
  1217. if (global_object.vm().exception())
  1218. return {};
  1219. if (x_numeric.is_nan() || y_numeric.is_nan())
  1220. return TriState::Unknown;
  1221. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1222. return TriState::False;
  1223. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1224. return TriState::True;
  1225. if (x_numeric.is_number() && y_numeric.is_number()) {
  1226. if (x_numeric.as_double() < y_numeric.as_double())
  1227. return TriState::True;
  1228. else
  1229. return TriState::False;
  1230. }
  1231. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1232. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1233. return TriState::True;
  1234. else
  1235. return TriState::False;
  1236. }
  1237. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1238. bool x_lower_than_y;
  1239. if (x_numeric.is_number()) {
  1240. x_lower_than_y = x_numeric.is_integral_number()
  1241. ? Crypto::SignedBigInteger { x_numeric.to_i32(global_object) } < y_numeric.as_bigint().big_integer()
  1242. : (Crypto::SignedBigInteger { x_numeric.to_i32(global_object) } < y_numeric.as_bigint().big_integer() || Crypto::SignedBigInteger { x_numeric.to_i32(global_object) + 1 } < y_numeric.as_bigint().big_integer());
  1243. } else {
  1244. x_lower_than_y = y_numeric.is_integral_number()
  1245. ? x_numeric.as_bigint().big_integer() < Crypto::SignedBigInteger { y_numeric.to_i32(global_object) }
  1246. : (x_numeric.as_bigint().big_integer() < Crypto::SignedBigInteger { y_numeric.to_i32(global_object) } || x_numeric.as_bigint().big_integer() < Crypto::SignedBigInteger { y_numeric.to_i32(global_object) + 1 });
  1247. }
  1248. if (x_lower_than_y)
  1249. return TriState::True;
  1250. else
  1251. return TriState::False;
  1252. }
  1253. // 7.3.10 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  1254. Function* get_method(GlobalObject& global_object, Value value, const PropertyName& property_name)
  1255. {
  1256. auto& vm = global_object.vm();
  1257. auto* object = value.to_object(global_object);
  1258. if (vm.exception())
  1259. return nullptr;
  1260. auto property_value = object->get(property_name);
  1261. if (vm.exception())
  1262. return nullptr;
  1263. if (property_value.is_empty() || property_value.is_nullish())
  1264. return nullptr;
  1265. if (!property_value.is_function()) {
  1266. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, property_value.to_string_without_side_effects());
  1267. return nullptr;
  1268. }
  1269. return &property_value.as_function();
  1270. }
  1271. // 7.3.18 LengthOfArrayLike ( obj ), https://tc39.es/ecma262/#sec-lengthofarraylike
  1272. size_t length_of_array_like(GlobalObject& global_object, const Object& object)
  1273. {
  1274. auto& vm = global_object.vm();
  1275. auto result = object.get(vm.names.length).value_or(js_undefined());
  1276. if (vm.exception())
  1277. return INVALID;
  1278. return result.to_length(global_object);
  1279. }
  1280. // 7.3.22 SpeciesConstructor ( O, defaultConstructor ), https://tc39.es/ecma262/#sec-speciesconstructor
  1281. Function* species_constructor(GlobalObject& global_object, const Object& object, Function& default_constructor)
  1282. {
  1283. auto& vm = global_object.vm();
  1284. auto constructor = object.get(vm.names.constructor).value_or(js_undefined());
  1285. if (vm.exception())
  1286. return nullptr;
  1287. if (constructor.is_undefined())
  1288. return &default_constructor;
  1289. if (!constructor.is_object()) {
  1290. vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
  1291. return nullptr;
  1292. }
  1293. auto species = constructor.as_object().get(vm.well_known_symbol_species()).value_or(js_undefined());
  1294. if (species.is_nullish())
  1295. return &default_constructor;
  1296. if (species.is_constructor())
  1297. return &species.as_function();
  1298. vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, species.to_string_without_side_effects());
  1299. return nullptr;
  1300. }
  1301. // 7.2.1 RequireObjectCoercible ( argument ), https://tc39.es/ecma262/#sec-requireobjectcoercible
  1302. Value require_object_coercible(GlobalObject& global_object, Value value)
  1303. {
  1304. auto& vm = global_object.vm();
  1305. if (value.is_nullish()) {
  1306. vm.throw_exception<TypeError>(global_object, ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  1307. return {};
  1308. }
  1309. return value;
  1310. }
  1311. // 7.3.19 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike
  1312. MarkedValueList create_list_from_array_like(GlobalObject& global_object, Value value, AK::Function<Result<void, ErrorType>(Value)> check_value)
  1313. {
  1314. auto& vm = global_object.vm();
  1315. auto& heap = global_object.heap();
  1316. if (!value.is_object()) {
  1317. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
  1318. return MarkedValueList { heap };
  1319. }
  1320. auto& array_like = value.as_object();
  1321. auto length = length_of_array_like(global_object, array_like);
  1322. if (vm.exception())
  1323. return MarkedValueList { heap };
  1324. auto list = MarkedValueList { heap };
  1325. for (size_t i = 0; i < length; ++i) {
  1326. auto index_name = String::number(i);
  1327. auto next = array_like.get(index_name).value_or(js_undefined());
  1328. if (vm.exception())
  1329. return MarkedValueList { heap };
  1330. if (check_value) {
  1331. auto result = check_value(next);
  1332. if (result.is_error()) {
  1333. vm.throw_exception<TypeError>(global_object, result.release_error());
  1334. return MarkedValueList { heap };
  1335. }
  1336. }
  1337. list.append(next);
  1338. }
  1339. return list;
  1340. }
  1341. }