Value.cpp 56 KB

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