Skip to main content

rquickjs_core/
value.rs

1use crate::{qjs, Ctx, Error, Result};
2use core::{fmt, hash::Hash, mem, ops::Deref, result::Result as StdResult, str};
3
4pub mod array;
5pub mod atom;
6mod bigint;
7pub mod convert;
8pub(crate) mod exception;
9pub mod function;
10pub mod module;
11pub mod object;
12pub mod promise;
13pub mod proxy;
14mod string;
15mod symbol;
16
17pub use array::Array;
18pub use atom::Atom;
19pub use bigint::BigInt;
20pub use convert::{Coerced, FromAtom, FromIteratorJs, FromJs, IntoAtom, IntoJs, IteratorJs};
21pub use exception::Exception;
22pub use function::{Constructor, Function};
23pub use module::{Module, WriteOptions, WriteOptionsEndianness};
24pub use object::{Filter, Object};
25pub use promise::Promise;
26pub use proxy::Proxy;
27pub use string::{CString, CStringEncoding, String, Utf8, Wtf8};
28pub use symbol::Symbol;
29
30pub mod array_buffer;
31pub mod iterable;
32pub mod typed_array;
33
34pub use array_buffer::{ArrayBuffer, ArrayBufferSource};
35pub use iterable::{Iterable, IterableFn, JsIterator};
36pub use typed_array::{TypedArray, U8Clamped};
37
38/// Any JavaScript value
39pub struct Value<'js> {
40    pub(crate) ctx: Ctx<'js>,
41    pub(crate) value: qjs::JSValue,
42}
43
44impl<'js> PartialEq for Value<'js> {
45    /// Are two `Value`s identical?
46    ///
47    /// This is a very strict notion of equality that requires the two `Value`s
48    /// to refer to the same heap object or be bitwise equal (for values that
49    /// aren't stored on the heap).
50    ///
51    /// This doesn't agree with other notions of equality like
52    /// [`Value::strict_eq`]. For example, two strings may be strict-equal but
53    /// not `.eq()` if they are separate allocations with the same contents.
54    fn eq(&self, other: &Self) -> bool {
55        let tag = unsafe { qjs::JS_VALUE_GET_TAG(self.value) };
56        let tag_other = unsafe { qjs::JS_VALUE_GET_TAG(other.value) };
57
58        let bits = unsafe { qjs::JS_VALUE_GET_FLOAT64(self.value).to_bits() };
59        let bits_other = unsafe { qjs::JS_VALUE_GET_FLOAT64(other.value).to_bits() };
60
61        tag == tag_other && bits == bits_other
62    }
63}
64
65impl<'js> Eq for Value<'js> {}
66
67impl<'js> Hash for Value<'js> {
68    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
69        let tag = unsafe { qjs::JS_VALUE_GET_TAG(self.value) };
70        let bits = unsafe { qjs::JS_VALUE_GET_FLOAT64(self.value).to_bits() };
71        state.write_i32(tag);
72        state.write_u64(bits)
73    }
74}
75
76impl<'js> Clone for Value<'js> {
77    fn clone(&self) -> Self {
78        let ctx = self.ctx.clone();
79        let value = unsafe { qjs::JS_DupValue(ctx.as_ptr(), self.value) };
80        Self { ctx, value }
81    }
82}
83
84impl<'js> Drop for Value<'js> {
85    fn drop(&mut self) {
86        unsafe {
87            qjs::JS_FreeValue(self.ctx.as_ptr(), self.value);
88        }
89    }
90}
91
92impl<'js> fmt::Debug for Value<'js> {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        let type_ = self.type_of();
95        type_.fmt(f)?;
96        use Type::*;
97        match type_ {
98            Bool | Int | Float => {
99                write!(f, "(")?;
100                match type_ {
101                    Bool => unsafe { self.get_bool() }.fmt(f)?,
102                    Int => unsafe { self.get_int() }.fmt(f)?,
103                    Float => unsafe { self.get_float() }.fmt(f)?,
104                    _ => unreachable!(),
105                }
106                write!(f, ")")?;
107            }
108            String => {
109                write!(f, "(")?;
110                unsafe { self.ref_string() }.to_string().fmt(f)?;
111                write!(f, ")")?;
112            }
113            Symbol | Object | Array | Function | Constructor | Promise | Proxy => {
114                write!(f, "(")?;
115                unsafe { self.get_ptr() }.fmt(f)?;
116                write!(f, ")")?;
117            }
118            Exception => {
119                writeln!(f, "(")?;
120                self.as_exception().unwrap().fmt(f)?;
121                writeln!(f, ")")?;
122            }
123            Null => "null".fmt(f)?,
124            Undefined => "undefined".fmt(f)?,
125            Uninitialized => "uninitialized".fmt(f)?,
126            Module => "module".fmt(f)?,
127            BigInt => "BigInt".fmt(f)?,
128            Unknown => "unknown".fmt(f)?,
129        }
130        Ok(())
131    }
132}
133
134impl<'js> Value<'js> {
135    // unsafe because the value must belong the context and the lifetime must be constrained by its lifetime
136    #[inline]
137    pub(crate) unsafe fn from_js_value(ctx: Ctx<'js>, value: qjs::JSValue) -> Self {
138        Self { ctx, value }
139    }
140
141    #[inline]
142    pub(crate) unsafe fn from_js_value_const(ctx: Ctx<'js>, value: qjs::JSValueConst) -> Self {
143        let value = qjs::JS_DupValue(ctx.as_ptr(), value);
144        Self { ctx, value }
145    }
146
147    #[inline]
148    pub(crate) fn as_js_value(&self) -> qjs::JSValueConst {
149        self.value
150    }
151
152    #[inline]
153    pub(crate) fn into_js_value(self) -> qjs::JSValue {
154        let value = self.value;
155        unsafe { qjs::JS_FreeContext(self.ctx.as_ptr()) };
156        mem::forget(self);
157        value
158    }
159
160    #[inline]
161    pub fn new_uninitialized(ctx: Ctx<'js>) -> Self {
162        let value = qjs::JS_UNINITIALIZED;
163        Self { ctx, value }
164    }
165
166    #[inline]
167    pub fn new_undefined(ctx: Ctx<'js>) -> Self {
168        let value = qjs::JS_UNDEFINED;
169        Self { ctx, value }
170    }
171
172    #[inline]
173    pub fn new_null(ctx: Ctx<'js>) -> Self {
174        let value = qjs::JS_NULL;
175        Self { ctx, value }
176    }
177
178    /// Create new boolean value
179    #[inline]
180    pub fn new_bool(ctx: Ctx<'js>, value: bool) -> Self {
181        let value = if value { qjs::JS_TRUE } else { qjs::JS_FALSE };
182        Self { ctx, value }
183    }
184
185    /// Returns the Ctx object associated with this value.
186    #[inline]
187    pub fn ctx(&self) -> &Ctx<'js> {
188        &self.ctx
189    }
190
191    // unsafe because no type checking
192    #[inline]
193    pub(crate) unsafe fn get_bool(&self) -> bool {
194        qjs::JS_VALUE_GET_BOOL(self.value)
195    }
196
197    /// Try get bool from value
198    pub fn as_bool(&self) -> Option<bool> {
199        if self.is_bool() {
200            Some(unsafe { self.get_bool() })
201        } else {
202            None
203        }
204    }
205
206    /// Create new int value
207    #[inline]
208    pub fn new_int(ctx: Ctx<'js>, value: i32) -> Self {
209        let value = qjs::JS_MKVAL(qjs::JS_TAG_INT, value);
210        Self { ctx, value }
211    }
212
213    #[inline]
214    pub(crate) unsafe fn get_int(&self) -> i32 {
215        qjs::JS_VALUE_GET_INT(self.value)
216    }
217
218    /// Try get int from value
219    pub fn as_int(&self) -> Option<i32> {
220        if self.is_int() {
221            Some(unsafe { self.get_int() })
222        } else {
223            None
224        }
225    }
226
227    /// Create new float value
228    #[inline]
229    pub fn new_float(ctx: Ctx<'js>, value: f64) -> Self {
230        let value = qjs::JS_NewFloat64(value);
231        Self { ctx, value }
232    }
233
234    #[inline]
235    pub(crate) unsafe fn get_float(&self) -> f64 {
236        qjs::JS_VALUE_GET_FLOAT64(self.value)
237    }
238
239    /// Try get float from value
240    pub fn as_float(&self) -> Option<f64> {
241        if self.is_float() {
242            Some(unsafe { self.get_float() })
243        } else {
244            None
245        }
246    }
247
248    /// Create a new big int value.
249    ///
250    /// Returns an error if the underlying QuickJS allocation fails.
251    #[inline]
252    pub fn new_big_int(ctx: Ctx<'js>, value: i64) -> Result<Self> {
253        let value = unsafe { ctx.handle_exception(qjs::JS_NewBigInt64(ctx.as_ptr(), value))? };
254        Ok(Self { ctx, value })
255    }
256
257    /// Create a new number value
258    #[inline]
259    pub fn new_number(ctx: Ctx<'js>, value: f64) -> Self {
260        Self::new_float(ctx, value)
261    }
262
263    /// Try get any number from value
264    pub fn as_number(&self) -> Option<f64> {
265        if self.is_int() {
266            Some(unsafe { self.get_int() as _ })
267        } else if self.is_float() {
268            Some(unsafe { self.get_float() })
269        } else {
270            None
271        }
272    }
273
274    #[allow(unused)]
275    #[inline]
276    pub(crate) fn new_ptr(ctx: Ctx<'js>, tag: qjs::c_int, ptr: *mut qjs::c_void) -> Self {
277        let value = qjs::JS_MKPTR(tag, ptr);
278        Self { ctx, value }
279    }
280
281    #[allow(unused)]
282    #[inline]
283    pub(crate) fn new_ptr_const(ctx: Ctx<'js>, tag: qjs::c_int, ptr: *mut qjs::c_void) -> Self {
284        let value = unsafe { qjs::JS_DupValue(ctx.as_ptr(), qjs::JS_MKPTR(tag, ptr)) };
285        Self { ctx, value }
286    }
287
288    #[inline]
289    pub(crate) unsafe fn get_ptr(&self) -> *mut qjs::c_void {
290        qjs::JS_VALUE_GET_PTR(self.value)
291    }
292
293    /// Returns if the value is the JavaScript null value.
294    #[inline]
295    pub fn is_null(&self) -> bool {
296        let tag = unsafe { qjs::JS_VALUE_GET_NORM_TAG(self.value) };
297        qjs::JS_TAG_NULL == tag
298    }
299
300    /// Returns if the value is the JavaScript undefined value.
301    #[inline]
302    pub fn is_undefined(&self) -> bool {
303        let tag = unsafe { qjs::JS_VALUE_GET_NORM_TAG(self.value) };
304        qjs::JS_TAG_UNDEFINED == tag
305    }
306
307    /// Check if the value is a bool
308    #[inline]
309    pub fn is_bool(&self) -> bool {
310        qjs::JS_TAG_BOOL == unsafe { qjs::JS_VALUE_GET_TAG(self.value) }
311    }
312
313    /// Check if the value is an int
314    #[inline]
315    pub fn is_int(&self) -> bool {
316        qjs::JS_TAG_INT == unsafe { qjs::JS_VALUE_GET_TAG(self.value) }
317    }
318
319    /// Check if the value is a float
320    #[inline]
321    pub fn is_float(&self) -> bool {
322        qjs::JS_TAG_FLOAT64 == unsafe { qjs::JS_VALUE_GET_NORM_TAG(self.value) }
323    }
324
325    /// Check if the value is an any number
326    #[inline]
327    pub fn is_number(&self) -> bool {
328        let tag = unsafe { qjs::JS_VALUE_GET_NORM_TAG(self.value) };
329        qjs::JS_TAG_INT == tag || qjs::JS_TAG_FLOAT64 == tag
330    }
331
332    /// Check if the value is a string
333    #[inline]
334    pub fn is_string(&self) -> bool {
335        let tag = unsafe { qjs::JS_VALUE_GET_TAG(self.value) };
336        tag == qjs::JS_TAG_STRING || tag == qjs::JS_TAG_STRING_ROPE
337    }
338
339    /// Check if the value is a symbol
340    #[inline]
341    pub fn is_symbol(&self) -> bool {
342        qjs::JS_TAG_SYMBOL == unsafe { qjs::JS_VALUE_GET_TAG(self.value) }
343    }
344
345    /// Check if the value is an object
346    #[inline]
347    pub fn is_object(&self) -> bool {
348        qjs::JS_TAG_OBJECT == unsafe { qjs::JS_VALUE_GET_TAG(self.value) }
349    }
350
351    /// Check if the value is a module
352    #[inline]
353    pub fn is_module(&self) -> bool {
354        qjs::JS_TAG_MODULE == unsafe { qjs::JS_VALUE_GET_TAG(self.value) }
355    }
356
357    /// Check if the value is an array
358    #[inline]
359    pub fn is_array(&self) -> bool {
360        unsafe { qjs::JS_IsArray(self.value) }
361    }
362
363    /// Check if the value is a function
364    #[inline]
365    pub fn is_function(&self) -> bool {
366        unsafe { qjs::JS_IsFunction(self.ctx.as_ptr(), self.value) }
367    }
368
369    /// Check if the value is a constructor function
370    #[inline]
371    pub fn is_constructor(&self) -> bool {
372        unsafe { qjs::JS_IsConstructor(self.ctx.as_ptr(), self.value) }
373    }
374
375    /// Check if the value is a promise.
376    #[inline]
377    pub fn is_promise(&self) -> bool {
378        unsafe { qjs::JS_PromiseState(self.ctx.as_ptr(), self.value) >= 0 }
379    }
380
381    /// Check if the value is an exception
382    #[inline]
383    pub fn is_exception(&self) -> bool {
384        unsafe { qjs::JS_IsException(self.value) }
385    }
386
387    /// Check if the value is an error
388    #[inline]
389    pub fn is_error(&self) -> bool {
390        unsafe { qjs::JS_IsError(self.value) }
391    }
392
393    /// Check if the value is an uncatchable error (e.g. from an interrupt handler)
394    #[inline]
395    pub fn is_uncatchable_error(&self) -> bool {
396        unsafe { qjs::JS_IsUncatchableError(self.value) }
397    }
398
399    /// Check if the value is a BigInt
400    #[inline]
401    pub fn is_big_int(&self) -> bool {
402        unsafe { qjs::JS_IsBigInt(self.value) }
403    }
404
405    /// Check if the value is a proxy
406    #[inline]
407    pub fn is_proxy(&self) -> bool {
408        unsafe { qjs::JS_IsProxy(self.value) }
409    }
410
411    /// Reference as value
412    #[inline]
413    pub fn as_value(&self) -> &Self {
414        self
415    }
416
417    #[inline]
418    pub(crate) fn into_value(self) -> Self {
419        self
420    }
421
422    /// Convert from value to specified type
423    pub fn get<T: FromJs<'js>>(&self) -> Result<T> {
424        T::from_js(self.ctx(), self.clone())
425    }
426
427    /// Loose equality, like the `==` operator.
428    ///
429    /// Beware that this coerces its input and may therefore run arbitrary JS, and could throw exceptions.
430    pub fn loose_eq(&self, other: &Value<'js>) -> Result<bool> {
431        unsafe {
432            // N.B.: the specific `ctx` does not matter for the comparison
433            let ret = qjs::JS_IsEqual(self.ctx.as_ptr(), self.value, other.value);
434            if ret < 0 {
435                self.ctx.handle_exception(qjs::JS_EXCEPTION)?;
436            }
437            Ok(ret != 0)
438        }
439    }
440
441    /// Strict equality, like the `===` operator
442    pub fn strict_eq(&self, other: &Value<'js>) -> bool {
443        unsafe { qjs::JS_IsStrictEqual(self.ctx.as_ptr(), self.value, other.value) }
444    }
445
446    /// Like [`Value::strict_eq`], but NaNs are equal while positive/negative zero are distinguished.
447    ///
448    /// - Two NaNs are considered `same_value`, but not `strict_eq`.
449    /// - `+0` and `-0` are not considered `same_value`, but _are_ considered `strict_eq`.
450    pub fn same_value(&self, other: &Value<'js>) -> bool {
451        unsafe { qjs::JS_IsSameValue(self.ctx.as_ptr(), self.value, other.value) }
452    }
453
454    /// Like [`Value::strict_eq`], but NaNs are equal.
455    ///
456    /// - Two NaNs are considered `same_value_zero`, but not `strict_eq`.
457    /// - `+0` and `-0` are considered both `same_value_zero` and `strict_eq`.
458    pub fn same_value_zero(&self, other: &Value<'js>) -> bool {
459        unsafe { qjs::JS_IsSameValueZero(self.ctx.as_ptr(), self.value, other.value) }
460    }
461
462    /// Returns the raw C library JavaScript value.
463    pub fn as_raw(&self) -> qjs::JSValue {
464        self.value
465    }
466
467    /// Create a value from the C library JavaScript value.
468    ///
469    /// # Safety
470    /// The value cannot be from an unrelated runtime and the value must be owned.
471    /// QuickJS JavaScript values are reference counted. The drop implementation of this type
472    /// decrements the reference count so the value must have count which won't be decremented
473    /// elsewhere. Use [`qjs::JS_DupValue`] to increment the reference count of the value.
474    pub unsafe fn from_raw(ctx: Ctx<'js>, value: qjs::JSValue) -> Self {
475        Self::from_js_value(ctx, value)
476    }
477}
478
479impl<'js> AsRef<Value<'js>> for Value<'js> {
480    fn as_ref(&self) -> &Value<'js> {
481        self
482    }
483}
484
485macro_rules! type_impls {
486    // type: name => tag
487    ($($type:ident: $name:ident => $($tag:ident)|+,)*) => {
488        /// The type of JavaScript value
489        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
490        #[repr(u8)]
491        pub enum Type {
492            $($type,)*
493            Unknown
494        }
495
496        impl Type {
497            /// Returns true if the type is one of `uninitialized`, `undefined` or `null`
498            pub const fn is_void(self) -> bool {
499                use Type::*;
500                matches!(self, Uninitialized | Undefined | Null)
501            }
502
503            /// Check the type for similarity
504            pub const fn interpretable_as(self, other: Self) -> bool {
505                use Type::*;
506
507                if (self as u8) == (other as u8){
508                    return true
509                }
510                match other{
511                    Float => matches!(self, Int),
512                    Object => matches!(self, Array | Function | Constructor | Exception | Promise | Proxy),
513                    Function => matches!(self, Constructor),
514                    _ => false
515                }
516            }
517
518            /// Returns string representation of type
519            pub const fn as_str(self) -> &'static str {
520                match self {
521                    $(Type::$type => stringify!($name),)*
522                    Type::Unknown => "Unknown type",
523                }
524            }
525        }
526
527        impl AsRef<str> for Type {
528            fn as_ref(&self) -> &str {
529                self.as_str()
530            }
531        }
532
533        impl fmt::Display for Type {
534            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
535                self.as_str().fmt(f)
536            }
537        }
538
539        impl str::FromStr for Type {
540            type Err = ();
541
542            fn from_str(s: &str) -> StdResult<Self, Self::Err> {
543                Ok(match s {
544                    $(stringify!($name) => Type::$type,)*
545                    _ => return Err(()),
546                })
547            }
548        }
549
550        impl<'js> Value<'js> {
551            /// Get the type of value
552            pub fn type_of(&self) -> Type {
553                let tag = unsafe { qjs::JS_VALUE_GET_NORM_TAG(self.value) };
554                match tag {
555                    $($(qjs::$tag)|+ if type_impls!(@cond $type self) => Type::$type,)*
556                    _ => Type::Unknown,
557                }
558            }
559
560            /// Get the name of type
561            pub fn type_name(&self) -> &'static str {
562                self.type_of().as_str()
563            }
564        }
565    };
566
567    (@cond Array $self:expr) => { $self.is_array() };
568    (@cond Constructor $self:expr) => { $self.is_constructor() };
569    (@cond Function $self:expr) => { $self.is_function() };
570    (@cond Promise $self:expr) => { $self.is_promise() };
571    (@cond Exception $self:expr) => { $self.is_error() };
572    (@cond Proxy $self:expr) => { $self.is_proxy() };
573    (@cond $type:ident $self:expr) => { true };
574}
575
576type_impls! {
577    Uninitialized: uninitialized => JS_TAG_UNINITIALIZED,
578    Undefined: undefined => JS_TAG_UNDEFINED,
579    Null: null => JS_TAG_NULL,
580    Bool: bool => JS_TAG_BOOL,
581    Int: int => JS_TAG_INT,
582    Float: float => JS_TAG_FLOAT64,
583    String: string => JS_TAG_STRING | JS_TAG_STRING_ROPE,
584    Symbol: symbol => JS_TAG_SYMBOL,
585    Array: array => JS_TAG_OBJECT,
586    Constructor: constructor => JS_TAG_OBJECT,
587    Function: function => JS_TAG_OBJECT,
588    Promise: promise => JS_TAG_OBJECT,
589    Exception: exception => JS_TAG_OBJECT,
590    Proxy: proxy => JS_TAG_OBJECT,
591    Object: object => JS_TAG_OBJECT,
592    Module: module => JS_TAG_MODULE,
593    BigInt: big_int => JS_TAG_BIG_INT | JS_TAG_SHORT_BIG_INT,
594}
595
596macro_rules! sub_types {
597    ($( $head:ident$(->$sub_type:ident)* $as:ident $ref:ident $into:ident $try_into:ident $from:ident,)*) => {
598        $(
599            impl<'js> $head<'js> {
600                /// Reference to value
601                #[inline]
602                pub fn as_value(&self) -> &Value<'js> {
603                    &self.0.as_value()
604                }
605
606                /// Convert into value
607                #[inline]
608                pub fn into_value(self) -> Value<'js> {
609                    self.0.into_value()
610                }
611
612                /// Returns the underlying super type.
613                pub fn into_inner(self) -> sub_types!(@head_ty $($sub_type),*) {
614                    self.0
615                }
616                /// Returns a reference to the underlying super type.
617                pub fn as_inner(&self) -> & sub_types!(@head_ty $($sub_type),*) {
618                    &self.0
619                }
620
621                /// Returns the [`Ctx`] object associated with this value
622                pub fn ctx(&self) -> &Ctx<'js>{
623                    self.0.ctx()
624                }
625
626                /// Convert from value
627                pub fn from_value(value: Value<'js>) -> Result<Self> {
628                    let type_ = value.type_of();
629                    if type_.interpretable_as(Type::$head) {
630                        Ok(sub_types!(@wrap $head$(->$sub_type)*  value))
631                    } else {
632                        Err(Error::new_from_js(type_.as_str(), Type::$head.as_str()))
633                    }
634                }
635
636                #[allow(unused)]
637                pub(crate) unsafe fn from_js_value_const(ctx: Ctx<'js>, value: qjs::JSValueConst) -> Self {
638                    let v = Value::from_js_value_const(ctx, value);
639                    debug_assert!(v.$as().is_some(),"tried to cource js value {:?} to the wrong type `{}`, this is a rquickjs bug",v, stringify!($head));
640                    sub_types!(@wrap $head$(->$sub_type)*  v)
641                }
642
643                #[allow(unused)]
644                pub(crate) unsafe fn from_js_value(ctx: Ctx<'js>, value: qjs::JSValue) -> Self {
645                    let v = Value::from_js_value(ctx, value);
646                    debug_assert!(v.$as().is_some(),"tried to cource js value {:?} to the wrong type `{}`, this is a rquickjs bug",v, stringify!($head));
647                    sub_types!(@wrap $head$(->$sub_type)*  v)
648                }
649
650                #[allow(unused)]
651                pub(crate) fn into_js_value(self) -> qjs::JSValue{
652                    self.0.into_js_value()
653                }
654
655                #[allow(unused)]
656                pub(crate) fn as_js_value(&self) -> qjs::JSValueConst{
657                    self.0.as_js_value()
658                }
659            }
660
661            impl<'js> Deref for $head<'js> {
662                type Target = sub_types!(@head_ty $($sub_type),*);
663
664                fn deref(&self) -> &Self::Target {
665                    &self.0
666                }
667            }
668
669            sub_types!(@imp_as_ref $head$(,$sub_type)*);
670
671            impl<'js> Value<'js> {
672                #[doc = concat!("Interpret as [`",stringify!($head),"`]")]
673                ///
674                /// # Safety
675                /// You should be sure that the value already is of required type before to do it.
676                #[inline]
677                pub unsafe fn $ref(&self) -> &$head<'js> {
678                    &*(self as *const _ as *const $head)
679                }
680
681                #[doc = concat!("Try reinterpret as [`",stringify!($head),"`]")]
682                pub fn $as(&self) -> Option<&$head<'js>> {
683                    if self.type_of().interpretable_as(Type::$head) {
684                        Some(unsafe { self.$ref() })
685                    } else {
686                        None
687                    }
688                }
689
690                #[doc = concat!("Try convert into [`",stringify!($head),"`]")]
691                pub fn $into(self) -> Option<$head<'js>> {
692                    if self.type_of().interpretable_as(Type::$head) {
693                        Some(sub_types!(@wrap $head$(->$sub_type)* self))
694                    } else {
695                        None
696                    }
697                }
698
699                #[doc = concat!("Try convert into [`",stringify!($head),"`] returning self if the conversion fails.")]
700                pub fn $try_into(self) -> core::result::Result<$head<'js>, Value<'js>> {
701                    if self.type_of().interpretable_as(Type::$head) {
702                        Ok(sub_types!(@wrap $head$(->$sub_type)* self))
703                    } else {
704                        Err(self)
705                    }
706                }
707
708                #[doc = concat!("Convert from [`",stringify!($head),"`]")]
709                pub fn $from(value: $head<'js>) -> Self {
710                    value.into_value()
711                }
712            }
713
714            impl<'js> From<$head<'js>> for Value<'js> {
715                fn from(value: $head<'js>) -> Self {
716                    value.into_value()
717                }
718            }
719
720            impl<'js> FromJs<'js> for $head<'js> {
721                fn from_js(_: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
722                    Self::from_value(value)
723                }
724            }
725
726            impl<'js> IntoJs<'js> for $head<'js> {
727                fn into_js(self, _ctx: &Ctx<'js>) -> Result<Value<'js>> {
728                    Ok(self.into_value())
729                }
730            }
731
732            impl<'js> IntoAtom<'js> for $head<'js>{
733                fn into_atom(self, ctx: &Ctx<'js>) -> Result<Atom<'js>> {
734                    Atom::from_value(ctx.clone(), &self.into_value())
735                }
736            }
737        )*
738    };
739
740    (@type $type:ident) => { $type<'js> };
741
742    (@head $head:ident $(rem:ident)*)  => { $head };
743    (@head_ty $head:ident$(,$rem:ident)*)  => { $head<'js> };
744
745    (@wrap $type:ident$(->$rem:ident)+ $val:expr) => { $type(sub_types!(@wrap $($rem)->* $val)) };
746    (@wrap Value $val:expr) => { $val };
747
748    /*
749    (@into_inner $head:ident->$inner:ident$(->$rem:ident)*) => {
750        impl<'js> $head<'js>{
751            pub fn into_inner($
752        }
753    }*/
754
755    (@imp_as_ref $type:ident,Value) => {
756        impl<'js> AsRef<Value<'js>> for $type<'js> {
757            fn as_ref(&self) -> &Value<'js> {
758                &self.0
759            }
760        }
761    };
762    (@imp_as_ref $type:ident,$inner:ident$(,$rem:ident)*) => {
763        impl<'js> AsRef<$inner<'js>> for $type<'js> {
764            fn as_ref(&self) -> &$inner<'js> {
765                &self.0
766            }
767        }
768
769        impl<'js> AsRef<Value<'js>> for $type<'js> {
770            fn as_ref(&self) -> &Value<'js> {
771                self.0.as_ref()
772            }
773        }
774    };
775}
776
777sub_types! {
778    String->Value as_string ref_string into_string try_into_string from_string,
779    Symbol->Value as_symbol ref_symbol into_symbol try_into_symbol from_symbol,
780    Object->Value as_object ref_object into_object try_into_object from_object,
781    Function->Object->Value as_function ref_function into_function try_into_function from_function,
782    Constructor->Function->Object->Value as_constructor ref_constructor into_constructor try_into_constructor from_constructor,
783    Promise->Object->Value as_promise ref_promise into_promise try_into_promise from_promise,
784    Array->Object->Value as_array ref_array into_array try_into_array from_array,
785    Exception->Object->Value as_exception ref_exception into_exception try_into_exception from_exception,
786    BigInt->Value as_big_int ref_big_int into_big_int try_into_big_int from_big_int,
787    Proxy->Object->Value as_proxy ref_proxy into_proxy try_into_proxy from_proxy,
788}
789
790macro_rules! void_types {
791    ($($(#[$meta:meta])* $type:ident $new:ident;)*) => {
792        $(
793            $(#[$meta])*
794            #[derive(Debug, Copy, Clone, PartialEq, Eq)]
795            #[allow(dead_code)]
796            pub struct $type;
797
798            #[allow(dead_code)]
799            impl $type {
800                /// Convert into value
801                pub fn into_value<'js>(self, ctx: Ctx<'js>) -> Value<'js> {
802                    Value::$new(ctx)
803                }
804
805                /// Convert from value
806                pub fn from_value<'js>(value: Value<'js>) -> Result<Self> {
807                    if value.type_of() == Type::$type {
808                        Ok(Self)
809                    } else {
810                        Err(Error::new_from_js("value", Type::$type.as_str()))
811                    }
812                }
813            }
814
815            impl<'js> FromJs<'js> for $type {
816                fn from_js(_: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
817                    Self::from_value(value)
818                }
819            }
820
821            impl<'js> IntoJs<'js> for $type {
822                fn into_js(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
823                    Ok(self.into_value(ctx.clone()))
824                }
825            }
826        )*
827    };
828}
829
830void_types! {
831    /// The placeholder which treated as uninitialized JS value
832    Uninitialized new_uninitialized;
833
834    /// The placeholder which treated as `undefined` value
835    Undefined new_undefined;
836
837    /// The placeholder which treated as `null` value
838    Null new_null;
839}
840
841#[cfg(test)]
842mod test {
843    use crate::*;
844
845    #[test]
846    fn equality() {
847        test_with(|ctx| {
848            // Expected results: loose, strict, SameValue, SameValueZero.
849            for (source, expected) in [
850                ("[1, '1']", [true, false, false, false]),
851                ("[1, 2]", [false; 4]),
852                ("[null, undefined]", [true, false, false, false]),
853                ("[NaN, NaN]", [false, false, true, true]),
854                ("[0, -0]", [true, true, false, true]),
855                ("['abc', ['a', 'b', 'c'].join('')]", [true; 4]),
856                ("['abc', 'def']", [false; 4]),
857                ("[1n, 1]", [true, false, false, false]),
858                ("[12345678901234567890n, 12345678901234567890n]", [true; 4]),
859                ("[{}, {}]", [false; 4]),
860                ("(() => { const x = {}; return [x, x]; })()", [true; 4]),
861                ("[Symbol('x'), Symbol('x')]", [false; 4]),
862                ("[Symbol.for('x'), Symbol.for('x')]", [true; 4]),
863                (
864                    "[{ valueOf() { return 1; } }, 1]",
865                    [true, false, false, false],
866                ),
867            ] {
868                let pair: Array = ctx.eval(source).unwrap();
869                let a: Value = pair.get(0).unwrap();
870                let b: Value = pair.get(1).unwrap();
871                for (a, b) in [(&a, &b), (&b, &a)] {
872                    assert_eq!(
873                        [
874                            a.loose_eq(b).unwrap(),
875                            a.strict_eq(b),
876                            a.same_value(b),
877                            a.same_value_zero(b),
878                        ],
879                        expected,
880                        "{source}",
881                    );
882                }
883            }
884        });
885    }
886
887    #[test]
888    fn equality_errors() {
889        test_with(|ctx| {
890            for (source, thrown) in [
891                ("({ valueOf() { throw 42; } })", Some(42)),
892                ("({ [Symbol.toPrimitive]() { throw 42; } })", Some(42)),
893                ("({ [Symbol.toPrimitive]() { return {}; } })", None),
894            ] {
895                let object: Value = ctx.eval(source).unwrap();
896                let number = Value::new_int(ctx.clone(), 1);
897                for (a, b) in [(&object, &number), (&number, &object)] {
898                    // These comparisons don't coerce and are infallible.
899                    assert!(!a.strict_eq(b));
900                    assert!(!a.same_value(b));
901                    assert!(!a.same_value_zero(b));
902                    assert!(matches!(a.loose_eq(b), Err(Error::Exception)));
903                    let exception = ctx.catch();
904                    if let Some(thrown) = thrown {
905                        assert_eq!(exception.as_int(), Some(thrown));
906                    } else {
907                        let name: StdString = exception.as_object().unwrap().get("name").unwrap();
908                        assert_eq!(name, "TypeError");
909                    }
910                }
911            }
912        });
913    }
914
915    #[test]
916    fn new_number_keeps_negative_zero() {
917        test_with(|ctx| {
918            let neg_zero: Value = ctx.eval("-0").unwrap();
919            assert!(Value::new_number(ctx, -0.0).same_value(&neg_zero));
920        });
921    }
922
923    #[test]
924    fn type_matches() {
925        assert!(Type::Bool.interpretable_as(Type::Bool));
926
927        assert!(Type::Object.interpretable_as(Type::Object));
928        assert!(Type::Array.interpretable_as(Type::Object));
929        assert!(Type::Function.interpretable_as(Type::Object));
930
931        assert!(!Type::Object.interpretable_as(Type::Array));
932        assert!(!Type::Object.interpretable_as(Type::Function));
933
934        assert!(!Type::Bool.interpretable_as(Type::Int));
935    }
936
937    #[test]
938    fn big_int() {
939        test_with(|ctx| {
940            let val: Value = ctx.eval(r#"1n"#).unwrap();
941            assert_eq!(val.type_of(), Type::BigInt);
942            let val: Value = ctx.eval(r#"999999999999999999999n"#).unwrap();
943            assert_eq!(val.type_of(), Type::BigInt);
944            let val = Value::new_big_int(ctx.clone(), 1245).unwrap();
945            assert_eq!(val.type_of(), Type::BigInt);
946            let val = Value::new_big_int(ctx, 9999999999999999).unwrap();
947            assert_eq!(val.type_of(), Type::BigInt);
948        });
949    }
950
951    // Regression for https://github.com/DelSkayn/rquickjs/issues/585:
952    // `Value::new_big_int` must surface QuickJS allocation failures as
953    // `Err(Error::Exception)` rather than returning a `Value` that wraps a
954    // `JS_EXCEPTION` sentinel.
955    #[test]
956    fn big_int_oom_is_reported() {
957        let rt = crate::Runtime::new().unwrap();
958        let ctx = crate::Context::full(&rt).unwrap();
959        // Shrink the memory allowance *after* the context has been built so
960        // that the context itself can allocate, but new heap allocations
961        // like the one inside `JS_NewBigInt64` will fail.
962        rt.set_memory_limit(0x1000);
963        ctx.with(|ctx| {
964            // A value outside the short big-int range forces a heap
965            // allocation inside QuickJS, which will fail under the tiny
966            // memory limit set above.
967            let err = Value::new_big_int(ctx.clone(), i64::MAX)
968                .expect_err("expected allocation failure to be reported");
969            assert!(matches!(err, Error::Exception));
970        });
971    }
972}