Value.h 24 KB

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