Value.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  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 (is<Array>(object))
  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() && is<Array>(as_object()));
  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_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, *global_object.string_prototype());
  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 (u32)min(as_double(), (double)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. VERIFY(property_name.is_valid());
  733. // 2. Let O be ? ToObject(V).
  734. auto* object = to_object(global_object);
  735. if (vm.exception())
  736. return {};
  737. // 3. Return ? O.[[Get]](P, V).
  738. return object->internal_get(property_name, *this);
  739. }
  740. // 7.3.10 GetMethod ( V, P ), https://tc39.es/ecma262/#sec-getmethod
  741. FunctionObject* Value::get_method(GlobalObject& global_object, PropertyName const& property_name) const
  742. {
  743. auto& vm = global_object.vm();
  744. // 1. Assert: IsPropertyKey(P) is true.
  745. VERIFY(property_name.is_valid());
  746. // 2. Let func be ? GetV(V, P).
  747. auto function = get(global_object, property_name);
  748. if (vm.exception())
  749. return nullptr;
  750. // 3. If func is either undefined or null, return undefined.
  751. if (function.is_nullish())
  752. return nullptr;
  753. // 4. If IsCallable(func) is false, throw a TypeError exception.
  754. if (!function.is_function()) {
  755. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, function.to_string_without_side_effects());
  756. return nullptr;
  757. }
  758. // 5. Return func.
  759. return &function.as_function();
  760. }
  761. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  762. Value greater_than(GlobalObject& global_object, Value lhs, Value rhs)
  763. {
  764. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  765. if (relation == TriState::Unknown)
  766. return Value(false);
  767. return Value(relation == TriState::True);
  768. }
  769. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  770. Value greater_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  771. {
  772. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  773. if (relation == TriState::Unknown || relation == TriState::True)
  774. return Value(false);
  775. return Value(true);
  776. }
  777. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  778. Value less_than(GlobalObject& global_object, Value lhs, Value rhs)
  779. {
  780. TriState relation = abstract_relation(global_object, true, lhs, rhs);
  781. if (relation == TriState::Unknown)
  782. return Value(false);
  783. return Value(relation == TriState::True);
  784. }
  785. // 13.10 Relational Operators, https://tc39.es/ecma262/#sec-relational-operators
  786. Value less_than_equals(GlobalObject& global_object, Value lhs, Value rhs)
  787. {
  788. TriState relation = abstract_relation(global_object, false, lhs, rhs);
  789. if (relation == TriState::Unknown || relation == TriState::True)
  790. return Value(false);
  791. return Value(true);
  792. }
  793. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  794. Value bitwise_and(GlobalObject& global_object, Value lhs, Value rhs)
  795. {
  796. auto lhs_numeric = lhs.to_numeric(global_object);
  797. if (global_object.vm().exception())
  798. return {};
  799. auto rhs_numeric = rhs.to_numeric(global_object);
  800. if (global_object.vm().exception())
  801. return {};
  802. if (both_number(lhs_numeric, rhs_numeric)) {
  803. if (!lhs_numeric.is_finite_number() || !rhs_numeric.is_finite_number())
  804. return Value(0);
  805. return Value(lhs_numeric.to_i32(global_object) & rhs_numeric.to_i32(global_object));
  806. }
  807. if (both_bigint(lhs_numeric, rhs_numeric))
  808. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_and(rhs_numeric.as_bigint().big_integer()));
  809. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise AND");
  810. return {};
  811. }
  812. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  813. Value bitwise_or(GlobalObject& global_object, Value lhs, Value rhs)
  814. {
  815. auto lhs_numeric = lhs.to_numeric(global_object);
  816. if (global_object.vm().exception())
  817. return {};
  818. auto rhs_numeric = rhs.to_numeric(global_object);
  819. if (global_object.vm().exception())
  820. return {};
  821. if (both_number(lhs_numeric, rhs_numeric)) {
  822. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  823. return Value(0);
  824. if (!lhs_numeric.is_finite_number())
  825. return rhs_numeric;
  826. if (!rhs_numeric.is_finite_number())
  827. return lhs_numeric;
  828. return Value(lhs_numeric.to_i32(global_object) | rhs_numeric.to_i32(global_object));
  829. }
  830. if (both_bigint(lhs_numeric, rhs_numeric))
  831. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_or(rhs_numeric.as_bigint().big_integer()));
  832. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise OR");
  833. return {};
  834. }
  835. // 13.12 Binary Bitwise Operators, https://tc39.es/ecma262/#sec-binary-bitwise-operators
  836. Value bitwise_xor(GlobalObject& global_object, Value lhs, Value rhs)
  837. {
  838. auto lhs_numeric = lhs.to_numeric(global_object);
  839. if (global_object.vm().exception())
  840. return {};
  841. auto rhs_numeric = rhs.to_numeric(global_object);
  842. if (global_object.vm().exception())
  843. return {};
  844. if (both_number(lhs_numeric, rhs_numeric)) {
  845. if (!lhs_numeric.is_finite_number() && !rhs_numeric.is_finite_number())
  846. return Value(0);
  847. if (!lhs_numeric.is_finite_number())
  848. return rhs_numeric;
  849. if (!rhs_numeric.is_finite_number())
  850. return lhs_numeric;
  851. return Value(lhs_numeric.to_i32(global_object) ^ rhs_numeric.to_i32(global_object));
  852. }
  853. if (both_bigint(lhs_numeric, rhs_numeric))
  854. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().bitwise_xor(rhs_numeric.as_bigint().big_integer()));
  855. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "bitwise XOR");
  856. return {};
  857. }
  858. // 13.5.6 Bitwise NOT Operator ( ~ ), https://tc39.es/ecma262/#sec-bitwise-not-operator
  859. Value bitwise_not(GlobalObject& global_object, Value lhs)
  860. {
  861. auto lhs_numeric = lhs.to_numeric(global_object);
  862. if (global_object.vm().exception())
  863. return {};
  864. if (lhs_numeric.is_number())
  865. return Value(~lhs_numeric.to_i32(global_object));
  866. auto big_integer_bitwise_not = lhs_numeric.as_bigint().big_integer();
  867. big_integer_bitwise_not = big_integer_bitwise_not.plus(Crypto::SignedBigInteger { 1 });
  868. big_integer_bitwise_not.negate();
  869. return js_bigint(global_object.heap(), big_integer_bitwise_not);
  870. }
  871. // 13.5.4 Unary + Operator, https://tc39.es/ecma262/#sec-unary-plus-operator
  872. Value unary_plus(GlobalObject& global_object, Value lhs)
  873. {
  874. return lhs.to_number(global_object);
  875. }
  876. // 13.5.5 Unary - Operator, https://tc39.es/ecma262/#sec-unary-minus-operator
  877. Value unary_minus(GlobalObject& global_object, Value lhs)
  878. {
  879. auto lhs_numeric = lhs.to_numeric(global_object);
  880. if (global_object.vm().exception())
  881. return {};
  882. if (lhs_numeric.is_number()) {
  883. if (lhs_numeric.is_nan())
  884. return js_nan();
  885. return Value(-lhs_numeric.as_double());
  886. }
  887. if (lhs_numeric.as_bigint().big_integer() == BIGINT_ZERO)
  888. return js_bigint(global_object.heap(), BIGINT_ZERO);
  889. auto big_integer_negated = lhs_numeric.as_bigint().big_integer();
  890. big_integer_negated.negate();
  891. return js_bigint(global_object.heap(), big_integer_negated);
  892. }
  893. // 13.9.1 The Left Shift Operator ( << ), https://tc39.es/ecma262/#sec-left-shift-operator
  894. Value left_shift(GlobalObject& global_object, Value lhs, Value rhs)
  895. {
  896. auto lhs_numeric = lhs.to_numeric(global_object);
  897. if (global_object.vm().exception())
  898. return {};
  899. auto rhs_numeric = rhs.to_numeric(global_object);
  900. if (global_object.vm().exception())
  901. return {};
  902. if (both_number(lhs_numeric, rhs_numeric)) {
  903. if (!lhs_numeric.is_finite_number())
  904. return Value(0);
  905. if (!rhs_numeric.is_finite_number())
  906. return lhs_numeric;
  907. // Ok, so this performs toNumber() again but that "can't" throw
  908. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  909. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  910. return Value(lhs_i32 << rhs_u32);
  911. }
  912. if (both_bigint(lhs_numeric, rhs_numeric)) {
  913. auto multiplier_divisor = Crypto::SignedBigInteger { Crypto::NumberTheory::Power(Crypto::UnsignedBigInteger(2), rhs_numeric.as_bigint().big_integer().unsigned_value()) };
  914. if (rhs_numeric.as_bigint().big_integer().is_negative())
  915. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(multiplier_divisor).quotient);
  916. else
  917. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(multiplier_divisor));
  918. }
  919. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "left-shift");
  920. return {};
  921. }
  922. // 13.9.2 The Signed Right Shift Operator ( >> ), https://tc39.es/ecma262/#sec-signed-right-shift-operator
  923. Value right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  924. {
  925. auto lhs_numeric = lhs.to_numeric(global_object);
  926. if (global_object.vm().exception())
  927. return {};
  928. auto rhs_numeric = rhs.to_numeric(global_object);
  929. if (global_object.vm().exception())
  930. return {};
  931. if (both_number(lhs_numeric, rhs_numeric)) {
  932. if (!lhs_numeric.is_finite_number())
  933. return Value(0);
  934. if (!rhs_numeric.is_finite_number())
  935. return lhs_numeric;
  936. auto lhs_i32 = lhs_numeric.to_i32(global_object);
  937. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  938. return Value(lhs_i32 >> rhs_u32);
  939. }
  940. if (both_bigint(lhs_numeric, rhs_numeric)) {
  941. auto rhs_negated = rhs_numeric.as_bigint().big_integer();
  942. rhs_negated.negate();
  943. return left_shift(global_object, lhs, js_bigint(global_object.heap(), rhs_negated));
  944. }
  945. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "right-shift");
  946. return {};
  947. }
  948. // 13.9.3 The Unsigned Right Shift Operator ( >>> ), https://tc39.es/ecma262/#sec-unsigned-right-shift-operator
  949. Value unsigned_right_shift(GlobalObject& global_object, Value lhs, Value rhs)
  950. {
  951. auto lhs_numeric = lhs.to_numeric(global_object);
  952. if (global_object.vm().exception())
  953. return {};
  954. auto rhs_numeric = rhs.to_numeric(global_object);
  955. if (global_object.vm().exception())
  956. return {};
  957. if (both_number(lhs_numeric, rhs_numeric)) {
  958. if (!lhs_numeric.is_finite_number())
  959. return Value(0);
  960. if (!rhs_numeric.is_finite_number())
  961. return lhs_numeric;
  962. // Ok, so this performs toNumber() again but that "can't" throw
  963. auto lhs_u32 = lhs_numeric.to_u32(global_object);
  964. auto rhs_u32 = rhs_numeric.to_u32(global_object) % 32;
  965. return Value(lhs_u32 >> rhs_u32);
  966. }
  967. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperator, "unsigned right-shift");
  968. return {};
  969. }
  970. // 13.8.1 The Addition Operator ( + ), https://tc39.es/ecma262/#sec-addition-operator-plus
  971. Value add(GlobalObject& global_object, Value lhs, Value rhs)
  972. {
  973. if (both_number(lhs, rhs)) {
  974. if (lhs.type() == Value::Type::Int32 && rhs.type() == Value::Type::Int32) {
  975. Checked<i32> result;
  976. result = lhs.to_i32(global_object);
  977. result += rhs.to_i32(global_object);
  978. if (!result.has_overflow())
  979. return Value(result.value());
  980. }
  981. return Value(lhs.as_double() + rhs.as_double());
  982. }
  983. auto& vm = global_object.vm();
  984. auto lhs_primitive = lhs.to_primitive(global_object);
  985. if (vm.exception())
  986. return {};
  987. auto rhs_primitive = rhs.to_primitive(global_object);
  988. if (vm.exception())
  989. return {};
  990. if (lhs_primitive.is_string() || rhs_primitive.is_string()) {
  991. auto lhs_string = lhs_primitive.to_string(global_object);
  992. if (vm.exception())
  993. return {};
  994. auto rhs_string = rhs_primitive.to_string(global_object);
  995. if (vm.exception())
  996. return {};
  997. StringBuilder builder(lhs_string.length() + rhs_string.length());
  998. builder.append(lhs_string);
  999. builder.append(rhs_string);
  1000. return js_string(vm.heap(), builder.to_string());
  1001. }
  1002. auto lhs_numeric = lhs_primitive.to_numeric(global_object);
  1003. if (vm.exception())
  1004. return {};
  1005. auto rhs_numeric = rhs_primitive.to_numeric(global_object);
  1006. if (vm.exception())
  1007. return {};
  1008. if (both_number(lhs_numeric, rhs_numeric))
  1009. return Value(lhs_numeric.as_double() + rhs_numeric.as_double());
  1010. if (both_bigint(lhs_numeric, rhs_numeric))
  1011. return js_bigint(vm.heap(), lhs_numeric.as_bigint().big_integer().plus(rhs_numeric.as_bigint().big_integer()));
  1012. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "addition");
  1013. return {};
  1014. }
  1015. // 13.8.2 The Subtraction Operator ( - ), https://tc39.es/ecma262/#sec-subtraction-operator-minus
  1016. Value sub(GlobalObject& global_object, Value lhs, Value rhs)
  1017. {
  1018. auto lhs_numeric = lhs.to_numeric(global_object);
  1019. if (global_object.vm().exception())
  1020. return {};
  1021. auto rhs_numeric = rhs.to_numeric(global_object);
  1022. if (global_object.vm().exception())
  1023. return {};
  1024. if (both_number(lhs_numeric, rhs_numeric))
  1025. return Value(lhs_numeric.as_double() - rhs_numeric.as_double());
  1026. if (both_bigint(lhs_numeric, rhs_numeric))
  1027. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().minus(rhs_numeric.as_bigint().big_integer()));
  1028. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "subtraction");
  1029. return {};
  1030. }
  1031. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1032. Value mul(GlobalObject& global_object, Value lhs, Value rhs)
  1033. {
  1034. auto lhs_numeric = lhs.to_numeric(global_object);
  1035. if (global_object.vm().exception())
  1036. return {};
  1037. auto rhs_numeric = rhs.to_numeric(global_object);
  1038. if (global_object.vm().exception())
  1039. return {};
  1040. if (both_number(lhs_numeric, rhs_numeric))
  1041. return Value(lhs_numeric.as_double() * rhs_numeric.as_double());
  1042. if (both_bigint(lhs_numeric, rhs_numeric))
  1043. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().multiplied_by(rhs_numeric.as_bigint().big_integer()));
  1044. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "multiplication");
  1045. return {};
  1046. }
  1047. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1048. Value div(GlobalObject& global_object, Value lhs, Value rhs)
  1049. {
  1050. auto& vm = global_object.vm();
  1051. auto lhs_numeric = lhs.to_numeric(global_object);
  1052. if (vm.exception())
  1053. return {};
  1054. auto rhs_numeric = rhs.to_numeric(global_object);
  1055. if (vm.exception())
  1056. return {};
  1057. if (both_number(lhs_numeric, rhs_numeric))
  1058. return Value(lhs_numeric.as_double() / rhs_numeric.as_double());
  1059. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1060. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  1061. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  1062. return {};
  1063. }
  1064. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).quotient);
  1065. }
  1066. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "division");
  1067. return {};
  1068. }
  1069. // 13.7 Multiplicative Operators, https://tc39.es/ecma262/#sec-multiplicative-operators
  1070. Value mod(GlobalObject& global_object, Value lhs, Value rhs)
  1071. {
  1072. auto& vm = global_object.vm();
  1073. auto lhs_numeric = lhs.to_numeric(global_object);
  1074. if (vm.exception())
  1075. return {};
  1076. auto rhs_numeric = rhs.to_numeric(global_object);
  1077. if (vm.exception())
  1078. return {};
  1079. if (both_number(lhs_numeric, rhs_numeric)) {
  1080. if (lhs_numeric.is_nan() || rhs_numeric.is_nan())
  1081. return js_nan();
  1082. auto index = lhs_numeric.as_double();
  1083. auto period = rhs_numeric.as_double();
  1084. auto trunc = (double)(i32)(index / period);
  1085. return Value(index - trunc * period);
  1086. }
  1087. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1088. if (rhs_numeric.as_bigint().big_integer() == BIGINT_ZERO) {
  1089. vm.throw_exception<RangeError>(global_object, ErrorType::DivisionByZero);
  1090. return {};
  1091. }
  1092. return js_bigint(global_object.heap(), lhs_numeric.as_bigint().big_integer().divided_by(rhs_numeric.as_bigint().big_integer()).remainder);
  1093. }
  1094. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "modulo");
  1095. return {};
  1096. }
  1097. // 13.6 Exponentiation Operator, https://tc39.es/ecma262/#sec-exp-operator
  1098. Value exp(GlobalObject& global_object, Value lhs, Value rhs)
  1099. {
  1100. auto& vm = global_object.vm();
  1101. auto lhs_numeric = lhs.to_numeric(global_object);
  1102. if (vm.exception())
  1103. return {};
  1104. auto rhs_numeric = rhs.to_numeric(global_object);
  1105. if (vm.exception())
  1106. return {};
  1107. if (both_number(lhs_numeric, rhs_numeric))
  1108. return Value(pow(lhs_numeric.as_double(), rhs_numeric.as_double()));
  1109. if (both_bigint(lhs_numeric, rhs_numeric)) {
  1110. if (rhs_numeric.as_bigint().big_integer().is_negative()) {
  1111. vm.throw_exception<RangeError>(global_object, ErrorType::NegativeExponent);
  1112. return {};
  1113. }
  1114. return js_bigint(vm.heap(), Crypto::NumberTheory::Power(lhs_numeric.as_bigint().big_integer(), rhs_numeric.as_bigint().big_integer()));
  1115. }
  1116. vm.throw_exception<TypeError>(global_object, ErrorType::BigIntBadOperatorOtherType, "exponentiation");
  1117. return {};
  1118. }
  1119. Value in(GlobalObject& global_object, Value lhs, Value rhs)
  1120. {
  1121. if (!rhs.is_object()) {
  1122. global_object.vm().throw_exception<TypeError>(global_object, ErrorType::InOperatorWithObject);
  1123. return {};
  1124. }
  1125. auto lhs_property_key = lhs.to_property_key(global_object);
  1126. if (global_object.vm().exception())
  1127. return {};
  1128. return Value(rhs.as_object().has_property(lhs_property_key));
  1129. }
  1130. // 13.10.2 InstanceofOperator ( V, target ), https://tc39.es/ecma262/#sec-instanceofoperator
  1131. Value instance_of(GlobalObject& global_object, Value lhs, Value rhs)
  1132. {
  1133. auto& vm = global_object.vm();
  1134. if (!rhs.is_object()) {
  1135. vm.throw_exception<TypeError>(global_object, ErrorType::NotAnObject, rhs.to_string_without_side_effects());
  1136. return {};
  1137. }
  1138. auto has_instance_method = rhs.get_method(global_object, *vm.well_known_symbol_has_instance());
  1139. if (vm.exception())
  1140. return {};
  1141. if (has_instance_method) {
  1142. auto has_instance_result = vm.call(*has_instance_method, rhs, lhs);
  1143. if (vm.exception())
  1144. return {};
  1145. return Value(has_instance_result.to_boolean());
  1146. }
  1147. if (!rhs.is_function()) {
  1148. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, rhs.to_string_without_side_effects());
  1149. return {};
  1150. }
  1151. return ordinary_has_instance(global_object, lhs, rhs);
  1152. }
  1153. // 7.3.21 OrdinaryHasInstance ( C, O ), https://tc39.es/ecma262/#sec-ordinaryhasinstance
  1154. Value ordinary_has_instance(GlobalObject& global_object, Value lhs, Value rhs)
  1155. {
  1156. auto& vm = global_object.vm();
  1157. if (!rhs.is_function())
  1158. return Value(false);
  1159. auto& rhs_function = rhs.as_function();
  1160. if (is<BoundFunction>(rhs_function)) {
  1161. auto& bound_target = static_cast<const BoundFunction&>(rhs_function);
  1162. return instance_of(global_object, lhs, Value(&bound_target.target_function()));
  1163. }
  1164. if (!lhs.is_object())
  1165. return Value(false);
  1166. Object* lhs_object = &lhs.as_object();
  1167. auto rhs_prototype = rhs_function.get(vm.names.prototype);
  1168. if (vm.exception())
  1169. return {};
  1170. if (!rhs_prototype.is_object()) {
  1171. vm.throw_exception<TypeError>(global_object, ErrorType::InstanceOfOperatorBadPrototype, rhs.to_string_without_side_effects());
  1172. return {};
  1173. }
  1174. while (true) {
  1175. lhs_object = lhs_object->internal_get_prototype_of();
  1176. if (vm.exception())
  1177. return {};
  1178. if (!lhs_object)
  1179. return Value(false);
  1180. if (same_value(rhs_prototype, lhs_object))
  1181. return Value(true);
  1182. }
  1183. }
  1184. // 7.2.10 SameValue ( x, y ), https://tc39.es/ecma262/#sec-samevalue
  1185. bool same_value(Value lhs, Value rhs)
  1186. {
  1187. if (!same_type_for_equality(lhs, rhs))
  1188. return false;
  1189. if (lhs.is_number()) {
  1190. if (lhs.is_nan() && rhs.is_nan())
  1191. return true;
  1192. if (lhs.is_positive_zero() && rhs.is_negative_zero())
  1193. return false;
  1194. if (lhs.is_negative_zero() && rhs.is_positive_zero())
  1195. return false;
  1196. return lhs.as_double() == rhs.as_double();
  1197. }
  1198. if (lhs.is_bigint()) {
  1199. auto lhs_big_integer = lhs.as_bigint().big_integer();
  1200. auto rhs_big_integer = rhs.as_bigint().big_integer();
  1201. if (lhs_big_integer == BIGINT_ZERO && rhs_big_integer == BIGINT_ZERO && lhs_big_integer.is_negative() != rhs_big_integer.is_negative())
  1202. return false;
  1203. return lhs_big_integer == rhs_big_integer;
  1204. }
  1205. return same_value_non_numeric(lhs, rhs);
  1206. }
  1207. // 7.2.11 SameValueZero ( x, y ), https://tc39.es/ecma262/#sec-samevaluezero
  1208. bool same_value_zero(Value lhs, Value rhs)
  1209. {
  1210. if (!same_type_for_equality(lhs, rhs))
  1211. return false;
  1212. if (lhs.is_number()) {
  1213. if (lhs.is_nan() && rhs.is_nan())
  1214. return true;
  1215. return lhs.as_double() == rhs.as_double();
  1216. }
  1217. if (lhs.is_bigint())
  1218. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1219. return same_value_non_numeric(lhs, rhs);
  1220. }
  1221. // 7.2.12 SameValueNonNumeric ( x, y ), https://tc39.es/ecma262/#sec-samevaluenonnumeric
  1222. bool same_value_non_numeric(Value lhs, Value rhs)
  1223. {
  1224. VERIFY(!lhs.is_number() && !lhs.is_bigint());
  1225. VERIFY(same_type_for_equality(lhs, rhs));
  1226. switch (lhs.type()) {
  1227. case Value::Type::Undefined:
  1228. case Value::Type::Null:
  1229. return true;
  1230. case Value::Type::String:
  1231. return lhs.as_string().string() == rhs.as_string().string();
  1232. case Value::Type::Symbol:
  1233. return &lhs.as_symbol() == &rhs.as_symbol();
  1234. case Value::Type::Boolean:
  1235. return lhs.as_bool() == rhs.as_bool();
  1236. case Value::Type::Object:
  1237. return &lhs.as_object() == &rhs.as_object();
  1238. default:
  1239. VERIFY_NOT_REACHED();
  1240. }
  1241. }
  1242. // 7.2.15 IsStrictlyEqual ( x, y ), https://tc39.es/ecma262/#sec-isstrictlyequal
  1243. bool strict_eq(Value lhs, Value rhs)
  1244. {
  1245. if (!same_type_for_equality(lhs, rhs))
  1246. return false;
  1247. if (lhs.is_number()) {
  1248. if (lhs.is_nan() || rhs.is_nan())
  1249. return false;
  1250. if (lhs.as_double() == rhs.as_double())
  1251. return true;
  1252. return false;
  1253. }
  1254. if (lhs.is_bigint())
  1255. return lhs.as_bigint().big_integer() == rhs.as_bigint().big_integer();
  1256. return same_value_non_numeric(lhs, rhs);
  1257. }
  1258. // 7.2.14 IsLooselyEqual ( x, y ), https://tc39.es/ecma262/#sec-islooselyequal
  1259. bool abstract_eq(GlobalObject& global_object, Value lhs, Value rhs)
  1260. {
  1261. if (same_type_for_equality(lhs, rhs))
  1262. return strict_eq(lhs, rhs);
  1263. if (lhs.is_nullish() && rhs.is_nullish())
  1264. return true;
  1265. // B.3.7.2 Changes to IsLooselyEqual, https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
  1266. if (lhs.is_object() && lhs.as_object().is_htmldda() && rhs.is_nullish())
  1267. return true;
  1268. if (lhs.is_nullish() && rhs.is_object() && rhs.as_object().is_htmldda())
  1269. return true;
  1270. if (lhs.is_number() && rhs.is_string())
  1271. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1272. if (lhs.is_string() && rhs.is_number())
  1273. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1274. if (lhs.is_bigint() && rhs.is_string()) {
  1275. auto& rhs_string = rhs.as_string().string();
  1276. if (!is_valid_bigint_value(rhs_string))
  1277. return false;
  1278. return abstract_eq(global_object, lhs, js_bigint(global_object.heap(), Crypto::SignedBigInteger::from_base(10, rhs_string)));
  1279. }
  1280. if (lhs.is_string() && rhs.is_bigint())
  1281. return abstract_eq(global_object, rhs, lhs);
  1282. if (lhs.is_boolean())
  1283. return abstract_eq(global_object, lhs.to_number(global_object), rhs);
  1284. if (rhs.is_boolean())
  1285. return abstract_eq(global_object, lhs, rhs.to_number(global_object));
  1286. if ((lhs.is_string() || lhs.is_number() || lhs.is_bigint() || lhs.is_symbol()) && rhs.is_object()) {
  1287. auto rhs_primitive = rhs.to_primitive(global_object);
  1288. if (global_object.vm().exception())
  1289. return false;
  1290. return abstract_eq(global_object, lhs, rhs_primitive);
  1291. }
  1292. if (lhs.is_object() && (rhs.is_string() || rhs.is_number() || lhs.is_bigint() || rhs.is_symbol())) {
  1293. auto lhs_primitive = lhs.to_primitive(global_object);
  1294. if (global_object.vm().exception())
  1295. return false;
  1296. return abstract_eq(global_object, lhs_primitive, rhs);
  1297. }
  1298. if ((lhs.is_bigint() && rhs.is_number()) || (lhs.is_number() && rhs.is_bigint())) {
  1299. if (lhs.is_nan() || lhs.is_infinity() || rhs.is_nan() || rhs.is_infinity())
  1300. return false;
  1301. if ((lhs.is_number() && !lhs.is_integral_number()) || (rhs.is_number() && !rhs.is_integral_number()))
  1302. return false;
  1303. if (lhs.is_number())
  1304. return Crypto::SignedBigInteger { lhs.to_i32(global_object) } == rhs.as_bigint().big_integer();
  1305. else
  1306. return Crypto::SignedBigInteger { rhs.to_i32(global_object) } == lhs.as_bigint().big_integer();
  1307. }
  1308. return false;
  1309. }
  1310. // 7.2.13 IsLessThan ( x, y, LeftFirst ), https://tc39.es/ecma262/#sec-islessthan
  1311. TriState abstract_relation(GlobalObject& global_object, bool left_first, Value lhs, Value rhs)
  1312. {
  1313. Value x_primitive;
  1314. Value y_primitive;
  1315. if (left_first) {
  1316. x_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1317. if (global_object.vm().exception())
  1318. return {};
  1319. y_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1320. if (global_object.vm().exception())
  1321. return {};
  1322. } else {
  1323. y_primitive = lhs.to_primitive(global_object, Value::PreferredType::Number);
  1324. if (global_object.vm().exception())
  1325. return {};
  1326. x_primitive = rhs.to_primitive(global_object, Value::PreferredType::Number);
  1327. if (global_object.vm().exception())
  1328. return {};
  1329. }
  1330. if (x_primitive.is_string() && y_primitive.is_string()) {
  1331. auto x_string = x_primitive.as_string().string();
  1332. auto y_string = y_primitive.as_string().string();
  1333. Utf8View x_code_points { x_string };
  1334. Utf8View y_code_points { y_string };
  1335. if (x_code_points.starts_with(y_code_points))
  1336. return TriState::False;
  1337. if (y_code_points.starts_with(x_code_points))
  1338. return TriState::True;
  1339. for (auto k = x_code_points.begin(), l = y_code_points.begin();
  1340. k != x_code_points.end() && l != y_code_points.end();
  1341. ++k, ++l) {
  1342. if (*k != *l) {
  1343. if (*k < *l) {
  1344. return TriState::True;
  1345. } else {
  1346. return TriState::False;
  1347. }
  1348. }
  1349. }
  1350. VERIFY_NOT_REACHED();
  1351. }
  1352. if (x_primitive.is_bigint() && y_primitive.is_string()) {
  1353. auto& y_string = y_primitive.as_string().string();
  1354. if (!is_valid_bigint_value(y_string))
  1355. return TriState::Unknown;
  1356. if (x_primitive.as_bigint().big_integer() < Crypto::SignedBigInteger::from_base(10, y_string))
  1357. return TriState::True;
  1358. else
  1359. return TriState::False;
  1360. }
  1361. if (x_primitive.is_string() && y_primitive.is_bigint()) {
  1362. auto& x_string = x_primitive.as_string().string();
  1363. if (!is_valid_bigint_value(x_string))
  1364. return TriState::Unknown;
  1365. if (Crypto::SignedBigInteger::from_base(10, x_string) < y_primitive.as_bigint().big_integer())
  1366. return TriState::True;
  1367. else
  1368. return TriState::False;
  1369. }
  1370. auto x_numeric = x_primitive.to_numeric(global_object);
  1371. if (global_object.vm().exception())
  1372. return {};
  1373. auto y_numeric = y_primitive.to_numeric(global_object);
  1374. if (global_object.vm().exception())
  1375. return {};
  1376. if (x_numeric.is_nan() || y_numeric.is_nan())
  1377. return TriState::Unknown;
  1378. if (x_numeric.is_positive_infinity() || y_numeric.is_negative_infinity())
  1379. return TriState::False;
  1380. if (x_numeric.is_negative_infinity() || y_numeric.is_positive_infinity())
  1381. return TriState::True;
  1382. if (x_numeric.is_number() && y_numeric.is_number()) {
  1383. if (x_numeric.as_double() < y_numeric.as_double())
  1384. return TriState::True;
  1385. else
  1386. return TriState::False;
  1387. }
  1388. if (x_numeric.is_bigint() && y_numeric.is_bigint()) {
  1389. if (x_numeric.as_bigint().big_integer() < y_numeric.as_bigint().big_integer())
  1390. return TriState::True;
  1391. else
  1392. return TriState::False;
  1393. }
  1394. VERIFY((x_numeric.is_number() && y_numeric.is_bigint()) || (x_numeric.is_bigint() && y_numeric.is_number()));
  1395. bool x_lower_than_y;
  1396. if (x_numeric.is_number()) {
  1397. x_lower_than_y = x_numeric.is_integral_number()
  1398. ? Crypto::SignedBigInteger { x_numeric.to_i32(global_object) } < y_numeric.as_bigint().big_integer()
  1399. : (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());
  1400. } else {
  1401. x_lower_than_y = y_numeric.is_integral_number()
  1402. ? x_numeric.as_bigint().big_integer() < Crypto::SignedBigInteger { y_numeric.to_i32(global_object) }
  1403. : (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 });
  1404. }
  1405. if (x_lower_than_y)
  1406. return TriState::True;
  1407. else
  1408. return TriState::False;
  1409. }
  1410. }