Value.cpp 57 KB

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