Skip to main content

wasmtime/runtime/gc/enabled/
structref.rs

1//! Working with GC `struct` objects.
2#![cfg(feature = "gc")]
3
4use crate::runtime::vm::VMGcRef;
5use crate::store::{Asyncness, StoreId};
6#[cfg(feature = "async")]
7use crate::vm::VMStore;
8use crate::vm::{self, VMGcHeader, VMStructRef};
9use crate::{AnyRef, FieldType};
10use crate::{
11    AsContext, AsContextMut, EqRef, GcHeapOutOfMemory, GcRefImpl, GcRootIndex, HeapType,
12    OwnedRooted, RefType, Rooted, StructType, Val, ValRaw, ValType, WasmTy, bail_bug,
13    prelude::*,
14    store::{AutoAssertNoGc, StoreContext, StoreOpaque, StoreResourceLimiter},
15};
16use alloc::sync::Arc;
17use core::mem::{self, MaybeUninit};
18use wasmtime_environ::{GcStructLayout, VMGcKind, VMSharedTypeIndex};
19
20/// An allocator for a particular Wasm GC struct type.
21///
22/// Every `StructRefPre` is associated with a particular
23/// [`Store`][crate::Store] and a particular [StructType][crate::StructType].
24///
25/// Reusing an allocator across many allocations amortizes some per-type runtime
26/// overheads inside Wasmtime. A `StructRefPre` is to `StructRef`s as an
27/// `InstancePre` is to `Instance`s.
28///
29/// # Example
30///
31/// ```
32/// use wasmtime::*;
33///
34/// # fn foo() -> Result<()> {
35/// let mut config = Config::new();
36/// config.wasm_function_references(true);
37/// config.wasm_gc(true);
38///
39/// let engine = Engine::new(&config)?;
40/// let mut store = Store::new(&engine, ());
41///
42/// // Define a struct type.
43/// let struct_ty = StructType::new(
44///    store.engine(),
45///    [FieldType::new(Mutability::Var, StorageType::I8)],
46/// )?;
47///
48/// // Create an allocator for the struct type.
49/// let allocator = StructRefPre::new(&mut store, struct_ty);
50///
51/// {
52///     let mut scope = RootScope::new(&mut store);
53///
54///     // Allocate a bunch of instances of our struct type using the same
55///     // allocator! This is faster than creating a new allocator for each
56///     // instance we want to allocate.
57///     for i in 0..10 {
58///         StructRef::new(&mut scope, &allocator, &[Val::I32(i)])?;
59///     }
60/// }
61/// # Ok(())
62/// # }
63/// # foo().unwrap();
64/// ```
65pub struct StructRefPre {
66    store_id: StoreId,
67    ty: StructType,
68}
69
70impl StructRefPre {
71    /// Create a new `StructRefPre` that is associated with the given store
72    /// and type.
73    ///
74    /// # Panics
75    ///
76    /// Panics if `ty` was not created with the same
77    /// [`Engine`](crate::Engine) as `store`.
78    pub fn new(mut store: impl AsContextMut, ty: StructType) -> Self {
79        Self::_new(store.as_context_mut().0, ty)
80    }
81
82    pub(crate) fn _new(store: &mut StoreOpaque, ty: StructType) -> Self {
83        store.insert_gc_host_alloc_type(ty.registered_type().clone());
84        let store_id = store.id();
85        StructRefPre { store_id, ty }
86    }
87
88    pub(crate) fn layout(&self) -> &GcStructLayout {
89        self.ty
90            .registered_type()
91            .layout()
92            .expect("struct types have a layout")
93            .unwrap_struct()
94    }
95
96    pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
97        self.ty.registered_type().index()
98    }
99}
100
101/// A reference to a GC-managed `struct` instance.
102///
103/// WebAssembly `struct`s are static, fixed-length, ordered sequences of
104/// fields. Fields are named by index, not by identifier; in this way, they are
105/// similar to Rust's tuples. Each field is mutable or constant and stores
106/// unpacked [`Val`][crate::Val]s or packed 8-/16-bit integers.
107///
108/// Like all WebAssembly references, these are opaque and unforgeable to Wasm:
109/// they cannot be faked and Wasm cannot, for example, cast the integer
110/// `0x12345678` into a reference, pretend it is a valid `structref`, and trick
111/// the host into dereferencing it and segfaulting or worse.
112///
113/// Note that you can also use `Rooted<StructRef>` and
114/// `OwnedRooted<StructRef>` as a type parameter with
115/// [`Func::typed`][crate::Func::typed]- and
116/// [`Func::wrap`][crate::Func::wrap]-style APIs.
117///
118/// # Example
119///
120/// ```
121/// use wasmtime::*;
122///
123/// # fn foo() -> Result<()> {
124/// let mut config = Config::new();
125/// config.wasm_function_references(true);
126/// config.wasm_gc(true);
127///
128/// let engine = Engine::new(&config)?;
129/// let mut store = Store::new(&engine, ());
130///
131/// // Define a struct type.
132/// let struct_ty = StructType::new(
133///    store.engine(),
134///    [FieldType::new(Mutability::Var, StorageType::I8)],
135/// )?;
136///
137/// // Create an allocator for the struct type.
138/// let allocator = StructRefPre::new(&mut store, struct_ty);
139///
140/// {
141///     let mut scope = RootScope::new(&mut store);
142///
143///     // Allocate an instance of the struct type.
144///     let my_struct = StructRef::new(&mut scope, &allocator, &[Val::I32(42)])?;
145///
146///     // That instance's field should have the expected value.
147///     let val = my_struct.field(&mut scope, 0)?.unwrap_i32();
148///     assert_eq!(val, 42);
149///
150///     // And we can update the field's value because it is a mutable field.
151///     my_struct.set_field(&mut scope, 0, Val::I32(36))?;
152///     let new_val = my_struct.field(&mut scope, 0)?.unwrap_i32();
153///     assert_eq!(new_val, 36);
154/// }
155/// # Ok(())
156/// # }
157/// # foo().unwrap();
158/// ```
159#[derive(Debug)]
160#[repr(transparent)]
161pub struct StructRef {
162    pub(super) inner: GcRootIndex,
163}
164
165unsafe impl GcRefImpl for StructRef {
166    fn transmute_ref(index: &GcRootIndex) -> &Self {
167        // Safety: `StructRef` is a newtype of a `GcRootIndex`.
168        let me: &Self = unsafe { mem::transmute(index) };
169
170        // Assert we really are just a newtype of a `GcRootIndex`.
171        assert!(matches!(
172            me,
173            Self {
174                inner: GcRootIndex { .. },
175            }
176        ));
177
178        me
179    }
180}
181
182impl Rooted<StructRef> {
183    /// Upcast this `structref` into an `anyref`.
184    #[inline]
185    pub fn to_anyref(self) -> Rooted<AnyRef> {
186        self.unchecked_cast()
187    }
188
189    /// Upcast this `structref` into an `eqref`.
190    #[inline]
191    pub fn to_eqref(self) -> Rooted<EqRef> {
192        self.unchecked_cast()
193    }
194}
195
196impl OwnedRooted<StructRef> {
197    /// Upcast this `structref` into an `anyref`.
198    #[inline]
199    pub fn to_anyref(self) -> OwnedRooted<AnyRef> {
200        self.unchecked_cast()
201    }
202
203    /// Upcast this `structref` into an `eqref`.
204    #[inline]
205    pub fn to_eqref(self) -> OwnedRooted<EqRef> {
206        self.unchecked_cast()
207    }
208}
209
210impl StructRef {
211    /// Synchronously allocate a new `struct` and get a reference to it.
212    ///
213    /// # Automatic Garbage Collection
214    ///
215    /// If the GC heap is at capacity, and there isn't room for allocating this
216    /// new struct, then this method will automatically trigger a synchronous
217    /// collection in an attempt to free up space in the GC heap.
218    ///
219    /// # Errors
220    ///
221    /// If the given `fields` values' types do not match the field types of the
222    /// `allocator`'s struct type, an error is returned.
223    ///
224    /// If the `fields` values holds a GC reference that is not rooted, an error is
225    /// returned, since allocating may collect garbage; see
226    /// [`Val::ensure_rooted`].
227    ///
228    /// If the allocation cannot be satisfied because the GC heap is currently
229    /// out of memory, then a [`GcHeapOutOfMemory<()>`][crate::GcHeapOutOfMemory]
230    /// error is returned. The allocation might succeed on a second attempt if
231    /// you drop some rooted GC references and try again.
232    ///
233    /// If `store` is configured with a
234    /// [`ResourceLimiterAsync`](crate::ResourceLimiterAsync) then an error
235    /// will be returned because [`StructRef::new_async`] should be used
236    /// instead.
237    ///
238    /// # Panics
239    ///
240    /// Panics if the allocator, or any of the field values, is not associated
241    /// with the given store.
242    pub fn new(
243        mut store: impl AsContextMut,
244        allocator: &StructRefPre,
245        fields: &[Val],
246    ) -> Result<Rooted<StructRef>> {
247        let (mut limiter, store) = store
248            .as_context_mut()
249            .0
250            .validate_sync_resource_limiter_and_store_opaque()?;
251        vm::assert_ready(Self::_new_async(
252            store,
253            limiter.as_mut(),
254            allocator,
255            fields,
256            Asyncness::No,
257        ))
258    }
259
260    /// Asynchronously allocate a new `struct` and get a reference to it.
261    ///
262    /// # Automatic Garbage Collection
263    ///
264    /// If the GC heap is at capacity, and there isn't room for allocating this
265    /// new struct, then this method will automatically trigger a synchronous
266    /// collection in an attempt to free up space in the GC heap.
267    ///
268    /// # Errors
269    ///
270    /// If the given `fields` values' types do not match the field types of the
271    /// `allocator`'s struct type, an error is returned.
272    ///
273    /// If the `fields` values holds a GC reference that is not rooted, an error is
274    /// returned, since allocating may collect garbage; see
275    /// [`Val::ensure_rooted`].
276    ///
277    /// If the allocation cannot be satisfied because the GC heap is currently
278    /// out of memory, then a [`GcHeapOutOfMemory<()>`][crate::GcHeapOutOfMemory]
279    /// error is returned. The allocation might succeed on a second attempt if
280    /// you drop some rooted GC references and try again.
281    ///
282    /// # Panics
283    ///
284    /// Panics if the allocator, or any of the field values, is not associated
285    /// with the given store.
286    #[cfg(feature = "async")]
287    pub async fn new_async(
288        mut store: impl AsContextMut,
289        allocator: &StructRefPre,
290        fields: &[Val],
291    ) -> Result<Rooted<StructRef>> {
292        let (mut limiter, store) = store.as_context_mut().0.resource_limiter_and_store_opaque();
293        Self::_new_async(store, limiter.as_mut(), allocator, fields, Asyncness::Yes).await
294    }
295
296    pub(crate) async fn _new_async(
297        store: &mut StoreOpaque,
298        limiter: Option<&mut StoreResourceLimiter<'_>>,
299        allocator: &StructRefPre,
300        fields: &[Val],
301        asyncness: Asyncness,
302    ) -> Result<Rooted<StructRef>> {
303        Self::type_check_fields(store, allocator, fields)?;
304        store
305            .retry_after_gc_async(limiter, (), asyncness, |store, ()| {
306                Self::new_unchecked(store, allocator, fields)
307            })
308            .await
309    }
310
311    /// Type check the field values before allocating a new struct.
312    fn type_check_fields(
313        store: &mut StoreOpaque,
314        allocator: &StructRefPre,
315        fields: &[Val],
316    ) -> Result<(), Error> {
317        let expected_len = allocator.ty.fields().len();
318        let actual_len = fields.len();
319        ensure!(
320            actual_len == expected_len,
321            "expected {expected_len} fields, got {actual_len}"
322        );
323        for (ty, val) in allocator.ty.fields().zip(fields) {
324            assert!(
325                val.comes_from_same_store(store),
326                "field value comes from the wrong store",
327            );
328            // Allocation may collect garbage, so the values must be rooted.
329            val.validate_rooted().context("unrooted field value")?;
330            let ty = ty.element_type().unpack();
331            val.ensure_matches_ty(store, ty)
332                .context("field type mismatch")?;
333        }
334        Ok(())
335    }
336
337    /// Given that the field values have already been type checked, allocate a
338    /// new struct.
339    ///
340    /// Does not attempt GC+retry on OOM, that is the caller's responsibility.
341    fn new_unchecked(
342        store: &mut StoreOpaque,
343        allocator: &StructRefPre,
344        fields: &[Val],
345    ) -> Result<Rooted<StructRef>> {
346        assert_eq!(
347            store.id(),
348            allocator.store_id,
349            "attempted to use a `StructRefPre` with the wrong store"
350        );
351
352        // Allocate the struct and write each field value into the appropriate
353        // offset.
354        let structref = store
355            .require_gc_store_mut()?
356            .alloc_uninit_struct(allocator.type_index(), &allocator.layout())
357            .context("unrecoverable error when allocating new `structref`")?
358            .map_err(|n| GcHeapOutOfMemory::new((), n))?;
359
360        // From this point on, if we get any errors, then the struct is not
361        // fully initialized, so we need to eagerly deallocate it before the
362        // next GC where the collector might try to interpret one of the
363        // uninitialized fields as a GC reference.
364        let mut store = AutoAssertNoGc::new(store);
365        match (|| {
366            for (index, (ty, val)) in allocator.ty.fields().zip(fields).enumerate() {
367                structref.initialize_field(
368                    &mut store,
369                    allocator.layout(),
370                    ty.element_type(),
371                    index,
372                    *val,
373                )?;
374            }
375            Ok(())
376        })() {
377            Ok(()) => Ok(Rooted::new(&mut store, structref.into())),
378            Err(e) => {
379                store
380                    .require_gc_store_mut()?
381                    .dealloc_uninit_struct(structref)?;
382                Err(e)
383            }
384        }
385    }
386
387    #[inline]
388    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
389        self.inner.comes_from_same_store(store)
390    }
391
392    /// Get this `structref`'s type.
393    ///
394    /// # Errors
395    ///
396    /// Return an error if this reference has been unrooted.
397    ///
398    /// # Panics
399    ///
400    /// Panics if this reference is associated with a different store.
401    pub fn ty(&self, store: impl AsContext) -> Result<StructType> {
402        self._ty(store.as_context().0)
403    }
404
405    pub(crate) fn _ty(&self, store: &StoreOpaque) -> Result<StructType> {
406        assert!(self.comes_from_same_store(store));
407        let index = self.type_index(store)?;
408        match StructType::from_shared_type_index(store.engine(), index) {
409            Some(ty) => Ok(ty),
410            None => bail_bug!("invalid struct type index"),
411        }
412    }
413
414    /// Does this `structref` match the given type?
415    ///
416    /// That is, is this struct's type a subtype of the given type?
417    ///
418    /// # Errors
419    ///
420    /// Return an error if this reference has been unrooted.
421    ///
422    /// # Panics
423    ///
424    /// Panics if this reference is associated with a different store or if the
425    /// type is not associated with the store's engine.
426    pub fn matches_ty(&self, store: impl AsContext, ty: &StructType) -> Result<bool> {
427        self._matches_ty(store.as_context().0, ty)
428    }
429
430    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<bool> {
431        assert!(self.comes_from_same_store(store));
432        Ok(self._ty(store)?.matches(ty))
433    }
434
435    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &StructType) -> Result<()> {
436        if !self.comes_from_same_store(store) {
437            bail!("function used with wrong store");
438        }
439        if self._matches_ty(store, ty)? {
440            Ok(())
441        } else {
442            let actual_ty = self._ty(store)?;
443            bail!("type mismatch: expected `(ref {ty})`, found `(ref {actual_ty})`")
444        }
445    }
446
447    /// Get the values of this struct's fields.
448    ///
449    /// Note that `i8` and `i16` field values are zero-extended into
450    /// `Val::I32(_)`s.
451    ///
452    /// GC references are returned as unrooted references
453    /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
454    /// the store's GC heap next changes; root them with
455    /// [`Val::ensure_rooted`] or [`Val::ensure_all_rooted`] to keep them for
456    /// longer.
457    ///
458    /// # Errors
459    ///
460    /// Return an error if this reference has been unrooted.
461    ///
462    /// # Panics
463    ///
464    /// Panics if this reference is associated with a different store.
465    pub fn fields<'a, T: 'static>(
466        &'a self,
467        store: impl Into<StoreContext<'a, T>>,
468    ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
469        self._fields(store.into().0)
470    }
471
472    pub(crate) fn _fields<'a>(
473        &'a self,
474        store: &'a StoreOpaque,
475    ) -> Result<impl ExactSizeIterator<Item = Val> + 'a> {
476        assert!(self.comes_from_same_store(store));
477
478        let gc_ref = self.inner.try_gc_ref(store)?;
479        let header = store.require_gc_store()?.header(gc_ref)?;
480        debug_assert!(header.matches_kind(VMGcKind::StructRef));
481
482        let index = match header.ty() {
483            Some(index) => index,
484            None => bail_bug!("structrefs should have concrete types"),
485        };
486        let ty = match StructType::from_shared_type_index(store.engine(), index) {
487            Some(ty) => ty,
488            None => bail_bug!("invalid struct type index"),
489        };
490        let len = ty.fields().len();
491
492        return Ok(Fields {
493            structref: self,
494            store,
495            index: 0,
496            len,
497        });
498
499        struct Fields<'a> {
500            structref: &'a StructRef,
501            store: &'a StoreOpaque,
502            index: usize,
503            len: usize,
504        }
505
506        impl Iterator for Fields<'_> {
507            type Item = Val;
508
509            #[inline]
510            fn next(&mut self) -> Option<Self::Item> {
511                let i = self.index;
512                debug_assert!(i <= self.len);
513                if i >= self.len {
514                    return None;
515                }
516                self.index += 1;
517                self.structref._field(self.store, i).ok()
518            }
519
520            #[inline]
521            fn size_hint(&self) -> (usize, Option<usize>) {
522                let len = self.len - self.index;
523                (len, Some(len))
524            }
525        }
526
527        impl ExactSizeIterator for Fields<'_> {
528            #[inline]
529            fn len(&self) -> usize {
530                self.len - self.index
531            }
532        }
533    }
534
535    fn header<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMGcHeader> {
536        assert!(self.comes_from_same_store(&store));
537        let gc_ref = self.inner.try_gc_ref(store)?;
538        Ok(store.require_gc_store()?.header(gc_ref)?)
539    }
540
541    fn structref<'a>(&self, store: &'a StoreOpaque) -> Result<&'a VMStructRef> {
542        assert!(self.comes_from_same_store(&store));
543        let gc_ref = self.inner.try_gc_ref(store)?;
544        debug_assert!(self.header(store)?.matches_kind(VMGcKind::StructRef));
545        Ok(gc_ref.as_structref_unchecked())
546    }
547
548    fn layout(&self, store: &StoreOpaque) -> Result<Arc<GcStructLayout>> {
549        assert!(self.comes_from_same_store(&store));
550        let type_index = self.type_index(store)?;
551        super::gc_struct_layout(store.engine(), type_index)
552    }
553
554    fn field_ty(&self, store: &StoreOpaque, field: usize) -> Result<FieldType> {
555        let ty = self._ty(store)?;
556        match ty.field(field) {
557            Some(f) => Ok(f),
558            None => {
559                let len = ty.fields().len();
560                bail!("cannot access field {field}: struct only has {len} fields")
561            }
562        }
563    }
564
565    /// Get this struct's `index`th field.
566    ///
567    /// Note that `i8` and `i16` field values are zero-extended into
568    /// `Val::I32(_)`s.
569    ///
570    /// GC references are returned as unrooted references
571    /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
572    /// the store's GC heap next changes; root them with
573    /// [`Val::ensure_rooted`] or [`Val::ensure_all_rooted`] to keep them for
574    /// longer.
575    ///
576    /// # Errors
577    ///
578    /// Returns an `Err(_)` if the index is out of bounds or this reference has
579    /// been unrooted.
580    ///
581    /// # Panics
582    ///
583    /// Panics if this reference is associated with a different store.
584    pub fn field(&self, store: impl AsContext, index: usize) -> Result<Val> {
585        self._field(store.as_context().0, index)
586    }
587
588    pub(crate) fn _field(&self, store: &StoreOpaque, index: usize) -> Result<Val> {
589        assert!(self.comes_from_same_store(store));
590        let structref = self.structref(store)?;
591        let field_ty = self.field_ty(store, index)?;
592        let layout = self.layout(store)?;
593        structref.read_field(store, &layout, field_ty.element_type(), index)
594    }
595
596    /// Set this struct's `index`th field.
597    ///
598    /// # Errors
599    ///
600    /// Returns an error in the following scenarios:
601    ///
602    /// * When given a value of the wrong type, such as trying to set an `f32`
603    ///   field to an `i64` value.
604    ///
605    /// * When the field is not mutable.
606    ///
607    /// * When this struct does not have an `index`th field, i.e. `index` is out
608    ///   of bounds.
609    ///
610    /// * When `value` is a GC reference that has since been unrooted.
611    ///
612    /// # Panics
613    ///
614    /// Panics if this reference is associated with a different store.
615    pub fn set_field(&self, mut store: impl AsContextMut, index: usize, value: Val) -> Result<()> {
616        self._set_field(store.as_context_mut().0, index, value)
617    }
618
619    pub(crate) fn _set_field(
620        &self,
621        store: &mut StoreOpaque,
622        index: usize,
623        value: Val,
624    ) -> Result<()> {
625        assert!(self.comes_from_same_store(store));
626        value
627            .validate_rooted()
628            .with_context(|| format!("cannot set field {index}: unrooted value"))?;
629        let mut store = AutoAssertNoGc::new(store);
630
631        let field_ty = self.field_ty(&store, index)?;
632        ensure!(
633            field_ty.mutability().is_var(),
634            "cannot set field {index}: field is not mutable"
635        );
636
637        value
638            .ensure_matches_ty(&store, &field_ty.element_type().unpack())
639            .with_context(|| format!("cannot set field {index}: type mismatch"))?;
640
641        let layout = self.layout(&store)?;
642        let structref = self.structref(&store)?.unchecked_copy();
643
644        structref.write_field(&mut store, &layout, field_ty.element_type(), index, value)
645    }
646
647    pub(crate) fn type_index(&self, store: &StoreOpaque) -> Result<VMSharedTypeIndex> {
648        let gc_ref = self.inner.try_gc_ref(store)?;
649        let header = store.require_gc_store()?.header(gc_ref)?;
650        debug_assert!(header.matches_kind(VMGcKind::StructRef));
651        match header.ty() {
652            Some(ty) => Ok(ty),
653            None => bail_bug!("structrefs should have concrete types"),
654        }
655    }
656
657    /// Create a new `Rooted<StructRef>` from the given GC reference.
658    ///
659    /// `gc_ref` should point to a valid `structref` and should belong to the
660    /// store's GC heap. Failure to uphold these invariants is memory safe but
661    /// will lead to general incorrectness such as panics or wrong results.
662    pub(crate) fn from_cloned_gc_ref(
663        store: &mut AutoAssertNoGc<'_>,
664        gc_ref: VMGcRef,
665    ) -> Rooted<Self> {
666        debug_assert!(gc_ref.is_structref(&**store.unwrap_gc_store().gc_heap.get()));
667        Rooted::new(store, gc_ref)
668    }
669}
670
671unsafe impl WasmTy for Rooted<StructRef> {
672    #[inline]
673    fn valtype() -> ValType {
674        ValType::Ref(RefType::new(false, HeapType::Struct))
675    }
676
677    #[inline]
678    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
679        self.comes_from_same_store(store)
680    }
681
682    #[inline]
683    fn dynamic_concrete_type_check(
684        &self,
685        store: &StoreOpaque,
686        _nullable: bool,
687        ty: &HeapType,
688    ) -> Result<()> {
689        match ty {
690            HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()),
691            HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty),
692
693            HeapType::Extern
694            | HeapType::NoExtern
695            | HeapType::Func
696            | HeapType::ConcreteFunc(_)
697            | HeapType::NoFunc
698            | HeapType::I31
699            | HeapType::Array
700            | HeapType::ConcreteArray(_)
701            | HeapType::None
702            | HeapType::NoCont
703            | HeapType::Cont
704            | HeapType::ConcreteCont(_)
705            | HeapType::NoExn
706            | HeapType::Exn => bail!(
707                "type mismatch: expected `(ref {ty})`, got `(ref {})`",
708                self._ty(store)?,
709            ),
710        }
711    }
712
713    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
714        self.wasm_ty_store(store, ptr, ValRaw::anyref)
715    }
716
717    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
718        Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref)
719    }
720}
721
722unsafe impl WasmTy for Option<Rooted<StructRef>> {
723    #[inline]
724    fn valtype() -> ValType {
725        ValType::STRUCTREF
726    }
727
728    #[inline]
729    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
730        self.map_or(true, |x| x.comes_from_same_store(store))
731    }
732
733    #[inline]
734    fn dynamic_concrete_type_check(
735        &self,
736        store: &StoreOpaque,
737        nullable: bool,
738        ty: &HeapType,
739    ) -> Result<()> {
740        match self {
741            Some(s) => Rooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty),
742            None => {
743                ensure!(
744                    nullable,
745                    "expected a non-null reference, but found a null reference"
746                );
747                Ok(())
748            }
749        }
750    }
751
752    #[inline]
753    fn is_vmgcref_and_points_to_object(&self) -> bool {
754        self.is_some()
755    }
756
757    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
758        <Rooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
759    }
760
761    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
762        <Rooted<StructRef>>::wasm_ty_option_load(
763            store,
764            ptr.get_anyref(),
765            StructRef::from_cloned_gc_ref,
766        )
767    }
768}
769
770unsafe impl WasmTy for OwnedRooted<StructRef> {
771    #[inline]
772    fn valtype() -> ValType {
773        ValType::Ref(RefType::new(false, HeapType::Struct))
774    }
775
776    #[inline]
777    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
778        self.comes_from_same_store(store)
779    }
780
781    #[inline]
782    fn dynamic_concrete_type_check(
783        &self,
784        store: &StoreOpaque,
785        _: bool,
786        ty: &HeapType,
787    ) -> Result<()> {
788        match ty {
789            HeapType::Any | HeapType::Eq | HeapType::Struct => Ok(()),
790            HeapType::ConcreteStruct(ty) => self.ensure_matches_ty(store, ty),
791
792            HeapType::Extern
793            | HeapType::NoExtern
794            | HeapType::Func
795            | HeapType::ConcreteFunc(_)
796            | HeapType::NoFunc
797            | HeapType::I31
798            | HeapType::Array
799            | HeapType::ConcreteArray(_)
800            | HeapType::None
801            | HeapType::NoCont
802            | HeapType::Cont
803            | HeapType::ConcreteCont(_)
804            | HeapType::NoExn
805            | HeapType::Exn => bail!(
806                "type mismatch: expected `(ref {ty})`, got `(ref {})`",
807                self._ty(store)?,
808            ),
809        }
810    }
811
812    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
813        self.wasm_ty_store(store, ptr, ValRaw::anyref)
814    }
815
816    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
817        Self::wasm_ty_load(store, ptr.get_anyref(), StructRef::from_cloned_gc_ref)
818    }
819}
820
821unsafe impl WasmTy for Option<OwnedRooted<StructRef>> {
822    #[inline]
823    fn valtype() -> ValType {
824        ValType::STRUCTREF
825    }
826
827    #[inline]
828    fn compatible_with_store(&self, store: &StoreOpaque) -> bool {
829        self.as_ref()
830            .map_or(true, |x| x.comes_from_same_store(store))
831    }
832
833    #[inline]
834    fn dynamic_concrete_type_check(
835        &self,
836        store: &StoreOpaque,
837        nullable: bool,
838        ty: &HeapType,
839    ) -> Result<()> {
840        match self {
841            Some(s) => {
842                OwnedRooted::<StructRef>::dynamic_concrete_type_check(s, store, nullable, ty)
843            }
844            None => {
845                ensure!(
846                    nullable,
847                    "expected a non-null reference, but found a null reference"
848                );
849                Ok(())
850            }
851        }
852    }
853
854    #[inline]
855    fn is_vmgcref_and_points_to_object(&self) -> bool {
856        self.is_some()
857    }
858
859    fn store(self, store: &mut AutoAssertNoGc<'_>, ptr: &mut MaybeUninit<ValRaw>) -> Result<()> {
860        <OwnedRooted<StructRef>>::wasm_ty_option_store(self, store, ptr, ValRaw::anyref)
861    }
862
863    unsafe fn load(store: &mut AutoAssertNoGc<'_>, ptr: &ValRaw) -> Self {
864        <OwnedRooted<StructRef>>::wasm_ty_option_load(
865            store,
866            ptr.get_anyref(),
867            StructRef::from_cloned_gc_ref,
868        )
869    }
870}