Value.cpp 54 KB

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