Value.cpp 57 KB

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