Value.cpp 57 KB

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