Value.cpp 56 KB

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