Value.cpp 55 KB

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