Value.cpp 55 KB

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