Value.cpp 55 KB

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