Value.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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/String.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Utf8View.h>
  12. #include <LibCrypto/BigInt/SignedBigInteger.h>
  13. #include <LibCrypto/NumberTheory/ModularFunctions.h>
  14. #include <LibJS/Heap/Heap.h>
  15. #include <LibJS/Runtime/AbstractOperations.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/FunctionObject.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 constexpr 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. FunctionObject& Value::as_function()
  198. {
  199. VERIFY(is_function());
  200. return static_cast<FunctionObject&>(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. if (is<BoundFunction>(as_object()))
  210. return Value(&static_cast<const BoundFunction&>(as_object()).target_function()).is_constructor();
  211. // OrdinaryFunctionObject
  212. return true;
  213. }
  214. // 7.2.8 IsRegExp ( argument ), https://tc39.es/ecma262/#sec-isregexp
  215. bool Value::is_regexp(GlobalObject& global_object) const
  216. {
  217. if (!is_object())
  218. return false;
  219. auto& vm = global_object.vm();
  220. auto matcher = as_object().get(*vm.well_known_symbol_match());
  221. if (vm.exception())
  222. return false;
  223. if (!matcher.is_empty() && !matcher.is_undefined())
  224. return matcher.to_boolean();
  225. return is<RegExpObject>(as_object());
  226. }
  227. // 13.5.3 The typeof Operator, https://tc39.es/ecma262/#sec-typeof-operator
  228. String Value::typeof() const
  229. {
  230. switch (m_type) {
  231. case Value::Type::Undefined:
  232. return "undefined";
  233. case Value::Type::Null:
  234. return "object";
  235. case Value::Type::Int32:
  236. case Value::Type::Double:
  237. return "number";
  238. case Value::Type::String:
  239. return "string";
  240. case Value::Type::Object:
  241. // B.3.7.3 Changes to the typeof Operator, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-typeof
  242. if (as_object().is_htmldda())
  243. return "undefined";
  244. if (is_function())
  245. return "function";
  246. return "object";
  247. case Value::Type::Boolean:
  248. return "boolean";
  249. case Value::Type::Symbol:
  250. return "symbol";
  251. case Value::Type::BigInt:
  252. return "bigint";
  253. default:
  254. VERIFY_NOT_REACHED();
  255. }
  256. }
  257. String Value::to_string_without_side_effects() const
  258. {
  259. switch (m_type) {
  260. case Type::Undefined:
  261. return "undefined";
  262. case Type::Null:
  263. return "null";
  264. case Type::Boolean:
  265. return m_value.as_bool ? "true" : "false";
  266. case Type::Int32:
  267. return String::number(m_value.as_i32);
  268. case Type::Double:
  269. return double_to_string(m_value.as_double);
  270. case Type::String:
  271. return m_value.as_string->string();
  272. case Type::Symbol:
  273. return m_value.as_symbol->to_string();
  274. case Type::BigInt:
  275. return m_value.as_bigint->to_string();
  276. case Type::Object:
  277. return String::formatted("[object {}]", as_object().class_name());
  278. case Type::Accessor:
  279. return "<accessor>";
  280. case Type::NativeProperty:
  281. return "<native-property>";
  282. default:
  283. VERIFY_NOT_REACHED();
  284. }
  285. }
  286. PrimitiveString* Value::to_primitive_string(GlobalObject& global_object)
  287. {
  288. if (is_string())
  289. return &as_string();
  290. auto string = to_string(global_object);
  291. if (global_object.vm().exception())
  292. return nullptr;
  293. return js_string(global_object.heap(), string);
  294. }
  295. // 7.1.17 ToString ( argument ), https://tc39.es/ecma262/#sec-tostring
  296. String Value::to_string(GlobalObject& global_object, bool legacy_null_to_empty_string) const
  297. {
  298. switch (m_type) {
  299. case Type::Undefined:
  300. return "undefined";
  301. case Type::Null:
  302. return !legacy_null_to_empty_string ? "null" : String::empty();
  303. case Type::Boolean:
  304. return m_value.as_bool ? "true" : "false";
  305. case Type::Int32:
  306. return String::number(m_value.as_i32);
  307. case Type::Double:
  308. return double_to_string(m_value.as_double);
  309. case Type::String:
  310. return m_value.as_string->string();
  311. case Type::Symbol:
  312. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "string");
  313. return {};
  314. case Type::BigInt:
  315. return m_value.as_bigint->big_integer().to_base(10);
  316. case Type::Object: {
  317. auto primitive_value = to_primitive(global_object, PreferredType::String);
  318. if (global_object.vm().exception())
  319. return {};
  320. return primitive_value.to_string(global_object);
  321. }
  322. default:
  323. VERIFY_NOT_REACHED();
  324. }
  325. }
  326. // 7.1.2 ToBoolean ( argument ), https://tc39.es/ecma262/#sec-toboolean
  327. bool Value::to_boolean() const
  328. {
  329. switch (m_type) {
  330. case Type::Undefined:
  331. case Type::Null:
  332. return false;
  333. case Type::Boolean:
  334. return m_value.as_bool;
  335. case Type::Int32:
  336. return m_value.as_i32 != 0;
  337. case Type::Double:
  338. if (is_nan())
  339. return false;
  340. return m_value.as_double != 0;
  341. case Type::String:
  342. return !m_value.as_string->string().is_empty();
  343. case Type::Symbol:
  344. return true;
  345. case Type::BigInt:
  346. return m_value.as_bigint->big_integer() != BIGINT_ZERO;
  347. case Type::Object:
  348. // B.3.7.1 Changes to ToBoolean, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-to-boolean
  349. if (m_value.as_object->is_htmldda())
  350. return false;
  351. return true;
  352. default:
  353. VERIFY_NOT_REACHED();
  354. }
  355. }
  356. // 7.1.1 ToPrimitive ( input [ , preferredType ] ), https://tc39.es/ecma262/#sec-toprimitive
  357. Value Value::to_primitive(GlobalObject& global_object, PreferredType preferred_type) const
  358. {
  359. auto get_hint_for_preferred_type = [&]() -> String {
  360. switch (preferred_type) {
  361. case PreferredType::Default:
  362. return "default";
  363. case PreferredType::String:
  364. return "string";
  365. case PreferredType::Number:
  366. return "number";
  367. default:
  368. VERIFY_NOT_REACHED();
  369. }
  370. };
  371. if (is_object()) {
  372. auto& vm = global_object.vm();
  373. auto to_primitive_method = get_method(global_object, *vm.well_known_symbol_to_primitive());
  374. if (vm.exception())
  375. return {};
  376. if (to_primitive_method) {
  377. auto hint = get_hint_for_preferred_type();
  378. auto result = vm.call(*to_primitive_method, *this, js_string(vm, hint));
  379. if (vm.exception())
  380. return {};
  381. if (!result.is_object())
  382. return result;
  383. vm.throw_exception<TypeError>(global_object, ErrorType::ToPrimitiveReturnedObject, to_string_without_side_effects(), hint);
  384. return {};
  385. }
  386. if (preferred_type == PreferredType::Default)
  387. preferred_type = PreferredType::Number;
  388. return as_object().ordinary_to_primitive(preferred_type);
  389. }
  390. return *this;
  391. }
  392. // 7.1.18 ToObject ( argument ), https://tc39.es/ecma262/#sec-toobject
  393. Object* Value::to_object(GlobalObject& global_object) const
  394. {
  395. switch (m_type) {
  396. case Type::Undefined:
  397. case Type::Null:
  398. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::ToObjectNullOrUndefined);
  399. return nullptr;
  400. case Type::Boolean:
  401. return BooleanObject::create(global_object, m_value.as_bool);
  402. case Type::Int32:
  403. case Type::Double:
  404. return NumberObject::create(global_object, as_double());
  405. case Type::String:
  406. return StringObject::create(global_object, *m_value.as_string);
  407. case Type::Symbol:
  408. return SymbolObject::create(global_object, *m_value.as_symbol);
  409. case Type::BigInt:
  410. return BigIntObject::create(global_object, *m_value.as_bigint);
  411. case Type::Object:
  412. return &const_cast<Object&>(as_object());
  413. default:
  414. dbgln("Dying because I can't to_object() on {}", *this);
  415. VERIFY_NOT_REACHED();
  416. }
  417. }
  418. // 7.1.3 ToNumeric ( value ), https://tc39.es/ecma262/#sec-tonumeric
  419. FLATTEN Value Value::to_numeric(GlobalObject& global_object) const
  420. {
  421. auto primitive = to_primitive(global_object, Value::PreferredType::Number);
  422. if (global_object.vm().exception())
  423. return {};
  424. if (primitive.is_bigint())
  425. return primitive;
  426. return primitive.to_number(global_object);
  427. }
  428. // 7.1.4 ToNumber ( argument ), https://tc39.es/ecma262/#sec-tonumber
  429. Value Value::to_number(GlobalObject& global_object) const
  430. {
  431. switch (m_type) {
  432. case Type::Undefined:
  433. return js_nan();
  434. case Type::Null:
  435. return Value(0);
  436. case Type::Boolean:
  437. return Value(m_value.as_bool ? 1 : 0);
  438. case Type::Int32:
  439. case Type::Double:
  440. return *this;
  441. case Type::String: {
  442. auto string = as_string().string().trim_whitespace();
  443. if (string.is_empty())
  444. return Value(0);
  445. if (string == "Infinity" || string == "+Infinity")
  446. return js_infinity();
  447. if (string == "-Infinity")
  448. return js_negative_infinity();
  449. char* endptr;
  450. auto parsed_double = strtod(string.characters(), &endptr);
  451. if (*endptr)
  452. return js_nan();
  453. return Value(parsed_double);
  454. }
  455. case Type::Symbol:
  456. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "number");
  457. return {};
  458. case Type::BigInt:
  459. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "BigInt", "number");
  460. return {};
  461. case Type::Object: {
  462. auto primitive = to_primitive(global_object, PreferredType::Number);
  463. if (global_object.vm().exception())
  464. return {};
  465. return primitive.to_number(global_object);
  466. }
  467. default:
  468. VERIFY_NOT_REACHED();
  469. }
  470. }
  471. // 7.1.13 ToBigInt ( argument ), https://tc39.es/ecma262/#sec-tobigint
  472. BigInt* Value::to_bigint(GlobalObject& global_object) const
  473. {
  474. auto& vm = global_object.vm();
  475. auto primitive = to_primitive(global_object, PreferredType::Number);
  476. if (vm.exception())
  477. return nullptr;
  478. switch (primitive.type()) {
  479. case Type::Undefined:
  480. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "undefined", "BigInt");
  481. return nullptr;
  482. case Type::Null:
  483. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "null", "BigInt");
  484. return nullptr;
  485. case Type::Boolean: {
  486. auto value = primitive.as_bool() ? 1 : 0;
  487. return js_bigint(vm.heap(), Crypto::SignedBigInteger { value });
  488. }
  489. case Type::BigInt:
  490. return &primitive.as_bigint();
  491. case Type::Int32:
  492. case Type::Double:
  493. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "number", "BigInt");
  494. return {};
  495. case Type::String: {
  496. auto& string = primitive.as_string().string();
  497. if (!is_valid_bigint_value(string)) {
  498. vm.throw_exception<SyntaxError>(global_object, ErrorType::BigIntInvalidValue, string);
  499. return {};
  500. }
  501. return js_bigint(vm.heap(), Crypto::SignedBigInteger::from_base(10, string.trim_whitespace()));
  502. }
  503. case Type::Symbol:
  504. vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "symbol", "BigInt");
  505. return {};
  506. default:
  507. VERIFY_NOT_REACHED();
  508. }
  509. }
  510. // 7.1.15 ToBigInt64 ( argument ), https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tobigint64
  511. i64 Value::to_bigint_int64(GlobalObject& global_object) const
  512. {
  513. auto* bigint = to_bigint(global_object);
  514. if (global_object.vm().exception())
  515. return INVALID;
  516. return static_cast<i64>(bigint->big_integer().to_u64());
  517. }
  518. // 7.1.16 ToBigUint64 ( argument ), https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tobiguint64
  519. u64 Value::to_bigint_uint64(GlobalObject& global_object) const
  520. {
  521. auto* bigint = to_bigint(global_object);
  522. if (global_object.vm().exception())
  523. return INVALID;
  524. return bigint->big_integer().to_u64();
  525. }
  526. // FIXME: These two conversions are wrong for JS, and seem likely to be footguns
  527. i32 Value::as_i32() const
  528. {
  529. return static_cast<i32>(as_double());
  530. }
  531. u32 Value::as_u32() const
  532. {
  533. VERIFY(as_double() >= 0);
  534. return min((u32)as_i32(), NumericLimits<u32>::max());
  535. }
  536. double Value::to_double(GlobalObject& global_object) const
  537. {
  538. auto number = to_number(global_object);
  539. if (global_object.vm().exception())
  540. return INVALID;
  541. return number.as_double();
  542. }
  543. // 7.1.19 ToPropertyKey ( argument ), https://tc39.es/ecma262/#sec-topropertykey
  544. StringOrSymbol Value::to_property_key(GlobalObject& global_object) const
  545. {
  546. auto key = to_primitive(global_object, PreferredType::String);
  547. if (global_object.vm().exception())
  548. return {};
  549. if (key.is_symbol())
  550. return &key.as_symbol();
  551. return key.to_string(global_object);
  552. }
  553. i32 Value::to_i32_slow_case(GlobalObject& global_object) const
  554. {
  555. VERIFY(type() != Type::Int32);
  556. auto number = to_number(global_object);
  557. if (global_object.vm().exception())
  558. return INVALID;
  559. double value = number.as_double();
  560. if (!isfinite(value) || value == 0)
  561. return 0;
  562. auto abs = fabs(value);
  563. auto int_val = floor(abs);
  564. if (signbit(value))
  565. int_val = -int_val;
  566. auto remainder = fmod(int_val, 4294967296.0);
  567. auto int32bit = remainder >= 0.0 ? remainder : remainder + 4294967296.0; // The notation “x modulo y” computes a value k of the same sign as y
  568. if (int32bit >= 2147483648.0)
  569. int32bit -= 4294967296.0;
  570. return static_cast<i32>(int32bit);
  571. }
  572. // 7.1.7 ToUint32 ( argument ), https://tc39.es/ecma262/#sec-touint32
  573. u32 Value::to_u32(GlobalObject& global_object) const
  574. {
  575. auto number = to_number(global_object);
  576. if (global_object.vm().exception())
  577. return INVALID;
  578. double value = number.as_double();
  579. if (!isfinite(value) || value == 0)
  580. return 0;
  581. auto int_val = floor(fabs(value));
  582. if (signbit(value))
  583. int_val = -int_val;
  584. auto int32bit = fmod(int_val, NumericLimits<u32>::max() + 1.0);
  585. // Cast to i64 here to ensure that the double --> u32 cast doesn't invoke undefined behavior
  586. // Otherwise, negative numbers cause a UBSAN warning.
  587. return static_cast<u32>(static_cast<i64>(int32bit));
  588. }
  589. // 7.1.8 ToInt16 ( argument ), https://tc39.es/ecma262/#sec-toint16
  590. i16 Value::to_i16(GlobalObject& global_object) const
  591. {
  592. auto number = to_number(global_object);
  593. if (global_object.vm().exception())
  594. return INVALID;
  595. double value = number.as_double();
  596. if (!isfinite(value) || value == 0)
  597. return 0;
  598. auto abs = fabs(value);
  599. auto int_val = floor(abs);
  600. if (signbit(value))
  601. int_val = -int_val;
  602. auto remainder = fmod(int_val, 65536.0);
  603. auto int16bit = remainder >= 0.0 ? remainder : remainder + 65536.0; // The notation “x modulo y” computes a value k of the same sign as y
  604. if (int16bit >= 32768.0)
  605. int16bit -= 65536.0;
  606. return static_cast<i16>(int16bit);
  607. }
  608. // 7.1.9 ToUint16 ( argument ), https://tc39.es/ecma262/#sec-touint16
  609. u16 Value::to_u16(GlobalObject& global_object) const
  610. {
  611. auto number = to_number(global_object);
  612. if (global_object.vm().exception())
  613. return INVALID;
  614. double value = number.as_double();
  615. if (!isfinite(value) || value == 0)
  616. return 0;
  617. auto int_val = floor(fabs(value));
  618. if (signbit(value))
  619. int_val = -int_val;
  620. auto int16bit = fmod(int_val, NumericLimits<u16>::max() + 1.0);
  621. return static_cast<u16>(int16bit);
  622. }
  623. // 7.1.10 ToInt8 ( argument ), https://tc39.es/ecma262/#sec-toint8
  624. i8 Value::to_i8(GlobalObject& global_object) const
  625. {
  626. auto number = to_number(global_object);
  627. if (global_object.vm().exception())
  628. return INVALID;
  629. double value = number.as_double();
  630. if (!isfinite(value) || value == 0)
  631. return 0;
  632. auto abs = fabs(value);
  633. auto int_val = floor(abs);
  634. if (signbit(value))
  635. int_val = -int_val;
  636. auto remainder = fmod(int_val, 256.0);
  637. auto int8bit = remainder >= 0.0 ? remainder : remainder + 256.0; // The notation “x modulo y” computes a value k of the same sign as y
  638. if (int8bit >= 128.0)
  639. int8bit -= 256.0;
  640. return static_cast<i8>(int8bit);
  641. }
  642. // 7.1.11 ToUint8 ( argument ), https://tc39.es/ecma262/#sec-touint8
  643. u8 Value::to_u8(GlobalObject& global_object) const
  644. {
  645. auto number = to_number(global_object);
  646. if (global_object.vm().exception())
  647. return INVALID;
  648. double value = number.as_double();
  649. if (!isfinite(value) || value == 0)
  650. return 0;
  651. auto int_val = floor(fabs(value));
  652. if (signbit(value))
  653. int_val = -int_val;
  654. auto int8bit = fmod(int_val, NumericLimits<u8>::max() + 1.0);
  655. return static_cast<u8>(int8bit);
  656. }
  657. // 7.1.12 ToUint8Clamp ( argument ), https://tc39.es/ecma262/#sec-touint8clamp
  658. u8 Value::to_u8_clamp(GlobalObject& global_object) const
  659. {
  660. auto number = to_number(global_object);
  661. if (global_object.vm().exception())
  662. return INVALID;
  663. if (number.is_nan())
  664. return 0;
  665. double value = number.as_double();
  666. if (value <= 0.0)
  667. return 0;
  668. if (value >= 255.0)
  669. return 255;
  670. auto int_val = floor(value);
  671. if (int_val + 0.5 < value)
  672. return static_cast<u8>(int_val + 1.0);
  673. if (value < int_val + 0.5)
  674. return static_cast<u8>(int_val);
  675. if (fmod(int_val, 2.0) == 1.0)
  676. return static_cast<u8>(int_val + 1.0);
  677. return static_cast<u8>(int_val);
  678. }
  679. // 7.1.20 ToLength ( argument ), https://tc39.es/ecma262/#sec-tolength
  680. size_t Value::to_length(GlobalObject& global_object) const
  681. {
  682. auto& vm = global_object.vm();
  683. auto len = to_integer_or_infinity(global_object);
  684. if (vm.exception())
  685. return INVALID;
  686. if (len <= 0)
  687. return 0;
  688. return min(len, MAX_ARRAY_LIKE_INDEX);
  689. }
  690. // 7.1.22 ToIndex ( argument ), https://tc39.es/ecma262/#sec-toindex
  691. size_t Value::to_index(GlobalObject& global_object) const
  692. {
  693. auto& vm = global_object.vm();
  694. if (is_undefined())
  695. return 0;
  696. auto integer_index = to_integer_or_infinity(global_object);
  697. if (vm.exception())
  698. return INVALID;
  699. if (integer_index < 0) {
  700. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidIndex);
  701. return INVALID;
  702. }
  703. auto index = Value(integer_index).to_length(global_object);
  704. VERIFY(!vm.exception());
  705. if (integer_index != index) {
  706. vm.throw_exception<RangeError>(global_object, ErrorType::InvalidIndex);
  707. return INVALID;
  708. }
  709. return index;
  710. }
  711. // 7.1.5 ToIntegerOrInfinity ( argument ), https://tc39.es/ecma262/#sec-tointegerorinfinity
  712. double Value::to_integer_or_infinity(GlobalObject& global_object) const
  713. {
  714. auto& vm = global_object.vm();
  715. auto number = to_number(global_object);
  716. if (vm.exception())
  717. return INVALID;
  718. if (number.is_nan() || number.as_double() == 0)
  719. return 0;
  720. if (number.is_infinity())
  721. return number.as_double();
  722. auto integer = floor(fabs(number.as_double()));
  723. if (number.as_double() < 0)
  724. integer = -integer;
  725. return integer;
  726. }
  727. // 7.3.3 GetV ( V, P ), https://tc39.es/ecma262/#sec-getv
  728. Value Value::get(GlobalObject& global_object, PropertyName const& property_name) const
  729. {
  730. auto& vm = global_object.vm();
  731. // 1. Assert: IsPropertyKey(P) is true.
  732. // 2. Let O be ? ToObject(V).
  733. auto* object = to_object(global_object);
  734. if (vm.exception())
  735. return {};
  736. // 3. Return ? O.[[Get]](P, V).
  737. return object->get(property_name, *this);
  738. }
  739. // 7.3.10 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  740. FunctionObject* Value::get_method(GlobalObject& global_object, PropertyName const& property_name) const
  741. {
  742. auto& vm = global_object.vm();
  743. // 1. Assert: IsPropertyKey(P) is true.
  744. // 2. Let func be ? GetV(V, P).
  745. auto function = get(global_object, property_name).value_or(js_undefined());
  746. if (vm.exception())
  747. return nullptr;
  748. // 3. If func is either undefined or null, return undefined.
  749. if (function.is_nullish())
  750. return nullptr;
  751. // 4. If IsCallable(func) is false, throw a TypeError exception.
  752. if (!function.is_function()) {
  753. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, function.to_string_without_side_effects());
  754. return nullptr;
  755. }
  756. // 5. Return func.
  757. return &function.as_function();
  758. }
  759. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  760. Value greater_than(GlobalObject& global_object, Value lhs, Value rhs)
  761. {
  762. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  763. if (relation == TriState::Unknown)
  764. return Value(false);
  765. return Value(relation == TriState::True);
  766. }
  767. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  768. Value greater_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  769. {
  770. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  771. if (relation == TriState::Unknown || relation == TriState::True)
  772. return Value(false);
  773. return Value(true);
  774. }
  775. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  776. Value less_than(GlobalObject& global_object, Value lhs, Value rhs)
  777. {
  778. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  779. if (relation == TriState::Unknown)
  780. return Value(false);
  781. return Value(relation == TriState::True);
  782. }
  783. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  784. Value less_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  785. {
  786. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  787. if (relation == TriState::Unknown || relation == TriState::True)
  788. return Value(false);
  789. return Value(true);
  790. }
  791. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  792. Value bitwise_and(GlobalObject& global_object, Value lhs, Value rhs)
  793. {
  794. auto lhs_numeric = lhs.to_numeric(global_object);
  795. if (global_object.vm().exception())
  796. return {};
  797. auto rhs_numeric = rhs.to_numeric(global_object);
  798. if (global_object.vm().exception())
  799. return {};
  800. if (both_number(lhs_numeric, rhs_numeric)) {
  801. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  802. return Value(0);
  803. return Value(lhs_numeric.to_i32(global_object) & rhs_numeric.to_i32(global_object));
  804. }
  805. if (both_bigint(lhs_numeric, rhs_numeric))
  806. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  807. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  808. return {};
  809. }
  810. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  811. Value bitwise_or(GlobalObject& global_object, Value lhs, Value rhs)
  812. {
  813. auto lhs_numeric = lhs.to_numeric(global_object);
  814. if (global_object.vm().exception())
  815. return {};
  816. auto rhs_numeric = rhs.to_numeric(global_object);
  817. if (global_object.vm().exception())
  818. return {};
  819. if (both_number(lhs_numeric, rhs_numeric)) {
  820. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  821. return Value(0);
  822. if (!lhs_numeric.is_finite_number())
  823. return rhs_numeric;
  824. if (!rhs_numeric.is_finite_number())
  825. return lhs_numeric;
  826. return Value(lhs_numeric.to_i32(global_object) | rhs_numeric.to_i32(global_object));
  827. }
  828. if (both_bigint(lhs_numeric, rhs_numeric))
  829. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  830. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  831. return {};
  832. }
  833. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  834. Value bitwise_xor(GlobalObject& global_object, Value lhs, Value rhs)
  835. {
  836. auto lhs_numeric = lhs.to_numeric(global_object);
  837. if (global_object.vm().exception())
  838. return {};
  839. auto rhs_numeric = rhs.to_numeric(global_object);
  840. if (global_object.vm().exception())
  841. return {};
  842. if (both_number(lhs_numeric, rhs_numeric)) {
  843. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  844. return Value(0);
  845. if (!lhs_numeric.is_finite_number())
  846. return rhs_numeric;
  847. if (!rhs_numeric.is_finite_number())
  848. return lhs_numeric;
  849. return Value(lhs_numeric.to_i32(global_object) ^ rhs_numeric.to_i32(global_object));
  850. }
  851. if (both_bigint(lhs_numeric, rhs_numeric))
  852. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  853. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  854. return {};
  855. }
  856. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  857. Value bitwise_not(GlobalObject& global_object, Value lhs)
  858. {
  859. auto lhs_numeric = lhs.to_numeric(global_object);
  860. if (global_object.vm().exception())
  861. return {};
  862. if (lhs_numeric.is_number())
  863. return Value(~lhs_numeric.to_i32(global_object));
  864. auto big_integer_bitwise_not = lhs_numeric.as_bigint().big_integer();
  865. big_integer_bitwise_not = big_integer_bitwise_not.plus(Crypto::SignedBigInteger { 1 });
  866. big_integer_bitwise_not.negate();
  867. return js_bigint(global_object.heap(), big_integer_bitwise_not);
  868. }
  869. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  870. Value unary_plus(GlobalObject& global_object, Value lhs)
  871. {
  872. return lhs.to_number(global_object);
  873. }
  874. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  875. Value unary_minus(GlobalObject& global_object, Value lhs)
  876. {
  877. auto lhs_numeric = lhs.to_numeric(global_object);
  878. if (global_object.vm().exception())
  879. return {};
  880. if (lhs_numeric.is_number()) {
  881. if (lhs_numeric.is_nan())
  882. return js_nan();
  883. return Value(-lhs_numeric.as_double());
  884. }
  885. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  886. return js_bigint(global_object.heap(), BIGINT_ZERO);
  887. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  888. big_integer_negated.negate();
  889. return js_bigint(global_object.heap(), big_integer_negated);
  890. }
  891. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  892. Value left_shift(GlobalObject& global_object, Value lhs, Value rhs)
  893. {
  894. auto lhs_numeric = lhs.to_numeric(global_object);
  895. if (global_object.vm().exception())
  896. return {};
  897. auto rhs_numeric = rhs.to_numeric(global_object);
  898. if (global_object.vm().exception())
  899. return {};
  900. if (both_number(lhs_numeric, rhs_numeric)) {
  901. if (!lhs_numeric.is_finite_number())
  902. return Value(0);
  903. if (!rhs_numeric.is_finite_number())
  904. return lhs_numeric;
  905. // Ok, so this performs toNumber() again but that "can't" throw
  906. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  907. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  908. return Value(lhs_i32 << rhs_u32);
  909. }
  910. if (both_bigint(lhs_numeric, rhs_numeric)) {
  911. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  912. if (rhs_numeric.as_bigint().big_integer().is_negative())
  913. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(multiplier_divisor).quotient);
  914. else
  915. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor));
  916. }
  917. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "left-shift");
  918. return {};
  919. }
  920. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  921. Value right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  922. {
  923. auto lhs_numeric = lhs.to_numeric(global_object);
  924. if (global_object.vm().exception())
  925. return {};
  926. auto rhs_numeric = rhs.to_numeric(global_object);
  927. if (global_object.vm().exception())
  928. return {};
  929. if (both_number(lhs_numeric, rhs_numeric)) {
  930. if (!lhs_numeric.is_finite_number())
  931. return Value(0);
  932. if (!rhs_numeric.is_finite_number())
  933. return lhs_numeric;
  934. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  935. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  936. return Value(lhs_i32 >> rhs_u32);
  937. }
  938. if (both_bigint(lhs_numeric, rhs_numeric)) {
  939. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  940. rhs_negated.negate();
  941. return left_shift(global_object, lhs, js_bigint(global_object.heap(), rhs_negated));
  942. }
  943. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "right-shift");
  944. return {};
  945. }
  946. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  947. Value unsigned_right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  948. {
  949. auto lhs_numeric = lhs.to_numeric(global_object);
  950. if (global_object.vm().exception())
  951. return {};
  952. auto rhs_numeric = rhs.to_numeric(global_object);
  953. if (global_object.vm().exception())
  954. return {};
  955. if (both_number(lhs_numeric, rhs_numeric)) {
  956. if (!lhs_numeric.is_finite_number())
  957. return Value(0);
  958. if (!rhs_numeric.is_finite_number())
  959. return lhs_numeric;
  960. // Ok, so this performs toNumber() again but that "can't" throw
  961. auto lhs_u32 = lhs_numeric.to_u32(global_object);
  962. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  963. return Value(lhs_u32 >> rhs_u32);
  964. }
  965. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperator, "unsigned right-shift");
  966. return {};
  967. }
  968. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  969. Value add(GlobalObject& global_object, Value lhs, Value rhs)
  970. {
  971. if (both_number(lhs, rhs)) {
  972. if (lhs.type() == Value::Type::Int32 && rhs.type() == Value::Type::Int32) {
  973. Checked<i32> result;
  974. result = lhs.to_i32(global_object);
  975. result += rhs.to_i32(global_object);
  976. if (!result.has_overflow())
  977. return Value(result.value());
  978. }
  979. return Value(lhs.as_double() + rhs.as_double());
  980. }
  981. auto& vm = global_object.vm();
  982. auto lhs_primitive = lhs.to_primitive(global_object);
  983. if (vm.exception())
  984. return {};
  985. auto rhs_primitive = rhs.to_primitive(global_object);
  986. if (vm.exception())
  987. return {};
  988. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  989. auto lhs_string = lhs_primitive.to_string(global_object);
  990. if (vm.exception())
  991. return {};
  992. auto rhs_string = rhs_primitive.to_string(global_object);
  993. if (vm.exception())
  994. return {};
  995. StringBuilder builder(lhs_string.length() + rhs_string.length());
  996. builder.append(lhs_string);
  997. builder.append(rhs_string);
  998. return js_string(vm.heap(), builder.to_string());
  999. }
  1000. auto lhs_numeric = lhs_primitive.to_numeric(global_object);
  1001. if (vm.exception())
  1002. return {};
  1003. auto rhs_numeric = rhs_primitive.to_numeric(global_object);
  1004. if (vm.exception())
  1005. return {};
  1006. if (both_number(lhs_numeric, rhs_numeric))
  1007. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  1008. if (both_bigint(lhs_numeric, rhs_numeric))
  1009. return js_bigint(vm.heap(), lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer()));
  1010. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "addition");
  1011. return {};
  1012. }
  1013. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1014. Value sub(GlobalObject& global_object, Value lhs, Value rhs)
  1015. {
  1016. auto lhs_numeric = lhs.to_numeric(global_object);
  1017. if (global_object.vm().exception())
  1018. return {};
  1019. auto rhs_numeric = rhs.to_numeric(global_object);
  1020. if (global_object.vm().exception())
  1021. return {};
  1022. if (both_number(lhs_numeric, rhs_numeric))
  1023. return Value(lhs_numeric.as_double() - rhs_numeric.as_double());
  1024. if (both_bigint(lhs_numeric, rhs_numeric))
  1025. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer()));
  1026. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1027. return {};
  1028. }
  1029. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1030. Value mul(GlobalObject& global_object, Value lhs, Value rhs)
  1031. {
  1032. auto lhs_numeric = lhs.to_numeric(global_object);
  1033. if (global_object.vm().exception())
  1034. return {};
  1035. auto rhs_numeric = rhs.to_numeric(global_object);
  1036. if (global_object.vm().exception())
  1037. return {};
  1038. if (both_number(lhs_numeric, rhs_numeric))
  1039. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  1040. if (both_bigint(lhs_numeric, rhs_numeric))
  1041. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer()));
  1042. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1043. return {};
  1044. }
  1045. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1046. Value div(GlobalObject& global_object, Value lhs, Value rhs)
  1047. {
  1048. auto& vm = global_object.vm();
  1049. auto lhs_numeric = lhs.to_numeric(global_object);
  1050. if (vm.exception())
  1051. return {};
  1052. auto rhs_numeric = rhs.to_numeric(global_object);
  1053. if (vm.exception())
  1054. return {};
  1055. if (both_number(lhs_numeric, rhs_numeric))
  1056. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1057. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1058. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  1059. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  1060. return {};
  1061. }
  1062. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient);
  1063. }
  1064. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "division");
  1065. return {};
  1066. }
  1067. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1068. Value mod(GlobalObject& global_object, Value lhs, Value rhs)
  1069. {
  1070. auto& vm = global_object.vm();
  1071. auto lhs_numeric = lhs.to_numeric(global_object);
  1072. if (vm.exception())
  1073. return {};
  1074. auto rhs_numeric = rhs.to_numeric(global_object);
  1075. if (vm.exception())
  1076. return {};
  1077. if (both_number(lhs_numeric, rhs_numeric)) {
  1078. if (lhs_numeric.is_nan() || rhs_numeric.is_nan())
  1079. return js_nan();
  1080. auto index = lhs_numeric.as_double();
  1081. auto period = rhs_numeric.as_double();
  1082. auto trunc = (double)(i32)(index / period);
  1083. return Value(index - trunc * period);
  1084. }
  1085. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1086. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  1087. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  1088. return {};
  1089. }
  1090. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder);
  1091. }
  1092. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "modulo");
  1093. return {};
  1094. }
  1095. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1096. Value exp(GlobalObject& global_object, Value lhs, Value rhs)
  1097. {
  1098. auto& vm = global_object.vm();
  1099. auto lhs_numeric = lhs.to_numeric(global_object);
  1100. if (vm.exception())
  1101. return {};
  1102. auto rhs_numeric = rhs.to_numeric(global_object);
  1103. if (vm.exception())
  1104. return {};
  1105. if (both_number(lhs_numeric, rhs_numeric))
  1106. return Value(pow(lhs_numeric.as_double(), rhs_numeric.as_double()));
  1107. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1108. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  1109. vm.throw_exception<RangeError>(global_object, ErrorType::NegativeExponent);
  1110. return {};
  1111. }
  1112. return js_bigint(vm.heap(), Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
  1113. }
  1114. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1115. return {};
  1116. }
  1117. Value in(GlobalObject& global_object, Value lhs, Value rhs)
  1118. {
  1119. if (!rhs.is_object()) {
  1120. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::InOperatorWithObject);
  1121. return {};
  1122. }
  1123. auto lhs_property_key = lhs.to_property_key(global_object);
  1124. if (global_object.vm().exception())
  1125. return {};
  1126. return Value(rhs.as_object().has_property(lhs_property_key));
  1127. }
  1128. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1129. Value instance_of(GlobalObject& global_object, Value lhs, Value rhs)
  1130. {
  1131. auto& vm = global_object.vm();
  1132. if (!rhs.is_object()) {
  1133. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  1134. return {};
  1135. }
  1136. auto has_instance_method = rhs.get_method(global_object, *vm.well_known_symbol_has_instance());
  1137. if (vm.exception())
  1138. return {};
  1139. if (has_instance_method) {
  1140. auto has_instance_result = vm.call(*has_instance_method, rhs, lhs);
  1141. if (vm.exception())
  1142. return {};
  1143. return Value(has_instance_result.to_boolean());
  1144. }
  1145. if (!rhs.is_function()) {
  1146. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  1147. return {};
  1148. }
  1149. return ordinary_has_instance(global_object, lhs, rhs);
  1150. }
  1151. Value ordinary_has_instance(GlobalObject& global_object, Value lhs, Value rhs)
  1152. {
  1153. auto& vm = global_object.vm();
  1154. if (!rhs.is_function())
  1155. return Value(false);
  1156. auto& rhs_function = rhs.as_function();
  1157. if (is<BoundFunction>(rhs_function)) {
  1158. auto& bound_target = static_cast<const BoundFunction&>(rhs_function);
  1159. return instance_of(global_object, lhs, Value(&bound_target.target_function()));
  1160. }
  1161. if (!lhs.is_object())
  1162. return Value(false);
  1163. Object* lhs_object = &lhs.as_object();
  1164. auto rhs_prototype = rhs_function.get(vm.names.prototype);
  1165. if (vm.exception())
  1166. return {};
  1167. if (!rhs_prototype.is_object()) {
  1168. vm.throw_exception<TypeError>(global_object, ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1169. return {};
  1170. }
  1171. while (true) {
  1172. lhs_object = lhs_object->prototype();
  1173. if (vm.exception())
  1174. return {};
  1175. if (!lhs_object)
  1176. return Value(false);
  1177. if (same_value(rhs_prototype, lhs_object))
  1178. return Value(true);
  1179. }
  1180. }
  1181. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1182. bool same_value(Value lhs, Value rhs)
  1183. {
  1184. if (!same_type_for_equality(lhs, rhs))
  1185. return false;
  1186. if (lhs.is_number()) {
  1187. if (lhs.is_nan() && rhs.is_nan())
  1188. return true;
  1189. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1190. return false;
  1191. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1192. return false;
  1193. return lhs.as_double() == rhs.as_double();
  1194. }
  1195. if (lhs.is_bigint()) {
  1196. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1197. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1198. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1199. return false;
  1200. return lhs_big_integer == rhs_big_integer;
  1201. }
  1202. return same_value_non_numeric(lhs, rhs);
  1203. }
  1204. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1205. bool same_value_zero(Value lhs, Value rhs)
  1206. {
  1207. if (!same_type_for_equality(lhs, rhs))
  1208. return false;
  1209. if (lhs.is_number()) {
  1210. if (lhs.is_nan() && rhs.is_nan())
  1211. return true;
  1212. return lhs.as_double() == rhs.as_double();
  1213. }
  1214. if (lhs.is_bigint())
  1215. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1216. return same_value_non_numeric(lhs, rhs);
  1217. }
  1218. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1219. bool same_value_non_numeric(Value lhs, Value rhs)
  1220. {
  1221. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1222. VERIFY(same_type_for_equality(lhs, rhs));
  1223. switch (lhs.type()) {
  1224. case Value::Type::Undefined:
  1225. case Value::Type::Null:
  1226. return true;
  1227. case Value::Type::String:
  1228. return lhs.as_string().string() == rhs.as_string().string();
  1229. case Value::Type::Symbol:
  1230. return &lhs.as_symbol() == &rhs.as_symbol();
  1231. case Value::Type::Boolean:
  1232. return lhs.as_bool() == rhs.as_bool();
  1233. case Value::Type::Object:
  1234. return &lhs.as_object() == &rhs.as_object();
  1235. default:
  1236. VERIFY_NOT_REACHED();
  1237. }
  1238. }
  1239. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1240. bool strict_eq(Value lhs, Value rhs)
  1241. {
  1242. if (!same_type_for_equality(lhs, rhs))
  1243. return false;
  1244. if (lhs.is_number()) {
  1245. if (lhs.is_nan() || rhs.is_nan())
  1246. return false;
  1247. if (lhs.as_double() == rhs.as_double())
  1248. return true;
  1249. return false;
  1250. }
  1251. if (lhs.is_bigint())
  1252. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1253. return same_value_non_numeric(lhs, rhs);
  1254. }
  1255. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1256. bool abstract_eq(GlobalObject& global_object, Value lhs, Value rhs)
  1257. {
  1258. if (same_type_for_equality(lhs, rhs))
  1259. return strict_eq(lhs, rhs);
  1260. if (lhs.is_nullish() && rhs.is_nullish())
  1261. return true;
  1262. // B.3.7.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1263. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1264. return true;
  1265. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1266. return true;
  1267. if (lhs.is_number() && rhs.is_string())
  1268. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1269. if (lhs.is_string() && rhs.is_number())
  1270. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1271. if (lhs.is_bigint() && rhs.is_string()) {
  1272. auto& rhs_string = rhs.as_string().string();
  1273. if (!is_valid_bigint_value(rhs_string))
  1274. return false;
  1275. return abstract_eq(global_object, lhs, js_bigint(global_object.heap(), Crypto::SignedBigInteger::from_base(10, rhs_string)));
  1276. }
  1277. if (lhs.is_string() && rhs.is_bigint())
  1278. return abstract_eq(global_object, rhs, lhs);
  1279. if (lhs.is_boolean())
  1280. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1281. if (rhs.is_boolean())
  1282. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1283. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1284. auto rhs_primitive = rhs.to_primitive(global_object);
  1285. if (global_object.vm().exception())
  1286. return false;
  1287. return abstract_eq(global_object, lhs, rhs_primitive);
  1288. }
  1289. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || lhs.is_bigint() || rhs.is_symbol())) {
  1290. auto lhs_primitive = lhs.to_primitive(global_object);
  1291. if (global_object.vm().exception())
  1292. return false;
  1293. return abstract_eq(global_object, lhs_primitive, rhs);
  1294. }
  1295. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1296. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1297. return false;
  1298. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1299. return false;
  1300. if (lhs.is_number())
  1301. return Crypto::SignedBigInteger { lhs.to_i32(global_object) } == rhs.as_bigint().big_integer();
  1302. else
  1303. return Crypto::SignedBigInteger { rhs.to_i32(global_object) } == lhs.as_bigint().big_integer();
  1304. }
  1305. return false;
  1306. }
  1307. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1308. TriState abstract_relation(GlobalObject& global_object, bool left_first, Value lhs, Value rhs)
  1309. {
  1310. Value x_primitive;
  1311. Value y_primitive;
  1312. if (left_first) {
  1313. x_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1314. if (global_object.vm().exception())
  1315. return {};
  1316. y_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1317. if (global_object.vm().exception())
  1318. return {};
  1319. } else {
  1320. y_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1321. if (global_object.vm().exception())
  1322. return {};
  1323. x_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1324. if (global_object.vm().exception())
  1325. return {};
  1326. }
  1327. if (x_primitive.is_string() && y_primitive.is_string()) {
  1328. auto x_string = x_primitive.as_string().string();
  1329. auto y_string = y_primitive.as_string().string();
  1330. Utf8View x_code_points { x_string };
  1331. Utf8View y_code_points { y_string };
  1332. if (x_code_points.starts_with(y_code_points))
  1333. return TriState::False;
  1334. if (y_code_points.starts_with(x_code_points))
  1335. return TriState::True;
  1336. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1337. k != x_code_points.end() && l != y_code_points.end();
  1338. ++k, ++l) {
  1339. if (*k != *l) {
  1340. if (*k < *l) {
  1341. return TriState::True;
  1342. } else {
  1343. return TriState::False;
  1344. }
  1345. }
  1346. }
  1347. VERIFY_NOT_REACHED();
  1348. }
  1349. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1350. auto& y_string = y_primitive.as_string().string();
  1351. if (!is_valid_bigint_value(y_string))
  1352. return TriState::Unknown;
  1353. if (x_primitive.as_bigint().big_integer() < Crypto::SignedBigInteger::from_base(10, y_string))
  1354. return TriState::True;
  1355. else
  1356. return TriState::False;
  1357. }
  1358. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1359. auto& x_string = x_primitive.as_string().string();
  1360. if (!is_valid_bigint_value(x_string))
  1361. return TriState::Unknown;
  1362. if (Crypto::SignedBigInteger::from_base(10, x_string) < y_primitive.as_bigint().big_integer())
  1363. return TriState::True;
  1364. else
  1365. return TriState::False;
  1366. }
  1367. auto x_numeric = x_primitive.to_numeric(global_object);
  1368. if (global_object.vm().exception())
  1369. return {};
  1370. auto y_numeric = y_primitive.to_numeric(global_object);
  1371. if (global_object.vm().exception())
  1372. return {};
  1373. if (x_numeric.is_nan() || y_numeric.is_nan())
  1374. return TriState::Unknown;
  1375. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1376. return TriState::False;
  1377. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1378. return TriState::True;
  1379. if (x_numeric.is_number() && y_numeric.is_number()) {
  1380. if (x_numeric.as_double() < y_numeric.as_double())
  1381. return TriState::True;
  1382. else
  1383. return TriState::False;
  1384. }
  1385. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1386. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1387. return TriState::True;
  1388. else
  1389. return TriState::False;
  1390. }
  1391. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1392. bool x_lower_than_y;
  1393. if (x_numeric.is_number()) {
  1394. x_lower_than_y = x_numeric.is_integral_number()
  1395. ? Crypto::SignedBigInteger { x_numeric.to_i32(global_object) } < y_numeric.as_bigint().big_integer()
  1396. : (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());
  1397. } else {
  1398. x_lower_than_y = y_numeric.is_integral_number()
  1399. ? x_numeric.as_bigint().big_integer() < Crypto::SignedBigInteger { y_numeric.to_i32(global_object) }
  1400. : (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 });
  1401. }
  1402. if (x_lower_than_y)
  1403. return TriState::True;
  1404. else
  1405. return TriState::False;
  1406. }
  1407. }