Value.cpp 57 KB

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