Value.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/Assertions.h>
  10. #include <AK/BitCast.h>
  11. #include <AK/DeprecatedString.h>
  12. #include <AK/Format.h>
  13. #include <AK/Forward.h>
  14. #include <AK/Function.h>
  15. #include <AK/Result.h>
  16. #include <AK/String.h>
  17. #include <AK/Types.h>
  18. #include <LibJS/Forward.h>
  19. #include <LibJS/Heap/GCPtr.h>
  20. #include <math.h>
  21. // 2 ** 53 - 1
  22. static constexpr double MAX_ARRAY_LIKE_INDEX = 9007199254740991.0;
  23. // Unique bit representation of negative zero (only sign bit set)
  24. static constexpr u64 NEGATIVE_ZERO_BITS = ((u64)1 << 63);
  25. namespace JS {
  26. static_assert(sizeof(double) == 8);
  27. static_assert(sizeof(void*) == sizeof(double) || sizeof(void*) == sizeof(u32));
  28. // To make our Value representation compact we can use the fact that IEEE
  29. // doubles have a lot (2^52 - 2) of NaN bit patterns. The canonical form being
  30. // just 0x7FF8000000000000 i.e. sign = 0 exponent is all ones and the top most
  31. // bit of the mantissa set.
  32. static constexpr u64 CANON_NAN_BITS = bit_cast<u64>(__builtin_nan(""));
  33. static_assert(CANON_NAN_BITS == 0x7FF8000000000000);
  34. // (Unfortunately all the other values are valid so we have to convert any
  35. // incoming NaNs to this pattern although in practice it seems only the negative
  36. // version of these CANON_NAN_BITS)
  37. // +/- Infinity are represented by a full exponent but without any bits of the
  38. // mantissa set.
  39. static constexpr u64 POSITIVE_INFINITY_BITS = bit_cast<u64>(__builtin_huge_val());
  40. static constexpr u64 NEGATIVE_INFINITY_BITS = bit_cast<u64>(-__builtin_huge_val());
  41. static_assert(POSITIVE_INFINITY_BITS == 0x7FF0000000000000);
  42. static_assert(NEGATIVE_INFINITY_BITS == 0xFFF0000000000000);
  43. // However as long as any bit is set in the mantissa with the exponent of all
  44. // ones this value is a NaN, and it even ignores the sign bit.
  45. // (NOTE: we have to use __builtin_isnan here since some isnan implementations are not constexpr)
  46. static_assert(__builtin_isnan(bit_cast<double>(0x7FF0000000000001)));
  47. static_assert(__builtin_isnan(bit_cast<double>(0xFFF0000000040000)));
  48. // This means we can use all of these NaNs to store all other options for Value.
  49. // To make sure all of these other representations we use 0x7FF8 as the base top
  50. // 2 bytes which ensures the value is always a NaN.
  51. static constexpr u64 BASE_TAG = 0x7FF8;
  52. // This leaves the sign bit and the three lower bits for tagging a value and then
  53. // 48 bits of potential payload.
  54. // First the pointer backed types (Object, String etc.), to signify this category
  55. // and make stack scanning easier we use the sign bit (top most bit) of 1 to
  56. // signify that it is a pointer backed type.
  57. static constexpr u64 IS_CELL_BIT = 0x8000 | BASE_TAG;
  58. // On all current 64-bit systems this code runs pointer actually only use the
  59. // lowest 6 bytes which fits neatly into our NaN payload with the top two bytes
  60. // left over for marking it as a NaN and tagging the type.
  61. // Note that we do need to take care when extracting the pointer value but this
  62. // is explained in the extract_pointer method.
  63. // This leaves us 3 bits to tag the type of pointer:
  64. static constexpr u64 OBJECT_TAG = 0b001 | IS_CELL_BIT;
  65. static constexpr u64 STRING_TAG = 0b010 | IS_CELL_BIT;
  66. static constexpr u64 SYMBOL_TAG = 0b011 | IS_CELL_BIT;
  67. static constexpr u64 ACCESSOR_TAG = 0b100 | IS_CELL_BIT;
  68. static constexpr u64 BIGINT_TAG = 0b101 | IS_CELL_BIT;
  69. // We can then by extracting the top 13 bits quickly check if a Value is
  70. // pointer backed.
  71. static constexpr u64 IS_CELL_PATTERN = 0xFFF8ULL;
  72. static_assert((OBJECT_TAG & IS_CELL_PATTERN) == IS_CELL_PATTERN);
  73. static_assert((STRING_TAG & IS_CELL_PATTERN) == IS_CELL_PATTERN);
  74. static_assert((CANON_NAN_BITS & IS_CELL_PATTERN) != IS_CELL_PATTERN);
  75. static_assert((NEGATIVE_INFINITY_BITS & IS_CELL_PATTERN) != IS_CELL_PATTERN);
  76. // Then for the non pointer backed types we don't set the sign bit and use the
  77. // three lower bits for tagging as well.
  78. static constexpr u64 UNDEFINED_TAG = 0b110 | BASE_TAG;
  79. static constexpr u64 NULL_TAG = 0b111 | BASE_TAG;
  80. static constexpr u64 BOOLEAN_TAG = 0b001 | BASE_TAG;
  81. static constexpr u64 INT32_TAG = 0b010 | BASE_TAG;
  82. static constexpr u64 EMPTY_TAG = 0b011 | BASE_TAG;
  83. // Notice how only undefined and null have the top bit set, this mean we can
  84. // quickly check for nullish values by checking if the top and bottom bits are set
  85. // but the middle one isn't.
  86. static constexpr u64 IS_NULLISH_EXTRACT_PATTERN = 0xFFFEULL;
  87. static constexpr u64 IS_NULLISH_PATTERN = 0x7FFEULL;
  88. static_assert((UNDEFINED_TAG & IS_NULLISH_EXTRACT_PATTERN) == IS_NULLISH_PATTERN);
  89. static_assert((NULL_TAG & IS_NULLISH_EXTRACT_PATTERN) == IS_NULLISH_PATTERN);
  90. static_assert((BOOLEAN_TAG & IS_NULLISH_EXTRACT_PATTERN) != IS_NULLISH_PATTERN);
  91. static_assert((INT32_TAG & IS_NULLISH_EXTRACT_PATTERN) != IS_NULLISH_PATTERN);
  92. static_assert((EMPTY_TAG & IS_NULLISH_EXTRACT_PATTERN) != IS_NULLISH_PATTERN);
  93. // We also have the empty tag to represent array holes however since empty
  94. // values are not valid anywhere else we can use this "value" to our advantage
  95. // in Optional<Value> to represent the empty optional.
  96. static constexpr u64 TAG_EXTRACTION = 0xFFFF000000000000;
  97. static constexpr u64 TAG_SHIFT = 48;
  98. static constexpr u64 SHIFTED_INT32_TAG = INT32_TAG << TAG_SHIFT;
  99. static constexpr u64 SHIFTED_IS_CELL_PATTERN = IS_CELL_PATTERN << TAG_SHIFT;
  100. // Summary:
  101. // To pack all the different value in to doubles we use the following schema:
  102. // s = sign, e = exponent, m = mantissa
  103. // The top part is the tag and the bottom the payload.
  104. // 0bseeeeeeeeeeemmmm mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
  105. // 0b0111111111111000 0... is the only real NaN
  106. // 0b1111111111111xxx yyy... xxx = pointer type, yyy = pointer value
  107. // 0b0111111111111xxx yyy... xxx = non-pointer type, yyy = value or 0 if just type
  108. // Future expansion: We are not fully utilizing all the possible bit patterns
  109. // yet, these choices were made to make it easy to implement and understand.
  110. // We can for example drop the always 1 top bit of the mantissa expanding our
  111. // options from 8 tags to 15 but since we currently only use 5 for both sign bits
  112. // this is not needed.
  113. class Value {
  114. public:
  115. enum class PreferredType {
  116. Default,
  117. String,
  118. Number,
  119. };
  120. bool is_empty() const { return m_value.tag == EMPTY_TAG; }
  121. bool is_undefined() const { return m_value.tag == UNDEFINED_TAG; }
  122. bool is_null() const { return m_value.tag == NULL_TAG; }
  123. bool is_number() const { return is_double() || is_int32(); }
  124. bool is_string() const { return m_value.tag == STRING_TAG; }
  125. bool is_object() const { return m_value.tag == OBJECT_TAG; }
  126. bool is_boolean() const { return m_value.tag == BOOLEAN_TAG; }
  127. bool is_symbol() const { return m_value.tag == SYMBOL_TAG; }
  128. bool is_accessor() const { return m_value.tag == ACCESSOR_TAG; };
  129. bool is_bigint() const { return m_value.tag == BIGINT_TAG; };
  130. bool is_nullish() const { return (m_value.tag & IS_NULLISH_EXTRACT_PATTERN) == IS_NULLISH_PATTERN; }
  131. bool is_cell() const { return (m_value.tag & IS_CELL_PATTERN) == IS_CELL_PATTERN; }
  132. ThrowCompletionOr<bool> is_array(VM&) const;
  133. bool is_function() const;
  134. bool is_constructor() const;
  135. ThrowCompletionOr<bool> is_regexp(VM&) const;
  136. bool is_nan() const
  137. {
  138. return m_value.encoded == CANON_NAN_BITS;
  139. }
  140. bool is_infinity() const
  141. {
  142. static_assert(NEGATIVE_INFINITY_BITS == (0x1ULL << 63 | POSITIVE_INFINITY_BITS));
  143. return (0x1ULL << 63 | m_value.encoded) == NEGATIVE_INFINITY_BITS;
  144. }
  145. bool is_positive_infinity() const
  146. {
  147. return m_value.encoded == POSITIVE_INFINITY_BITS;
  148. }
  149. bool is_negative_infinity() const
  150. {
  151. return m_value.encoded == NEGATIVE_INFINITY_BITS;
  152. }
  153. bool is_positive_zero() const
  154. {
  155. return m_value.encoded == 0 || (is_int32() && as_i32() == 0);
  156. }
  157. bool is_negative_zero() const
  158. {
  159. return m_value.encoded == NEGATIVE_ZERO_BITS;
  160. }
  161. bool is_integral_number() const
  162. {
  163. if (is_int32())
  164. return true;
  165. return is_finite_number() && trunc(as_double()) == as_double();
  166. }
  167. bool is_finite_number() const
  168. {
  169. if (!is_number())
  170. return false;
  171. if (is_int32())
  172. return true;
  173. return !is_nan() && !is_infinity();
  174. }
  175. Value()
  176. : Value(EMPTY_TAG << TAG_SHIFT, (u64)0)
  177. {
  178. }
  179. template<typename T>
  180. requires(IsSameIgnoringCV<T, bool>) explicit Value(T value)
  181. : Value(BOOLEAN_TAG << TAG_SHIFT, (u64)value)
  182. {
  183. }
  184. explicit Value(double value)
  185. {
  186. bool is_negative_zero = bit_cast<u64>(value) == NEGATIVE_ZERO_BITS;
  187. if (value >= NumericLimits<i32>::min() && value <= NumericLimits<i32>::max() && trunc(value) == value && !is_negative_zero) {
  188. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  189. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  190. } else {
  191. if (isnan(value)) [[unlikely]]
  192. m_value.encoded = CANON_NAN_BITS;
  193. else
  194. m_value.as_double = value;
  195. }
  196. }
  197. // NOTE: A couple of integral types are excluded here:
  198. // - i32 has its own dedicated Value constructor
  199. // - i64 cannot safely be cast to a double
  200. // - bool isn't a number type and has its own dedicated Value constructor
  201. template<typename T>
  202. requires(IsIntegral<T> && !IsSameIgnoringCV<T, i32> && !IsSameIgnoringCV<T, i64> && !IsSameIgnoringCV<T, bool>) explicit Value(T value)
  203. {
  204. if (value > NumericLimits<i32>::max()) {
  205. m_value.as_double = static_cast<double>(value);
  206. } else {
  207. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  208. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  209. }
  210. }
  211. explicit Value(unsigned value)
  212. {
  213. if (value > NumericLimits<i32>::max()) {
  214. m_value.as_double = static_cast<double>(value);
  215. } else {
  216. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  217. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  218. }
  219. }
  220. explicit Value(i32 value)
  221. : Value(SHIFTED_INT32_TAG, (u32)value)
  222. {
  223. }
  224. Value(Object const* object)
  225. : Value(OBJECT_TAG << TAG_SHIFT, reinterpret_cast<void const*>(object))
  226. {
  227. }
  228. Value(PrimitiveString const* string)
  229. : Value(STRING_TAG << TAG_SHIFT, reinterpret_cast<void const*>(string))
  230. {
  231. }
  232. Value(Symbol const* symbol)
  233. : Value(SYMBOL_TAG << TAG_SHIFT, reinterpret_cast<void const*>(symbol))
  234. {
  235. }
  236. Value(Accessor const* accessor)
  237. : Value(ACCESSOR_TAG << TAG_SHIFT, reinterpret_cast<void const*>(accessor))
  238. {
  239. }
  240. Value(BigInt const* bigint)
  241. : Value(BIGINT_TAG << TAG_SHIFT, reinterpret_cast<void const*>(bigint))
  242. {
  243. }
  244. template<typename T>
  245. Value(GCPtr<T> ptr)
  246. : Value(ptr.ptr())
  247. {
  248. }
  249. template<typename T>
  250. Value(NonnullGCPtr<T> ptr)
  251. : Value(ptr.ptr())
  252. {
  253. }
  254. double as_double() const
  255. {
  256. VERIFY(is_number());
  257. if (is_int32())
  258. return as_i32();
  259. return m_value.as_double;
  260. }
  261. bool as_bool() const
  262. {
  263. VERIFY(is_boolean());
  264. return static_cast<bool>(m_value.encoded & 0x1);
  265. }
  266. Object& as_object()
  267. {
  268. VERIFY(is_object());
  269. return *extract_pointer<Object>();
  270. }
  271. Object const& as_object() const
  272. {
  273. VERIFY(is_object());
  274. return *extract_pointer<Object>();
  275. }
  276. PrimitiveString& as_string()
  277. {
  278. VERIFY(is_string());
  279. return *extract_pointer<PrimitiveString>();
  280. }
  281. PrimitiveString const& as_string() const
  282. {
  283. VERIFY(is_string());
  284. return *extract_pointer<PrimitiveString>();
  285. }
  286. Symbol& as_symbol()
  287. {
  288. VERIFY(is_symbol());
  289. return *extract_pointer<Symbol>();
  290. }
  291. Symbol const& as_symbol() const
  292. {
  293. VERIFY(is_symbol());
  294. return *extract_pointer<Symbol>();
  295. }
  296. Cell& as_cell()
  297. {
  298. VERIFY(is_cell());
  299. return *extract_pointer<Cell>();
  300. }
  301. Accessor& as_accessor()
  302. {
  303. VERIFY(is_accessor());
  304. return *extract_pointer<Accessor>();
  305. }
  306. BigInt const& as_bigint() const
  307. {
  308. VERIFY(is_bigint());
  309. return *extract_pointer<BigInt>();
  310. }
  311. BigInt& as_bigint()
  312. {
  313. VERIFY(is_bigint());
  314. return *extract_pointer<BigInt>();
  315. }
  316. Array& as_array();
  317. FunctionObject& as_function();
  318. FunctionObject const& as_function() const;
  319. u64 encoded() const { return m_value.encoded; }
  320. ThrowCompletionOr<String> to_string(VM&) const;
  321. ThrowCompletionOr<DeprecatedString> to_deprecated_string(VM&) const;
  322. ThrowCompletionOr<Utf16String> to_utf16_string(VM&) const;
  323. ThrowCompletionOr<NonnullGCPtr<PrimitiveString>> to_primitive_string(VM&);
  324. ThrowCompletionOr<Value> to_primitive(VM&, PreferredType preferred_type = PreferredType::Default) const;
  325. ThrowCompletionOr<NonnullGCPtr<Object>> to_object(VM&) const;
  326. ThrowCompletionOr<Value> to_numeric(VM&) const;
  327. ThrowCompletionOr<Value> to_number(VM&) const;
  328. ThrowCompletionOr<NonnullGCPtr<BigInt>> to_bigint(VM&) const;
  329. ThrowCompletionOr<i64> to_bigint_int64(VM&) const;
  330. ThrowCompletionOr<u64> to_bigint_uint64(VM&) const;
  331. ThrowCompletionOr<double> to_double(VM&) const;
  332. ThrowCompletionOr<PropertyKey> to_property_key(VM&) const;
  333. ThrowCompletionOr<i32> to_i32(VM&) const;
  334. ThrowCompletionOr<u32> to_u32(VM&) const;
  335. ThrowCompletionOr<i16> to_i16(VM&) const;
  336. ThrowCompletionOr<u16> to_u16(VM&) const;
  337. ThrowCompletionOr<i8> to_i8(VM&) const;
  338. ThrowCompletionOr<u8> to_u8(VM&) const;
  339. ThrowCompletionOr<u8> to_u8_clamp(VM&) const;
  340. ThrowCompletionOr<size_t> to_length(VM&) const;
  341. ThrowCompletionOr<size_t> to_index(VM&) const;
  342. ThrowCompletionOr<double> to_integer_or_infinity(VM&) const;
  343. bool to_boolean() const;
  344. ThrowCompletionOr<Value> get(VM&, PropertyKey const&) const;
  345. ThrowCompletionOr<FunctionObject*> get_method(VM&, PropertyKey const&) const;
  346. ErrorOr<String> to_string_without_side_effects() const;
  347. Value value_or(Value fallback) const
  348. {
  349. if (is_empty())
  350. return fallback;
  351. return *this;
  352. }
  353. StringView typeof() const;
  354. bool operator==(Value const&) const;
  355. template<typename... Args>
  356. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> invoke(VM&, PropertyKey const& property_key, Args... args);
  357. static constexpr FlatPtr extract_pointer_bits(u64 encoded)
  358. {
  359. #ifdef AK_ARCH_32_BIT
  360. // For 32-bit system the pointer fully fits so we can just return it directly.
  361. static_assert(sizeof(void*) == sizeof(u32));
  362. return static_cast<FlatPtr>(encoded & 0xffff'ffff);
  363. #elif ARCH(X86_64)
  364. // For x86_64 the top 16 bits should be sign extending the "real" top bit (47th).
  365. // So first shift the top 16 bits away then using the right shift it sign extends the top 16 bits.
  366. return static_cast<FlatPtr>((static_cast<i64>(encoded << 16)) >> 16);
  367. #elif ARCH(AARCH64)
  368. // For AArch64 the top 16 bits of the pointer should be zero.
  369. return static_cast<FlatPtr>(encoded & 0xffff'ffff'ffffULL);
  370. #else
  371. # error "Unknown architecture. Don't know whether pointers need to be sign-extended."
  372. #endif
  373. }
  374. private:
  375. Value(u64 tag, u64 val)
  376. {
  377. VERIFY(!(tag & val));
  378. m_value.encoded = tag | val;
  379. }
  380. template<typename PointerType>
  381. Value(u64 tag, PointerType const* ptr)
  382. {
  383. if (!ptr) {
  384. // Make sure all nullptrs are null
  385. m_value.tag = NULL_TAG;
  386. return;
  387. }
  388. VERIFY((tag & 0x8000000000000000ul) == 0x8000000000000000ul);
  389. if constexpr (sizeof(PointerType*) < sizeof(u64)) {
  390. m_value.encoded = tag | reinterpret_cast<u32>(ptr);
  391. } else {
  392. // NOTE: Pointers in x86-64 use just 48 bits however are supposed to be
  393. // sign extended up from the 47th bit.
  394. // This means that all bits above the 47th should be the same as
  395. // the 47th. When storing a pointer we thus drop the top 16 bits as
  396. // we can recover it when extracting the pointer again.
  397. // See also: Value::extract_pointer.
  398. m_value.encoded = tag | (reinterpret_cast<u64>(ptr) & 0x0000ffffffffffffULL);
  399. }
  400. }
  401. // A double is any Value which does not have the full exponent and top mantissa bit set or has
  402. // exactly only those bits set.
  403. bool is_double() const { return (m_value.encoded & CANON_NAN_BITS) != CANON_NAN_BITS || (m_value.encoded == CANON_NAN_BITS); }
  404. bool is_int32() const { return m_value.tag == INT32_TAG; }
  405. i32 as_i32() const
  406. {
  407. VERIFY(is_int32());
  408. return static_cast<i32>(m_value.encoded & 0xFFFFFFFF);
  409. }
  410. template<typename PointerType>
  411. PointerType* extract_pointer() const
  412. {
  413. VERIFY(is_cell());
  414. return reinterpret_cast<PointerType*>(extract_pointer_bits(m_value.encoded));
  415. }
  416. [[nodiscard]] ThrowCompletionOr<Value> invoke_internal(VM&, PropertyKey const&, Optional<MarkedVector<Value>> arguments);
  417. ThrowCompletionOr<i32> to_i32_slow_case(VM&) const;
  418. union {
  419. double as_double;
  420. struct {
  421. u64 payload : 48;
  422. u64 tag : 16;
  423. };
  424. u64 encoded;
  425. } m_value { .encoded = 0 };
  426. friend Value js_undefined();
  427. friend Value js_null();
  428. friend ThrowCompletionOr<Value> greater_than(VM&, Value lhs, Value rhs);
  429. friend ThrowCompletionOr<Value> greater_than_equals(VM&, Value lhs, Value rhs);
  430. friend ThrowCompletionOr<Value> less_than(VM&, Value lhs, Value rhs);
  431. friend ThrowCompletionOr<Value> less_than_equals(VM&, Value lhs, Value rhs);
  432. friend ThrowCompletionOr<Value> add(VM&, Value lhs, Value rhs);
  433. friend bool same_value_non_number(Value lhs, Value rhs);
  434. };
  435. inline Value js_undefined()
  436. {
  437. return Value(UNDEFINED_TAG << TAG_SHIFT, (u64)0);
  438. }
  439. inline Value js_null()
  440. {
  441. return Value(NULL_TAG << TAG_SHIFT, (u64)0);
  442. }
  443. inline Value js_nan()
  444. {
  445. return Value(NAN);
  446. }
  447. inline Value js_infinity()
  448. {
  449. return Value(INFINITY);
  450. }
  451. inline Value js_negative_infinity()
  452. {
  453. return Value(-INFINITY);
  454. }
  455. ThrowCompletionOr<Value> greater_than(VM&, Value lhs, Value rhs);
  456. ThrowCompletionOr<Value> greater_than_equals(VM&, Value lhs, Value rhs);
  457. ThrowCompletionOr<Value> less_than(VM&, Value lhs, Value rhs);
  458. ThrowCompletionOr<Value> less_than_equals(VM&, Value lhs, Value rhs);
  459. ThrowCompletionOr<Value> bitwise_and(VM&, Value lhs, Value rhs);
  460. ThrowCompletionOr<Value> bitwise_or(VM&, Value lhs, Value rhs);
  461. ThrowCompletionOr<Value> bitwise_xor(VM&, Value lhs, Value rhs);
  462. ThrowCompletionOr<Value> bitwise_not(VM&, Value);
  463. ThrowCompletionOr<Value> unary_plus(VM&, Value);
  464. ThrowCompletionOr<Value> unary_minus(VM&, Value);
  465. ThrowCompletionOr<Value> left_shift(VM&, Value lhs, Value rhs);
  466. ThrowCompletionOr<Value> right_shift(VM&, Value lhs, Value rhs);
  467. ThrowCompletionOr<Value> unsigned_right_shift(VM&, Value lhs, Value rhs);
  468. ThrowCompletionOr<Value> add(VM&, Value lhs, Value rhs);
  469. ThrowCompletionOr<Value> sub(VM&, Value lhs, Value rhs);
  470. ThrowCompletionOr<Value> mul(VM&, Value lhs, Value rhs);
  471. ThrowCompletionOr<Value> div(VM&, Value lhs, Value rhs);
  472. ThrowCompletionOr<Value> mod(VM&, Value lhs, Value rhs);
  473. ThrowCompletionOr<Value> exp(VM&, Value lhs, Value rhs);
  474. ThrowCompletionOr<Value> in(VM&, Value lhs, Value rhs);
  475. ThrowCompletionOr<Value> instance_of(VM&, Value lhs, Value rhs);
  476. ThrowCompletionOr<Value> ordinary_has_instance(VM&, Value lhs, Value rhs);
  477. ThrowCompletionOr<bool> is_loosely_equal(VM&, Value lhs, Value rhs);
  478. bool is_strictly_equal(Value lhs, Value rhs);
  479. bool same_value(Value lhs, Value rhs);
  480. bool same_value_zero(Value lhs, Value rhs);
  481. bool same_value_non_number(Value lhs, Value rhs);
  482. ThrowCompletionOr<TriState> is_less_than(VM&, Value lhs, Value rhs, bool left_first);
  483. double to_integer_or_infinity(double);
  484. enum class NumberToStringMode {
  485. WithExponent,
  486. WithoutExponent,
  487. };
  488. ErrorOr<String> number_to_string(double, NumberToStringMode = NumberToStringMode::WithExponent);
  489. DeprecatedString number_to_deprecated_string(double, NumberToStringMode = NumberToStringMode::WithExponent);
  490. double string_to_number(StringView);
  491. inline bool Value::operator==(Value const& value) const { return same_value(*this, value); }
  492. }
  493. namespace AK {
  494. static_assert(sizeof(JS::Value) == sizeof(double));
  495. template<>
  496. class Optional<JS::Value> {
  497. template<typename U>
  498. friend class Optional;
  499. public:
  500. using ValueType = JS::Value;
  501. Optional() = default;
  502. Optional(Optional<JS::Value> const& other)
  503. {
  504. if (other.has_value())
  505. m_value = other.m_value;
  506. }
  507. Optional(Optional&& other)
  508. : m_value(other.m_value)
  509. {
  510. }
  511. template<typename U = JS::Value>
  512. explicit(!IsConvertible<U&&, JS::Value>) Optional(U&& value)
  513. requires(!IsSame<RemoveCVReference<U>, Optional<JS::Value>> && IsConstructible<JS::Value, U &&>)
  514. : m_value(forward<U>(value))
  515. {
  516. }
  517. Optional& operator=(Optional const& other)
  518. {
  519. if (this != &other) {
  520. clear();
  521. m_value = other.m_value;
  522. }
  523. return *this;
  524. }
  525. Optional& operator=(Optional&& other)
  526. {
  527. if (this != &other) {
  528. clear();
  529. m_value = other.m_value;
  530. }
  531. return *this;
  532. }
  533. void clear()
  534. {
  535. m_value = {};
  536. }
  537. [[nodiscard]] bool has_value() const
  538. {
  539. return !m_value.is_empty();
  540. }
  541. [[nodiscard]] JS::Value& value() &
  542. {
  543. VERIFY(has_value());
  544. return m_value;
  545. }
  546. [[nodiscard]] JS::Value const& value() const&
  547. {
  548. VERIFY(has_value());
  549. return m_value;
  550. }
  551. [[nodiscard]] JS::Value value() &&
  552. {
  553. return release_value();
  554. }
  555. [[nodiscard]] JS::Value release_value()
  556. {
  557. VERIFY(has_value());
  558. JS::Value released_value = m_value;
  559. clear();
  560. return released_value;
  561. }
  562. JS::Value value_or(JS::Value const& fallback) const&
  563. {
  564. if (has_value())
  565. return value();
  566. return fallback;
  567. }
  568. [[nodiscard]] JS::Value value_or(JS::Value&& fallback) &&
  569. {
  570. if (has_value())
  571. return value();
  572. return fallback;
  573. }
  574. JS::Value const& operator*() const { return value(); }
  575. JS::Value& operator*() { return value(); }
  576. JS::Value const* operator->() const { return &value(); }
  577. JS::Value* operator->() { return &value(); }
  578. private:
  579. JS::Value m_value;
  580. };
  581. template<>
  582. struct Formatter<JS::Value> : Formatter<StringView> {
  583. ErrorOr<void> format(FormatBuilder& builder, JS::Value value)
  584. {
  585. if (value.is_empty())
  586. return Formatter<StringView>::format(builder, "<empty>"sv);
  587. return Formatter<StringView>::format(builder, TRY(value.to_string_without_side_effects()));
  588. }
  589. };
  590. }