Skip to main content

wasmtime/runtime/
values.rs

1use crate::store::{AutoAssertNoGc, StoreOpaque};
2use crate::{
3    AnyRef, ArrayRef, AsContext, AsContextMut, ExnRef, ExternRef, Func, HeapTopType, HeapType,
4    RefType, Rooted, StructRef, V128, ValType, prelude::*,
5};
6use core::ptr;
7
8pub use crate::runtime::vm::ValRaw;
9
10/// A stub implementation for continuation references.
11///
12/// This is a placeholder until continuation objects are fully integrated
13/// with the GC system (see #10248).
14#[derive(Debug, Clone, Copy)]
15pub struct ContRef;
16
17/// Possible runtime values that a WebAssembly module can either consume or
18/// produce.
19///
20/// Note that we inline the `enum Ref { ... }` variants into `enum Val { ... }`
21/// here as a size optimization.
22#[derive(Debug, Clone, Copy)]
23pub enum Val {
24    // NB: the ordering here is intended to match the ordering in
25    // `ValType` to improve codegen when learning the type of a value.
26    //
27    /// A 32-bit integer.
28    I32(i32),
29
30    /// A 64-bit integer.
31    I64(i64),
32
33    /// A 32-bit float.
34    ///
35    /// Note that the raw bits of the float are stored here, and you can use
36    /// `f32::from_bits` to create an `f32` value.
37    F32(u32),
38
39    /// A 64-bit float.
40    ///
41    /// Note that the raw bits of the float are stored here, and you can use
42    /// `f64::from_bits` to create an `f64` value.
43    F64(u64),
44
45    /// A 128-bit number.
46    V128(V128),
47
48    /// A function reference.
49    FuncRef(Option<Func>),
50
51    /// An external reference.
52    ExternRef(Option<Rooted<ExternRef>>),
53
54    /// An internal reference.
55    AnyRef(Option<Rooted<AnyRef>>),
56
57    /// An exception reference.
58    ExnRef(Option<Rooted<ExnRef>>),
59
60    /// A continuation reference.
61    ///
62    /// Note: This is currently a stub implementation as continuation objects
63    /// are not yet fully integrated with the GC system. See #10248.
64    ContRef(Option<ContRef>),
65}
66
67macro_rules! accessors {
68    ($bind:ident $(($variant:ident($ty:ty) $get:ident $unwrap:ident $cvt:expr))*) => ($(
69        /// Attempt to access the underlying value of this `Val`, returning
70        /// `None` if it is not the correct type.
71        #[inline]
72        pub fn $get(&self) -> Option<$ty> {
73            if let Val::$variant($bind) = self {
74                Some($cvt)
75            } else {
76                None
77            }
78        }
79
80        /// Returns the underlying value of this `Val`, panicking if it's the
81        /// wrong type.
82        ///
83        /// # Panics
84        ///
85        /// Panics if `self` is not of the right type.
86        #[inline]
87        pub fn $unwrap(&self) -> $ty {
88            self.$get().expect(concat!("expected ", stringify!($ty)))
89        }
90    )*)
91}
92
93impl Val {
94    /// Returns the null reference for the given heap type.
95    #[inline]
96    pub fn null_ref(heap_type: &HeapType) -> Val {
97        Ref::null(&heap_type).into()
98    }
99
100    /// Returns the null function reference value.
101    ///
102    /// The return value has type `(ref null nofunc)` aka `nullfuncref` and is a
103    /// subtype of all function references.
104    #[inline]
105    pub const fn null_func_ref() -> Val {
106        Val::FuncRef(None)
107    }
108
109    /// Returns the null external reference value.
110    ///
111    /// The return value has type `(ref null noextern)` aka `nullexternref` and
112    /// is a subtype of all external references.
113    #[inline]
114    pub const fn null_extern_ref() -> Val {
115        Val::ExternRef(None)
116    }
117
118    /// Returns the null internal reference value.
119    ///
120    /// The return value has type `(ref null none)` aka `nullref` and is a
121    /// subtype of all internal references.
122    #[inline]
123    pub const fn null_any_ref() -> Val {
124        Val::AnyRef(None)
125    }
126
127    /// Returns the default value for the given type, if any exists.
128    ///
129    /// Returns `None` if there is no default value for the given type (for
130    /// example, non-nullable reference types do not have a default value).
131    pub fn default_for_ty(ty: &ValType) -> Option<Val> {
132        match ty {
133            ValType::I32 => Some(Val::I32(0)),
134            ValType::I64 => Some(Val::I64(0)),
135            ValType::F32 => Some(Val::F32(0)),
136            ValType::F64 => Some(Val::F64(0)),
137            ValType::V128 => Some(Val::V128(V128::from(0))),
138            ValType::Ref(ref_ty) => {
139                if ref_ty.is_nullable() {
140                    Some(Val::null_ref(ref_ty.heap_type()))
141                } else {
142                    None
143                }
144            }
145        }
146    }
147
148    /// Returns the corresponding [`ValType`] for this `Val`.
149    ///
150    /// # Errors
151    ///
152    /// Returns an error if this value is a GC reference that has since been
153    /// unrooted.
154    ///
155    /// # Panics
156    ///
157    /// Panics if this value is associated with a different store.
158    #[inline]
159    pub fn ty(&self, store: impl AsContext) -> Result<ValType> {
160        self.load_ty(&store.as_context().0)
161    }
162
163    #[inline]
164    pub(crate) fn load_ty(&self, store: &StoreOpaque) -> Result<ValType> {
165        Ok(match self {
166            Val::I32(_) => ValType::I32,
167            Val::I64(_) => ValType::I64,
168            Val::F32(_) => ValType::F32,
169            Val::F64(_) => ValType::F64,
170            Val::V128(_) => ValType::V128,
171            Val::ExternRef(Some(e)) => {
172                e.try_gc_ref(store)?;
173                ValType::Ref(RefType::new(false, HeapType::Extern))
174            }
175            Val::ExternRef(None) => ValType::NULLEXTERNREF,
176            Val::FuncRef(None) => ValType::NULLFUNCREF,
177            Val::FuncRef(Some(f)) => ValType::Ref(RefType::new(
178                false,
179                HeapType::ConcreteFunc(f.load_ty(store)),
180            )),
181            Val::AnyRef(None) => ValType::NULLREF,
182            Val::AnyRef(Some(a)) => ValType::Ref(RefType::new(false, a._ty(store)?)),
183            Val::ExnRef(None) => ValType::NULLEXNREF,
184            Val::ExnRef(Some(e)) => {
185                e.try_gc_ref(store)?;
186                ValType::Ref(RefType::new(false, HeapType::Exn))
187            }
188            Val::ContRef(_) => {
189                // TODO(#10248): Return proper continuation reference type when available
190                return Err(crate::format_err!(
191                    "continuation references not yet supported in embedder API"
192                ));
193            }
194        })
195    }
196
197    /// Does this value match the given type?
198    ///
199    /// Returns an error is an underlying `Rooted` has been unrooted.
200    ///
201    /// # Panics
202    ///
203    /// Panics if this value is not associated with the given store.
204    pub fn matches_ty(&self, store: impl AsContext, ty: &ValType) -> Result<bool> {
205        self._matches_ty(&store.as_context().0, ty)
206    }
207
208    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &ValType) -> Result<bool> {
209        assert!(self.comes_from_same_store(store));
210        assert!(ty.comes_from_same_engine(store.engine()));
211        Ok(match (self, ty) {
212            (Val::I32(_), ValType::I32)
213            | (Val::I64(_), ValType::I64)
214            | (Val::F32(_), ValType::F32)
215            | (Val::F64(_), ValType::F64)
216            | (Val::V128(_), ValType::V128) => true,
217
218            (Val::FuncRef(f), ValType::Ref(ref_ty)) => Ref::from(*f)._matches_ty(store, ref_ty)?,
219            (Val::ExternRef(e), ValType::Ref(ref_ty)) => {
220                Ref::from(*e)._matches_ty(store, ref_ty)?
221            }
222            (Val::AnyRef(a), ValType::Ref(ref_ty)) => Ref::from(*a)._matches_ty(store, ref_ty)?,
223            (Val::ExnRef(e), ValType::Ref(ref_ty)) => Ref::from(*e)._matches_ty(store, ref_ty)?,
224
225            (Val::I32(_), _)
226            | (Val::I64(_), _)
227            | (Val::F32(_), _)
228            | (Val::F64(_), _)
229            | (Val::V128(_), _)
230            | (Val::FuncRef(_), _)
231            | (Val::ExternRef(_), _)
232            | (Val::AnyRef(_), _)
233            | (Val::ExnRef(_), _)
234            | (Val::ContRef(_), _) => false,
235        })
236    }
237
238    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &ValType) -> Result<()> {
239        if !self.comes_from_same_store(store) {
240            bail!("value used with wrong store")
241        }
242        if !ty.comes_from_same_engine(store.engine()) {
243            bail!("type used with wrong engine")
244        }
245        if self._matches_ty(store, ty)? {
246            Ok(())
247        } else {
248            let actual_ty = self.load_ty(store)?;
249            bail!("type mismatch: expected {ty}, found {actual_ty}")
250        }
251    }
252
253    /// Convenience method to convert this [`Val`] into a [`ValRaw`].
254    ///
255    /// Returns an error if this value is a GC reference and the GC reference
256    /// has been unrooted.
257    ///
258    /// # Safety
259    ///
260    /// The returned [`ValRaw`] does not carry type information and is only safe
261    /// to use within the context of this store itself. For more information see
262    /// [`ExternRef::to_raw`] and [`Func::to_raw`].
263    pub fn to_raw(&self, mut store: impl AsContextMut) -> Result<ValRaw> {
264        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
265        self.to_raw_(&mut store)
266    }
267
268    pub(crate) fn to_raw_(&self, store: &mut AutoAssertNoGc) -> Result<ValRaw> {
269        match self {
270            Val::I32(i) => Ok(ValRaw::i32(*i)),
271            Val::I64(i) => Ok(ValRaw::i64(*i)),
272            Val::F32(u) => Ok(ValRaw::f32(*u)),
273            Val::F64(u) => Ok(ValRaw::f64(*u)),
274            Val::V128(b) => Ok(ValRaw::v128(b.as_u128())),
275            Val::ExternRef(e) => Ok(ValRaw::externref(match e {
276                None => 0,
277                Some(e) => e._to_raw(store)?,
278            })),
279            Val::AnyRef(e) => Ok(ValRaw::anyref(match e {
280                None => 0,
281                Some(e) => e._to_raw(store)?,
282            })),
283            Val::ExnRef(e) => Ok(ValRaw::exnref(match e {
284                None => 0,
285                Some(e) => e._to_raw(store)?,
286            })),
287            Val::FuncRef(f) => Ok(ValRaw::funcref(match f {
288                Some(f) => f.to_raw_(store),
289                None => ptr::null_mut(),
290            })),
291            Val::ContRef(_) => {
292                // TODO(#10248): Implement proper continuation reference to_raw conversion
293                Err(crate::format_err!(
294                    "continuation references not yet supported in to_raw conversion"
295                ))
296            }
297        }
298    }
299
300    /// Convenience method to convert a [`ValRaw`] into a [`Val`].
301    ///
302    /// # Unsafety
303    ///
304    /// This method is unsafe for the reasons that [`ExternRef::from_raw`] and
305    /// [`Func::from_raw`] are unsafe. Additionally there's no guarantee
306    /// otherwise that `raw` should have the type `ty` specified.
307    pub unsafe fn from_raw(mut store: impl AsContextMut, raw: ValRaw, ty: ValType) -> Val {
308        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
309        // SAFETY: `_from_raw` has the same contract as this function.
310        unsafe { Self::_from_raw(&mut store, raw, &ty) }
311    }
312
313    /// Same as [`Self::from_raw`], but with a monomorphic store.
314    pub(crate) unsafe fn _from_raw(
315        store: &mut AutoAssertNoGc<'_>,
316        raw: ValRaw,
317        ty: &ValType,
318    ) -> Val {
319        match ty {
320            ValType::I32 => Val::I32(raw.get_i32()),
321            ValType::I64 => Val::I64(raw.get_i64()),
322            ValType::F32 => Val::F32(raw.get_f32()),
323            ValType::F64 => Val::F64(raw.get_f64()),
324            ValType::V128 => Val::V128(raw.get_v128().into()),
325            ValType::Ref(ref_ty) => {
326                let ref_ = match ref_ty.heap_type() {
327                    // SAFETY: it's a safety contract of this function that the
328                    // funcref is valid and owned by the provided store.
329                    HeapType::Func | HeapType::ConcreteFunc(_) => unsafe {
330                        Func::_from_raw(store, raw.get_funcref()).into()
331                    },
332
333                    HeapType::NoFunc => Ref::Func(None),
334
335                    HeapType::NoCont | HeapType::ConcreteCont(_) | HeapType::Cont => {
336                        // TODO(#10248): Required to support stack switching in the embedder API.
337                        unimplemented!()
338                    }
339
340                    HeapType::Extern => ExternRef::_from_raw(store, raw.get_externref()).into(),
341
342                    HeapType::NoExtern => Ref::Extern(None),
343
344                    HeapType::Any
345                    | HeapType::Eq
346                    | HeapType::I31
347                    | HeapType::Array
348                    | HeapType::ConcreteArray(_)
349                    | HeapType::Struct
350                    | HeapType::ConcreteStruct(_) => {
351                        AnyRef::_from_raw(store, raw.get_anyref()).into()
352                    }
353
354                    HeapType::Exn => ExnRef::_from_raw(store, raw.get_exnref()).into(),
355                    HeapType::NoExn => Ref::Exn(None),
356
357                    HeapType::None => Ref::Any(None),
358                };
359                assert!(
360                    ref_ty.is_nullable() || !ref_.is_null(),
361                    "if the type is not nullable, we shouldn't get null; got \
362                     type = {ref_ty}, ref = {ref_:?}"
363                );
364                ref_.into()
365            }
366        }
367    }
368
369    accessors! {
370        e
371        (I32(i32) i32 unwrap_i32 *e)
372        (I64(i64) i64 unwrap_i64 *e)
373        (F32(f32) f32 unwrap_f32 f32::from_bits(*e))
374        (F64(f64) f64 unwrap_f64 f64::from_bits(*e))
375        (FuncRef(Option<&Func>) func_ref unwrap_func_ref e.as_ref())
376        (ExternRef(Option<&Rooted<ExternRef>>) extern_ref unwrap_extern_ref e.as_ref())
377        (AnyRef(Option<&Rooted<AnyRef>>) any_ref unwrap_any_ref e.as_ref())
378        (V128(V128) v128 unwrap_v128 *e)
379    }
380
381    /// Get this value's underlying reference, if any.
382    #[inline]
383    pub fn ref_(self) -> Option<Ref> {
384        match self {
385            Val::FuncRef(f) => Some(Ref::Func(f)),
386            Val::ExternRef(e) => Some(Ref::Extern(e)),
387            Val::AnyRef(a) => Some(Ref::Any(a)),
388            Val::ExnRef(e) => Some(Ref::Exn(e)),
389            Val::I32(_) | Val::I64(_) | Val::F32(_) | Val::F64(_) | Val::V128(_) => None,
390            Val::ContRef(_) => None, // TODO(#10248): Return proper Ref::Cont when available
391        }
392    }
393
394    /// Attempt to access the underlying `externref` value of this `Val`.
395    ///
396    /// If this is not an `externref`, then `None` is returned.
397    ///
398    /// If this is a null `externref`, then `Some(None)` is returned.
399    ///
400    /// If this is a non-null `externref`, then `Some(Some(..))` is returned.
401    #[inline]
402    pub fn externref(&self) -> Option<Option<&Rooted<ExternRef>>> {
403        match self {
404            Val::ExternRef(None) => Some(None),
405            Val::ExternRef(Some(e)) => Some(Some(e)),
406            _ => None,
407        }
408    }
409
410    /// Returns the underlying `externref` value of this `Val`, panicking if it's the
411    /// wrong type.
412    ///
413    /// If this is a null `externref`, then `None` is returned.
414    ///
415    /// If this is a non-null `externref`, then `Some(..)` is returned.
416    ///
417    /// # Panics
418    ///
419    /// Panics if `self` is not a (nullable) `externref`.
420    #[inline]
421    pub fn unwrap_externref(&self) -> Option<&Rooted<ExternRef>> {
422        self.externref().expect("expected externref")
423    }
424
425    /// Attempt to access the underlying `anyref` value of this `Val`.
426    ///
427    /// If this is not an `anyref`, then `None` is returned.
428    ///
429    /// If this is a null `anyref`, then `Some(None)` is returned.
430    ///
431    /// If this is a non-null `anyref`, then `Some(Some(..))` is returned.
432    #[inline]
433    pub fn anyref(&self) -> Option<Option<&Rooted<AnyRef>>> {
434        match self {
435            Val::AnyRef(None) => Some(None),
436            Val::AnyRef(Some(e)) => Some(Some(e)),
437            _ => None,
438        }
439    }
440
441    /// Returns the underlying `anyref` value of this `Val`, panicking if it's the
442    /// wrong type.
443    ///
444    /// If this is a null `anyref`, then `None` is returned.
445    ///
446    /// If this is a non-null `anyref`, then `Some(..)` is returned.
447    ///
448    /// # Panics
449    ///
450    /// Panics if `self` is not a (nullable) `anyref`.
451    #[inline]
452    pub fn unwrap_anyref(&self) -> Option<&Rooted<AnyRef>> {
453        self.anyref().expect("expected anyref")
454    }
455
456    /// Attempt to access the underlying `exnref` value of this `Val`.
457    ///
458    /// If this is not an `exnref`, then `None` is returned.
459    ///
460    /// If this is a null `exnref`, then `Some(None)` is returned.
461    ///
462    /// If this is a non-null `exnref`, then `Some(Some(..))` is returned.
463    #[inline]
464    pub fn exnref(&self) -> Option<Option<&Rooted<ExnRef>>> {
465        match self {
466            Val::ExnRef(None) => Some(None),
467            Val::ExnRef(Some(e)) => Some(Some(e)),
468            _ => None,
469        }
470    }
471
472    /// Returns the underlying `exnref` value of this `Val`, panicking if it's the
473    /// wrong type.
474    ///
475    /// If this is a null `exnref`, then `None` is returned.
476    ///
477    /// If this is a non-null `exnref`, then `Some(..)` is returned.
478    ///
479    /// # Panics
480    ///
481    /// Panics if `self` is not a (nullable) `exnref`.
482    #[inline]
483    pub fn unwrap_exnref(&self) -> Option<&Rooted<ExnRef>> {
484        self.exnref().expect("expected exnref")
485    }
486
487    /// Attempt to access the underlying `funcref` value of this `Val`.
488    ///
489    /// If this is not an `funcref`, then `None` is returned.
490    ///
491    /// If this is a null `funcref`, then `Some(None)` is returned.
492    ///
493    /// If this is a non-null `funcref`, then `Some(Some(..))` is returned.
494    #[inline]
495    pub fn funcref(&self) -> Option<Option<&Func>> {
496        match self {
497            Val::FuncRef(None) => Some(None),
498            Val::FuncRef(Some(f)) => Some(Some(f)),
499            _ => None,
500        }
501    }
502
503    /// Returns the underlying `funcref` value of this `Val`, panicking if it's the
504    /// wrong type.
505    ///
506    /// If this is a null `funcref`, then `None` is returned.
507    ///
508    /// If this is a non-null `funcref`, then `Some(..)` is returned.
509    ///
510    /// # Panics
511    ///
512    /// Panics if `self` is not a (nullable) `funcref`.
513    #[inline]
514    pub fn unwrap_funcref(&self) -> Option<&Func> {
515        self.funcref().expect("expected funcref")
516    }
517
518    #[inline]
519    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
520        match self {
521            Val::FuncRef(Some(f)) => f.comes_from_same_store(store),
522            Val::FuncRef(None) => true,
523
524            Val::ExternRef(Some(x)) => x.comes_from_same_store(store),
525            Val::ExternRef(None) => true,
526
527            Val::AnyRef(Some(a)) => a.comes_from_same_store(store),
528            Val::AnyRef(None) => true,
529
530            Val::ExnRef(Some(e)) => e.comes_from_same_store(store),
531            Val::ExnRef(None) => true,
532
533            // Integers, floats, and vectors have no association with any
534            // particular store, so they're always considered as "yes I came
535            // from that store",
536            Val::I32(_) | Val::I64(_) | Val::F32(_) | Val::F64(_) | Val::V128(_) => true,
537
538            // Continuation references are not yet associated with stores
539            Val::ContRef(_) => true, // TODO(#10248): Proper store association when implemented
540        }
541    }
542}
543
544impl From<i32> for Val {
545    #[inline]
546    fn from(val: i32) -> Val {
547        Val::I32(val)
548    }
549}
550
551impl From<i64> for Val {
552    #[inline]
553    fn from(val: i64) -> Val {
554        Val::I64(val)
555    }
556}
557
558impl From<f32> for Val {
559    #[inline]
560    fn from(val: f32) -> Val {
561        Val::F32(val.to_bits())
562    }
563}
564
565impl From<f64> for Val {
566    #[inline]
567    fn from(val: f64) -> Val {
568        Val::F64(val.to_bits())
569    }
570}
571
572impl From<Ref> for Val {
573    #[inline]
574    fn from(val: Ref) -> Val {
575        match val {
576            Ref::Extern(e) => Val::ExternRef(e),
577            Ref::Func(f) => Val::FuncRef(f),
578            Ref::Any(a) => Val::AnyRef(a),
579            Ref::Exn(e) => Val::ExnRef(e),
580        }
581    }
582}
583
584impl From<Rooted<ExternRef>> for Val {
585    #[inline]
586    fn from(val: Rooted<ExternRef>) -> Val {
587        Val::ExternRef(Some(val))
588    }
589}
590
591impl From<Option<Rooted<ExternRef>>> for Val {
592    #[inline]
593    fn from(val: Option<Rooted<ExternRef>>) -> Val {
594        Val::ExternRef(val)
595    }
596}
597
598impl From<Rooted<AnyRef>> for Val {
599    #[inline]
600    fn from(val: Rooted<AnyRef>) -> Val {
601        Val::AnyRef(Some(val))
602    }
603}
604
605impl From<Option<Rooted<AnyRef>>> for Val {
606    #[inline]
607    fn from(val: Option<Rooted<AnyRef>>) -> Val {
608        Val::AnyRef(val)
609    }
610}
611
612impl From<Rooted<StructRef>> for Val {
613    #[inline]
614    fn from(val: Rooted<StructRef>) -> Val {
615        Val::AnyRef(Some(val.into()))
616    }
617}
618
619impl From<Option<Rooted<StructRef>>> for Val {
620    #[inline]
621    fn from(val: Option<Rooted<StructRef>>) -> Val {
622        Val::AnyRef(val.map(Into::into))
623    }
624}
625
626impl From<Rooted<ArrayRef>> for Val {
627    #[inline]
628    fn from(val: Rooted<ArrayRef>) -> Val {
629        Val::AnyRef(Some(val.into()))
630    }
631}
632
633impl From<Option<Rooted<ArrayRef>>> for Val {
634    #[inline]
635    fn from(val: Option<Rooted<ArrayRef>>) -> Val {
636        Val::AnyRef(val.map(Into::into))
637    }
638}
639
640impl From<Rooted<ExnRef>> for Val {
641    #[inline]
642    fn from(val: Rooted<ExnRef>) -> Val {
643        Val::ExnRef(Some(val))
644    }
645}
646
647impl From<Option<Rooted<ExnRef>>> for Val {
648    #[inline]
649    fn from(val: Option<Rooted<ExnRef>>) -> Val {
650        Val::ExnRef(val)
651    }
652}
653
654impl From<Func> for Val {
655    #[inline]
656    fn from(val: Func) -> Val {
657        Val::FuncRef(Some(val))
658    }
659}
660
661impl From<Option<Func>> for Val {
662    #[inline]
663    fn from(val: Option<Func>) -> Val {
664        Val::FuncRef(val)
665    }
666}
667
668impl From<u128> for Val {
669    #[inline]
670    fn from(val: u128) -> Val {
671        Val::V128(val.into())
672    }
673}
674
675impl From<V128> for Val {
676    #[inline]
677    fn from(val: V128) -> Val {
678        Val::V128(val)
679    }
680}
681
682/// A reference.
683///
684/// References come in three broad flavors:
685///
686/// 1. Function references. These are references to a function that can be
687///    invoked.
688///
689/// 2. External references. These are references to data that is external
690///    and opaque to the Wasm guest, provided by the host.
691///
692/// 3. Internal references. These are references to allocations inside the
693///    Wasm's heap, such as structs and arrays. These are part of the GC
694///    proposal, and not yet implemented in Wasmtime.
695///
696/// At the Wasm level, there are nullable and non-nullable variants of each type
697/// of reference. Both variants are represented with `Ref` at the Wasmtime API
698/// level. For example, values of both `(ref extern)` and `(ref null extern)`
699/// types will be represented as `Ref::Extern(Option<ExternRef>)` in the
700/// Wasmtime API. Nullable references are represented as `Option<Ref>` where
701/// null references are represented as `None`. Wasm can construct null
702/// references via the `ref.null <heap-type>` instruction.
703///
704/// References are non-forgable: Wasm cannot create invalid references, for
705/// example, by claiming that the integer `0xbad1bad2` is actually a reference.
706#[derive(Debug, Clone)]
707pub enum Ref {
708    // NB: We have a variant for each of the type hierarchies defined in Wasm,
709    // and push the `Option` that provides nullability into each variant. This
710    // allows us to get the most-precise type of any reference value, whether it
711    // is null or not, without any additional metadata.
712    //
713    // Consider if we instead had the nullability inside `Val::Ref` and each of
714    // the `Ref` variants did not have an `Option`:
715    //
716    //     enum Val {
717    //         Ref(Option<Ref>),
718    //         // Etc...
719    //     }
720    //     enum Ref {
721    //         Func(Func),
722    //         External(ExternRef),
723    //         // Etc...
724    //     }
725    //
726    // In this scenario, what type would we return from `Val::ty` for
727    // `Val::Ref(None)`? Because Wasm has multiple separate type hierarchies,
728    // there is no single common bottom type for all the different kinds of
729    // references. So in this scenario, `Val::Ref(None)` doesn't have enough
730    // information to reconstruct the value's type. That's a problem for us
731    // because we need to get a value's type at various times all over the code
732    // base.
733    //
734    /// A first-class reference to a WebAssembly function.
735    ///
736    /// The host, or the Wasm guest, can invoke this function.
737    ///
738    /// The host can create function references via [`Func::new`] or
739    /// [`Func::wrap`].
740    ///
741    /// The Wasm guest can create non-null function references via the
742    /// `ref.func` instruction, or null references via the `ref.null func`
743    /// instruction.
744    Func(Option<Func>),
745
746    /// A reference to an value outside of the Wasm heap.
747    ///
748    /// These references are opaque to the Wasm itself. Wasm can't create
749    /// non-null external references, nor do anything with them accept pass them
750    /// around as function arguments and returns and place them into globals and
751    /// tables.
752    ///
753    /// Wasm can create null external references via the `ref.null extern`
754    /// instruction.
755    Extern(Option<Rooted<ExternRef>>),
756
757    /// An internal reference.
758    ///
759    /// The `AnyRef` type represents WebAssembly `anyref` values. These can be
760    /// references to `struct`s and `array`s or inline/unboxed 31-bit
761    /// integers.
762    ///
763    /// Unlike `externref`, Wasm guests can directly allocate `anyref`s, and
764    /// does not need to rely on the host to do that.
765    Any(Option<Rooted<AnyRef>>),
766
767    /// An exception-object reference.
768    ///
769    /// The `ExnRef` type represents WebAssembly `exnref`
770    /// values. These are references to exception objects as caught by
771    /// `catch_ref` clauses on `try_table` instructions, or as
772    /// allocated via the host API.
773    Exn(Option<Rooted<ExnRef>>),
774}
775
776impl From<Func> for Ref {
777    #[inline]
778    fn from(f: Func) -> Ref {
779        Ref::Func(Some(f))
780    }
781}
782
783impl From<Option<Func>> for Ref {
784    #[inline]
785    fn from(f: Option<Func>) -> Ref {
786        Ref::Func(f)
787    }
788}
789
790impl From<Rooted<ExternRef>> for Ref {
791    #[inline]
792    fn from(e: Rooted<ExternRef>) -> Ref {
793        Ref::Extern(Some(e))
794    }
795}
796
797impl From<Option<Rooted<ExternRef>>> for Ref {
798    #[inline]
799    fn from(e: Option<Rooted<ExternRef>>) -> Ref {
800        Ref::Extern(e)
801    }
802}
803
804impl From<Rooted<AnyRef>> for Ref {
805    #[inline]
806    fn from(e: Rooted<AnyRef>) -> Ref {
807        Ref::Any(Some(e))
808    }
809}
810
811impl From<Option<Rooted<AnyRef>>> for Ref {
812    #[inline]
813    fn from(e: Option<Rooted<AnyRef>>) -> Ref {
814        Ref::Any(e)
815    }
816}
817
818impl From<Rooted<StructRef>> for Ref {
819    #[inline]
820    fn from(e: Rooted<StructRef>) -> Ref {
821        Ref::Any(Some(e.into()))
822    }
823}
824
825impl From<Option<Rooted<StructRef>>> for Ref {
826    #[inline]
827    fn from(e: Option<Rooted<StructRef>>) -> Ref {
828        Ref::Any(e.map(Into::into))
829    }
830}
831
832impl From<Rooted<ArrayRef>> for Ref {
833    #[inline]
834    fn from(e: Rooted<ArrayRef>) -> Ref {
835        Ref::Any(Some(e.into()))
836    }
837}
838
839impl From<Option<Rooted<ArrayRef>>> for Ref {
840    #[inline]
841    fn from(e: Option<Rooted<ArrayRef>>) -> Ref {
842        Ref::Any(e.map(Into::into))
843    }
844}
845
846impl From<Rooted<ExnRef>> for Ref {
847    #[inline]
848    fn from(e: Rooted<ExnRef>) -> Ref {
849        Ref::Exn(Some(e))
850    }
851}
852
853impl From<Option<Rooted<ExnRef>>> for Ref {
854    #[inline]
855    fn from(e: Option<Rooted<ExnRef>>) -> Ref {
856        Ref::Exn(e)
857    }
858}
859
860impl Ref {
861    /// Create a null reference to the given heap type.
862    #[inline]
863    pub fn null(heap_type: &HeapType) -> Self {
864        match heap_type.top() {
865            HeapTopType::Any => Ref::Any(None),
866            HeapTopType::Extern => Ref::Extern(None),
867            HeapTopType::Func => Ref::Func(None),
868            HeapTopType::Exn => Ref::Exn(None),
869            HeapTopType::Cont => unimplemented!("embedding API for `(ref cont)`"),
870        }
871    }
872
873    /// Is this a null reference?
874    #[inline]
875    pub fn is_null(&self) -> bool {
876        match self {
877            Ref::Any(None) | Ref::Extern(None) | Ref::Func(None) | Ref::Exn(None) => true,
878            Ref::Any(Some(_)) | Ref::Extern(Some(_)) | Ref::Func(Some(_)) | Ref::Exn(Some(_)) => {
879                false
880            }
881        }
882    }
883
884    /// Is this a non-null reference?
885    #[inline]
886    pub fn is_non_null(&self) -> bool {
887        !self.is_null()
888    }
889
890    /// Is this an `extern` reference?
891    #[inline]
892    pub fn is_extern(&self) -> bool {
893        matches!(self, Ref::Extern(_))
894    }
895
896    /// Get the underlying `extern` reference, if any.
897    ///
898    /// Returns `None` if this `Ref` is not an `extern` reference, eg it is a
899    /// `func` reference.
900    ///
901    /// Returns `Some(None)` if this `Ref` is a null `extern` reference.
902    ///
903    /// Returns `Some(Some(_))` if this `Ref` is a non-null `extern` reference.
904    #[inline]
905    pub fn as_extern(&self) -> Option<Option<&Rooted<ExternRef>>> {
906        match self {
907            Ref::Extern(e) => Some(e.as_ref()),
908            _ => None,
909        }
910    }
911
912    /// Get the underlying `extern` reference, panicking if this is a different
913    /// kind of reference.
914    ///
915    /// Returns `None` if this `Ref` is a null `extern` reference.
916    ///
917    /// Returns `Some(_)` if this `Ref` is a non-null `extern` reference.
918    #[inline]
919    pub fn unwrap_extern(&self) -> Option<&Rooted<ExternRef>> {
920        self.as_extern()
921            .expect("Ref::unwrap_extern on non-extern reference")
922    }
923
924    /// Is this an `any` reference?
925    #[inline]
926    pub fn is_any(&self) -> bool {
927        matches!(self, Ref::Any(_))
928    }
929
930    /// Get the underlying `any` reference, if any.
931    ///
932    /// Returns `None` if this `Ref` is not an `any` reference, eg it is a
933    /// `func` reference.
934    ///
935    /// Returns `Some(None)` if this `Ref` is a null `any` reference.
936    ///
937    /// Returns `Some(Some(_))` if this `Ref` is a non-null `any` reference.
938    #[inline]
939    pub fn as_any(&self) -> Option<Option<&Rooted<AnyRef>>> {
940        match self {
941            Ref::Any(e) => Some(e.as_ref()),
942            _ => None,
943        }
944    }
945
946    /// Get the underlying `any` reference, panicking if this is a different
947    /// kind of reference.
948    ///
949    /// Returns `None` if this `Ref` is a null `any` reference.
950    ///
951    /// Returns `Some(_)` if this `Ref` is a non-null `any` reference.
952    #[inline]
953    pub fn unwrap_any(&self) -> Option<&Rooted<AnyRef>> {
954        self.as_any().expect("Ref::unwrap_any on non-any reference")
955    }
956
957    /// Is this an `exn` reference?
958    #[inline]
959    pub fn is_exn(&self) -> bool {
960        matches!(self, Ref::Exn(_))
961    }
962
963    /// Get the underlying `exn` reference, if any.
964    ///
965    /// Returns `None` if this `Ref` is not an `exn` reference, eg it is a
966    /// `func` reference.
967    ///
968    /// Returns `Some(None)` if this `Ref` is a null `exn` reference.
969    ///
970    /// Returns `Some(Some(_))` if this `Ref` is a non-null `exn` reference.
971    #[inline]
972    pub fn as_exn(&self) -> Option<Option<&Rooted<ExnRef>>> {
973        match self {
974            Ref::Exn(e) => Some(e.as_ref()),
975            _ => None,
976        }
977    }
978
979    /// Get the underlying `exn` reference, panicking if this is a different
980    /// kind of reference.
981    ///
982    /// Returns `None` if this `Ref` is a null `exn` reference.
983    ///
984    /// Returns `Some(_)` if this `Ref` is a non-null `exn` reference.
985    #[inline]
986    pub fn unwrap_exn(&self) -> Option<&Rooted<ExnRef>> {
987        self.as_exn().expect("Ref::unwrap_exn on non-exn reference")
988    }
989
990    /// Is this a `func` reference?
991    #[inline]
992    pub fn is_func(&self) -> bool {
993        matches!(self, Ref::Func(_))
994    }
995
996    /// Get the underlying `func` reference, if any.
997    ///
998    /// Returns `None` if this `Ref` is not an `func` reference, eg it is an
999    /// `extern` reference.
1000    ///
1001    /// Returns `Some(None)` if this `Ref` is a null `func` reference.
1002    ///
1003    /// Returns `Some(Some(_))` if this `Ref` is a non-null `func` reference.
1004    #[inline]
1005    pub fn as_func(&self) -> Option<Option<&Func>> {
1006        match self {
1007            Ref::Func(f) => Some(f.as_ref()),
1008            _ => None,
1009        }
1010    }
1011
1012    /// Get the underlying `func` reference, panicking if this is a different
1013    /// kind of reference.
1014    ///
1015    /// Returns `None` if this `Ref` is a null `func` reference.
1016    ///
1017    /// Returns `Some(_)` if this `Ref` is a non-null `func` reference.
1018    #[inline]
1019    pub fn unwrap_func(&self) -> Option<&Func> {
1020        self.as_func()
1021            .expect("Ref::unwrap_func on non-func reference")
1022    }
1023
1024    /// Get the type of this reference.
1025    ///
1026    /// # Errors
1027    ///
1028    /// Return an error if this reference has been unrooted.
1029    ///
1030    /// # Panics
1031    ///
1032    /// Panics if this reference is associated with a different store.
1033    pub fn ty(&self, store: impl AsContext) -> Result<RefType> {
1034        self.load_ty(&store.as_context().0)
1035    }
1036
1037    pub(crate) fn load_ty(&self, store: &StoreOpaque) -> Result<RefType> {
1038        assert!(self.comes_from_same_store(store));
1039        Ok(RefType::new(
1040            self.is_null(),
1041            // NB: We choose the most-specific heap type we can here and let
1042            // subtyping do its thing if callers are matching against a
1043            // `HeapType::Func`.
1044            match self {
1045                Ref::Extern(None) => HeapType::NoExtern,
1046                Ref::Extern(Some(e)) => {
1047                    e.try_gc_ref(store)?;
1048                    HeapType::Extern
1049                }
1050
1051                Ref::Func(None) => HeapType::NoFunc,
1052                Ref::Func(Some(f)) => HeapType::ConcreteFunc(f.load_ty(store)),
1053
1054                Ref::Any(None) => HeapType::None,
1055                Ref::Any(Some(a)) => a._ty(store)?,
1056
1057                Ref::Exn(None) => HeapType::NoExn,
1058                Ref::Exn(Some(e)) => {
1059                    e.try_gc_ref(store)?;
1060                    HeapType::Exn
1061                }
1062            },
1063        ))
1064    }
1065
1066    /// Does this reference value match the given type?
1067    ///
1068    /// Returns an error if the underlying `Rooted` has been unrooted.
1069    ///
1070    /// # Panics
1071    ///
1072    /// Panics if this reference is not associated with the given store.
1073    pub fn matches_ty(&self, store: impl AsContext, ty: &RefType) -> Result<bool> {
1074        self._matches_ty(&store.as_context().0, ty)
1075    }
1076
1077    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &RefType) -> Result<bool> {
1078        assert!(self.comes_from_same_store(store));
1079        assert!(ty.comes_from_same_engine(store.engine()));
1080        if self.is_null() && !ty.is_nullable() {
1081            return Ok(false);
1082        }
1083        Ok(match (self, ty.heap_type()) {
1084            (Ref::Extern(Some(e)), HeapType::Extern) => {
1085                e.try_gc_ref(store)?;
1086                true
1087            }
1088            (Ref::Extern(None), HeapType::Extern) => true,
1089            (Ref::Extern(None), HeapType::NoExtern) => true,
1090            (Ref::Extern(_), _) => false,
1091
1092            (Ref::Func(_), HeapType::Func) => true,
1093            (Ref::Func(None), HeapType::NoFunc | HeapType::ConcreteFunc(_)) => true,
1094            (Ref::Func(Some(f)), HeapType::ConcreteFunc(func_ty)) => f._matches_ty(store, func_ty),
1095            (Ref::Func(_), _) => false,
1096
1097            (Ref::Any(Some(a)), HeapType::Any) => {
1098                a.try_gc_ref(store)?;
1099                true
1100            }
1101            (Ref::Any(None), HeapType::Any) => true,
1102            (Ref::Any(Some(a)), HeapType::I31) => a._is_i31(store)?,
1103            (Ref::Any(Some(a)), HeapType::Struct) => a._is_struct(store)?,
1104            (Ref::Any(Some(a)), HeapType::ConcreteStruct(_ty)) => match a._as_struct(store)? {
1105                None => false,
1106                Some(s) => s._matches_ty(store, _ty)?,
1107            },
1108            (Ref::Any(Some(a)), HeapType::Eq) => a._is_eqref(store)?,
1109            (Ref::Any(Some(a)), HeapType::Array) => a._is_array(store)?,
1110            (Ref::Any(Some(a)), HeapType::ConcreteArray(_ty)) => match a._as_array(store)? {
1111                None => false,
1112                Some(a) => a._matches_ty(store, _ty)?,
1113            },
1114            (
1115                Ref::Any(None),
1116                HeapType::None
1117                | HeapType::I31
1118                | HeapType::ConcreteStruct(_)
1119                | HeapType::Struct
1120                | HeapType::ConcreteArray(_)
1121                | HeapType::Array
1122                | HeapType::Eq,
1123            ) => true,
1124            (Ref::Any(_), _) => false,
1125
1126            (Ref::Exn(Some(e)), HeapType::Exn) => {
1127                e.try_gc_ref(store)?;
1128                true
1129            }
1130            (Ref::Exn(None), HeapType::Exn) => true,
1131            (Ref::Exn(None), HeapType::NoExn) => true,
1132            (Ref::Exn(_), _) => false,
1133        })
1134    }
1135
1136    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &RefType) -> Result<()> {
1137        if !self.comes_from_same_store(store) {
1138            bail!("reference used with wrong store")
1139        }
1140        if !ty.comes_from_same_engine(store.engine()) {
1141            bail!("type used with wrong engine")
1142        }
1143        if self._matches_ty(store, ty)? {
1144            Ok(())
1145        } else {
1146            let actual_ty = self.load_ty(store)?;
1147            bail!("type mismatch: expected {ty}, found {actual_ty}")
1148        }
1149    }
1150
1151    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1152        match self {
1153            Ref::Func(Some(f)) => f.comes_from_same_store(store),
1154            Ref::Func(None) => true,
1155            Ref::Extern(Some(x)) => x.comes_from_same_store(store),
1156            Ref::Extern(None) => true,
1157            Ref::Any(Some(a)) => a.comes_from_same_store(store),
1158            Ref::Any(None) => true,
1159            Ref::Exn(Some(e)) => e.comes_from_same_store(store),
1160            Ref::Exn(None) => true,
1161        }
1162    }
1163}
1164
1165#[cfg(test)]
1166mod tests {
1167    use crate::*;
1168
1169    #[test]
1170    fn size_of_val() {
1171        // Try to keep tabs on the size of `Val` and make sure we don't grow its
1172        // size.
1173        let expected = if cfg!(target_arch = "x86_64")
1174            || cfg!(target_arch = "aarch64")
1175            || cfg!(target_arch = "s390x")
1176            || cfg!(target_arch = "riscv64")
1177            || cfg!(target_arch = "arm")
1178        {
1179            24
1180        } else if cfg!(target_arch = "x86") {
1181            20
1182        } else {
1183            panic!("unsupported architecture")
1184        };
1185        assert_eq!(std::mem::size_of::<Val>(), expected);
1186    }
1187
1188    #[test]
1189    fn size_of_ref() {
1190        // Try to keep tabs on the size of `Ref` and make sure we don't grow its
1191        // size.
1192        let expected = if cfg!(target_arch = "x86_64")
1193            || cfg!(target_arch = "aarch64")
1194            || cfg!(target_arch = "s390x")
1195            || cfg!(target_arch = "riscv64")
1196            || cfg!(target_arch = "arm")
1197        {
1198            24
1199        } else if cfg!(target_arch = "x86") {
1200            20
1201        } else {
1202            panic!("unsupported architecture")
1203        };
1204        assert_eq!(std::mem::size_of::<Ref>(), expected);
1205    }
1206
1207    #[test]
1208    #[should_panic]
1209    fn val_matches_ty_wrong_engine() {
1210        let e1 = Engine::default();
1211        let e2 = Engine::default();
1212
1213        let t1 = FuncType::new(&e1, None, None);
1214        let t2 = FuncType::new(&e2, None, None);
1215
1216        let mut s1 = Store::new(&e1, ());
1217        let f = Func::new(&mut s1, t1.clone(), |_caller, _args, _results| Ok(()));
1218
1219        // Should panic.
1220        let _ = Val::FuncRef(Some(f)).matches_ty(
1221            &s1,
1222            &ValType::Ref(RefType::new(true, HeapType::ConcreteFunc(t2))),
1223        );
1224    }
1225
1226    #[test]
1227    #[should_panic]
1228    fn ref_matches_ty_wrong_engine() {
1229        let e1 = Engine::default();
1230        let e2 = Engine::default();
1231
1232        let t1 = FuncType::new(&e1, None, None);
1233        let t2 = FuncType::new(&e2, None, None);
1234
1235        let mut s1 = Store::new(&e1, ());
1236        let f = Func::new(&mut s1, t1.clone(), |_caller, _args, _results| Ok(()));
1237
1238        // Should panic.
1239        let _ = Ref::Func(Some(f)).matches_ty(&s1, &RefType::new(true, HeapType::ConcreteFunc(t2)));
1240    }
1241}