Value.cpp 57 KB

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