Value.cpp 57 KB

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