Skip to main content

wasmtime/runtime/gc/enabled/
anyref.rs

1//! Implementation of `anyref` in Wasmtime.
2
3use super::ExternRef;
4use crate::prelude::*;
5use crate::runtime::vm::VMGcRef;
6use crate::{
7    ArrayRef, ArrayType, AsContext, AsContextMut, EqRef, GcRefImpl, GcRootIndex, HeapType, I31,
8    OwnedRooted, RefType, Result, Rooted, StructRef, StructType, ValRaw, ValType, WasmTy, bail_bug,
9    store::{AutoAssertNoGc, StoreOpaque},
10};
11use core::mem;
12use core::mem::MaybeUninit;
13use wasmtime_environ::VMGcKind;
14
15/// An `anyref` GC reference.
16///
17/// The `AnyRef` type represents WebAssembly `anyref` values. These can be
18/// references to `struct`s and `array`s or inline/unboxed 31-bit
19/// integers. Unlike `externref`, Wasm guests can directly allocate `anyref`s.
20///
21/// Like all WebAssembly references, these are opaque and unforgable to Wasm:
22/// they cannot be faked and Wasm cannot, for example, cast the integer
23/// `0x12345678` into a reference, pretend it is a valid `anyref`, and trick the
24/// host into dereferencing it and segfaulting or worse.
25///
26/// Note that you can also use `Rooted<AnyRef>` and `OwnedRooted<AnyRef>` as
27/// a type parameter with [`Func::typed`][crate::Func::typed]- and
28/// [`Func::wrap`][crate::Func::wrap]-style APIs.
29///
30/// # Example
31///
32/// ```
33/// # use wasmtime::*;
34/// # fn _foo() -> Result<()> {
35/// let mut config = Config::new();
36/// config.wasm_gc(true);
37///
38/// let engine = Engine::new(&config)?;
39///
40/// // Define a module which does stuff with `anyref`s.
41/// let module = Module::new(&engine, r#"
42///     (module
43///         (func (export "increment-if-i31") (param (ref null any)) (result (ref null any))
44///             block
45///                 ;; Try to cast the arg to an `i31`, otherwise branch out
46///                 ;; of this `block`.
47///                 local.get 0
48///                 br_on_cast_fail (ref null any) (ref i31) 0
49///                 ;; Get the `i31`'s inner value and add one to it.
50///                 i31.get_u
51///                 i32.const 1
52///                 i32.add
53///                 ;; Wrap the incremented value back into an `i31` reference and
54///                 ;; return it.
55///                 ref.i31
56///                 return
57///             end
58///
59///             ;; If the `anyref` we were given is not an `i31`, just return it
60///             ;; as-is.
61///             local.get 0
62///         )
63///     )
64/// "#)?;
65///
66/// // Instantiate the module.
67/// let mut store = Store::new(&engine, ());
68/// let instance = Instance::new(&mut store, &module, &[])?;
69///
70/// // Extract the function.
71/// let increment_if_i31 = instance
72///     .get_typed_func::<Option<Rooted<AnyRef>>, Option<Rooted<AnyRef>>>(
73///         &mut store,
74///         "increment-if-i31",
75///     )?;
76///
77/// {
78///     // Create a new scope for the `Rooted` arguments and returns.
79///     let mut scope = RootScope::new(&mut store);
80///
81///     // Call the function with an `i31`.
82///     let arg = AnyRef::from_i31(&mut scope, I31::wrapping_u32(419));
83///     let result = increment_if_i31.call(&mut scope, Some(arg))?;
84///     assert_eq!(result.unwrap().as_i31(&scope)?, Some(I31::wrapping_u32(420)));
85///
86///     // Call the function with something that isn't an `i31`.
87///     let result = increment_if_i31.call(&mut scope, None)?;
88///     assert!(result.is_none());
89/// }
90/// # Ok(())
91/// # }
92/// ```
93#[derive(Debug)]
94#[repr(transparent)]
95pub struct AnyRef {
96    pub(super) inner: GcRootIndex,
97}
98
99impl From<Rooted<EqRef>> for Rooted<AnyRef> {
100    #[inline]
101    fn from(e: Rooted<EqRef>) -> Self {
102        e.to_anyref()
103    }
104}
105
106impl From<OwnedRooted<EqRef>> for OwnedRooted<AnyRef> {
107    #[inline]
108    fn from(e: OwnedRooted<EqRef>) -> Self {
109        e.to_anyref()
110    }
111}
112
113impl From<Rooted<StructRef>> for Rooted<AnyRef> {
114    #[inline]
115    fn from(s: Rooted<StructRef>) -> Self {
116        s.to_anyref()
117    }
118}
119
120impl From<OwnedRooted<StructRef>> for OwnedRooted<AnyRef> {
121    #[inline]
122    fn from(s: OwnedRooted<StructRef>) -> Self {
123        s.to_anyref()
124    }
125}
126
127impl From<Rooted<ArrayRef>> for Rooted<AnyRef> {
128    #[inline]
129    fn from(s: Rooted<ArrayRef>) -> Self {
130        s.to_anyref()
131    }
132}
133
134impl From<OwnedRooted<ArrayRef>> for OwnedRooted<AnyRef> {
135    #[inline]
136    fn from(s: OwnedRooted<ArrayRef>) -> Self {
137        s.to_anyref()
138    }
139}
140
141unsafe impl GcRefImpl for AnyRef {
142    fn transmute_ref(index: &GcRootIndex) -> &Self {
143        // Safety: `AnyRef` is a newtype of a `GcRootIndex`.
144        let me: &Self = unsafe { mem::transmute(index) };
145
146        // Assert we really are just a newtype of a `GcRootIndex`.
147        assert!(matches!(
148            me,
149            Self {
150                inner: GcRootIndex { .. },
151            }
152        ));
153
154        me
155    }
156}
157
158impl AnyRef {
159    /// Construct an `anyref` from an `i31`.
160    ///
161    /// # Example
162    ///
163    /// ```
164    /// # use wasmtime::*;
165    /// # fn _foo() -> Result<()> {
166    /// let mut store = Store::<()>::default();
167    ///
168    /// // Create an `i31`.
169    /// let i31 = I31::wrapping_u32(999);
170    ///
171    /// // Convert it into an `anyref`.
172    /// let anyref = AnyRef::from_i31(&mut store, i31);
173    /// # Ok(())
174    /// # }
175    /// ```
176    pub fn from_i31(mut store: impl AsContextMut, value: I31) -> Rooted<Self> {
177        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
178        Self::_from_i31(&mut store, value)
179    }
180
181    pub(crate) fn _from_i31(store: &mut AutoAssertNoGc<'_>, value: I31) -> Rooted<Self> {
182        let gc_ref = VMGcRef::from_i31(value.runtime_i31());
183        Rooted::new(store, gc_ref)
184    }
185
186    /// Convert an `externref` into an `anyref`.
187    ///
188    /// This is equivalent to the `any.convert_extern` instruction in Wasm.
189    ///
190    /// You can recover the underlying `externref` again via the
191    /// [`ExternRef::convert_any`] method or the `extern.convert_any` Wasm
192    /// instruction.
193    ///
194    /// Returns an error if the `externref` GC reference has been unrooted (eg
195    /// if you attempt to use a `Rooted<ExternRef>` after exiting the scope it
196    /// was rooted within). See the documentation for
197    /// [`Rooted<T>`][crate::Rooted] for more details.
198    ///
199    /// # Example
200    ///
201    /// ```
202    /// use wasmtime::*;
203    /// # fn foo() -> Result<()> {
204    /// let engine = Engine::default();
205    /// let mut store = Store::new(&engine, ());
206    ///
207    /// // Create an `externref`.
208    /// let externref = ExternRef::new(&mut store, "hello")?;
209    ///
210    /// // Convert that `externref` into an `anyref`.
211    /// let anyref = AnyRef::convert_extern(&mut store, externref)?;
212    ///
213    /// // The converted value is an `anyref` but is not an `eqref`.
214    /// assert_eq!(anyref.matches_ty(&store, &HeapType::Any)?, true);
215    /// assert_eq!(anyref.matches_ty(&store, &HeapType::Eq)?, false);
216    ///
217    /// // We can convert it back to the original `externref` and get its
218    /// // associated host data again.
219    /// let externref = ExternRef::convert_any(&mut store, anyref)?;
220    /// let data = externref
221    ///     .data(&store)?
222    ///     .expect("externref should have host data")
223    ///     .downcast_ref::<&str>()
224    ///     .expect("host data should be a str");
225    /// assert_eq!(*data, "hello");
226    /// # Ok(()) }
227    /// # foo().unwrap();
228    pub fn convert_extern(
229        mut store: impl AsContextMut,
230        externref: Rooted<ExternRef>,
231    ) -> Result<Rooted<Self>> {
232        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
233        Self::_convert_extern(&mut store, externref)
234    }
235
236    pub(crate) fn _convert_extern(
237        store: &mut AutoAssertNoGc<'_>,
238        externref: Rooted<ExternRef>,
239    ) -> Result<Rooted<Self>> {
240        let gc_ref = externref.try_clone_gc_ref(store)?;
241        Ok(Self::from_cloned_gc_ref(store, gc_ref))
242    }
243
244    /// Creates a new strongly-owned [`AnyRef`] from the raw value provided.
245    ///
246    /// This is intended to be used in conjunction with [`Func::new_unchecked`],
247    /// [`Func::call_unchecked`], and [`ValRaw`] with its `anyref` field.
248    ///
249    /// This function assumes that `raw` is an `anyref` value which is currently
250    /// rooted within the [`Store`].
251    ///
252    /// # Correctness
253    ///
254    /// This function is tricky to get right because `raw` not only must be a
255    /// valid `anyref` value produced prior by [`AnyRef::to_raw`] but it
256    /// must also be correctly rooted within the store. When arguments are
257    /// provided to a callback with [`Func::new_unchecked`], for example, or
258    /// returned via [`Func::call_unchecked`], if a GC is performed within the
259    /// store then floating `anyref` values are not rooted and will be GC'd,
260    /// meaning that this function will no longer be correct to call with the
261    /// values cleaned up. This function must be invoked *before* possible GC
262    /// operations can happen (such as calling Wasm).
263    ///
264    ///
265    /// When in doubt try to not use this. Instead use the Rust APIs of
266    /// [`TypedFunc`] and friends. Note though that this function is not
267    /// `unsafe` as any value can be passed in. Incorrect values can result in
268    /// runtime panics, however, so care must still be taken with this method.
269    ///
270    /// [`Func::call_unchecked`]: crate::Func::call_unchecked
271    /// [`Func::new_unchecked`]: crate::Func::new_unchecked
272    /// [`Store`]: crate::Store
273    /// [`TypedFunc`]: crate::TypedFunc
274    /// [`ValRaw`]: crate::ValRaw
275    pub fn from_raw(mut store: impl AsContextMut, raw: u32) -> Option<Rooted<Self>> {
276        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
277        Self::_from_raw(&mut store, raw)
278    }
279
280    // (Not actually memory unsafe since we have indexed GC heaps.)
281    pub(crate) fn _from_raw(store: &mut AutoAssertNoGc, raw: u32) -> Option<Rooted<Self>> {
282        let gc_ref = VMGcRef::from_raw_u32(raw)?;
283        let gc_ref = store.clone_gc_ref(&gc_ref);
284        Some(Self::from_cloned_gc_ref(store, gc_ref))
285    }
286
287    /// Create a new `Rooted<AnyRef>` from the given GC reference.
288    ///
289    /// `gc_ref` should point to a valid `anyref` and should belong to the
290    /// store's GC heap. Failure to uphold these invariants is memory safe but
291    /// will lead to general incorrectness such as panics or wrong results.
292    pub(crate) fn from_cloned_gc_ref(
293        store: &mut AutoAssertNoGc<'_>,
294        gc_ref: VMGcRef,
295    ) -> Rooted<Self> {
296        debug_assert!(
297            gc_ref.is_i31()
298                || store
299                    .unwrap_gc_store()
300                    .kind(&gc_ref)
301                    .unwrap()
302                    .matches(VMGcKind::AnyRef)
303                || store
304                    .unwrap_gc_store()
305                    .kind(&gc_ref)
306                    .unwrap()
307                    .matches(VMGcKind::ExternRef)
308        );
309        Rooted::new(store, gc_ref)
310    }
311
312    #[inline]
313    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
314        self.inner.comes_from_same_store(store)
315    }
316
317    /// Converts this [`AnyRef`] to a raw value suitable to store within a
318    /// [`ValRaw`].
319    ///
320    /// Returns an error if this `anyref` has been unrooted.
321    ///
322    /// # Correctness
323    ///
324    /// Produces a raw value which is only valid to pass into a store if a GC
325    /// doesn't happen between when the value is produce and when it's passed
326    /// into the store.
327    ///
328    /// [`ValRaw`]: crate::ValRaw
329    pub fn to_raw(&self, mut store: impl AsContextMut) -> Result<u32> {
330        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
331        self._to_raw(&mut store)
332    }
333
334    pub(crate) fn _to_raw(&self, store: &mut AutoAssertNoGc<'_>) -> Result<u32> {
335        self.inner.expose_gc_ref_to_wasm(store).map(|r| r.get())
336    }
337
338    /// Get the type of this reference.
339    ///
340    /// # Errors
341    ///
342    /// Return an error if this reference has been unrooted.
343    ///
344    /// # Panics
345    ///
346    /// Panics if this reference is associated with a different store.
347    pub fn ty(&self, store: impl AsContext) -> Result<HeapType> {
348        self._ty(store.as_context().0)
349    }
350
351    pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<HeapType> {
352        Self::ty_of_(store, self.inner.try_gc_ref(store)?)
353    }
354
355    /// The type of the `anyref` object `gc_ref`.
356    pub(crate) fn ty_of_(store: &StoreOpaque, gc_ref: &VMGcRef) -> Result<HeapType> {
357        if gc_ref.is_i31() {
358            return Ok(HeapType::I31);
359        }
360
361        let header = store.require_gc_store()?.header(gc_ref)?;
362        let kind = match header.kind() {
363            Some(kind) => kind,
364            None => bail_bug!("invalid `VMGcKind`"),
365        };
366
367        if kind.matches(VMGcKind::ExternRef) {
368            return Ok(HeapType::Any);
369        }
370
371        debug_assert!(kind.matches(VMGcKind::AnyRef));
372        debug_assert!(kind.matches(VMGcKind::EqRef));
373        let ty = match header.ty() {
374            Some(ty) => ty,
375            None => bail_bug!("ty should be present"),
376        };
377
378        if kind.matches(VMGcKind::StructRef) {
379            return match StructType::from_shared_type_index(store.engine(), ty) {
380                Some(ty) => Ok(HeapType::ConcreteStruct(ty)),
381                None => bail_bug!("invalid struct type index"),
382            };
383        }
384
385        if kind.matches(VMGcKind::ArrayRef) {
386            return match ArrayType::from_shared_type_index(store.engine(), ty) {
387                Some(ty) => Ok(HeapType::ConcreteArray(ty)),
388                None => bail_bug!("invalid array type index"),
389            };
390        }
391
392        bail_bug!("no other kinds of `anyref`s")
393    }
394
395    /// Does this `anyref` match the given type?
396    ///
397    /// That is, is this object's type a subtype of the given type?
398    ///
399    /// # Errors
400    ///
401    /// Return an error if this reference has been unrooted.
402    ///
403    /// # Panics
404    ///
405    /// Panics if this reference is associated with a different store.
406    pub fn matches_ty(&self, store: impl AsContext, ty: &HeapType) -> Result<bool> {
407        self._matches_ty(store.as_context().0, ty)
408    }
409
410    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &HeapType) -> Result<bool> {
411        assert!(self.comes_from_same_store(store));
412        Ok(self._ty(store)?.matches(ty))
413    }
414
415    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &HeapType) -> Result<()> {
416        if !self.comes_from_same_store(store) {
417            bail!("function used with wrong store");
418        }
419        if self._matches_ty(store, ty)? {
420            Ok(())
421        } else {
422            let actual_ty = self._ty(store)?;
423            bail!("type mismatch: expected `(ref {ty})`, found `(ref {actual_ty})`")
424        }
425    }
426
427    /// Is this `anyref` an `eqref`?
428    ///
429    /// # Errors
430    ///
431    /// Return an error if this reference has been unrooted.
432    ///
433    /// # Panics
434    ///
435    /// Panics if this reference is associated with a different store.
436    pub fn is_eqref(&self, store: impl AsContext) -> Result<bool> {
437        self._is_eqref(store.as_context().0)
438    }
439
440    pub(crate) fn _is_eqref(&self, store: &StoreOpaque) -> Result<bool> {
441        assert!(self.comes_from_same_store(store));
442        let gc_ref = self.inner.try_gc_ref(store)?;
443        Ok(gc_ref.is_i31()
444            || store
445                .require_gc_store()?
446                .kind(gc_ref)?
447                .matches(VMGcKind::EqRef))
448    }
449
450    /// Downcast this `anyref` to an `eqref`.
451    ///
452    /// If this `anyref` is an `eqref`, then `Some(_)` is returned.
453    ///
454    /// If this `anyref` is not an `eqref`, then `None` is returned.
455    ///
456    /// # Errors
457    ///
458    /// Return an error if this reference has been unrooted.
459    ///
460    /// # Panics
461    ///
462    /// Panics if this reference is associated with a different store.
463    pub fn as_eqref(&self, store: impl AsContext) -> Result<Option<Rooted<EqRef>>> {
464        self._as_eqref(store.as_context().0)
465    }
466
467    pub(crate) fn _as_eqref(&self, store: &StoreOpaque) -> Result<Option<Rooted<EqRef>>> {
468        if self._is_eqref(store)? {
469            Ok(Some(Rooted::from_gc_root_index(self.inner)))
470        } else {
471            Ok(None)
472        }
473    }
474
475    /// Downcast this `anyref` to an `eqref`, panicking if this `anyref` is not
476    /// an `eqref`.
477    ///
478    /// # Errors
479    ///
480    /// Return an error if this reference has been unrooted.
481    ///
482    /// # Panics
483    ///
484    /// Panics if this reference is associated with a different store, or if
485    /// this `anyref` is not an `eqref`.
486    pub fn unwrap_eqref(&self, store: impl AsContext) -> Result<Rooted<EqRef>> {
487        self._unwrap_eqref(store.as_context().0)
488    }
489
490    pub(crate) fn _unwrap_eqref(&self, store: &StoreOpaque) -> Result<Rooted<EqRef>> {
491        Ok(self
492            ._as_eqref(store)?
493            .expect("AnyRef::unwrap_eqref on non-eqref"))
494    }
495
496    /// Is this `anyref` an `i31`?
497    ///
498    /// # Errors
499    ///
500    /// Return an error if this reference has been unrooted.
501    ///
502    /// # Panics
503    ///
504    /// Panics if this reference is associated with a different store.
505    pub fn is_i31(&self, store: impl AsContext) -> Result<bool> {
506        self._is_i31(store.as_context().0)
507    }
508
509    pub(crate) fn _is_i31(&self, store: &StoreOpaque) -> Result<bool> {
510        assert!(self.comes_from_same_store(store));
511        let gc_ref = self.inner.try_gc_ref(store)?;
512        Ok(gc_ref.is_i31())
513    }
514
515    /// Downcast this `anyref` to an `i31`.
516    ///
517    /// If this `anyref` is an `i31`, then `Some(_)` is returned.
518    ///
519    /// If this `anyref` is not an `i31`, then `None` is returned.
520    ///
521    /// # Errors
522    ///
523    /// Return an error if this reference has been unrooted.
524    ///
525    /// # Panics
526    ///
527    /// Panics if this reference is associated with a different store.
528    pub fn as_i31(&self, store: impl AsContext) -> Result<Option<I31>> {
529        self._as_i31(store.as_context().0)
530    }
531
532    pub(crate) fn _as_i31(&self, store: &StoreOpaque) -> Result<Option<I31>> {
533        assert!(self.comes_from_same_store(store));
534        let gc_ref = self.inner.try_gc_ref(store)?;
535        Ok(gc_ref.as_i31().map(Into::into))
536    }
537
538    /// Downcast this `anyref` to an `i31`, panicking if this `anyref` is not an
539    /// `i31`.
540    ///
541    /// # Errors
542    ///
543    /// Return an error if this reference has been unrooted.
544    ///
545    /// # Panics
546    ///
547    /// Panics if this reference is associated with a different store, or if
548    /// this `anyref` is not an `i31`.
549    pub fn unwrap_i31(&self, store: impl AsContext) -> Result<I31> {
550        Ok(self.as_i31(store)?.expect("AnyRef::unwrap_i31 on non-i31"))
551    }
552
553    /// Is this `anyref` a `structref`?
554    ///
555    /// # Errors
556    ///
557    /// Return an error if this reference has been unrooted.
558    ///
559    /// # Panics
560    ///
561    /// Panics if this reference is associated with a different store.
562    pub fn is_struct(&self, store: impl AsContext) -> Result<bool> {
563        self._is_struct(store.as_context().0)
564    }
565
566    pub(crate) fn _is_struct(&self, store: &StoreOpaque) -> Result<bool> {
567        let gc_ref = self.inner.try_gc_ref(store)?;
568        Ok(!gc_ref.is_i31()
569            && store
570                .require_gc_store()?
571                .kind(gc_ref)?
572                .matches(VMGcKind::StructRef))
573    }
574
575    /// Downcast this `anyref` to a `structref`.
576    ///
577    /// If this `anyref` is a `structref`, then `Some(_)` is returned.
578    ///
579    /// If this `anyref` is not a `structref`, then `None` is returned.
580    ///
581    /// # Errors
582    ///
583    /// Return an error if this reference has been unrooted.
584    ///
585    /// # Panics
586    ///
587    /// Panics if this reference is associated with a different store.
588    pub fn as_struct(&self, store: impl AsContext) -> Result<Option<Rooted<StructRef>>> {
589        self._as_struct(store.as_context().0)
590    }
591
592    pub(crate) fn _as_struct(&self, store: &StoreOpaque) -> Result<Option<Rooted<StructRef>>> {
593        if self._is_struct(store)? {
594            Ok(Some(Rooted::from_gc_root_index(self.inner)))
595        } else {
596            Ok(None)
597        }
598    }
599
600    /// Downcast this `anyref` to a `structref`, panicking if this `anyref` is
601    /// not a `structref`.
602    ///
603    /// # Errors
604    ///
605    /// Return an error if this reference has been unrooted.
606    ///
607    /// # Panics
608    ///
609    /// Panics if this reference is associated with a different store, or if
610    /// this `anyref` is not a `struct`.
611    pub fn unwrap_struct(&self, store: impl AsContext) -> Result<Rooted<StructRef>> {
612        self._unwrap_struct(store.as_context().0)
613    }
614
615    pub(crate) fn _unwrap_struct(&self, store: &StoreOpaque) -> Result<Rooted<StructRef>> {
616        Ok(self
617            ._as_struct(store)?
618            .expect("AnyRef::unwrap_struct on non-structref"))
619    }
620
621    /// Is this `anyref` an `arrayref`?
622    ///
623    /// # Errors
624    ///
625    /// Return an error if this reference has been unrooted.
626    ///
627    /// # Panics
628    ///
629    /// Panics if this reference is associated with a different store.
630    pub fn is_array(&self, store: impl AsContext) -> Result<bool> {
631        self._is_array(store.as_context().0)
632    }
633
634    pub(crate) fn _is_array(&self, store: &StoreOpaque) -> Result<bool> {
635        let gc_ref = self.inner.try_gc_ref(store)?;
636        Ok(!gc_ref.is_i31()
637            && store
638                .require_gc_store()?
639                .kind(gc_ref)?
640                .matches(VMGcKind::ArrayRef))
641    }
642
643    /// Downcast this `anyref` to an `arrayref`.
644    ///
645    /// If this `anyref` is an `arrayref`, then `Some(_)` is returned.
646    ///
647    /// If this `anyref` is not an `arrayref`, then `None` is returned.
648    ///
649    /// # Errors
650    ///
651    /// Return an error if this reference has been unrooted.
652    ///
653    /// # Panics
654    ///
655    /// Panics if this reference is associated with a different store.
656    pub fn as_array(&self, store: impl AsContext) -> Result<Option<Rooted<ArrayRef>>> {
657        self._as_array(store.as_context().0)
658    }
659
660    pub(crate) fn _as_array(&self, store: &StoreOpaque) -> Result<Option<Rooted<ArrayRef>>> {
661        if self._is_array(store)? {
662            Ok(Some(Rooted::from_gc_root_index(self.inner)))
663        } else {
664            Ok(None)
665        }
666    }
667
668    /// Downcast this `anyref` to an `arrayref`, panicking if this `anyref` is
669    /// not an `arrayref`.
670    ///
671    /// # Errors
672    ///
673    /// Return an error if this reference has been unrooted.
674    ///
675    /// # Panics
676    ///
677    /// Panics if this reference is associated with a different store, or if
678    /// this `anyref` is not an `array`.
679    pub fn unwrap_array(&self, store: impl AsContext) -> Result<Rooted<ArrayRef>> {
680        self._unwrap_array(store.as_context().0)
681    }
682
683    pub(crate) fn _unwrap_array(&self, store: &StoreOpaque) -> Result<Rooted<ArrayRef>> {
684        Ok(self
685            ._as_array(store)?
686            .expect("AnyRef::unwrap_array on non-arrayref"))
687    }
688}
689
690unsafe impl WasmTy for Rooted<AnyRef> {
691    #[inline]
692    fn valtype() -> ValType {
693        ValType::Ref(RefType::new(false, HeapType::Any))
694    }
695
696    #[inline]
697    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
698        self.comes_from_same_store(store)
699    }
700
701    #[inline]
702    fn dynamic_concrete_type_check(
703        &self,
704        store: &StoreOpaque,
705        _nullable: bool,
706        ty: &HeapType,
707    ) -> Result<()> {
708        self.ensure_matches_ty(store, ty)
709    }
710
711    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
712        self.wasm_ty_store(store, ptr, ValRaw::anyref)
713    }
714
715    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
716        Self::wasm_ty_load(store, ptr.get_anyref(), AnyRef::from_cloned_gc_ref)
717    }
718}
719
720unsafe impl WasmTy for Option<Rooted<AnyRef>> {
721    #[inline]
722    fn valtype() -> ValType {
723        ValType::ANYREF
724    }
725
726    #[inline]
727    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
728        self.map_or(true, |x| x.comes_from_same_store(store))
729    }
730
731    #[inline]
732    fn dynamic_concrete_type_check(
733        &self,
734        store: &StoreOpaque,
735        nullable: bool,
736        ty: &HeapType,
737    ) -> Result<()> {
738        match self {
739            Some(a) => a.ensure_matches_ty(store, ty),
740            None => {
741                ensure!(
742                    nullable,
743                    "expected a non-null reference, but found a null reference"
744                );
745                Ok(())
746            }
747        }
748    }
749
750    #[inline]
751    fn is_vmgcref_and_points_to_object(&self) -> bool {
752        self.is_some()
753    }
754
755    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
756        <Rooted<AnyRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
757    }
758
759    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
760        <Rooted<AnyRef>>::wasm_ty_option_load(store, ptr.get_anyref(), AnyRef::from_cloned_gc_ref)
761    }
762}
763
764unsafe impl WasmTy for OwnedRooted<AnyRef> {
765    #[inline]
766    fn valtype() -> ValType {
767        ValType::Ref(RefType::new(false, HeapType::Any))
768    }
769
770    #[inline]
771    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
772        self.comes_from_same_store(store)
773    }
774
775    #[inline]
776    fn dynamic_concrete_type_check(
777        &self,
778        store: &StoreOpaque,
779        _nullable: bool,
780        ty: &HeapType,
781    ) -> Result<()> {
782        self.ensure_matches_ty(store, ty)
783    }
784
785    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
786        self.wasm_ty_store(store, ptr, ValRaw::anyref)
787    }
788
789    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
790        Self::wasm_ty_load(store, ptr.get_anyref(), AnyRef::from_cloned_gc_ref)
791    }
792}
793
794unsafe impl WasmTy for Option<OwnedRooted<AnyRef>> {
795    #[inline]
796    fn valtype() -> ValType {
797        ValType::ANYREF
798    }
799
800    #[inline]
801    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
802        self.as_ref()
803            .map_or(true, |x| x.comes_from_same_store(store))
804    }
805
806    #[inline]
807    fn dynamic_concrete_type_check(
808        &self,
809        store: &StoreOpaque,
810        nullable: bool,
811        ty: &HeapType,
812    ) -> Result<()> {
813        match self {
814            Some(a) => a.ensure_matches_ty(store, ty),
815            None => {
816                ensure!(
817                    nullable,
818                    "expected a non-null reference, but found a null reference"
819                );
820                Ok(())
821            }
822        }
823    }
824
825    #[inline]
826    fn is_vmgcref_and_points_to_object(&self) -> bool {
827        self.is_some()
828    }
829
830    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
831        <OwnedRooted<AnyRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
832    }
833
834    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
835        <OwnedRooted<AnyRef>>::wasm_ty_option_load(
836            store,
837            ptr.get_anyref(),
838            AnyRef::from_cloned_gc_ref,
839        )
840    }
841}