Value.cpp 57 KB

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