Value.cpp 54 KB

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