Value.cpp 55 KB

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