Value.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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/ByteString.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. namespace JS {
  22. // 2 ** 53 - 1
  23. static constexpr double MAX_ARRAY_LIKE_INDEX = 9007199254740991.0;
  24. // Unique bit representation of negative zero (only sign bit set)
  25. static constexpr u64 NEGATIVE_ZERO_BITS = ((u64)1 << 63);
  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_BOOLEAN_TAG = BOOLEAN_TAG << TAG_SHIFT;
  99. static constexpr u64 SHIFTED_INT32_TAG = INT32_TAG << TAG_SHIFT;
  100. static constexpr u64 SHIFTED_IS_CELL_PATTERN = IS_CELL_PATTERN << TAG_SHIFT;
  101. // Summary:
  102. // To pack all the different value in to doubles we use the following schema:
  103. // s = sign, e = exponent, m = mantissa
  104. // The top part is the tag and the bottom the payload.
  105. // 0bseeeeeeeeeeemmmm mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
  106. // 0b0111111111111000 0... is the only real NaN
  107. // 0b1111111111111xxx yyy... xxx = pointer type, yyy = pointer value
  108. // 0b0111111111111xxx yyy... xxx = non-pointer type, yyy = value or 0 if just type
  109. // Future expansion: We are not fully utilizing all the possible bit patterns
  110. // yet, these choices were made to make it easy to implement and understand.
  111. // We can for example drop the always 1 top bit of the mantissa expanding our
  112. // options from 8 tags to 15 but since we currently only use 5 for both sign bits
  113. // this is not needed.
  114. class Value {
  115. public:
  116. enum class PreferredType {
  117. Default,
  118. String,
  119. Number,
  120. };
  121. [[nodiscard]] u16 tag() const { return m_value.tag; }
  122. bool is_empty() const { return m_value.tag == EMPTY_TAG; }
  123. bool is_undefined() const { return m_value.tag == UNDEFINED_TAG; }
  124. bool is_null() const { return m_value.tag == NULL_TAG; }
  125. bool is_number() const { return is_double() || is_int32(); }
  126. bool is_string() const { return m_value.tag == STRING_TAG; }
  127. bool is_object() const { return m_value.tag == OBJECT_TAG; }
  128. bool is_boolean() const { return m_value.tag == BOOLEAN_TAG; }
  129. bool is_symbol() const { return m_value.tag == SYMBOL_TAG; }
  130. bool is_accessor() const { return m_value.tag == ACCESSOR_TAG; }
  131. bool is_bigint() const { return m_value.tag == BIGINT_TAG; }
  132. bool is_nullish() const { return (m_value.tag & IS_NULLISH_EXTRACT_PATTERN) == IS_NULLISH_PATTERN; }
  133. bool is_cell() const { return (m_value.tag & IS_CELL_PATTERN) == IS_CELL_PATTERN; }
  134. ThrowCompletionOr<bool> is_array(VM&) const;
  135. bool is_function() const;
  136. bool is_constructor() const;
  137. ThrowCompletionOr<bool> is_regexp(VM&) const;
  138. bool is_nan() const
  139. {
  140. return m_value.encoded == CANON_NAN_BITS;
  141. }
  142. bool is_infinity() const
  143. {
  144. static_assert(NEGATIVE_INFINITY_BITS == (0x1ULL << 63 | POSITIVE_INFINITY_BITS));
  145. return (0x1ULL << 63 | m_value.encoded) == NEGATIVE_INFINITY_BITS;
  146. }
  147. bool is_positive_infinity() const
  148. {
  149. return m_value.encoded == POSITIVE_INFINITY_BITS;
  150. }
  151. bool is_negative_infinity() const
  152. {
  153. return m_value.encoded == NEGATIVE_INFINITY_BITS;
  154. }
  155. bool is_positive_zero() const
  156. {
  157. return m_value.encoded == 0 || (is_int32() && as_i32() == 0);
  158. }
  159. bool is_negative_zero() const
  160. {
  161. return m_value.encoded == NEGATIVE_ZERO_BITS;
  162. }
  163. bool is_integral_number() const
  164. {
  165. if (is_int32())
  166. return true;
  167. return is_finite_number() && trunc(as_double()) == as_double();
  168. }
  169. bool is_finite_number() const
  170. {
  171. if (!is_number())
  172. return false;
  173. if (is_int32())
  174. return true;
  175. return !is_nan() && !is_infinity();
  176. }
  177. Value()
  178. : Value(EMPTY_TAG << TAG_SHIFT, (u64)0)
  179. {
  180. }
  181. template<typename T>
  182. requires(IsSameIgnoringCV<T, bool>) explicit Value(T value)
  183. : Value(BOOLEAN_TAG << TAG_SHIFT, (u64)value)
  184. {
  185. }
  186. explicit Value(double value)
  187. {
  188. bool is_negative_zero = bit_cast<u64>(value) == NEGATIVE_ZERO_BITS;
  189. if (value >= NumericLimits<i32>::min() && value <= NumericLimits<i32>::max() && trunc(value) == value && !is_negative_zero) {
  190. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  191. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  192. } else {
  193. if (isnan(value)) [[unlikely]]
  194. m_value.encoded = CANON_NAN_BITS;
  195. else
  196. m_value.as_double = value;
  197. }
  198. }
  199. // NOTE: A couple of integral types are excluded here:
  200. // - i32 has its own dedicated Value constructor
  201. // - i64 cannot safely be cast to a double
  202. // - bool isn't a number type and has its own dedicated Value constructor
  203. template<typename T>
  204. requires(IsIntegral<T> && !IsSameIgnoringCV<T, i32> && !IsSameIgnoringCV<T, i64> && !IsSameIgnoringCV<T, bool>) explicit Value(T value)
  205. {
  206. if (value > NumericLimits<i32>::max()) {
  207. m_value.as_double = static_cast<double>(value);
  208. } else {
  209. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  210. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  211. }
  212. }
  213. explicit Value(unsigned value)
  214. {
  215. if (value > NumericLimits<i32>::max()) {
  216. m_value.as_double = static_cast<double>(value);
  217. } else {
  218. VERIFY(!(SHIFTED_INT32_TAG & (static_cast<i32>(value) & 0xFFFFFFFFul)));
  219. m_value.encoded = SHIFTED_INT32_TAG | (static_cast<i32>(value) & 0xFFFFFFFFul);
  220. }
  221. }
  222. explicit Value(i32 value)
  223. : Value(SHIFTED_INT32_TAG, (u32)value)
  224. {
  225. }
  226. Value(Object const* object)
  227. : Value(OBJECT_TAG << TAG_SHIFT, reinterpret_cast<void const*>(object))
  228. {
  229. }
  230. Value(PrimitiveString const* string)
  231. : Value(STRING_TAG << TAG_SHIFT, reinterpret_cast<void const*>(string))
  232. {
  233. }
  234. Value(Symbol const* symbol)
  235. : Value(SYMBOL_TAG << TAG_SHIFT, reinterpret_cast<void const*>(symbol))
  236. {
  237. }
  238. Value(Accessor const* accessor)
  239. : Value(ACCESSOR_TAG << TAG_SHIFT, reinterpret_cast<void const*>(accessor))
  240. {
  241. }
  242. Value(BigInt const* bigint)
  243. : Value(BIGINT_TAG << TAG_SHIFT, reinterpret_cast<void const*>(bigint))
  244. {
  245. }
  246. template<typename T>
  247. Value(GCPtr<T> ptr)
  248. : Value(ptr.ptr())
  249. {
  250. }
  251. template<typename T>
  252. Value(NonnullGCPtr<T> ptr)
  253. : Value(ptr.ptr())
  254. {
  255. }
  256. template<typename T>
  257. Value(Handle<T> const& ptr)
  258. : Value(ptr.ptr())
  259. {
  260. }
  261. double as_double() const
  262. {
  263. VERIFY(is_number());
  264. if (is_int32())
  265. return as_i32();
  266. return m_value.as_double;
  267. }
  268. bool as_bool() const
  269. {
  270. VERIFY(is_boolean());
  271. return static_cast<bool>(m_value.encoded & 0x1);
  272. }
  273. Object& as_object()
  274. {
  275. VERIFY(is_object());
  276. return *extract_pointer<Object>();
  277. }
  278. Object const& as_object() const
  279. {
  280. VERIFY(is_object());
  281. return *extract_pointer<Object>();
  282. }
  283. PrimitiveString& as_string()
  284. {
  285. VERIFY(is_string());
  286. return *extract_pointer<PrimitiveString>();
  287. }
  288. PrimitiveString const& as_string() const
  289. {
  290. VERIFY(is_string());
  291. return *extract_pointer<PrimitiveString>();
  292. }
  293. Symbol& as_symbol()
  294. {
  295. VERIFY(is_symbol());
  296. return *extract_pointer<Symbol>();
  297. }
  298. Symbol const& as_symbol() const
  299. {
  300. VERIFY(is_symbol());
  301. return *extract_pointer<Symbol>();
  302. }
  303. Cell& as_cell()
  304. {
  305. VERIFY(is_cell());
  306. return *extract_pointer<Cell>();
  307. }
  308. Cell& as_cell() const
  309. {
  310. VERIFY(is_cell());
  311. return *extract_pointer<Cell>();
  312. }
  313. Accessor& as_accessor()
  314. {
  315. VERIFY(is_accessor());
  316. return *extract_pointer<Accessor>();
  317. }
  318. BigInt const& as_bigint() const
  319. {
  320. VERIFY(is_bigint());
  321. return *extract_pointer<BigInt>();
  322. }
  323. BigInt& as_bigint()
  324. {
  325. VERIFY(is_bigint());
  326. return *extract_pointer<BigInt>();
  327. }
  328. Array& as_array();
  329. FunctionObject& as_function();
  330. FunctionObject const& as_function() const;
  331. u64 encoded() const { return m_value.encoded; }
  332. ThrowCompletionOr<String> to_string(VM&) const;
  333. ThrowCompletionOr<ByteString> to_byte_string(VM&) const;
  334. ThrowCompletionOr<Utf16String> to_utf16_string(VM&) const;
  335. ThrowCompletionOr<NonnullGCPtr<PrimitiveString>> to_primitive_string(VM&);
  336. ThrowCompletionOr<Value> to_primitive(VM&, PreferredType preferred_type = PreferredType::Default) const;
  337. ThrowCompletionOr<NonnullGCPtr<Object>> to_object(VM&) const;
  338. ThrowCompletionOr<Value> to_numeric(VM&) const;
  339. ThrowCompletionOr<Value> to_number(VM&) const;
  340. ThrowCompletionOr<NonnullGCPtr<BigInt>> to_bigint(VM&) const;
  341. ThrowCompletionOr<i64> to_bigint_int64(VM&) const;
  342. ThrowCompletionOr<u64> to_bigint_uint64(VM&) const;
  343. ThrowCompletionOr<double> to_double(VM&) const;
  344. ThrowCompletionOr<PropertyKey> to_property_key(VM&) const;
  345. ThrowCompletionOr<i32> to_i32(VM&) const;
  346. ThrowCompletionOr<u32> to_u32(VM&) const;
  347. ThrowCompletionOr<i16> to_i16(VM&) const;
  348. ThrowCompletionOr<u16> to_u16(VM&) const;
  349. ThrowCompletionOr<i8> to_i8(VM&) const;
  350. ThrowCompletionOr<u8> to_u8(VM&) const;
  351. ThrowCompletionOr<u8> to_u8_clamp(VM&) const;
  352. ThrowCompletionOr<size_t> to_length(VM&) const;
  353. ThrowCompletionOr<size_t> to_index(VM&) const;
  354. ThrowCompletionOr<double> to_integer_or_infinity(VM&) const;
  355. bool to_boolean() const;
  356. ThrowCompletionOr<Value> get(VM&, PropertyKey const&) const;
  357. ThrowCompletionOr<GCPtr<FunctionObject>> get_method(VM&, PropertyKey const&) const;
  358. [[nodiscard]] String to_string_without_side_effects() const;
  359. Value value_or(Value fallback) const
  360. {
  361. if (is_empty())
  362. return fallback;
  363. return *this;
  364. }
  365. StringView typeof() const;
  366. bool operator==(Value const&) const;
  367. template<typename... Args>
  368. [[nodiscard]] ALWAYS_INLINE ThrowCompletionOr<Value> invoke(VM&, PropertyKey const& property_key, Args... args);
  369. static constexpr FlatPtr extract_pointer_bits(u64 encoded)
  370. {
  371. #ifdef AK_ARCH_32_BIT
  372. // For 32-bit system the pointer fully fits so we can just return it directly.
  373. static_assert(sizeof(void*) == sizeof(u32));
  374. return static_cast<FlatPtr>(encoded & 0xffff'ffff);
  375. #elif ARCH(X86_64) || ARCH(RISCV64)
  376. // For x86_64 and riscv64 the top 16 bits should be sign extending the "real" top bit (47th).
  377. // So first shift the top 16 bits away then using the right shift it sign extends the top 16 bits.
  378. return static_cast<FlatPtr>((static_cast<i64>(encoded << 16)) >> 16);
  379. #elif ARCH(AARCH64)
  380. // For AArch64 the top 16 bits of the pointer should be zero.
  381. return static_cast<FlatPtr>(encoded & 0xffff'ffff'ffffULL);
  382. #else
  383. # error "Unknown architecture. Don't know whether pointers need to be sign-extended."
  384. #endif
  385. }
  386. // A double is any Value which does not have the full exponent and top mantissa bit set or has
  387. // exactly only those bits set.
  388. bool is_double() const { return (m_value.encoded & CANON_NAN_BITS) != CANON_NAN_BITS || (m_value.encoded == CANON_NAN_BITS); }
  389. bool is_int32() const { return m_value.tag == INT32_TAG; }
  390. i32 as_i32() const
  391. {
  392. VERIFY(is_int32());
  393. return static_cast<i32>(m_value.encoded & 0xFFFFFFFF);
  394. }
  395. bool to_boolean_slow_case() const;
  396. private:
  397. ThrowCompletionOr<Value> to_number_slow_case(VM&) const;
  398. ThrowCompletionOr<Value> to_numeric_slow_case(VM&) const;
  399. ThrowCompletionOr<Value> to_primitive_slow_case(VM&, PreferredType) const;
  400. Value(u64 tag, u64 val)
  401. {
  402. VERIFY(!(tag & val));
  403. m_value.encoded = tag | val;
  404. }
  405. template<typename PointerType>
  406. Value(u64 tag, PointerType const* ptr)
  407. {
  408. if (!ptr) {
  409. // Make sure all nullptrs are null
  410. m_value.tag = NULL_TAG;
  411. return;
  412. }
  413. VERIFY((tag & 0x8000000000000000ul) == 0x8000000000000000ul);
  414. if constexpr (sizeof(PointerType*) < sizeof(u64)) {
  415. m_value.encoded = tag | reinterpret_cast<u32>(ptr);
  416. } else {
  417. // NOTE: Pointers in x86-64 use just 48 bits however are supposed to be
  418. // sign extended up from the 47th bit.
  419. // This means that all bits above the 47th should be the same as
  420. // the 47th. When storing a pointer we thus drop the top 16 bits as
  421. // we can recover it when extracting the pointer again.
  422. // See also: Value::extract_pointer.
  423. m_value.encoded = tag | (reinterpret_cast<u64>(ptr) & 0x0000ffffffffffffULL);
  424. }
  425. }
  426. template<typename PointerType>
  427. PointerType* extract_pointer() const
  428. {
  429. VERIFY(is_cell());
  430. return reinterpret_cast<PointerType*>(extract_pointer_bits(m_value.encoded));
  431. }
  432. [[nodiscard]] ThrowCompletionOr<Value> invoke_internal(VM&, PropertyKey const&, Optional<MarkedVector<Value>> arguments);
  433. ThrowCompletionOr<i32> to_i32_slow_case(VM&) const;
  434. union {
  435. double as_double;
  436. struct {
  437. u64 payload : 48;
  438. u64 tag : 16;
  439. };
  440. u64 encoded;
  441. } m_value { .encoded = 0 };
  442. friend Value js_undefined();
  443. friend Value js_null();
  444. friend ThrowCompletionOr<Value> greater_than(VM&, Value lhs, Value rhs);
  445. friend ThrowCompletionOr<Value> greater_than_equals(VM&, Value lhs, Value rhs);
  446. friend ThrowCompletionOr<Value> less_than(VM&, Value lhs, Value rhs);
  447. friend ThrowCompletionOr<Value> less_than_equals(VM&, Value lhs, Value rhs);
  448. friend ThrowCompletionOr<Value> add(VM&, Value lhs, Value rhs);
  449. friend bool same_value_non_number(Value lhs, Value rhs);
  450. };
  451. inline Value js_undefined()
  452. {
  453. return Value(UNDEFINED_TAG << TAG_SHIFT, (u64)0);
  454. }
  455. inline Value js_null()
  456. {
  457. return Value(NULL_TAG << TAG_SHIFT, (u64)0);
  458. }
  459. inline Value js_nan()
  460. {
  461. return Value(NAN);
  462. }
  463. inline Value js_infinity()
  464. {
  465. return Value(INFINITY);
  466. }
  467. inline Value js_negative_infinity()
  468. {
  469. return Value(-INFINITY);
  470. }
  471. ThrowCompletionOr<Value> greater_than(VM&, Value lhs, Value rhs);
  472. ThrowCompletionOr<Value> greater_than_equals(VM&, Value lhs, Value rhs);
  473. ThrowCompletionOr<Value> less_than(VM&, Value lhs, Value rhs);
  474. ThrowCompletionOr<Value> less_than_equals(VM&, Value lhs, Value rhs);
  475. ThrowCompletionOr<Value> bitwise_and(VM&, Value lhs, Value rhs);
  476. ThrowCompletionOr<Value> bitwise_or(VM&, Value lhs, Value rhs);
  477. ThrowCompletionOr<Value> bitwise_xor(VM&, Value lhs, Value rhs);
  478. ThrowCompletionOr<Value> bitwise_not(VM&, Value);
  479. ThrowCompletionOr<Value> unary_plus(VM&, Value);
  480. ThrowCompletionOr<Value> unary_minus(VM&, Value);
  481. ThrowCompletionOr<Value> left_shift(VM&, Value lhs, Value rhs);
  482. ThrowCompletionOr<Value> right_shift(VM&, Value lhs, Value rhs);
  483. ThrowCompletionOr<Value> unsigned_right_shift(VM&, Value lhs, Value rhs);
  484. ThrowCompletionOr<Value> add(VM&, Value lhs, Value rhs);
  485. ThrowCompletionOr<Value> sub(VM&, Value lhs, Value rhs);
  486. ThrowCompletionOr<Value> mul(VM&, Value lhs, Value rhs);
  487. ThrowCompletionOr<Value> div(VM&, Value lhs, Value rhs);
  488. ThrowCompletionOr<Value> mod(VM&, Value lhs, Value rhs);
  489. ThrowCompletionOr<Value> exp(VM&, Value lhs, Value rhs);
  490. ThrowCompletionOr<Value> in(VM&, Value lhs, Value rhs);
  491. ThrowCompletionOr<Value> instance_of(VM&, Value lhs, Value rhs);
  492. ThrowCompletionOr<Value> ordinary_has_instance(VM&, Value lhs, Value rhs);
  493. ThrowCompletionOr<bool> is_loosely_equal(VM&, Value lhs, Value rhs);
  494. bool is_strictly_equal(Value lhs, Value rhs);
  495. bool same_value(Value lhs, Value rhs);
  496. bool same_value_zero(Value lhs, Value rhs);
  497. bool same_value_non_number(Value lhs, Value rhs);
  498. ThrowCompletionOr<TriState> is_less_than(VM&, Value lhs, Value rhs, bool left_first);
  499. double to_integer_or_infinity(double);
  500. enum class NumberToStringMode {
  501. WithExponent,
  502. WithoutExponent,
  503. };
  504. [[nodiscard]] String number_to_string(double, NumberToStringMode = NumberToStringMode::WithExponent);
  505. [[nodiscard]] ByteString number_to_byte_string(double, NumberToStringMode = NumberToStringMode::WithExponent);
  506. double string_to_number(StringView);
  507. inline bool Value::operator==(Value const& value) const { return same_value(*this, value); }
  508. }
  509. namespace AK {
  510. static_assert(sizeof(JS::Value) == sizeof(double));
  511. template<>
  512. class Optional<JS::Value> {
  513. template<typename U>
  514. friend class Optional;
  515. public:
  516. using ValueType = JS::Value;
  517. Optional() = default;
  518. template<SameAs<OptionalNone> V>
  519. Optional(V) { }
  520. Optional(Optional<JS::Value> const& other)
  521. {
  522. if (other.has_value())
  523. m_value = other.m_value;
  524. }
  525. Optional(Optional&& other)
  526. : m_value(other.m_value)
  527. {
  528. }
  529. template<typename U = JS::Value>
  530. requires(!IsSame<OptionalNone, RemoveCVReference<U>>)
  531. explicit(!IsConvertible<U&&, JS::Value>) Optional(U&& value)
  532. requires(!IsSame<RemoveCVReference<U>, Optional<JS::Value>> && IsConstructible<JS::Value, U &&>)
  533. : m_value(forward<U>(value))
  534. {
  535. }
  536. template<SameAs<OptionalNone> V>
  537. Optional& operator=(V)
  538. {
  539. clear();
  540. return *this;
  541. }
  542. Optional& operator=(Optional const& other)
  543. {
  544. if (this != &other) {
  545. clear();
  546. m_value = other.m_value;
  547. }
  548. return *this;
  549. }
  550. Optional& operator=(Optional&& other)
  551. {
  552. if (this != &other) {
  553. clear();
  554. m_value = other.m_value;
  555. }
  556. return *this;
  557. }
  558. template<typename O>
  559. ALWAYS_INLINE bool operator==(Optional<O> const& other) const
  560. {
  561. return has_value() == other.has_value() && (!has_value() || value() == other.value());
  562. }
  563. template<typename O>
  564. ALWAYS_INLINE bool operator==(O const& other) const
  565. {
  566. return has_value() && value() == other;
  567. }
  568. void clear()
  569. {
  570. m_value = {};
  571. }
  572. [[nodiscard]] bool has_value() const
  573. {
  574. return !m_value.is_empty();
  575. }
  576. [[nodiscard]] JS::Value& value() &
  577. {
  578. VERIFY(has_value());
  579. return m_value;
  580. }
  581. [[nodiscard]] JS::Value const& value() const&
  582. {
  583. VERIFY(has_value());
  584. return m_value;
  585. }
  586. [[nodiscard]] JS::Value value() &&
  587. {
  588. return release_value();
  589. }
  590. [[nodiscard]] JS::Value release_value()
  591. {
  592. VERIFY(has_value());
  593. JS::Value released_value = m_value;
  594. clear();
  595. return released_value;
  596. }
  597. JS::Value value_or(JS::Value const& fallback) const&
  598. {
  599. if (has_value())
  600. return value();
  601. return fallback;
  602. }
  603. [[nodiscard]] JS::Value value_or(JS::Value&& fallback) &&
  604. {
  605. if (has_value())
  606. return value();
  607. return fallback;
  608. }
  609. JS::Value const& operator*() const { return value(); }
  610. JS::Value& operator*() { return value(); }
  611. JS::Value const* operator->() const { return &value(); }
  612. JS::Value* operator->() { return &value(); }
  613. private:
  614. JS::Value m_value;
  615. };
  616. template<>
  617. struct Formatter<JS::Value> : Formatter<StringView> {
  618. ErrorOr<void> format(FormatBuilder& builder, JS::Value value)
  619. {
  620. if (value.is_empty())
  621. return Formatter<StringView>::format(builder, "<empty>"sv);
  622. return Formatter<StringView>::format(builder, value.to_string_without_side_effects());
  623. }
  624. };
  625. template<>
  626. struct Traits<JS::Value> : DefaultTraits<JS::Value> {
  627. static unsigned hash(JS::Value value) { return Traits<u64>::hash(value.encoded()); }
  628. };
  629. }