Skip to main content

wasmtime/runtime/gc/enabled/
exnref.rs

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