Skip to main content

wasmtime/runtime/component/func/
typed.rs

1use crate::component::Instance;
2use crate::component::func::{Func, LiftContext, LowerContext};
3use crate::component::matching::InstanceType;
4use crate::component::storage::{storage_as_slice, storage_as_slice_mut};
5use crate::hash_map::HashMap;
6use crate::prelude::*;
7use crate::{AsContextMut, StoreContext, StoreContextMut, ValRaw};
8use alloc::borrow::Cow;
9use alloc::collections::BTreeMap;
10use core::fmt;
11use core::hash::{BuildHasher, Hash};
12use core::iter;
13use core::marker;
14use core::mem::{self, MaybeUninit};
15use core::str;
16use indexmap::IndexMap;
17use wasmtime_core::array::array_try_from_fn;
18use wasmtime_environ::component::{
19    CanonicalAbiInfo, ComponentTypes, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS,
20    OptionsIndex, StringEncoding, TypeMap, VariantInfo,
21};
22
23/// A statically-typed version of [`Func`] which takes `Params` as input and
24/// returns `Return`.
25///
26/// This is an efficient way to invoke a WebAssembly component where if the
27/// inputs and output are statically known this can eschew the vast majority of
28/// machinery and checks when calling WebAssembly. This is the most optimized
29/// way to call a WebAssembly component.
30///
31/// Note that like [`Func`] this is a pointer within a [`Store`](crate::Store)
32/// and usage will panic if used with the wrong store.
33///
34/// This type is primarily created with the [`Func::typed`] API.
35///
36/// See [`ComponentType`] for more information about supported types.
37pub struct TypedFunc<Params, Return> {
38    func: Func,
39
40    // The definition of this field is somewhat subtle and may be surprising.
41    // Naively one might expect something like
42    //
43    //      _marker: marker::PhantomData<fn(Params) -> Return>,
44    //
45    // Since this is a function pointer after all. The problem with this
46    // definition though is that it imposes the wrong variance on `Params` from
47    // what we want. Abstractly a `fn(Params)` is able to store `Params` within
48    // it meaning you can only give it `Params` that live longer than the
49    // function pointer.
50    //
51    // With a component model function, however, we're always copying data from
52    // the host into the guest, so we are never storing pointers to `Params`
53    // into the guest outside the duration of a `call`, meaning we can actually
54    // accept values in `TypedFunc::call` which live for a shorter duration
55    // than the `Params` argument on the struct.
56    //
57    // This all means that we don't use a phantom function pointer, but instead
58    // feign phantom storage here to get the variance desired.
59    _marker: marker::PhantomData<(Params, Return)>,
60}
61
62impl<Params, Return> Copy for TypedFunc<Params, Return> {}
63
64impl<Params, Return> Clone for TypedFunc<Params, Return> {
65    fn clone(&self) -> TypedFunc<Params, Return> {
66        *self
67    }
68}
69
70impl<Params, Return> TypedFunc<Params, Return>
71where
72    Params: ComponentNamedList + Lower,
73    Return: ComponentNamedList + Lift,
74{
75    /// Creates a new [`TypedFunc`] from the provided component [`Func`],
76    /// unsafely asserting that the underlying function takes `Params` as
77    /// input and returns `Return`.
78    ///
79    /// # Unsafety
80    ///
81    /// This is an unsafe function because it does not verify that the [`Func`]
82    /// provided actually implements this signature. It's up to the caller to
83    /// have performed some other sort of check to ensure that the signature is
84    /// correct.
85    pub unsafe fn new_unchecked(func: Func) -> TypedFunc<Params, Return> {
86        TypedFunc {
87            _marker: marker::PhantomData,
88            func,
89        }
90    }
91
92    /// Returns the underlying un-typed [`Func`] that this [`TypedFunc`]
93    /// references.
94    pub fn func(&self) -> &Func {
95        &self.func
96    }
97
98    /// Calls the underlying WebAssembly component function using the provided
99    /// `params` as input.
100    ///
101    /// This method is used to enter into a component. Execution happens within
102    /// the `store` provided. The `params` are copied into WebAssembly memory
103    /// as appropriate and a core wasm function is invoked.
104    ///
105    /// # Post-return
106    ///
107    /// In the component model each function can have a "post return" specified
108    /// which allows cleaning up the arguments returned to the host. For example
109    /// if WebAssembly returns a string to the host then it might be a uniquely
110    /// allocated string which, after the host finishes processing it, needs to
111    /// be deallocated in the wasm instance's own linear memory to prevent
112    /// memory leaks in wasm itself. The `post-return` canonical abi option is
113    /// used to configured this.
114    ///
115    /// If a post-return function is present, it will be called automatically by
116    /// this function.
117    ///
118    /// # Errors
119    ///
120    /// This function can return an error for a number of reasons:
121    ///
122    /// * If the wasm itself traps during execution.
123    /// * If the wasm traps while copying arguments into memory.
124    /// * If the wasm provides bad allocation pointers when copying arguments
125    ///   into memory.
126    /// * If the wasm returns a value which violates the canonical ABI.
127    /// * If this function's instances cannot be entered, for example if the
128    ///   instance is currently calling a host function.
129    /// * If `store` requires using [`Self::call_async`] instead, see
130    ///   [crate documentation](crate#async) for more info.
131    /// * The call is recursive from within e.g. a `call_async` invocation.
132    /// * If the function is async-typed or async-lifted, in which case either
133    ///   [`Self::call_async`] or [`Self::call_concurrent`] must be used.
134    ///
135    /// In general there are many ways that things could go wrong when copying
136    /// types in and out of a wasm module with the canonical ABI, and certain
137    /// error conditions are specific to certain types. For example a
138    /// WebAssembly module can't return an invalid `char`. When allocating space
139    /// for this host to copy a string into the returned pointer must be
140    /// in-bounds in memory.
141    ///
142    /// If an error happens then the error should contain detailed enough
143    /// information to understand which part of the canonical ABI went wrong
144    /// and what to inspect.
145    ///
146    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
147    /// memory allocation fails. See the `OutOfMemory` type's documentation for
148    /// details on Wasmtime's out-of-memory handling.
149    ///
150    /// # Panics
151    ///
152    /// Panics if `store` does not own this function.
153    pub fn call(&self, mut store: impl AsContextMut, params: Params) -> Result<Return> {
154        let mut store = store.as_context_mut();
155        store.0.validate_sync_call()?;
156        self.call_impl(store.as_context_mut(), params)
157    }
158
159    /// Exactly like [`Self::call`], except for invoking WebAssembly
160    /// [asynchronously](crate#async).
161    ///
162    /// # Errors
163    ///
164    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
165    /// memory allocation fails. See the `OutOfMemory` type's documentation for
166    /// details on Wasmtime's out-of-memory handling.
167    ///
168    /// # Panics
169    ///
170    /// Panics if `store` does not own this function.
171    #[cfg(feature = "async")]
172    pub async fn call_async(
173        &self,
174        mut store: impl AsContextMut<Data: Send>,
175        params: Params,
176    ) -> Result<Return>
177    where
178        Return: 'static,
179    {
180        let mut store = store.as_context_mut();
181
182        #[cfg(feature = "component-model-async")]
183        if store.0.concurrency_support() {
184            return self.call_async_concurrent(store, params).await;
185        }
186
187        store
188            .on_fiber(|store| self.call_impl(store, params))
189            .await?
190    }
191
192    pub(crate) fn lower_args<T>(
193        cx: &mut LowerContext<T>,
194        ty: InterfaceType,
195        dst: &mut [MaybeUninit<ValRaw>],
196        params: &Params,
197    ) -> Result<()> {
198        use crate::component::storage::slice_to_storage_mut;
199
200        if Params::flatten_count() <= MAX_FLAT_PARAMS {
201            // SAFETY: the safety of `slice_to_storage_mut` relies on
202            // `Params::Lower` being represented by a sequence of
203            // `ValRaw`, and that's a guarantee upheld by the `Lower`
204            // trait itself.
205            let dst: &mut MaybeUninit<Params::Lower> = unsafe { slice_to_storage_mut(dst) };
206            Self::lower_stack_args(cx, &params, ty, dst)
207        } else {
208            Self::lower_heap_args(cx, &params, ty, &mut dst[0])
209        }
210    }
211
212    fn call_impl(&self, mut store: impl AsContextMut, params: Params) -> Result<Return> {
213        let mut store = store.as_context_mut();
214
215        if self.func.is_async(store.0) {
216            bail!(
217                "cannot synchronously call an async function; \
218                 use `call_async` or `call_concurrent` instead"
219            );
220        }
221
222        // Note that this is in theory simpler than it might read at this time.
223        // Here we're doing a runtime dispatch on the `flatten_count` for the
224        // params/results to see whether they're inbounds. This creates 4 cases
225        // to handle. In reality this is a highly optimizable branch where LLVM
226        // will easily figure out that only one branch here is taken.
227        //
228        // Otherwise this current construction is done to ensure that the stack
229        // space reserved for the params/results is always of the appropriate
230        // size (as the params/results needed differ depending on the "flatten"
231        // count)
232        //
233        // SAFETY: the safety of these invocations of `call_raw` depends on the
234        // correctness of the ascription of the `LowerParams` and `LowerReturn`
235        // types on the `call_raw` function. That's upheld here through the
236        // safety requirements of `Lift` and `Lower` on `Params` and `Return` in
237        // combination with checking the various possible branches here and
238        // dispatching to appropriately typed functions.
239        let result = unsafe {
240            // This type is used as `LowerParams` for `call_raw` which is either
241            // `Params::Lower` or `ValRaw` representing it's either on the stack
242            // or it's on the heap. This allocates 1 extra `ValRaw` on the stack
243            // if `Params` is empty and `Return` is also empty, but that's a
244            // reasonable enough price to pay for now given the current code
245            // organization.
246            #[derive(Copy, Clone)]
247            union Union<T: Copy, U: Copy> {
248                _a: T,
249                _b: U,
250            }
251
252            if Return::flatten_count() <= MAX_FLAT_RESULTS {
253                self.func.call_raw(
254                    store.as_context_mut(),
255                    |cx, ty, dst: &mut MaybeUninit<Union<Params::Lower, ValRaw>>| {
256                        let dst = storage_as_slice_mut(dst);
257                        Self::lower_args(cx, ty, dst, &params)
258                    },
259                    Self::lift_stack_result,
260                )
261            } else {
262                self.func.call_raw(
263                    store.as_context_mut(),
264                    |cx, ty, dst: &mut MaybeUninit<Union<Params::Lower, ValRaw>>| {
265                        let dst = storage_as_slice_mut(dst);
266                        Self::lower_args(cx, ty, dst, &params)
267                    },
268                    Self::lift_heap_result,
269                )
270            }
271        };
272
273        if result.is_err() {
274            store.0.set_trapped();
275        }
276
277        result
278    }
279
280    /// Lower parameters directly onto the stack specified by the `dst`
281    /// location.
282    ///
283    /// This is only valid to call when the "flatten count" is small enough, or
284    /// when the canonical ABI says arguments go through the stack rather than
285    /// the heap.
286    fn lower_stack_args<T>(
287        cx: &mut LowerContext<'_, T>,
288        params: &Params,
289        ty: InterfaceType,
290        dst: &mut MaybeUninit<Params::Lower>,
291    ) -> Result<()> {
292        assert!(Params::flatten_count() <= MAX_FLAT_PARAMS);
293        params.linear_lower_to_flat(cx, ty, dst)?;
294        Ok(())
295    }
296
297    /// Lower parameters onto a heap-allocated location.
298    ///
299    /// This is used when the stack space to be used for the arguments is above
300    /// the `MAX_FLAT_PARAMS` threshold. Here the wasm's `realloc` function is
301    /// invoked to allocate space and then parameters are stored at that heap
302    /// pointer location.
303    fn lower_heap_args<T>(
304        cx: &mut LowerContext<'_, T>,
305        params: &Params,
306        ty: InterfaceType,
307        dst: &mut MaybeUninit<ValRaw>,
308    ) -> Result<()> {
309        // Memory must exist via validation if the arguments are stored on the
310        // heap, so we can create a `MemoryMut` at this point. Afterwards
311        // `realloc` is used to allocate space for all the arguments and then
312        // they're all stored in linear memory.
313        //
314        // Note that `realloc` will bake in a check that the returned pointer is
315        // in-bounds.
316        let ptr = cx.realloc(0, 0, Params::ALIGN32, Params::SIZE32)?;
317        params.linear_lower_to_memory(cx, ty, ptr)?;
318
319        // Note that the pointer here is stored as a 64-bit integer. This allows
320        // this to work with either 32 or 64-bit memories. For a 32-bit memory
321        // it'll just ignore the upper 32 zero bits, and for 64-bit memories
322        // this'll have the full 64-bits. Note that for 32-bit memories the call
323        // to `realloc` above guarantees that the `ptr` is in-bounds meaning
324        // that we will know that the zero-extended upper bits of `ptr` are
325        // guaranteed to be zero.
326        //
327        // This comment about 64-bit integers is also referred to below with
328        // "WRITEPTR64".
329        dst.write(ValRaw::i64(ptr as i64));
330
331        Ok(())
332    }
333
334    /// Lift the result of a function directly from the stack result.
335    ///
336    /// This is only used when the result fits in the maximum number of stack
337    /// slots.
338    pub(crate) fn lift_stack_result(
339        cx: &mut LiftContext<'_>,
340        ty: InterfaceType,
341        dst: &Return::Lower,
342    ) -> Result<Return> {
343        Return::linear_lift_from_flat(cx, ty, dst)
344    }
345
346    /// Lift the result of a function where the result is stored indirectly on
347    /// the heap.
348    pub(crate) fn lift_heap_result(
349        cx: &mut LiftContext<'_>,
350        ty: InterfaceType,
351        dst: &ValRaw,
352    ) -> Result<Return> {
353        assert!(Return::flatten_count() > MAX_FLAT_RESULTS);
354        // FIXME(#4311): needs to read an i64 for memory64
355        let ptr = usize::try_from(dst.get_u32())?;
356        if ptr % usize::try_from(Return::ALIGN32)? != 0 {
357            bail!("return pointer not aligned");
358        }
359
360        let bytes = cx
361            .memory()
362            .get(ptr..)
363            .and_then(|b| b.get(..Return::SIZE32))
364            .ok_or_else(|| crate::format_err!("pointer out of bounds of memory"))?;
365        Return::linear_lift_from_memory(cx, ty, bytes)
366    }
367
368    #[doc(hidden)]
369    #[deprecated(note = "no longer needs to be called; this function has no effect")]
370    pub fn post_return(&self, _store: impl AsContextMut) -> Result<()> {
371        Ok(())
372    }
373
374    #[doc(hidden)]
375    #[deprecated(note = "no longer needs to be called; this function has no effect")]
376    #[cfg(feature = "async")]
377    pub async fn post_return_async<T: Send>(
378        &self,
379        _store: impl AsContextMut<Data = T>,
380    ) -> Result<()> {
381        Ok(())
382    }
383}
384
385/// A trait representing a static list of named types that can be passed to or
386/// returned from a [`TypedFunc`].
387///
388/// This trait is implemented for a number of tuple types and is not expected
389/// to be implemented externally. The contents of this trait are hidden as it's
390/// intended to be an implementation detail of Wasmtime. The contents of this
391/// trait are not covered by Wasmtime's stability guarantees.
392///
393/// For more information about this trait see [`Func::typed`] and
394/// [`TypedFunc`].
395//
396// Note that this is an `unsafe` trait, and the unsafety means that
397// implementations of this trait must be correct or otherwise [`TypedFunc`]
398// would not be memory safe. The main reason this is `unsafe` is the
399// `typecheck` function which must operate correctly relative to the `AsTuple`
400// interpretation of the implementor.
401pub unsafe trait ComponentNamedList: ComponentType {}
402
403/// A trait representing types which can be passed to and read from components
404/// with the canonical ABI.
405///
406/// This trait is implemented for Rust types which can be communicated to
407/// components. The [`Func::typed`] and [`TypedFunc`] Rust items are the main
408/// consumers of this trait.
409///
410/// Supported Rust types include:
411///
412/// | Component Model Type              | Rust Type                            |
413/// |-----------------------------------|--------------------------------------|
414/// | `{s,u}{8,16,32,64}`               | `{i,u}{8,16,32,64}`                  |
415/// | `f{32,64}`                        | `f{32,64}`                           |
416/// | `bool`                            | `bool`                               |
417/// | `char`                            | `char`                               |
418/// | `tuple<A, B>`                     | `(A, B)`                             |
419/// | `option<T>`                       | `Option<T>`                          |
420/// | `result`                          | `Result<(), ()>`                     |
421/// | `result<T>`                       | `Result<T, ()>`                      |
422/// | `result<_, E>`                    | `Result<(), E>`                      |
423/// | `result<T, E>`                    | `Result<T, E>`                       |
424/// | `string`                          | `String`, `&str`, or [`WasmStr`]     |
425/// | `list<T>`                         | `Vec<T>`, `&[T]`, or [`WasmList`]    |
426/// | `map<K, V>`                       | `HashMap<K, V, S>`, `BTreeMap<K, V>`, or `IndexMap<K, V, S>` |
427/// | `own<T>`, `borrow<T>`             | [`Resource<T>`] or [`ResourceAny`]   |
428/// | `record`                          | [`#[derive(ComponentType)]`][d-cm]   |
429/// | `variant`                         | [`#[derive(ComponentType)]`][d-cm]   |
430/// | `enum`                            | [`#[derive(ComponentType)]`][d-cm]   |
431/// | `flags`                           | [`flags!`][f-m]                      |
432///
433/// [`Resource<T>`]: crate::component::Resource
434/// [`ResourceAny`]: crate::component::ResourceAny
435/// [d-cm]: macro@crate::component::ComponentType
436/// [f-m]: crate::component::flags
437/// [`Val::Map`]: crate::component::Val::Map
438///
439/// Rust standard library pointers such as `&T`, `Box<T>`, and `Arc<T>`
440/// additionally represent whatever type `T` represents in the component model.
441/// Note that types such as `record`, `variant`, `enum`, and `flags` are
442/// generated by the embedder at compile time. These macros derive
443/// implementation of this trait for custom types to map to custom types in the
444/// component model. Note that for `record`, `variant`, `enum`, and `flags`
445/// those types are often generated by the
446/// [`bindgen!`](crate::component::bindgen) macro from WIT definitions.
447///
448/// Lifting a `map<K, V>` keeps only the last value for each duplicate key. Use
449/// [`Val::Map`] to see every entry in order instead.
450///
451/// Types that implement [`ComponentType`] are used for `Params` and `Return`
452/// in [`TypedFunc`] and [`Func::typed`].
453///
454/// The contents of this trait are hidden as it's intended to be an
455/// implementation detail of Wasmtime. The contents of this trait are not
456/// covered by Wasmtime's stability guarantees.
457///
458/// # Safety
459///
460/// Note that this is an `unsafe` trait as `TypedFunc`'s safety heavily relies on
461/// the correctness of the implementations of this trait. Some ways in which this
462/// trait must be correct to be safe are:
463///
464/// * The `Lower` associated type must be a `ValRaw` sequence. It doesn't have to
465///   literally be `[ValRaw; N]` but when laid out in memory it must be adjacent
466///   `ValRaw` values and have a multiple of the size of `ValRaw` and the same
467///   alignment.
468///
469/// * The `lower` function must initialize the bits within `Lower` that are going
470///   to be read by the trampoline that's used to enter core wasm. A trampoline
471///   is passed `*mut Lower` and will read the canonical abi arguments in
472///   sequence, so all of the bits must be correctly initialized.
473///
474/// * The `size` and `align` functions must be correct for this value stored in
475///   the canonical ABI. The `Cursor<T>` iteration of these bytes rely on this
476///   for correctness as they otherwise eschew bounds-checking.
477///
478/// There are likely some other correctness issues which aren't documented as
479/// well, this isn't currently an exhaustive list. It suffices to say, though,
480/// that correctness bugs in this trait implementation are highly likely to
481/// lead to security bugs, which again leads to the `unsafe` in the trait.
482///
483/// Note that this trait specifically is not sealed because `bindgen!`-generated
484/// types must be able to implement this trait using a `#[derive]` macro. For
485/// users it's recommended to not implement this trait manually given the
486/// non-exhaustive list of safety requirements that must be upheld. This trait
487/// is implemented at your own risk if you do so.
488///
489/// # Send and Sync
490///
491/// While on the topic of safety it's worth discussing the `Send` and `Sync`
492/// bounds here as well. These bounds might naively seem like they shouldn't be
493/// required for all component types as they're host-level types not guest-level
494/// types persisted anywhere. Various subtleties lead to these bounds, however:
495///
496/// * Fibers require that all stack-local variables are `Send` and `Sync` for
497///   fibers themselves to be send/sync. Unfortunately we have no help from the
498///   compiler on this one so it's up to Wasmtime's discipline to maintain this.
499///   One instance of this is that return values are placed on the stack as
500///   they're lowered into guest memory. This lowering operation can involve
501///   malloc and context switches, so return values must be Send/Sync.
502///
503/// * In the implementation of component model async it's not uncommon for types
504///   to be "buffered" in the store temporarily. For example parameters might
505///   reside in a store temporarily while wasm has backpressure turned on.
506///
507/// Overall it's generally easiest to require `Send` and `Sync` for all
508/// component types. There additionally aren't known use case for non-`Send` or
509/// non-`Sync` types at this time.
510pub unsafe trait ComponentType: Send + Sync {
511    /// Representation of the "lowered" form of this component value.
512    ///
513    /// Lowerings lower into core wasm values which are represented by `ValRaw`.
514    /// This `Lower` type must be a list of `ValRaw` as either a literal array
515    /// or a struct where every field is a `ValRaw`. This must be `Copy` (as
516    /// `ValRaw` is `Copy`) and support all byte patterns. This being correct is
517    /// one reason why the trait is unsafe.
518    #[doc(hidden)]
519    type Lower: Copy;
520
521    /// The information about this type's canonical ABI (size/align/etc).
522    #[doc(hidden)]
523    const ABI: CanonicalAbiInfo;
524
525    #[doc(hidden)]
526    const SIZE32: usize = Self::ABI.size32 as usize;
527    #[doc(hidden)]
528    const ALIGN32: u32 = Self::ABI.align32;
529
530    #[doc(hidden)]
531    const IS_RUST_UNIT_TYPE: bool = false;
532
533    /// Whether this type might require a call to the guest's realloc function
534    /// to allocate linear memory when lowering (e.g. a non-empty `string`).
535    ///
536    /// If this is `false`, Wasmtime may optimize lowering by using
537    /// `LowerContext::new_without_realloc` and lowering values outside of any
538    /// fiber.  That will panic if the lowering process ends up needing realloc
539    /// after all, so `true` is a conservative default.
540    #[doc(hidden)]
541    const MAY_REQUIRE_REALLOC: bool = true;
542
543    /// Returns the number of core wasm abi values will be used to represent
544    /// this type in its lowered form.
545    ///
546    /// This divides the size of `Self::Lower` by the size of `ValRaw`.
547    #[doc(hidden)]
548    fn flatten_count() -> usize {
549        assert!(mem::size_of::<Self::Lower>() % mem::size_of::<ValRaw>() == 0);
550        assert!(mem::align_of::<Self::Lower>() == mem::align_of::<ValRaw>());
551        mem::size_of::<Self::Lower>() / mem::size_of::<ValRaw>()
552    }
553
554    /// Performs a type-check to see whether this component value type matches
555    /// the interface type `ty` provided.
556    #[doc(hidden)]
557    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()>;
558}
559
560#[doc(hidden)]
561pub unsafe trait ComponentVariant: ComponentType {
562    const CASES: &'static [Option<CanonicalAbiInfo>];
563    const INFO: VariantInfo = VariantInfo::new_static(Self::CASES);
564    const PAYLOAD_OFFSET32: usize = Self::INFO.payload_offset32 as usize;
565}
566
567/// Host types which can be passed to WebAssembly components.
568///
569/// This trait is implemented for all types that can be passed to components
570/// either as parameters of component exports or returns of component imports.
571/// This trait represents the ability to convert from the native host
572/// representation to the canonical ABI.
573///
574/// Built-in types to Rust such as `Option<T>` implement this trait as
575/// appropriate. For a mapping of component model to Rust types see
576/// [`ComponentType`].
577///
578/// For user-defined types, for example `record` types mapped to Rust `struct`s,
579/// this crate additionally has
580/// [`#[derive(Lower)]`](macro@crate::component::Lower).
581///
582/// Note that like [`ComponentType`] the definition of this trait is intended to
583/// be an internal implementation detail of Wasmtime at this time. It's
584/// recommended to use the `#[derive(Lower)]` implementation instead.
585pub unsafe trait Lower: ComponentType {
586    /// Performs the "lower" function in the linear memory version of the
587    /// canonical ABI.
588    ///
589    /// This method will lower the current value into a component. The `lower`
590    /// function performs a "flat" lowering into the `dst` specified which is
591    /// allowed to be uninitialized entering this method but is guaranteed to be
592    /// fully initialized if the method returns `Ok(())`.
593    ///
594    /// The `cx` context provided is the context within which this lowering is
595    /// happening. This contains information such as canonical options specified
596    /// (e.g. string encodings, memories, etc), the store itself, along with
597    /// type information.
598    ///
599    /// The `ty` parameter is the destination type that is being lowered into.
600    /// For example this is the component's "view" of the type that is being
601    /// lowered. This is guaranteed to have passed a `typecheck` earlier.
602    ///
603    /// It is invalid to call this unless `T::typecheck` passes for `ty`.
604    #[doc(hidden)]
605    fn linear_lower_to_flat<T>(
606        &self,
607        cx: &mut LowerContext<'_, T>,
608        ty: InterfaceType,
609        dst: &mut MaybeUninit<Self::Lower>,
610    ) -> Result<()>;
611
612    /// Performs the "store" operation in the linear memory version of the
613    /// canonical ABI.
614    ///
615    /// This function will store `self` into the linear memory described by
616    /// `cx` at the `offset` provided.
617    ///
618    /// It is expected that `offset` is a valid offset in memory for
619    /// `Self::SIZE32` bytes. At this time that's not an unsafe contract as it's
620    /// always re-checked on all stores, but this is something that will need to
621    /// be improved in the future to remove extra bounds checks. For now this
622    /// function will panic if there's a bug and `offset` isn't valid within
623    /// memory.
624    ///
625    /// The `ty` type information passed here is the same as the type
626    /// information passed to `lower` above, and is the component's own view of
627    /// what the resulting type should be.
628    ///
629    /// It is invalid to call this unless `T::typecheck` passes for `ty`.
630    #[doc(hidden)]
631    fn linear_lower_to_memory<T>(
632        &self,
633        cx: &mut LowerContext<'_, T>,
634        ty: InterfaceType,
635        offset: usize,
636    ) -> Result<()>;
637
638    /// Provided method to lower a list of `Self` into memory.
639    ///
640    /// Requires that `offset` has already been checked for alignment and
641    /// validity in terms of being in-bounds, otherwise this may panic.
642    ///
643    /// This is primarily here to get overridden for implementations of integers
644    /// which can avoid some extra fluff and use a pattern that's more easily
645    /// optimizable by LLVM.
646    ///
647    /// It is invalid to call this unless `T::typecheck` passes for `ty`.
648    #[doc(hidden)]
649    fn linear_store_list_to_memory<T>(
650        cx: &mut LowerContext<'_, T>,
651        ty: InterfaceType,
652        mut offset: usize,
653        items: &[Self],
654    ) -> Result<()>
655    where
656        Self: Sized,
657    {
658        for item in items {
659            item.linear_lower_to_memory(cx, ty, offset)?;
660            offset += Self::SIZE32;
661        }
662        Ok(())
663    }
664}
665
666/// Host types which can be created from the canonical ABI.
667///
668/// This is the mirror of the [`Lower`] trait where it represents the capability
669/// of acquiring items from WebAssembly and passing them to the host.
670///
671/// Built-in types to Rust such as `Option<T>` implement this trait as
672/// appropriate. For a mapping of component model to Rust types see
673/// [`ComponentType`].
674///
675/// For user-defined types, for example `record` types mapped to Rust `struct`s,
676/// this crate additionally has
677/// [`#[derive(Lift)]`](macro@crate::component::Lift).
678///
679/// Note that like [`ComponentType`] the definition of this trait is intended to
680/// be an internal implementation detail of Wasmtime at this time. It's
681/// recommended to use the `#[derive(Lift)]` implementation instead.
682pub unsafe trait Lift: Sized + ComponentType {
683    /// Performs the "lift" operation in the linear memory version of the
684    /// canonical ABI.
685    ///
686    /// This function performs a "flat" lift operation from the `src` specified
687    /// which is a sequence of core wasm values. The lifting operation will
688    /// validate core wasm values and produce a `Self` on success.
689    ///
690    /// The `cx` provided contains contextual information such as the store
691    /// that's being loaded from, canonical options, and type information.
692    ///
693    /// The `ty` parameter is the origin component's specification for what the
694    /// type that is being lifted is. For example this is the record type or the
695    /// resource type that is being lifted.
696    ///
697    /// Note that this has a default implementation but if `typecheck` passes
698    /// for `Op::Lift` this needs to be overridden.
699    #[doc(hidden)]
700    fn linear_lift_from_flat(
701        cx: &mut LiftContext<'_>,
702        ty: InterfaceType,
703        src: &Self::Lower,
704    ) -> Result<Self>;
705
706    /// Performs the "load" operation in the linear memory version of the
707    /// canonical ABI.
708    ///
709    /// This will read the `bytes` provided, which are a sub-slice into the
710    /// linear memory described by `cx`. The `bytes` array provided is
711    /// guaranteed to be `Self::SIZE32` bytes large. All of memory is then also
712    /// available through `cx` for bounds-checks and such as necessary for
713    /// strings/lists.
714    ///
715    /// The `ty` argument is the type that's being loaded, as described by the
716    /// original component.
717    ///
718    /// Note that this has a default implementation but if `typecheck` passes
719    /// for `Op::Lift` this needs to be overridden.
720    #[doc(hidden)]
721    fn linear_lift_from_memory(
722        cx: &mut LiftContext<'_>,
723        ty: InterfaceType,
724        bytes: &[u8],
725    ) -> Result<Self>;
726
727    /// Converts `list` into a `Vec<T>`, used in `Lift for Vec<T>`.
728    #[doc(hidden)]
729    fn linear_lift_list_from_memory(
730        cx: &mut LiftContext<'_>,
731        list: &WasmList<Self>,
732    ) -> Result<Vec<Self>>
733    where
734        Self: Sized,
735    {
736        let mut dst = Vec::with_capacity(list.len);
737        Self::linear_lift_into_from_memory(cx, list, &mut dst)?;
738        Ok(dst)
739    }
740
741    /// Load no more than `max_count` items from `list` into `dst`.
742    ///
743    /// This is primarily here to get overridden for implementations of integers
744    /// which can avoid some extra fluff and use a pattern that's more easily
745    /// optimizable by LLVM.
746    #[doc(hidden)]
747    fn linear_lift_into_from_memory(
748        cx: &mut LiftContext<'_>,
749        list: &WasmList<Self>,
750        dst: &mut impl Extend<Self>,
751    ) -> Result<()>
752    where
753        Self: Sized,
754    {
755        for i in 0..list.len {
756            dst.extend(Some(list.get_from_store(cx, i).unwrap()?));
757        }
758        Ok(())
759    }
760}
761
762// Macro to help generate "forwarding implementations" of `ComponentType` to
763// another type, used for wrappers in Rust like `&T`, `Box<T>`, etc. Note that
764// these wrappers only implement lowering because lifting native Rust types
765// cannot be done.
766macro_rules! forward_type_impls {
767    ($(
768        $(#[$attr:meta])*
769        ($($generics:tt)*) $a:ty => $b:ty,
770    )*) => ($(
771        $(#[$attr])*
772        unsafe impl <$($generics)*> ComponentType for $a {
773            type Lower = <$b as ComponentType>::Lower;
774
775            const ABI: CanonicalAbiInfo = <$b as ComponentType>::ABI;
776            const MAY_REQUIRE_REALLOC: bool = <$b as ComponentType>::MAY_REQUIRE_REALLOC;
777
778            #[inline]
779            fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
780                <$b as ComponentType>::typecheck(ty, types)
781            }
782        }
783    )*)
784}
785
786forward_type_impls! {
787    (T: ComponentType + ?Sized) &'_ T => T,
788    (T: ComponentType + ?Sized) Box<T> => T,
789    (T: ComponentType + ?Sized) alloc::sync::Arc<T> => T,
790    () String => str,
791    (T: ComponentType) Vec<T> => [T],
792    #[cfg(feature = "component-model-bytes")]
793    () bytes::Bytes => [u8],
794    #[cfg(feature = "component-model-bytes")]
795    () bytes::BytesMut => [u8],
796}
797
798macro_rules! forward_lowers {
799    ($(
800        $(#[$attr:meta])*
801        ($($generics:tt)*) $a:ty => $b:ty,
802    )*) => ($(
803        $(#[$attr])*
804        unsafe impl <$($generics)*> Lower for $a {
805            fn linear_lower_to_flat<U>(
806                &self,
807                cx: &mut LowerContext<'_, U>,
808                ty: InterfaceType,
809                dst: &mut MaybeUninit<Self::Lower>,
810            ) -> Result<()> {
811                <$b as Lower>::linear_lower_to_flat(self, cx, ty, dst)
812            }
813
814            fn linear_lower_to_memory<U>(
815                &self,
816                cx: &mut LowerContext<'_, U>,
817                ty: InterfaceType,
818                offset: usize,
819            ) -> Result<()> {
820                <$b as Lower>::linear_lower_to_memory(self, cx, ty, offset)
821            }
822        }
823    )*)
824}
825
826forward_lowers! {
827    (T: Lower + ?Sized) &'_ T => T,
828    (T: Lower + ?Sized) Box<T> => T,
829    (T: Lower + ?Sized) alloc::sync::Arc<T> => T,
830    () String => str,
831    (T: Lower) Vec<T> => [T],
832    #[cfg(feature = "component-model-bytes")]
833    () bytes::Bytes => [u8],
834    #[cfg(feature = "component-model-bytes")]
835    () bytes::BytesMut => [u8],
836}
837
838macro_rules! forward_string_lifts {
839    ($($a:ty,)*) => ($(
840        unsafe impl Lift for $a {
841            #[inline]
842            fn linear_lift_from_flat(cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
843                let s = <WasmStr as Lift>::linear_lift_from_flat(cx, ty, src)?;
844                let encoding = cx.options().string_encoding;
845                Ok(s.to_str_from_memory(encoding, cx.memory())?.into())
846            }
847
848            #[inline]
849            fn linear_lift_from_memory(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
850                let s = <WasmStr as Lift>::linear_lift_from_memory(cx, ty, bytes)?;
851                let encoding = cx.options().string_encoding;
852                Ok(s.to_str_from_memory(encoding, cx.memory())?.into())
853            }
854        }
855    )*)
856}
857
858forward_string_lifts! {
859    Box<str>,
860    alloc::sync::Arc<str>,
861    String,
862}
863
864macro_rules! forward_list_lifts {
865    ($(
866        $(#[$attr:meta])*
867        ($($generics:tt)*) $a:ty => WasmList<$b:ty> $(( $via:ident $c:ty ))?,
868    )*) => ($(
869        $(#[$attr])*
870        unsafe impl <$($generics)*> Lift for $a {
871            fn linear_lift_from_flat(cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
872                let list = <WasmList::<$b> as Lift>::linear_lift_from_flat(cx, ty, src)?;
873                let vec = <$b>::linear_lift_list_from_memory(cx, &list)?;
874                $(let vec = <$c>::from(vec);)?
875                Ok(Self::from(vec))
876            }
877
878            fn linear_lift_from_memory(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
879                let list = <WasmList::<$b> as Lift>::linear_lift_from_memory(cx, ty, bytes)?;
880                let vec = <$b>::linear_lift_list_from_memory(cx, &list)?;
881                $(let vec = <$c>::from(vec);)?
882                Ok(Self::from(vec))
883            }
884        }
885    )*)
886}
887
888forward_list_lifts! {
889    (T: Lift) Box<[T]> => WasmList<T>,
890    (T: Lift) alloc::sync::Arc<[T]> => WasmList<T>,
891    (T: Lift) Vec<T> => WasmList<T>,
892    #[cfg(feature = "component-model-bytes")]
893    () bytes::Bytes => WasmList<u8>,
894    // Note that `From<Vec<u8>> for BytesMut` is missing from the `bytes` crate
895    // and this is the subject of tokio-rs/bytes#615
896    #[cfg(feature = "component-model-bytes")]
897    () bytes::BytesMut => WasmList<u8> (via bytes::Bytes),
898}
899
900// Macro to help generate `ComponentType` implementations for primitive types
901// such as integers, char, bool, etc.
902macro_rules! integers {
903    ($($primitive:ident = $ty:ident in $field:ident/$get:ident with abi:$abi:ident,)*) => ($(
904        unsafe impl ComponentType for $primitive {
905            type Lower = ValRaw;
906
907            const ABI: CanonicalAbiInfo = CanonicalAbiInfo::$abi;
908
909            const MAY_REQUIRE_REALLOC: bool = false;
910
911            fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
912                match ty {
913                    InterfaceType::$ty => Ok(()),
914                    other => bail!("expected `{}` found `{}`", desc(&InterfaceType::$ty), desc(other))
915                }
916            }
917        }
918
919        unsafe impl Lower for $primitive {
920            #[inline]
921            #[allow(trivial_numeric_casts, reason = "macro-generated code")]
922            fn linear_lower_to_flat<T>(
923                &self,
924                _cx: &mut LowerContext<'_, T>,
925                ty: InterfaceType,
926                dst: &mut MaybeUninit<Self::Lower>,
927            ) -> Result<()> {
928                debug_assert!(matches!(ty, InterfaceType::$ty));
929                dst.write(ValRaw::$field(*self as $field));
930                Ok(())
931            }
932
933            #[inline]
934            fn linear_lower_to_memory<T>(
935                &self,
936                cx: &mut LowerContext<'_, T>,
937                ty: InterfaceType,
938                offset: usize,
939            ) -> Result<()> {
940                debug_assert!(matches!(ty, InterfaceType::$ty));
941                debug_assert!(offset % Self::SIZE32 == 0);
942                *cx.get(offset) = self.to_le_bytes();
943                Ok(())
944            }
945
946            fn linear_store_list_to_memory<T>(
947                cx: &mut LowerContext<'_, T>,
948                ty: InterfaceType,
949                offset: usize,
950                items: &[Self],
951            ) -> Result<()> {
952                debug_assert!(matches!(ty, InterfaceType::$ty));
953
954                // Double-check that the CM alignment is at least the host's
955                // alignment for this type which should be true for all
956                // platforms.
957                assert!((Self::ALIGN32 as usize) >= mem::align_of::<Self>());
958
959                // Slice `cx`'s memory to the window that we'll be modifying.
960                // This should all have already been verified in terms of
961                // alignment and sizing meaning that these assertions here are
962                // not truly necessary but are instead double-checks.
963                //
964                // Note that we're casting a `[u8]` slice to `[Self]` with
965                // `align_to_mut` which is not safe in general but is safe in
966                // our specific case as all `u8` patterns are valid `Self`
967                // patterns since `Self` is an integral type.
968                let dst = cx.slice_range_mut(offset, items.len() * Self::SIZE32);
969                let (before, middle, end) = unsafe { dst.align_to_mut::<Self>() };
970                assert!(before.is_empty() && end.is_empty());
971                assert_eq!(middle.len(), items.len());
972
973                // And with all that out of the way perform the copying loop.
974                // This is not a `copy_from_slice` because endianness needs to
975                // be handled here, but LLVM should pretty easily transform this
976                // into a memcpy on little-endian platforms.
977                for (dst, src) in middle.iter_mut().zip(items) {
978                    *dst = src.to_le();
979                }
980                Ok(())
981            }
982        }
983
984        unsafe impl Lift for $primitive {
985            #[inline]
986            #[allow(
987                trivial_numeric_casts,
988                clippy::cast_possible_truncation,
989                reason = "macro-generated code"
990            )]
991            fn linear_lift_from_flat(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
992                debug_assert!(matches!(ty, InterfaceType::$ty));
993                Ok(src.$get() as $primitive)
994            }
995
996            #[inline]
997            fn linear_lift_from_memory(_cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
998                debug_assert!(matches!(ty, InterfaceType::$ty));
999                debug_assert!((bytes.as_ptr() as usize) % Self::SIZE32 == 0);
1000                Ok($primitive::from_le_bytes(*bytes.as_array().unwrap()))
1001            }
1002
1003            fn linear_lift_into_from_memory(
1004                cx: &mut LiftContext<'_>,
1005                list: &WasmList<Self>,
1006                dst: &mut impl Extend<Self>,
1007            ) -> Result<()>
1008            where
1009                Self: Sized,
1010            {
1011                dst.extend(list._as_le_slice(cx.memory())
1012                           .iter()
1013                           .map(|i| Self::from_le(*i)));
1014                Ok(())
1015            }
1016        }
1017    )*)
1018}
1019
1020integers! {
1021    i8 = S8 in i32/get_i32 with abi:SCALAR1,
1022    u8 = U8 in u32/get_u32 with abi:SCALAR1,
1023    i16 = S16 in i32/get_i32 with abi:SCALAR2,
1024    u16 = U16 in u32/get_u32 with abi:SCALAR2,
1025    i32 = S32 in i32/get_i32 with abi:SCALAR4,
1026    u32 = U32 in u32/get_u32 with abi:SCALAR4,
1027    i64 = S64 in i64/get_i64 with abi:SCALAR8,
1028    u64 = U64 in u64/get_u64 with abi:SCALAR8,
1029}
1030
1031macro_rules! floats {
1032    ($($float:ident/$get_float:ident = $ty:ident with abi:$abi:ident)*) => ($(const _: () = {
1033        unsafe impl ComponentType for $float {
1034            type Lower = ValRaw;
1035
1036            const ABI: CanonicalAbiInfo = CanonicalAbiInfo::$abi;
1037            const MAY_REQUIRE_REALLOC: bool = false;
1038
1039            fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
1040                match ty {
1041                    InterfaceType::$ty => Ok(()),
1042                    other => bail!("expected `{}` found `{}`", desc(&InterfaceType::$ty), desc(other))
1043                }
1044            }
1045        }
1046
1047        unsafe impl Lower for $float {
1048            #[inline]
1049            fn linear_lower_to_flat<T>(
1050                &self,
1051                _cx: &mut LowerContext<'_, T>,
1052                ty: InterfaceType,
1053                dst: &mut MaybeUninit<Self::Lower>,
1054            ) -> Result<()> {
1055                debug_assert!(matches!(ty, InterfaceType::$ty));
1056                dst.write(ValRaw::$float(self.to_bits()));
1057                Ok(())
1058            }
1059
1060            #[inline]
1061            fn linear_lower_to_memory<T>(
1062                &self,
1063                cx: &mut LowerContext<'_, T>,
1064                ty: InterfaceType,
1065                offset: usize,
1066            ) -> Result<()> {
1067                debug_assert!(matches!(ty, InterfaceType::$ty));
1068                debug_assert!(offset % Self::SIZE32 == 0);
1069                let ptr = cx.get(offset);
1070                *ptr = self.to_bits().to_le_bytes();
1071                Ok(())
1072            }
1073
1074            fn linear_store_list_to_memory<T>(
1075                cx: &mut LowerContext<'_, T>,
1076                ty: InterfaceType,
1077                offset: usize,
1078                items: &[Self],
1079            ) -> Result<()> {
1080                debug_assert!(matches!(ty, InterfaceType::$ty));
1081
1082                // Double-check that the CM alignment is at least the host's
1083                // alignment for this type which should be true for all
1084                // platforms.
1085                assert!((Self::ALIGN32 as usize) >= mem::align_of::<Self>());
1086
1087                // Slice `cx`'s memory to the window that we'll be modifying.
1088                // This should all have already been verified in terms of
1089                // alignment and sizing meaning that these assertions here are
1090                // not truly necessary but are instead double-checks.
1091                let dst = cx.slice_range_mut(offset, items.len() * Self::SIZE32);
1092                assert!(dst.as_ptr().cast::<Self>().is_aligned());
1093
1094                // And with all that out of the way perform the copying loop.
1095                // This is not a `copy_from_slice` because endianness needs to
1096                // be handled here, but LLVM should pretty easily transform this
1097                // into a memcpy on little-endian platforms.
1098                let (dst, rest) = dst.as_chunks_mut::<{Self::SIZE32}>();
1099                debug_assert!(rest.is_empty());
1100                for (dst, src) in iter::zip(dst, items) {
1101                    *dst = src.to_le_bytes();
1102                }
1103                Ok(())
1104            }
1105        }
1106
1107        unsafe impl Lift for $float {
1108            #[inline]
1109            fn linear_lift_from_flat(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
1110                debug_assert!(matches!(ty, InterfaceType::$ty));
1111                Ok($float::from_bits(src.$get_float()))
1112            }
1113
1114            #[inline]
1115            fn linear_lift_from_memory(_cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
1116                debug_assert!(matches!(ty, InterfaceType::$ty));
1117                debug_assert!((bytes.as_ptr() as usize) % Self::SIZE32 == 0);
1118                Ok($float::from_le_bytes(*bytes.as_array().unwrap()))
1119            }
1120
1121            fn linear_lift_list_from_memory(cx: &mut LiftContext<'_>, list: &WasmList<Self>) -> Result<Vec<Self>> where Self: Sized {
1122                // See comments in `WasmList::get` for the panicking indexing
1123                let byte_size = list.len * mem::size_of::<Self>();
1124                let bytes = &cx.memory()[list.ptr..][..byte_size];
1125
1126                // The canonical ABI requires that everything is aligned to its
1127                // own size, so this should be an aligned array.
1128                assert!(bytes.as_ptr().cast::<Self>().is_aligned());
1129
1130                // Copy the resulting slice to a new Vec, handling endianness
1131                // in the process
1132                let (src, rest) = bytes.as_chunks::<{Self::SIZE32}>();
1133                debug_assert!(rest.is_empty());
1134                Ok(
1135                    src
1136                        .iter()
1137                        .map(|i| $float::from_le_bytes(*i))
1138                        .collect()
1139                )
1140            }
1141        }
1142    };)*)
1143}
1144
1145floats! {
1146    f32/get_f32 = Float32 with abi:SCALAR4
1147    f64/get_f64 = Float64 with abi:SCALAR8
1148}
1149
1150unsafe impl ComponentType for bool {
1151    type Lower = ValRaw;
1152
1153    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR1;
1154    const MAY_REQUIRE_REALLOC: bool = false;
1155
1156    fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
1157        match ty {
1158            InterfaceType::Bool => Ok(()),
1159            other => bail!("expected `bool` found `{}`", desc(other)),
1160        }
1161    }
1162}
1163
1164unsafe impl Lower for bool {
1165    fn linear_lower_to_flat<T>(
1166        &self,
1167        _cx: &mut LowerContext<'_, T>,
1168        ty: InterfaceType,
1169        dst: &mut MaybeUninit<Self::Lower>,
1170    ) -> Result<()> {
1171        debug_assert!(matches!(ty, InterfaceType::Bool));
1172        dst.write(ValRaw::i32(*self as i32));
1173        Ok(())
1174    }
1175
1176    fn linear_lower_to_memory<T>(
1177        &self,
1178        cx: &mut LowerContext<'_, T>,
1179        ty: InterfaceType,
1180        offset: usize,
1181    ) -> Result<()> {
1182        debug_assert!(matches!(ty, InterfaceType::Bool));
1183        debug_assert!(offset % Self::SIZE32 == 0);
1184        cx.get::<1>(offset)[0] = *self as u8;
1185        Ok(())
1186    }
1187}
1188
1189unsafe impl Lift for bool {
1190    #[inline]
1191    fn linear_lift_from_flat(
1192        _cx: &mut LiftContext<'_>,
1193        ty: InterfaceType,
1194        src: &Self::Lower,
1195    ) -> Result<Self> {
1196        debug_assert!(matches!(ty, InterfaceType::Bool));
1197        match src.get_i32() {
1198            0 => Ok(false),
1199            _ => Ok(true),
1200        }
1201    }
1202
1203    #[inline]
1204    fn linear_lift_from_memory(
1205        _cx: &mut LiftContext<'_>,
1206        ty: InterfaceType,
1207        bytes: &[u8],
1208    ) -> Result<Self> {
1209        debug_assert!(matches!(ty, InterfaceType::Bool));
1210        match bytes[0] {
1211            0 => Ok(false),
1212            _ => Ok(true),
1213        }
1214    }
1215}
1216
1217unsafe impl ComponentType for char {
1218    type Lower = ValRaw;
1219
1220    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
1221    const MAY_REQUIRE_REALLOC: bool = false;
1222
1223    fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
1224        match ty {
1225            InterfaceType::Char => Ok(()),
1226            other => bail!("expected `char` found `{}`", desc(other)),
1227        }
1228    }
1229}
1230
1231unsafe impl Lower for char {
1232    #[inline]
1233    fn linear_lower_to_flat<T>(
1234        &self,
1235        _cx: &mut LowerContext<'_, T>,
1236        ty: InterfaceType,
1237        dst: &mut MaybeUninit<Self::Lower>,
1238    ) -> Result<()> {
1239        debug_assert!(matches!(ty, InterfaceType::Char));
1240        dst.write(ValRaw::u32(u32::from(*self)));
1241        Ok(())
1242    }
1243
1244    #[inline]
1245    fn linear_lower_to_memory<T>(
1246        &self,
1247        cx: &mut LowerContext<'_, T>,
1248        ty: InterfaceType,
1249        offset: usize,
1250    ) -> Result<()> {
1251        debug_assert!(matches!(ty, InterfaceType::Char));
1252        debug_assert!(offset % Self::SIZE32 == 0);
1253        *cx.get::<4>(offset) = u32::from(*self).to_le_bytes();
1254        Ok(())
1255    }
1256}
1257
1258unsafe impl Lift for char {
1259    #[inline]
1260    fn linear_lift_from_flat(
1261        _cx: &mut LiftContext<'_>,
1262        ty: InterfaceType,
1263        src: &Self::Lower,
1264    ) -> Result<Self> {
1265        debug_assert!(matches!(ty, InterfaceType::Char));
1266        Ok(char::try_from(src.get_u32())?)
1267    }
1268
1269    #[inline]
1270    fn linear_lift_from_memory(
1271        _cx: &mut LiftContext<'_>,
1272        ty: InterfaceType,
1273        bytes: &[u8],
1274    ) -> Result<Self> {
1275        debug_assert!(matches!(ty, InterfaceType::Char));
1276        debug_assert!((bytes.as_ptr() as usize) % Self::SIZE32 == 0);
1277        let bits = u32::from_le_bytes(*bytes.as_array().unwrap());
1278        Ok(char::try_from(bits)?)
1279    }
1280}
1281
1282fn lift_pointer_pair_from_flat(
1283    cx: &mut LiftContext<'_>,
1284    src: &[ValRaw; 2],
1285) -> Result<(usize, usize)> {
1286    // FIXME(#4311): needs memory64 treatment
1287    let _ = cx; // this will be needed for memory64 in the future
1288    let ptr = src[0].get_u32();
1289    let len = src[1].get_u32();
1290    Ok((usize::try_from(ptr)?, usize::try_from(len)?))
1291}
1292
1293fn lift_pointer_pair_from_memory(cx: &mut LiftContext<'_>, bytes: &[u8]) -> Result<(usize, usize)> {
1294    // FIXME(#4311): needs memory64 treatment
1295    let _ = cx; // this will be needed for memory64 in the future
1296    let ptr = u32::from_le_bytes(*bytes[..4].as_array().unwrap());
1297    let len = u32::from_le_bytes(*bytes[4..].as_array().unwrap());
1298    Ok((usize::try_from(ptr)?, usize::try_from(len)?))
1299}
1300
1301fn lower_pointer_pair_to_flat<T>(
1302    cx: &mut LowerContext<T>,
1303    dst: &mut MaybeUninit<[ValRaw; 2]>,
1304    ptr: usize,
1305    len: usize,
1306) {
1307    // See "WRITEPTR64" above for why this is always storing a 64-bit
1308    // integer.
1309    let _ = cx; // this will eventually be needed for memory64 information.
1310    map_maybe_uninit!(dst[0]).write(ValRaw::i64(ptr as i64));
1311    map_maybe_uninit!(dst[1]).write(ValRaw::i64(len as i64));
1312}
1313
1314fn lower_pointer_pair_to_memory<T>(
1315    cx: &mut LowerContext<T>,
1316    offset: usize,
1317    ptr: usize,
1318    len: usize,
1319) {
1320    // FIXME(#4311): needs memory64 handling
1321    *cx.get(offset + 0) = u32::try_from(ptr).unwrap().to_le_bytes();
1322    *cx.get(offset + 4) = u32::try_from(len).unwrap().to_le_bytes();
1323}
1324
1325// FIXME(#4311): these probably need different constants for memory64
1326const UTF16_TAG: usize = 1 << 31;
1327const MAX_STRING_BYTE_LENGTH: usize = (1 << 31) - 1;
1328
1329// Note that this is similar to `ComponentType for WasmStr` except it can only
1330// be used for lowering, not lifting.
1331unsafe impl ComponentType for str {
1332    type Lower = [ValRaw; 2];
1333
1334    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::POINTER_PAIR;
1335
1336    fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
1337        match ty {
1338            InterfaceType::String => Ok(()),
1339            other => bail!("expected `string` found `{}`", desc(other)),
1340        }
1341    }
1342}
1343
1344unsafe impl Lower for str {
1345    fn linear_lower_to_flat<T>(
1346        &self,
1347        cx: &mut LowerContext<'_, T>,
1348        ty: InterfaceType,
1349        dst: &mut MaybeUninit<[ValRaw; 2]>,
1350    ) -> Result<()> {
1351        debug_assert!(matches!(ty, InterfaceType::String));
1352        let (ptr, len) = lower_string(cx, self)?;
1353        lower_pointer_pair_to_flat(cx, dst, ptr, len);
1354        Ok(())
1355    }
1356
1357    fn linear_lower_to_memory<T>(
1358        &self,
1359        cx: &mut LowerContext<'_, T>,
1360        ty: InterfaceType,
1361        offset: usize,
1362    ) -> Result<()> {
1363        debug_assert!(matches!(ty, InterfaceType::String));
1364        debug_assert!(offset % (Self::ALIGN32 as usize) == 0);
1365        let (ptr, len) = lower_string(cx, self)?;
1366        lower_pointer_pair_to_memory(cx, offset, ptr, len);
1367        Ok(())
1368    }
1369}
1370
1371fn lower_string<T>(cx: &mut LowerContext<'_, T>, string: &str) -> Result<(usize, usize)> {
1372    // Note that in general the wasm module can't assume anything about what the
1373    // host strings are encoded as. Additionally hosts are allowed to have
1374    // differently-encoded strings at runtime. Finally when copying a string
1375    // into wasm it's somewhat strict in the sense that the various patterns of
1376    // allocation and such are already dictated for us.
1377    //
1378    // In general what this means is that when copying a string from the host
1379    // into the destination we need to follow one of the cases of copying into
1380    // WebAssembly. It doesn't particularly matter which case as long as it ends
1381    // up in the right encoding. For example a destination encoding of
1382    // latin1+utf16 has a number of ways to get copied into and we do something
1383    // here that isn't the default "utf8 to latin1+utf16" since we have access
1384    // to simd-accelerated helpers in the `encoding_rs` crate. This is ok though
1385    // because we can fake that the host string was already stored in latin1
1386    // format and follow that copy pattern instead.
1387    match cx.options().string_encoding {
1388        // This corresponds to `store_string_copy` in the canonical ABI where
1389        // the host's representation is utf-8 and the wasm module wants utf-8 so
1390        // a copy is all that's needed (and the `realloc` can be precise for the
1391        // initial memory allocation).
1392        StringEncoding::Utf8 => {
1393            if string.len() > MAX_STRING_BYTE_LENGTH {
1394                bail!(
1395                    "string length of {} too large to copy into wasm",
1396                    string.len()
1397                );
1398            }
1399            let ptr = cx.realloc(0, 0, 1, string.len())?;
1400            cx.slice_range_mut(ptr, string.len())
1401                .copy_from_slice(string.as_bytes());
1402            Ok((ptr, string.len()))
1403        }
1404
1405        // This corresponds to `store_utf8_to_utf16` in the canonical ABI. Here
1406        // an over-large allocation is performed and then shrunk afterwards if
1407        // necessary.
1408        StringEncoding::Utf16 => {
1409            let size = string.len() * 2;
1410            if size > MAX_STRING_BYTE_LENGTH {
1411                bail!(
1412                    "string length of {} too large to copy into wasm",
1413                    string.len()
1414                );
1415            }
1416            let mut ptr = cx.realloc(0, 0, 2, size)?;
1417            let mut copied = 0;
1418            let bytes = cx.slice_range_mut(ptr, size);
1419            for (u, bytes) in string.encode_utf16().zip(bytes.chunks_mut(2)) {
1420                let u_bytes = u.to_le_bytes();
1421                bytes[0] = u_bytes[0];
1422                bytes[1] = u_bytes[1];
1423                copied += 1;
1424            }
1425            if (copied * 2) < size {
1426                ptr = cx.realloc(ptr, size, 2, copied * 2)?;
1427            }
1428            Ok((ptr, copied))
1429        }
1430
1431        StringEncoding::CompactUtf16 => {
1432            // This corresponds to `store_string_to_latin1_or_utf16`
1433            let bytes = string.as_bytes();
1434            let mut iter = string.char_indices();
1435            let mut ptr = cx.realloc(0, 0, 2, bytes.len())?;
1436            let mut dst = cx.slice_range_mut(ptr, bytes.len());
1437            let mut result = 0;
1438            while let Some((i, ch)) = iter.next() {
1439                // Test if this `char` fits into the latin1 encoding.
1440                if let Ok(byte) = u8::try_from(u32::from(ch)) {
1441                    dst[result] = byte;
1442                    result += 1;
1443                    continue;
1444                }
1445
1446                // .. if utf16 is forced to be used then the allocation is
1447                // bumped up to the maximum size.
1448                let worst_case = bytes
1449                    .len()
1450                    .checked_mul(2)
1451                    .ok_or_else(|| format_err!("byte length overflow"))?;
1452                if worst_case > MAX_STRING_BYTE_LENGTH {
1453                    bail!("byte length too large");
1454                }
1455                ptr = cx.realloc(ptr, bytes.len(), 2, worst_case)?;
1456                dst = cx.slice_range_mut(ptr, worst_case);
1457
1458                // Previously encoded latin1 bytes are inflated to their 16-bit
1459                // size for utf16
1460                for i in (0..result).rev() {
1461                    dst[2 * i] = dst[i];
1462                    dst[2 * i + 1] = 0;
1463                }
1464
1465                // and then the remainder of the string is encoded.
1466                for (u, bytes) in string[i..]
1467                    .encode_utf16()
1468                    .zip(dst[2 * result..].chunks_mut(2))
1469                {
1470                    let u_bytes = u.to_le_bytes();
1471                    bytes[0] = u_bytes[0];
1472                    bytes[1] = u_bytes[1];
1473                    result += 1;
1474                }
1475                if worst_case > 2 * result {
1476                    ptr = cx.realloc(ptr, worst_case, 2, 2 * result)?;
1477                }
1478                return Ok((ptr, result | UTF16_TAG));
1479            }
1480            if result < bytes.len() {
1481                ptr = cx.realloc(ptr, bytes.len(), 2, result)?;
1482            }
1483            Ok((ptr, result))
1484        }
1485    }
1486}
1487
1488/// Representation of a string located in linear memory in a WebAssembly
1489/// instance.
1490///
1491/// This type can be used in place of `String` and `str` for string-taking APIs
1492/// in some situations. The purpose of this type is to represent a range of
1493/// validated bytes within a component but does not actually copy the bytes. The
1494/// primary method, [`WasmStr::to_str`], attempts to return a reference to the
1495/// string directly located in the component's memory, avoiding a copy into the
1496/// host if possible.
1497///
1498/// The downside of this type, however, is that accessing a string requires a
1499/// [`Store`](crate::Store) pointer (via [`StoreContext`]). Bindings generated
1500/// by [`bindgen!`](crate::component::bindgen), for example, do not have access
1501/// to [`StoreContext`] and thus can't use this type.
1502///
1503/// This is intended for more advanced use cases such as defining functions
1504/// directly in a [`Linker`](crate::component::Linker). It's expected that in
1505/// the future [`bindgen!`](crate::component::bindgen) will also have a way to
1506/// use this type.
1507///
1508/// This type is used with [`TypedFunc`], for example, when WebAssembly returns
1509/// a string. This type cannot be used to give a string to WebAssembly, instead
1510/// `&str` should be used for that (since it's coming from the host).
1511///
1512/// Note that this type represents an in-bounds string in linear memory, but it
1513/// does not represent a valid string (e.g. valid utf-8). Validation happens
1514/// when [`WasmStr::to_str`] is called.
1515///
1516/// Also note that this type does not implement [`Lower`], it only implements
1517/// [`Lift`].
1518pub struct WasmStr {
1519    ptr: usize,
1520    len: usize,
1521    options: OptionsIndex,
1522    instance: Instance,
1523}
1524
1525impl WasmStr {
1526    pub(crate) fn new(ptr: usize, len: usize, cx: &mut LiftContext<'_>) -> Result<WasmStr> {
1527        let (byte_len, align) = match cx.options().string_encoding {
1528            StringEncoding::Utf8 => (Some(len), 1_usize),
1529            StringEncoding::Utf16 => (len.checked_mul(2), 2),
1530            StringEncoding::CompactUtf16 => {
1531                if len & UTF16_TAG == 0 {
1532                    (Some(len), 2)
1533                } else {
1534                    ((len ^ UTF16_TAG).checked_mul(2), 2)
1535                }
1536            }
1537        };
1538        debug_assert!(align.is_power_of_two());
1539        if ptr & (align - 1) != 0 {
1540            bail!("string pointer not aligned to {align}");
1541        }
1542        match byte_len.and_then(|len| ptr.checked_add(len)) {
1543            Some(n) if n <= cx.memory().len() => cx.consume_fuel(n - ptr)?,
1544            _ => bail!("string pointer/length out of bounds of memory"),
1545        }
1546        Ok(WasmStr {
1547            ptr,
1548            len,
1549            options: cx.options_index(),
1550            instance: cx.instance_handle(),
1551        })
1552    }
1553
1554    /// Returns the underlying string that this cursor points to.
1555    ///
1556    /// Note that this will internally decode the string from the wasm's
1557    /// encoding to utf-8 and additionally perform validation.
1558    ///
1559    /// The `store` provided must be the store where this string lives to
1560    /// access the correct memory.
1561    ///
1562    /// # Errors
1563    ///
1564    /// Returns an error if the string wasn't encoded correctly (e.g. invalid
1565    /// utf-8).
1566    ///
1567    /// # Panics
1568    ///
1569    /// Panics if this string is not owned by `store`.
1570    //
1571    // TODO: should add accessors for specifically utf-8 and utf-16 that perhaps
1572    // in an opt-in basis don't do validation. Additionally there should be some
1573    // method that returns `[u16]` after validating to avoid the utf16-to-utf8
1574    // transcode.
1575    pub fn to_str<'a, T: 'static>(
1576        &self,
1577        store: impl Into<StoreContext<'a, T>>,
1578    ) -> Result<Cow<'a, str>> {
1579        let store = store.into().0;
1580        let memory = self.instance.options_memory(store, self.options);
1581        let encoding = self.instance.options(store, self.options).string_encoding;
1582        self.to_str_from_memory(encoding, memory)
1583    }
1584
1585    pub(crate) fn to_str_from_memory<'a>(
1586        &self,
1587        encoding: StringEncoding,
1588        memory: &'a [u8],
1589    ) -> Result<Cow<'a, str>> {
1590        match encoding {
1591            StringEncoding::Utf8 => self.decode_utf8(memory),
1592            StringEncoding::Utf16 => self.decode_utf16(memory, self.len),
1593            StringEncoding::CompactUtf16 => {
1594                if self.len & UTF16_TAG == 0 {
1595                    self.decode_latin1(memory)
1596                } else {
1597                    self.decode_utf16(memory, self.len ^ UTF16_TAG)
1598                }
1599            }
1600        }
1601    }
1602
1603    fn decode_utf8<'a>(&self, memory: &'a [u8]) -> Result<Cow<'a, str>> {
1604        // Note that bounds-checking already happen in construction of `WasmStr`
1605        // so this is never expected to panic. This could theoretically be
1606        // unchecked indexing if we're feeling wild enough.
1607        Ok(str::from_utf8(&memory[self.ptr..][..self.len])?.into())
1608    }
1609
1610    fn decode_utf16<'a>(&self, memory: &'a [u8], len: usize) -> Result<Cow<'a, str>> {
1611        // See notes in `decode_utf8` for why this is panicking indexing.
1612        let (chunks, rest) = &memory[self.ptr..][..len * 2].as_chunks::<2>();
1613        debug_assert!(rest.is_empty());
1614        Ok(
1615            core::char::decode_utf16(chunks.iter().map(|chunk| u16::from_le_bytes(*chunk)))
1616                .collect::<Result<String, _>>()?
1617                .into(),
1618        )
1619    }
1620
1621    fn decode_latin1<'a>(&self, memory: &'a [u8]) -> Result<Cow<'a, str>> {
1622        // See notes in `decode_utf8` for why this is panicking indexing.
1623        Ok(encoding_rs::mem::decode_latin1(
1624            &memory[self.ptr..][..self.len],
1625        ))
1626    }
1627}
1628
1629// Note that this is similar to `ComponentType for str` except it can only be
1630// used for lifting, not lowering.
1631unsafe impl ComponentType for WasmStr {
1632    type Lower = <str as ComponentType>::Lower;
1633
1634    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::POINTER_PAIR;
1635
1636    fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
1637        match ty {
1638            InterfaceType::String => Ok(()),
1639            other => bail!("expected `string` found `{}`", desc(other)),
1640        }
1641    }
1642}
1643
1644unsafe impl Lift for WasmStr {
1645    #[inline]
1646    fn linear_lift_from_flat(
1647        cx: &mut LiftContext<'_>,
1648        ty: InterfaceType,
1649        src: &Self::Lower,
1650    ) -> Result<Self> {
1651        debug_assert!(matches!(ty, InterfaceType::String));
1652        let (ptr, len) = lift_pointer_pair_from_flat(cx, src)?;
1653        WasmStr::new(ptr, len, cx)
1654    }
1655
1656    #[inline]
1657    fn linear_lift_from_memory(
1658        cx: &mut LiftContext<'_>,
1659        ty: InterfaceType,
1660        bytes: &[u8],
1661    ) -> Result<Self> {
1662        debug_assert!(matches!(ty, InterfaceType::String));
1663        debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
1664        let (ptr, len) = lift_pointer_pair_from_memory(cx, bytes)?;
1665        WasmStr::new(ptr, len, cx)
1666    }
1667}
1668
1669unsafe impl<T> ComponentType for [T]
1670where
1671    T: ComponentType,
1672{
1673    type Lower = [ValRaw; 2];
1674
1675    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::POINTER_PAIR;
1676
1677    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
1678        match ty {
1679            InterfaceType::List(t) => T::typecheck(&types.types[*t].element, types),
1680            other => bail!("expected `list` found `{}`", desc(other)),
1681        }
1682    }
1683}
1684
1685unsafe impl<T> Lower for [T]
1686where
1687    T: Lower,
1688{
1689    fn linear_lower_to_flat<U>(
1690        &self,
1691        cx: &mut LowerContext<'_, U>,
1692        ty: InterfaceType,
1693        dst: &mut MaybeUninit<[ValRaw; 2]>,
1694    ) -> Result<()> {
1695        let elem = match ty {
1696            InterfaceType::List(i) => cx.types[i].element,
1697            _ => bad_type_info(),
1698        };
1699        let (ptr, len) = lower_list(cx, elem, self)?;
1700        lower_pointer_pair_to_flat(cx, dst, ptr, len);
1701        Ok(())
1702    }
1703
1704    fn linear_lower_to_memory<U>(
1705        &self,
1706        cx: &mut LowerContext<'_, U>,
1707        ty: InterfaceType,
1708        offset: usize,
1709    ) -> Result<()> {
1710        let elem = match ty {
1711            InterfaceType::List(i) => cx.types[i].element,
1712            _ => bad_type_info(),
1713        };
1714        debug_assert!(offset % (Self::ALIGN32 as usize) == 0);
1715        let (ptr, len) = lower_list(cx, elem, self)?;
1716        lower_pointer_pair_to_memory(cx, offset, ptr, len);
1717        Ok(())
1718    }
1719}
1720
1721// FIXME: this is not a memcpy for `T` where `T` is something like `u8`.
1722//
1723// Some attempts to fix this have proved not fruitful. In isolation an attempt
1724// was made where:
1725//
1726// * `MemoryMut` stored a `*mut [u8]` as its "last view" of memory to avoid
1727//   reloading the base pointer constantly. This view is reset on `realloc`.
1728// * The bounds-checks in `MemoryMut::get` were removed (replaced with unsafe
1729//   indexing)
1730//
1731// Even then though this didn't correctly vectorized for `Vec<u8>`. It's not
1732// entirely clear why but it appeared that it's related to reloading the base
1733// pointer to memory (I guess from `MemoryMut` itself?). Overall I'm not really
1734// clear on what's happening there, but this is surely going to be a performance
1735// bottleneck in the future.
1736fn lower_list<T, U>(
1737    cx: &mut LowerContext<'_, U>,
1738    ty: InterfaceType,
1739    list: &[T],
1740) -> Result<(usize, usize)>
1741where
1742    T: Lower,
1743{
1744    let elem_size = T::SIZE32;
1745    let size = list
1746        .len()
1747        .checked_mul(elem_size)
1748        .ok_or_else(|| format_err!("size overflow copying a list"))?;
1749    let ptr = cx.realloc(0, 0, T::ALIGN32, size)?;
1750    T::linear_store_list_to_memory(cx, ty, ptr, list)?;
1751    Ok((ptr, list.len()))
1752}
1753
1754/// Representation of a list of values that are owned by a WebAssembly instance.
1755///
1756/// For some more commentary about the rationale for this type see the
1757/// documentation of [`WasmStr`]. In summary this type can avoid a copy when
1758/// passing data to the host in some situations but is additionally more
1759/// cumbersome to use by requiring a [`Store`](crate::Store) to be provided.
1760///
1761/// This type is used whenever a `(list T)` is returned from a [`TypedFunc`],
1762/// for example. This type represents a list of values that are stored in linear
1763/// memory which are waiting to be read.
1764///
1765/// Note that this type represents only a valid range of bytes for the list
1766/// itself, it does not represent validity of the elements themselves and that's
1767/// performed when they're iterated.
1768///
1769/// Note that this type does not implement the [`Lower`] trait, only [`Lift`].
1770pub struct WasmList<T> {
1771    ptr: usize,
1772    len: usize,
1773    options: OptionsIndex,
1774    elem: InterfaceType,
1775    instance: Instance,
1776    _marker: marker::PhantomData<T>,
1777}
1778
1779impl<T: Lift> WasmList<T> {
1780    pub(crate) fn new(
1781        ptr: usize,
1782        len: usize,
1783        cx: &mut LiftContext<'_>,
1784        elem: InterfaceType,
1785    ) -> Result<WasmList<T>> {
1786        match len
1787            .checked_mul(T::SIZE32)
1788            .and_then(|len| ptr.checked_add(len))
1789        {
1790            Some(n) if n <= cx.memory().len() => cx.consume_fuel_array(len, size_of::<T>())?,
1791            _ => bail!("list pointer/length out of bounds of memory"),
1792        }
1793        if ptr % usize::try_from(T::ALIGN32)? != 0 {
1794            bail!("list pointer is not aligned")
1795        }
1796        Ok(WasmList {
1797            ptr,
1798            len,
1799            options: cx.options_index(),
1800            elem,
1801            instance: cx.instance_handle(),
1802            _marker: marker::PhantomData,
1803        })
1804    }
1805
1806    /// Returns the item length of this vector
1807    #[inline]
1808    pub fn len(&self) -> usize {
1809        self.len
1810    }
1811
1812    /// Gets the `n`th element of this list.
1813    ///
1814    /// Returns `None` if `index` is out of bounds. Returns `Some(Err(..))` if
1815    /// the value couldn't be decoded (it was invalid). Returns `Some(Ok(..))`
1816    /// if the value is valid.
1817    ///
1818    /// # Panics
1819    ///
1820    /// This function will panic if the string did not originally come from the
1821    /// `store` specified.
1822    //
1823    // TODO: given that interface values are intended to be consumed in one go
1824    // should we even expose a random access iteration API? In theory all
1825    // consumers should be validating through the iterator.
1826    pub fn get(&self, mut store: impl AsContextMut, index: usize) -> Option<Result<T>> {
1827        let store = store.as_context_mut().0;
1828        let mut cx = match LiftContext::new(store, self.options, self.instance) {
1829            Ok(cx) => cx,
1830            Err(e) => return Some(Err(e)),
1831        };
1832        self.get_from_store(&mut cx, index)
1833    }
1834
1835    fn get_from_store(&self, cx: &mut LiftContext<'_>, index: usize) -> Option<Result<T>> {
1836        if index >= self.len {
1837            return None;
1838        }
1839        // Note that this is using panicking indexing and this is expected to
1840        // never fail. The bounds-checking here happened during the construction
1841        // of the `WasmList` itself which means these should always be in-bounds
1842        // (and wasm memory can only grow). This could theoretically be
1843        // unchecked indexing if we're confident enough and it's actually a perf
1844        // issue one day.
1845        let bytes = &cx.memory()[self.ptr + index * T::SIZE32..][..T::SIZE32];
1846        Some(T::linear_lift_from_memory(cx, self.elem, bytes))
1847    }
1848
1849    /// Returns an iterator over the elements of this list.
1850    ///
1851    /// Each item of the list may fail to decode and is represented through the
1852    /// `Result` value of the iterator.
1853    pub fn iter<'a, U: 'static>(
1854        &'a self,
1855        store: impl Into<StoreContextMut<'a, U>>,
1856    ) -> Result<impl ExactSizeIterator<Item = Result<T>> + 'a> {
1857        let store = store.into().0;
1858        let mut cx = LiftContext::new(store, self.options, self.instance)?;
1859        Ok((0..self.len).map(move |i| self.get_from_store(&mut cx, i).unwrap()))
1860    }
1861}
1862
1863macro_rules! raw_wasm_list_accessors {
1864    ($($i:ident)*) => ($(
1865        impl WasmList<$i> {
1866            /// Get access to the raw underlying memory for this list.
1867            ///
1868            /// This method will return a direct slice into the original wasm
1869            /// module's linear memory where the data for this slice is stored.
1870            /// This allows the embedder to have efficient access to the
1871            /// underlying memory if needed and avoid copies and such if
1872            /// desired.
1873            ///
1874            /// Note that multi-byte integers are stored in little-endian format
1875            /// so portable processing of this slice must be aware of the host's
1876            /// byte-endianness. The `from_le` constructors in the Rust standard
1877            /// library should be suitable for converting from little-endian.
1878            ///
1879            /// # Panics
1880            ///
1881            /// Panics if the `store` provided is not the one from which this
1882            /// slice originated.
1883            pub fn as_le_slice<'a, T: 'static>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a [$i] {
1884                let memory = self.instance.options_memory(store.into().0, self.options);
1885                self._as_le_slice(memory)
1886            }
1887
1888            fn _as_le_slice<'a>(&self, all_of_memory: &'a [u8]) -> &'a [$i] {
1889                // See comments in `WasmList::get` for the panicking indexing
1890                let byte_size = self.len * mem::size_of::<$i>();
1891                let bytes = &all_of_memory[self.ptr..][..byte_size];
1892
1893                // The canonical ABI requires that everything is aligned to its
1894                // own size, so this should be an aligned array. Furthermore the
1895                // alignment of primitive integers for hosts should be smaller
1896                // than or equal to the size of the primitive itself, meaning
1897                // that a wasm canonical-abi-aligned list is also aligned for
1898                // the host. That should mean that the head/tail slices here are
1899                // empty.
1900                //
1901                // Also note that the `unsafe` here is needed since the type
1902                // we're aligning to isn't guaranteed to be valid, but in our
1903                // case it's just integers and bytes so this should be safe.
1904                unsafe {
1905                    let (head, body, tail) = bytes.align_to::<$i>();
1906                    assert!(head.is_empty() && tail.is_empty());
1907                    body
1908                }
1909            }
1910        }
1911    )*)
1912}
1913
1914raw_wasm_list_accessors! {
1915    i8 i16 i32 i64
1916    u8 u16 u32 u64
1917}
1918
1919// Note that this is similar to `ComponentType for str` except it can only be
1920// used for lifting, not lowering.
1921unsafe impl<T: ComponentType> ComponentType for WasmList<T> {
1922    type Lower = <[T] as ComponentType>::Lower;
1923
1924    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::POINTER_PAIR;
1925
1926    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
1927        <[T] as ComponentType>::typecheck(ty, types)
1928    }
1929}
1930
1931unsafe impl<T: Lift> Lift for WasmList<T> {
1932    fn linear_lift_from_flat(
1933        cx: &mut LiftContext<'_>,
1934        ty: InterfaceType,
1935        src: &Self::Lower,
1936    ) -> Result<Self> {
1937        let elem = match ty {
1938            InterfaceType::List(i) => cx.types[i].element,
1939            _ => bad_type_info(),
1940        };
1941        let (ptr, len) = lift_pointer_pair_from_flat(cx, src)?;
1942        WasmList::new(ptr, len, cx, elem)
1943    }
1944
1945    fn linear_lift_from_memory(
1946        cx: &mut LiftContext<'_>,
1947        ty: InterfaceType,
1948        bytes: &[u8],
1949    ) -> Result<Self> {
1950        let elem = match ty {
1951            InterfaceType::List(i) => cx.types[i].element,
1952            _ => bad_type_info(),
1953        };
1954        debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
1955        let (ptr, len) = lift_pointer_pair_from_memory(cx, bytes)?;
1956        WasmList::new(ptr, len, cx, elem)
1957    }
1958}
1959
1960// =============================================================================
1961// Support for component model `map<K, V>`
1962//
1963// Maps are represented as `list<tuple<K, V>>` in the canonical ABI, so the
1964// lowered form is a (pointer, length) pair just like lists.
1965
1966fn map_abi<'a>(ty: InterfaceType, types: &'a ComponentTypes) -> &'a TypeMap {
1967    match ty {
1968        InterfaceType::Map(i) => &types[i],
1969        _ => bad_type_info(),
1970    }
1971}
1972
1973unsafe impl<K, V> ComponentType for BTreeMap<K, V>
1974where
1975    K: ComponentType,
1976    V: ComponentType,
1977{
1978    type Lower = [ValRaw; 2];
1979
1980    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::POINTER_PAIR;
1981
1982    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
1983        match ty {
1984            InterfaceType::Map(t) => {
1985                let map_ty = &types.types[*t];
1986                K::typecheck(&map_ty.key, types)?;
1987                V::typecheck(&map_ty.value, types)?;
1988                Ok(())
1989            }
1990            other => bail!("expected `map` found `{}`", desc(other)),
1991        }
1992    }
1993}
1994
1995// All map types have the same representation as `BTreeMap`.
1996forward_type_impls! {
1997    (K: ComponentType, V: ComponentType, S: Send + Sync) HashMap<K, V, S> => BTreeMap<K, V>,
1998    (K: ComponentType, V: ComponentType, S: Send + Sync) TryHashMap<K, V, S> => BTreeMap<K, V>,
1999    (K: ComponentType, V: ComponentType, S: Send + Sync) IndexMap<K, V, S> => BTreeMap<K, V>,
2000}
2001
2002macro_rules! map_lowers {
2003    ($(($($generics:tt)*) $a:ty,)*) => ($(
2004        unsafe impl <$($generics)*> Lower for $a {
2005            fn linear_lower_to_flat<U>(
2006                &self,
2007                cx: &mut LowerContext<'_, U>,
2008                ty: InterfaceType,
2009                dst: &mut MaybeUninit<[ValRaw; 2]>,
2010            ) -> Result<()> {
2011                lower_map_to_flat(cx, ty, dst, self.iter())
2012            }
2013
2014            fn linear_lower_to_memory<U>(
2015                &self,
2016                cx: &mut LowerContext<'_, U>,
2017                ty: InterfaceType,
2018                offset: usize,
2019            ) -> Result<()> {
2020                lower_map_to_memory(cx, ty, offset, self.iter())
2021            }
2022        }
2023    )*)
2024}
2025
2026map_lowers! {
2027    (K: Lower, V: Lower, S: Send + Sync) HashMap<K, V, S>,
2028    (K: Lower, V: Lower, S: Send + Sync) TryHashMap<K, V, S>,
2029    (K: Lower, V: Lower) BTreeMap<K, V>,
2030    (K: Lower, V: Lower, S: Send + Sync) IndexMap<K, V, S>,
2031}
2032
2033unsafe impl<K, V, S> Lift for HashMap<K, V, S>
2034where
2035    K: Lift + Eq + Hash,
2036    V: Lift,
2037    S: BuildHasher + Default + Send + Sync,
2038{
2039    fn linear_lift_from_flat(
2040        cx: &mut LiftContext<'_>,
2041        ty: InterfaceType,
2042        src: &Self::Lower,
2043    ) -> Result<Self> {
2044        Ok(TryHashMap::<K, V, S>::linear_lift_from_flat(cx, ty, src)?.into())
2045    }
2046
2047    fn linear_lift_from_memory(
2048        cx: &mut LiftContext<'_>,
2049        ty: InterfaceType,
2050        bytes: &[u8],
2051    ) -> Result<Self> {
2052        Ok(TryHashMap::<K, V, S>::linear_lift_from_memory(cx, ty, bytes)?.into())
2053    }
2054}
2055
2056macro_rules! map_lifts {
2057    ($(($($generics:tt)*) $a:ty,)*) => ($(
2058        unsafe impl <$($generics)*> Lift for $a {
2059            fn linear_lift_from_flat(
2060                cx: &mut LiftContext<'_>,
2061                ty: InterfaceType,
2062                src: &Self::Lower,
2063            ) -> Result<Self> {
2064                let (ptr, len) = lift_pointer_pair_from_flat(cx, src)?;
2065                lift_map(cx, ty, ptr, len)
2066            }
2067
2068            fn linear_lift_from_memory(
2069                cx: &mut LiftContext<'_>,
2070                ty: InterfaceType,
2071                bytes: &[u8],
2072            ) -> Result<Self> {
2073                debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
2074                let (ptr, len) = lift_pointer_pair_from_memory(cx, bytes)?;
2075                lift_map(cx, ty, ptr, len)
2076            }
2077        }
2078    )*)
2079}
2080
2081map_lifts! {
2082    (K: Lift + Eq + Hash, V: Lift, S: BuildHasher + Default + Send + Sync) TryHashMap<K, V, S>,
2083    (K: Lift + Ord, V: Lift) BTreeMap<K, V>,
2084    (K: Lift + Eq + Hash, V: Lift, S: BuildHasher + Default + Send + Sync) IndexMap<K, V, S>,
2085}
2086
2087fn lower_map_to_flat<'a, K, V, U>(
2088    cx: &mut LowerContext<'_, U>,
2089    ty: InterfaceType,
2090    dst: &mut MaybeUninit<[ValRaw; 2]>,
2091    entries: impl ExactSizeIterator<Item = (&'a K, &'a V)>,
2092) -> Result<()>
2093where
2094    K: Lower + 'a,
2095    V: Lower + 'a,
2096{
2097    let map = map_abi(ty, &cx.types);
2098    let (ptr, len) = lower_map_iter(cx, map, entries)?;
2099    lower_pointer_pair_to_flat(cx, dst, ptr, len);
2100    Ok(())
2101}
2102
2103fn lower_map_to_memory<'a, K, V, U>(
2104    cx: &mut LowerContext<'_, U>,
2105    ty: InterfaceType,
2106    offset: usize,
2107    entries: impl ExactSizeIterator<Item = (&'a K, &'a V)>,
2108) -> Result<()>
2109where
2110    K: Lower + 'a,
2111    V: Lower + 'a,
2112{
2113    let map = map_abi(ty, &cx.types);
2114    debug_assert!(offset % (CanonicalAbiInfo::POINTER_PAIR.align32 as usize) == 0);
2115    let (ptr, len) = lower_map_iter(cx, map, entries)?;
2116    lower_pointer_pair_to_memory(cx, offset, ptr, len);
2117    Ok(())
2118}
2119
2120fn lower_map_iter<'a, K, V, U>(
2121    cx: &mut LowerContext<'_, U>,
2122    map: &TypeMap,
2123    entries: impl ExactSizeIterator<Item = (&'a K, &'a V)>,
2124) -> Result<(usize, usize)>
2125where
2126    K: Lower + 'a,
2127    V: Lower + 'a,
2128{
2129    let len = entries.len();
2130    let size = len
2131        .checked_mul(usize::try_from(map.entry_abi.size32)?)
2132        .ok_or_else(|| format_err!("size overflow copying a map"))?;
2133    let ptr = cx.realloc(0, 0, map.entry_abi.align32, size)?;
2134
2135    let mut entry_offset = ptr;
2136    for (key, value) in entries {
2137        // Keys are the first field in each entry tuple.
2138        <K as Lower>::linear_lower_to_memory(key, cx, map.key, entry_offset)?;
2139        // Values start at the precomputed value offset within the tuple.
2140        <V as Lower>::linear_lower_to_memory(
2141            value,
2142            cx,
2143            map.value,
2144            entry_offset + usize::try_from(map.value_offset32)?,
2145        )?;
2146        entry_offset += usize::try_from(map.entry_abi.size32)?;
2147    }
2148
2149    Ok((ptr, len))
2150}
2151
2152/// Helper trait for the Rust types that a `map<K, V>` can be lifted into.
2153trait LiftMap<K, V>: Sized {
2154    /// Creates an empty map with room for `len` entries.
2155    fn with_capacity(len: usize) -> Result<Self>;
2156
2157    /// Adds an entry, replacing any previous value for `key`.
2158    fn push(&mut self, key: K, value: V) -> Result<()>;
2159}
2160
2161impl<K, V, S> LiftMap<K, V> for TryHashMap<K, V, S>
2162where
2163    K: Eq + Hash,
2164    S: BuildHasher + Default,
2165{
2166    fn with_capacity(len: usize) -> Result<Self> {
2167        Ok(TryHashMap::with_capacity_and_hasher(len, S::default())?)
2168    }
2169
2170    fn push(&mut self, key: K, value: V) -> Result<()> {
2171        self.insert(key, value)?;
2172        Ok(())
2173    }
2174}
2175
2176impl<K, V> LiftMap<K, V> for BTreeMap<K, V>
2177where
2178    K: Ord,
2179{
2180    fn with_capacity(_len: usize) -> Result<Self> {
2181        Ok(BTreeMap::new())
2182    }
2183
2184    fn push(&mut self, key: K, value: V) -> Result<()> {
2185        self.insert(key, value);
2186        Ok(())
2187    }
2188}
2189
2190impl<K, V, S> LiftMap<K, V> for IndexMap<K, V, S>
2191where
2192    K: Eq + Hash,
2193    S: BuildHasher + Default,
2194{
2195    fn with_capacity(len: usize) -> Result<Self> {
2196        let mut map = IndexMap::with_hasher(S::default());
2197        map.try_reserve(len)
2198            .map_err(|_| OutOfMemory::new(len.saturating_mul(mem::size_of::<(K, V)>())))?;
2199        Ok(map)
2200    }
2201
2202    // A replaced value keeps the position of the key's first entry.
2203    fn push(&mut self, key: K, value: V) -> Result<()> {
2204        self.insert(key, value);
2205        Ok(())
2206    }
2207}
2208
2209fn lift_map<M, K, V>(
2210    cx: &mut LiftContext<'_>,
2211    ty: InterfaceType,
2212    ptr: usize,
2213    len: usize,
2214) -> Result<M>
2215where
2216    M: LiftMap<K, V>,
2217    K: Lift,
2218    V: Lift,
2219{
2220    let map = map_abi(ty, &cx.types);
2221    match len
2222        .checked_mul(usize::try_from(map.entry_abi.size32)?)
2223        .and_then(|total| ptr.checked_add(total))
2224    {
2225        Some(n) if n <= cx.memory().len() => cx.consume_fuel_array(len, size_of::<(K, V)>())?,
2226        _ => bail!("map pointer/length out of bounds of memory"),
2227    }
2228    if ptr % (map.entry_abi.align32 as usize) != 0 {
2229        bail!("map pointer is not aligned");
2230    }
2231
2232    let mut result = M::with_capacity(len)?;
2233    for i in 0..len {
2234        let entry_base = ptr + (i * usize::try_from(map.entry_abi.size32)?);
2235
2236        let key_bytes = &cx.memory()[entry_base..][..K::SIZE32];
2237        let key = K::linear_lift_from_memory(cx, map.key, key_bytes)?;
2238
2239        let value_bytes =
2240            &cx.memory()[entry_base + usize::try_from(map.value_offset32)?..][..V::SIZE32];
2241        let value = V::linear_lift_from_memory(cx, map.value, value_bytes)?;
2242
2243        result.push(key, value)?;
2244    }
2245
2246    Ok(result)
2247}
2248
2249/// Verify that the given wasm type is a tuple with the expected fields in the right order.
2250fn typecheck_tuple(
2251    ty: &InterfaceType,
2252    types: &InstanceType<'_>,
2253    expected: &[fn(&InterfaceType, &InstanceType<'_>) -> Result<()>],
2254) -> Result<()> {
2255    match ty {
2256        InterfaceType::Tuple(t) => {
2257            let tuple = &types.types[*t];
2258            if tuple.types.len() != expected.len() {
2259                bail!(
2260                    "expected {}-tuple, found {}-tuple",
2261                    expected.len(),
2262                    tuple.types.len()
2263                );
2264            }
2265            for (ty, check) in tuple.types.iter().zip(expected) {
2266                check(ty, types)?;
2267            }
2268            Ok(())
2269        }
2270        other => bail!("expected `tuple` found `{}`", desc(other)),
2271    }
2272}
2273
2274/// Verify that the given wasm type is a record with the expected fields in the right order and with the right
2275/// names.
2276pub fn typecheck_record(
2277    ty: &InterfaceType,
2278    types: &InstanceType<'_>,
2279    expected: &[(&str, fn(&InterfaceType, &InstanceType<'_>) -> Result<()>)],
2280) -> Result<()> {
2281    match ty {
2282        InterfaceType::Record(index) => {
2283            let fields = &types.types[*index].fields;
2284
2285            if fields.len() != expected.len() {
2286                bail!(
2287                    "expected record of {} fields, found {} fields",
2288                    expected.len(),
2289                    fields.len()
2290                );
2291            }
2292
2293            for (field, &(name, check)) in fields.iter().zip(expected) {
2294                check(&field.ty, types)
2295                    .with_context(|| format!("type mismatch for field {name}"))?;
2296
2297                if *field.name != *name {
2298                    bail!("expected record field named {}, found {}", name, field.name);
2299                }
2300            }
2301
2302            Ok(())
2303        }
2304        other => bail!("expected `record` found `{}`", desc(other)),
2305    }
2306}
2307
2308/// Verify that the given wasm type is a variant with the expected cases in the right order and with the right
2309/// names.
2310pub fn typecheck_variant(
2311    ty: &InterfaceType,
2312    types: &InstanceType<'_>,
2313    expected: &[(
2314        &str,
2315        Option<fn(&InterfaceType, &InstanceType<'_>) -> Result<()>>,
2316    )],
2317) -> Result<()> {
2318    match ty {
2319        InterfaceType::Variant(index) => {
2320            let cases = &types.types[*index].cases;
2321
2322            if cases.len() != expected.len() {
2323                bail!(
2324                    "expected variant of {} cases, found {} cases",
2325                    expected.len(),
2326                    cases.len()
2327                );
2328            }
2329
2330            for ((case_name, case_ty), &(name, check)) in cases.iter().zip(expected) {
2331                if **case_name != *name {
2332                    bail!("expected variant case named {name}, found {case_name}");
2333                }
2334
2335                match (check, case_ty) {
2336                    (Some(check), Some(ty)) => check(ty, types)
2337                        .with_context(|| format!("type mismatch for case {name}"))?,
2338                    (None, None) => {}
2339                    (Some(_), None) => {
2340                        bail!("case `{name}` has no type but one was expected")
2341                    }
2342                    (None, Some(_)) => {
2343                        bail!("case `{name}` has a type but none was expected")
2344                    }
2345                }
2346            }
2347
2348            Ok(())
2349        }
2350        other => bail!("expected `variant` found `{}`", desc(other)),
2351    }
2352}
2353
2354/// Verify that the given wasm type is a enum with the expected cases in the right order and with the right
2355/// names.
2356pub fn typecheck_enum(
2357    ty: &InterfaceType,
2358    types: &InstanceType<'_>,
2359    expected: &[&str],
2360) -> Result<()> {
2361    match ty {
2362        InterfaceType::Enum(index) => {
2363            let names = &types.types[*index].names;
2364
2365            if names.len() != expected.len() {
2366                bail!(
2367                    "expected enum of {} names, found {} names",
2368                    expected.len(),
2369                    names.len()
2370                );
2371            }
2372
2373            for (name, expected) in names.iter().zip(expected) {
2374                if **name != **expected {
2375                    bail!("expected enum case named {expected}, found {name}");
2376                }
2377            }
2378
2379            Ok(())
2380        }
2381        other => bail!("expected `enum` found `{}`", desc(other)),
2382    }
2383}
2384
2385/// Verify that the given wasm type is a flags type with the expected flags in the right order and with the right
2386/// names.
2387pub fn typecheck_flags(
2388    ty: &InterfaceType,
2389    types: &InstanceType<'_>,
2390    expected: &[&str],
2391) -> Result<()> {
2392    match ty {
2393        InterfaceType::Flags(index) => {
2394            let names = &types.types[*index].names;
2395
2396            if names.len() != expected.len() {
2397                bail!(
2398                    "expected flags type with {} names, found {} names",
2399                    expected.len(),
2400                    names.len()
2401                );
2402            }
2403
2404            for (name, expected) in names.iter().zip(expected) {
2405                if **name != **expected {
2406                    bail!("expected flag named {expected}, found {name}");
2407                }
2408            }
2409
2410            Ok(())
2411        }
2412        other => bail!("expected `flags` found `{}`", desc(other)),
2413    }
2414}
2415
2416/// Format the specified bitflags using the specified names for debugging
2417pub fn format_flags(bits: &[u32], names: &[&str], f: &mut fmt::Formatter) -> fmt::Result {
2418    f.write_str("(")?;
2419    let mut wrote = false;
2420    for (index, name) in names.iter().enumerate() {
2421        if ((bits[index / 32] >> (index % 32)) & 1) != 0 {
2422            if wrote {
2423                f.write_str("|")?;
2424            } else {
2425                wrote = true;
2426            }
2427
2428            f.write_str(name)?;
2429        }
2430    }
2431    f.write_str(")")
2432}
2433
2434unsafe impl<T> ComponentType for Option<T>
2435where
2436    T: ComponentType,
2437{
2438    type Lower = TupleLower<<u32 as ComponentType>::Lower, T::Lower>;
2439
2440    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::variant_static(&[None, Some(T::ABI)]);
2441    const MAY_REQUIRE_REALLOC: bool = T::MAY_REQUIRE_REALLOC;
2442
2443    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
2444        match ty {
2445            InterfaceType::Option(t) => T::typecheck(&types.types[*t].ty, types),
2446            other => bail!("expected `option` found `{}`", desc(other)),
2447        }
2448    }
2449}
2450
2451unsafe impl<T> ComponentVariant for Option<T>
2452where
2453    T: ComponentType,
2454{
2455    const CASES: &'static [Option<CanonicalAbiInfo>] = &[None, Some(T::ABI)];
2456}
2457
2458unsafe impl<T> Lower for Option<T>
2459where
2460    T: Lower,
2461{
2462    fn linear_lower_to_flat<U>(
2463        &self,
2464        cx: &mut LowerContext<'_, U>,
2465        ty: InterfaceType,
2466        dst: &mut MaybeUninit<Self::Lower>,
2467    ) -> Result<()> {
2468        let payload = match ty {
2469            InterfaceType::Option(ty) => cx.types[ty].ty,
2470            _ => bad_type_info(),
2471        };
2472        match self {
2473            None => {
2474                map_maybe_uninit!(dst.A1).write(ValRaw::i32(0));
2475                // Note that this is unsafe as we're writing an arbitrary
2476                // bit-pattern to an arbitrary type, but part of the unsafe
2477                // contract of the `ComponentType` trait is that we can assign
2478                // any bit-pattern. By writing all zeros here we're ensuring
2479                // that the core wasm arguments this translates to will all be
2480                // zeros (as the canonical ABI requires).
2481                unsafe {
2482                    map_maybe_uninit!(dst.A2).as_mut_ptr().write_bytes(0u8, 1);
2483                }
2484            }
2485            Some(val) => {
2486                map_maybe_uninit!(dst.A1).write(ValRaw::i32(1));
2487                val.linear_lower_to_flat(cx, payload, map_maybe_uninit!(dst.A2))?;
2488            }
2489        }
2490        Ok(())
2491    }
2492
2493    fn linear_lower_to_memory<U>(
2494        &self,
2495        cx: &mut LowerContext<'_, U>,
2496        ty: InterfaceType,
2497        offset: usize,
2498    ) -> Result<()> {
2499        debug_assert!(offset % (Self::ALIGN32 as usize) == 0);
2500        let payload = match ty {
2501            InterfaceType::Option(ty) => cx.types[ty].ty,
2502            _ => bad_type_info(),
2503        };
2504        match self {
2505            None => {
2506                cx.get::<1>(offset)[0] = 0;
2507            }
2508            Some(val) => {
2509                cx.get::<1>(offset)[0] = 1;
2510                val.linear_lower_to_memory(
2511                    cx,
2512                    payload,
2513                    offset + (Self::INFO.payload_offset32 as usize),
2514                )?;
2515            }
2516        }
2517        Ok(())
2518    }
2519}
2520
2521unsafe impl<T> Lift for Option<T>
2522where
2523    T: Lift,
2524{
2525    fn linear_lift_from_flat(
2526        cx: &mut LiftContext<'_>,
2527        ty: InterfaceType,
2528        src: &Self::Lower,
2529    ) -> Result<Self> {
2530        let payload = match ty {
2531            InterfaceType::Option(ty) => cx.types[ty].ty,
2532            _ => bad_type_info(),
2533        };
2534        Ok(match src.A1.get_i32() {
2535            0 => None,
2536            1 => Some(T::linear_lift_from_flat(cx, payload, &src.A2)?),
2537            _ => bail!("invalid option discriminant"),
2538        })
2539    }
2540
2541    fn linear_lift_from_memory(
2542        cx: &mut LiftContext<'_>,
2543        ty: InterfaceType,
2544        bytes: &[u8],
2545    ) -> Result<Self> {
2546        debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
2547        let payload_ty = match ty {
2548            InterfaceType::Option(ty) => cx.types[ty].ty,
2549            _ => bad_type_info(),
2550        };
2551        let discrim = bytes[0];
2552        let payload = &bytes[Self::INFO.payload_offset32 as usize..];
2553        match discrim {
2554            0 => Ok(None),
2555            1 => Ok(Some(T::linear_lift_from_memory(cx, payload_ty, payload)?)),
2556            _ => bail!("invalid option discriminant"),
2557        }
2558    }
2559}
2560
2561#[derive(Clone, Copy)]
2562#[repr(C)]
2563pub struct ResultLower<T: Copy, E: Copy> {
2564    tag: ValRaw,
2565    payload: ResultLowerPayload<T, E>,
2566}
2567
2568#[derive(Clone, Copy)]
2569#[repr(C)]
2570union ResultLowerPayload<T: Copy, E: Copy> {
2571    ok: T,
2572    err: E,
2573}
2574
2575unsafe impl<T, E> ComponentType for Result<T, E>
2576where
2577    T: ComponentType,
2578    E: ComponentType,
2579{
2580    type Lower = ResultLower<T::Lower, E::Lower>;
2581
2582    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::variant_static(&[Some(T::ABI), Some(E::ABI)]);
2583    const MAY_REQUIRE_REALLOC: bool = T::MAY_REQUIRE_REALLOC || E::MAY_REQUIRE_REALLOC;
2584
2585    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
2586        match ty {
2587            InterfaceType::Result(r) => {
2588                let result = &types.types[*r];
2589                match &result.ok {
2590                    Some(ty) => T::typecheck(ty, types)?,
2591                    None if T::IS_RUST_UNIT_TYPE => {}
2592                    None => bail!("expected no `ok` type"),
2593                }
2594                match &result.err {
2595                    Some(ty) => E::typecheck(ty, types)?,
2596                    None if E::IS_RUST_UNIT_TYPE => {}
2597                    None => bail!("expected no `err` type"),
2598                }
2599                Ok(())
2600            }
2601            other => bail!("expected `result` found `{}`", desc(other)),
2602        }
2603    }
2604}
2605
2606/// Lowers the payload of a variant into the storage for the entire payload,
2607/// handling writing zeros at the end of the representation if this payload is
2608/// smaller than the entire flat representation.
2609///
2610/// * `payload` - the flat storage space for the entire payload of the variant
2611/// * `typed_payload` - projection from the payload storage space to the
2612///   individual storage space for this variant.
2613/// * `lower` - lowering operation used to initialize the `typed_payload` return
2614///   value.
2615///
2616/// For more information on this se the comments in the `Lower for Result`
2617/// implementation below.
2618pub unsafe fn lower_payload<P, T>(
2619    payload: &mut MaybeUninit<P>,
2620    typed_payload: impl FnOnce(&mut MaybeUninit<P>) -> &mut MaybeUninit<T>,
2621    lower: impl FnOnce(&mut MaybeUninit<T>) -> Result<()>,
2622) -> Result<()> {
2623    let typed = typed_payload(payload);
2624    lower(typed)?;
2625
2626    let typed_len = unsafe { storage_as_slice(typed).len() };
2627    let payload = unsafe { storage_as_slice_mut(payload) };
2628    for slot in payload[typed_len..].iter_mut() {
2629        slot.write(ValRaw::u64(0));
2630    }
2631    Ok(())
2632}
2633
2634unsafe impl<T, E> ComponentVariant for Result<T, E>
2635where
2636    T: ComponentType,
2637    E: ComponentType,
2638{
2639    const CASES: &'static [Option<CanonicalAbiInfo>] = &[Some(T::ABI), Some(E::ABI)];
2640}
2641
2642unsafe impl<T, E> Lower for Result<T, E>
2643where
2644    T: Lower,
2645    E: Lower,
2646{
2647    fn linear_lower_to_flat<U>(
2648        &self,
2649        cx: &mut LowerContext<'_, U>,
2650        ty: InterfaceType,
2651        dst: &mut MaybeUninit<Self::Lower>,
2652    ) -> Result<()> {
2653        let (ok, err) = match ty {
2654            InterfaceType::Result(ty) => {
2655                let ty = &cx.types[ty];
2656                (ty.ok, ty.err)
2657            }
2658            _ => bad_type_info(),
2659        };
2660
2661        // This implementation of `Lower::lower`, if you're reading these from
2662        // the top of this file, is the first location that the "join" logic of
2663        // the component model's canonical ABI encountered. The rough problem is
2664        // that let's say we have a component model type of the form:
2665        //
2666        //      (result u64 (error (tuple f32 u16)))
2667        //
2668        // The flat representation of this is actually pretty tricky. Currently
2669        // it is:
2670        //
2671        //      i32 i64 i32
2672        //
2673        // The first `i32` is the discriminant for the `result`, and the payload
2674        // is represented by `i64 i32`. The "ok" variant will only use the `i64`
2675        // and the "err" variant will use both `i64` and `i32`.
2676        //
2677        // In the "ok" variant the first issue is encountered. The size of one
2678        // variant may not match the size of the other variants. All variants
2679        // start at the "front" but when lowering a type we need to be sure to
2680        // initialize the later variants (lest we leak random host memory into
2681        // the guest module). Due to how the `Lower` type is represented as a
2682        // `union` of all the variants what ends up happening here is that
2683        // internally within the `lower_payload` after the typed payload is
2684        // lowered the remaining bits of the payload that weren't initialized
2685        // are all set to zero. This will guarantee that we'll write to all the
2686        // slots for each variant.
2687        //
2688        // The "err" variant encounters the second issue, however, which is that
2689        // the flat representation for each type may differ between payloads. In
2690        // the "ok" arm an `i64` is written, but the `lower` implementation for
2691        // the "err" arm will write an `f32` and then an `i32`. For this
2692        // implementation of `lower` to be valid the `f32` needs to get inflated
2693        // to an `i64` with zero-padding in the upper bits. What may be
2694        // surprising, however, is that none of this is handled in this file.
2695        // This implementation looks like it's blindly deferring to `E::lower`
2696        // and hoping it does the right thing.
2697        //
2698        // In reality, however, the correctness of variant lowering relies on
2699        // two subtle details of the `ValRaw` implementation in Wasmtime:
2700        //
2701        // 1. First the `ValRaw` value always contains little-endian values.
2702        //    This means that if a `u32` is written, a `u64` is read, and then
2703        //    the `u64` has its upper bits truncated the original value will
2704        //    always be retained. This is primarily here for big-endian
2705        //    platforms where if it weren't little endian then the opposite
2706        //    would occur and the wrong value would be read.
2707        //
2708        // 2. Second, and perhaps even more subtly, the `ValRaw` constructors
2709        //    for 32-bit types actually always initialize 64-bits of the
2710        //    `ValRaw`. In the component model flat ABI only 32 and 64-bit types
2711        //    are used so 64-bits is big enough to contain everything. This
2712        //    means that when a `ValRaw` is written into the destination it will
2713        //    always, whether it's needed or not, be "ready" to get extended up
2714        //    to 64-bits.
2715        //
2716        // Put together these two subtle guarantees means that all `Lower`
2717        // implementations can be written "naturally" as one might naively
2718        // expect. Variants will, on each arm, zero out remaining fields and all
2719        // writes to the flat representation will automatically be 64-bit writes
2720        // meaning that if the value is read as a 64-bit value, which isn't
2721        // known at the time of the write, it'll still be correct.
2722        match self {
2723            Ok(e) => {
2724                map_maybe_uninit!(dst.tag).write(ValRaw::i32(0));
2725                unsafe {
2726                    lower_payload(
2727                        map_maybe_uninit!(dst.payload),
2728                        |payload| map_maybe_uninit!(payload.ok),
2729                        |dst| match ok {
2730                            Some(ok) => e.linear_lower_to_flat(cx, ok, dst),
2731                            None => Ok(()),
2732                        },
2733                    )
2734                }
2735            }
2736            Err(e) => {
2737                map_maybe_uninit!(dst.tag).write(ValRaw::i32(1));
2738                unsafe {
2739                    lower_payload(
2740                        map_maybe_uninit!(dst.payload),
2741                        |payload| map_maybe_uninit!(payload.err),
2742                        |dst| match err {
2743                            Some(err) => e.linear_lower_to_flat(cx, err, dst),
2744                            None => Ok(()),
2745                        },
2746                    )
2747                }
2748            }
2749        }
2750    }
2751
2752    fn linear_lower_to_memory<U>(
2753        &self,
2754        cx: &mut LowerContext<'_, U>,
2755        ty: InterfaceType,
2756        offset: usize,
2757    ) -> Result<()> {
2758        let (ok, err) = match ty {
2759            InterfaceType::Result(ty) => {
2760                let ty = &cx.types[ty];
2761                (ty.ok, ty.err)
2762            }
2763            _ => bad_type_info(),
2764        };
2765        debug_assert!(offset % (Self::ALIGN32 as usize) == 0);
2766        let payload_offset = Self::INFO.payload_offset32 as usize;
2767        match self {
2768            Ok(e) => {
2769                cx.get::<1>(offset)[0] = 0;
2770                if let Some(ok) = ok {
2771                    e.linear_lower_to_memory(cx, ok, offset + payload_offset)?;
2772                }
2773            }
2774            Err(e) => {
2775                cx.get::<1>(offset)[0] = 1;
2776                if let Some(err) = err {
2777                    e.linear_lower_to_memory(cx, err, offset + payload_offset)?;
2778                }
2779            }
2780        }
2781        Ok(())
2782    }
2783}
2784
2785unsafe impl<T, E> Lift for Result<T, E>
2786where
2787    T: Lift,
2788    E: Lift,
2789{
2790    #[inline]
2791    fn linear_lift_from_flat(
2792        cx: &mut LiftContext<'_>,
2793        ty: InterfaceType,
2794        src: &Self::Lower,
2795    ) -> Result<Self> {
2796        let (ok, err) = match ty {
2797            InterfaceType::Result(ty) => {
2798                let ty = &cx.types[ty];
2799                (ty.ok, ty.err)
2800            }
2801            _ => bad_type_info(),
2802        };
2803        // Note that this implementation specifically isn't trying to actually
2804        // reinterpret or alter the bits of `lower` depending on which variant
2805        // we're lifting. This ends up all working out because the value is
2806        // stored in little-endian format.
2807        //
2808        // When stored in little-endian format the `{T,E}::Lower`, when each
2809        // individual `ValRaw` is read, means that if an i64 value, extended
2810        // from an i32 value, was stored then when the i32 value is read it'll
2811        // automatically ignore the upper bits.
2812        //
2813        // This "trick" allows us to seamlessly pass through the `Self::Lower`
2814        // representation into the lifting/lowering without trying to handle
2815        // "join"ed types as per the canonical ABI. It just so happens that i64
2816        // bits will naturally be reinterpreted as f64. Additionally if the
2817        // joined type is i64 but only the lower bits are read that's ok and we
2818        // don't need to validate the upper bits.
2819        //
2820        // This is largely enabled by WebAssembly/component-model#35 where no
2821        // validation needs to be performed for ignored bits and bytes here.
2822        Ok(match src.tag.get_i32() {
2823            0 => Ok(unsafe { lift_option(cx, ok, &src.payload.ok)? }),
2824            1 => Err(unsafe { lift_option(cx, err, &src.payload.err)? }),
2825            _ => bail!("invalid expected discriminant"),
2826        })
2827    }
2828
2829    #[inline]
2830    fn linear_lift_from_memory(
2831        cx: &mut LiftContext<'_>,
2832        ty: InterfaceType,
2833        bytes: &[u8],
2834    ) -> Result<Self> {
2835        debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
2836        let discrim = bytes[0];
2837        let payload = &bytes[Self::INFO.payload_offset32 as usize..];
2838        let (ok, err) = match ty {
2839            InterfaceType::Result(ty) => {
2840                let ty = &cx.types[ty];
2841                (ty.ok, ty.err)
2842            }
2843            _ => bad_type_info(),
2844        };
2845        match discrim {
2846            0 => Ok(Ok(load_option(cx, ok, &payload[..T::SIZE32])?)),
2847            1 => Ok(Err(load_option(cx, err, &payload[..E::SIZE32])?)),
2848            _ => bail!("invalid expected discriminant"),
2849        }
2850    }
2851}
2852
2853fn lift_option<T>(cx: &mut LiftContext<'_>, ty: Option<InterfaceType>, src: &T::Lower) -> Result<T>
2854where
2855    T: Lift,
2856{
2857    match ty {
2858        Some(ty) => T::linear_lift_from_flat(cx, ty, src),
2859        None => Ok(empty_lift()),
2860    }
2861}
2862
2863fn load_option<T>(cx: &mut LiftContext<'_>, ty: Option<InterfaceType>, bytes: &[u8]) -> Result<T>
2864where
2865    T: Lift,
2866{
2867    match ty {
2868        Some(ty) => T::linear_lift_from_memory(cx, ty, bytes),
2869        None => Ok(empty_lift()),
2870    }
2871}
2872
2873fn empty_lift<T>() -> T
2874where
2875    T: Lift,
2876{
2877    assert!(T::IS_RUST_UNIT_TYPE);
2878    assert_eq!(mem::size_of::<T>(), 0);
2879    unsafe { MaybeUninit::uninit().assume_init() }
2880}
2881
2882/// Helper structure to define `Lower` for tuples below.
2883///
2884/// Uses default type parameters to have fields be zero-sized and not present
2885/// in memory for smaller tuple values.
2886#[expect(non_snake_case, reason = "more amenable to macro-generated code")]
2887#[doc(hidden)]
2888#[derive(Clone, Copy)]
2889#[repr(C)]
2890pub struct TupleLower<
2891    T1 = (),
2892    T2 = (),
2893    T3 = (),
2894    T4 = (),
2895    T5 = (),
2896    T6 = (),
2897    T7 = (),
2898    T8 = (),
2899    T9 = (),
2900    T10 = (),
2901    T11 = (),
2902    T12 = (),
2903    T13 = (),
2904    T14 = (),
2905    T15 = (),
2906    T16 = (),
2907    T17 = (),
2908> {
2909    // NB: these names match the names in `for_each_function_signature!`
2910    A1: T1,
2911    A2: T2,
2912    A3: T3,
2913    A4: T4,
2914    A5: T5,
2915    A6: T6,
2916    A7: T7,
2917    A8: T8,
2918    A9: T9,
2919    A10: T10,
2920    A11: T11,
2921    A12: T12,
2922    A13: T13,
2923    A14: T14,
2924    A15: T15,
2925    A16: T16,
2926    A17: T17,
2927    _align_tuple_lower0_correctly: [ValRaw; 0],
2928}
2929
2930macro_rules! impl_component_ty_for_tuples {
2931    ($n:tt $($t:ident)*) => {
2932        #[allow(non_snake_case, reason = "macro-generated code")]
2933        unsafe impl<$($t,)*> ComponentType for ($($t,)*)
2934            where $($t: ComponentType),*
2935        {
2936            type Lower = TupleLower<$($t::Lower),*>;
2937
2938            const ABI: CanonicalAbiInfo = CanonicalAbiInfo::record_static(&[
2939                $($t::ABI),*
2940            ]);
2941            const MAY_REQUIRE_REALLOC: bool = false $(|| $t::MAY_REQUIRE_REALLOC)*;
2942
2943            const IS_RUST_UNIT_TYPE: bool = {
2944                let mut _is_unit = true;
2945                $(
2946                    let _anything_to_bind_the_macro_variable = $t::IS_RUST_UNIT_TYPE;
2947                    _is_unit = false;
2948                )*
2949                _is_unit
2950            };
2951
2952            fn typecheck(
2953                ty: &InterfaceType,
2954                types: &InstanceType<'_>,
2955            ) -> Result<()> {
2956                typecheck_tuple(ty, types, &[$($t::typecheck),*])
2957            }
2958        }
2959
2960        #[allow(non_snake_case, reason = "macro-generated code")]
2961        unsafe impl<$($t,)*> Lower for ($($t,)*)
2962            where $($t: Lower),*
2963        {
2964            fn linear_lower_to_flat<U>(
2965                &self,
2966                cx: &mut LowerContext<'_, U>,
2967                ty: InterfaceType,
2968                _dst: &mut MaybeUninit<Self::Lower>,
2969            ) -> Result<()> {
2970                let types = match ty {
2971                    InterfaceType::Tuple(t) => &cx.types[t].types,
2972                    _ => bad_type_info(),
2973                };
2974                let ($($t,)*) = self;
2975                let mut _types = types.iter();
2976                $(
2977                    let ty = *_types.next().unwrap_or_else(bad_type_info);
2978                    $t.linear_lower_to_flat(cx, ty, map_maybe_uninit!(_dst.$t))?;
2979                )*
2980                Ok(())
2981            }
2982
2983            fn linear_lower_to_memory<U>(
2984                &self,
2985                cx: &mut LowerContext<'_, U>,
2986                ty: InterfaceType,
2987                mut _offset: usize,
2988            ) -> Result<()> {
2989                debug_assert!(_offset % (Self::ALIGN32 as usize) == 0);
2990                let types = match ty {
2991                    InterfaceType::Tuple(t) => &cx.types[t].types,
2992                    _ => bad_type_info(),
2993                };
2994                let ($($t,)*) = self;
2995                let mut _types = types.iter();
2996                $(
2997                    let ty = *_types.next().unwrap_or_else(bad_type_info);
2998                    $t.linear_lower_to_memory(cx, ty, $t::ABI.next_field32_size(&mut _offset))?;
2999                )*
3000                Ok(())
3001            }
3002        }
3003
3004        #[allow(non_snake_case, reason = "macro-generated code")]
3005        unsafe impl<$($t,)*> Lift for ($($t,)*)
3006            where $($t: Lift),*
3007        {
3008            #[inline]
3009            fn linear_lift_from_flat(cx: &mut LiftContext<'_>, ty: InterfaceType, _src: &Self::Lower) -> Result<Self> {
3010                let types = match ty {
3011                    InterfaceType::Tuple(t) => &cx.types[t].types,
3012                    _ => bad_type_info(),
3013                };
3014                let mut _types = types.iter();
3015                Ok(($(
3016                    $t::linear_lift_from_flat(
3017                        cx,
3018                        *_types.next().unwrap_or_else(bad_type_info),
3019                        &_src.$t,
3020                    )?,
3021                )*))
3022            }
3023
3024            #[inline]
3025            fn linear_lift_from_memory(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
3026                debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
3027                let types = match ty {
3028                    InterfaceType::Tuple(t) => &cx.types[t].types,
3029                    _ => bad_type_info(),
3030                };
3031                let mut _types = types.iter();
3032                let mut _offset = 0;
3033                $(
3034                    let ty = *_types.next().unwrap_or_else(bad_type_info);
3035                    let $t = $t::linear_lift_from_memory(cx, ty, &bytes[$t::ABI.next_field32_size(&mut _offset)..][..$t::SIZE32])?;
3036                )*
3037                Ok(($($t,)*))
3038            }
3039        }
3040
3041        #[allow(non_snake_case, reason = "macro-generated code")]
3042        unsafe impl<$($t,)*> ComponentNamedList for ($($t,)*)
3043            where $($t: ComponentType),*
3044        {}
3045    };
3046}
3047
3048for_each_function_signature!(impl_component_ty_for_tuples);
3049
3050unsafe impl<T, const N: usize> ComponentType for [T; N]
3051where
3052    T: ComponentType,
3053{
3054    type Lower = [T::Lower; N];
3055
3056    const ABI: CanonicalAbiInfo = CanonicalAbiInfo::fixed_length_list_static(&T::ABI, N);
3057
3058    fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
3059        match ty {
3060            InterfaceType::FixedLengthList(t) => {
3061                let list = &types.types[*t];
3062                match usize::try_from(list.size) {
3063                    Ok(n) if n == N => {}
3064                    _ => bail!("expected `list<_, {}>` found `list<_, {N}>`", list.size),
3065                }
3066                T::typecheck(&list.element, types)
3067            }
3068            other => bail!("expected `list<_, {N}>` found `{}`", desc(other)),
3069        }
3070    }
3071}
3072
3073unsafe impl<T, const N: usize> Lower for [T; N]
3074where
3075    T: Lower,
3076{
3077    fn linear_lower_to_flat<U>(
3078        &self,
3079        cx: &mut LowerContext<'_, U>,
3080        ty: InterfaceType,
3081        dst: &mut MaybeUninit<Self::Lower>,
3082    ) -> Result<()> {
3083        let element = match ty {
3084            InterfaceType::FixedLengthList(ty) => cx.types[ty].element,
3085            _ => bad_type_info(),
3086        };
3087        for (i, val) in self.iter().enumerate() {
3088            val.linear_lower_to_flat(cx, element, map_maybe_uninit!(dst[i]))?;
3089        }
3090        Ok(())
3091    }
3092
3093    fn linear_lower_to_memory<U>(
3094        &self,
3095        cx: &mut LowerContext<'_, U>,
3096        ty: InterfaceType,
3097        offset: usize,
3098    ) -> Result<()> {
3099        debug_assert!(offset % (Self::ALIGN32 as usize) == 0);
3100        let element = match ty {
3101            InterfaceType::FixedLengthList(ty) => cx.types[ty].element,
3102            _ => bad_type_info(),
3103        };
3104        for (i, val) in self.iter().enumerate() {
3105            val.linear_lower_to_memory(cx, element, offset + i * T::SIZE32)?;
3106        }
3107        Ok(())
3108    }
3109}
3110
3111unsafe impl<T, const N: usize> Lift for [T; N]
3112where
3113    T: Lift + Sized,
3114{
3115    fn linear_lift_from_flat(
3116        cx: &mut LiftContext<'_>,
3117        ty: InterfaceType,
3118        src: &Self::Lower,
3119    ) -> Result<Self> {
3120        let element = match ty {
3121            InterfaceType::FixedLengthList(ty) => cx.types[ty].element,
3122            _ => bad_type_info(),
3123        };
3124        array_try_from_fn(|n| T::linear_lift_from_flat(cx, element, &src[n]))
3125    }
3126
3127    fn linear_lift_from_memory(
3128        cx: &mut LiftContext<'_>,
3129        ty: InterfaceType,
3130        bytes: &[u8],
3131    ) -> Result<Self> {
3132        debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);
3133        let element = match ty {
3134            InterfaceType::FixedLengthList(ty) => cx.types[ty].element,
3135            _ => bad_type_info(),
3136        };
3137        let mut offset = 0;
3138        array_try_from_fn(|_n| {
3139            let res = T::linear_lift_from_memory(cx, element, &bytes[offset..offset + T::SIZE32]);
3140            offset += T::SIZE32;
3141            res
3142        })
3143    }
3144}
3145
3146pub fn desc(ty: &InterfaceType) -> &'static str {
3147    match ty {
3148        InterfaceType::U8 => "u8",
3149        InterfaceType::S8 => "s8",
3150        InterfaceType::U16 => "u16",
3151        InterfaceType::S16 => "s16",
3152        InterfaceType::U32 => "u32",
3153        InterfaceType::S32 => "s32",
3154        InterfaceType::U64 => "u64",
3155        InterfaceType::S64 => "s64",
3156        InterfaceType::Float32 => "f32",
3157        InterfaceType::Float64 => "f64",
3158        InterfaceType::Bool => "bool",
3159        InterfaceType::Char => "char",
3160        InterfaceType::String => "string",
3161        InterfaceType::List(_) => "list",
3162        InterfaceType::Tuple(_) => "tuple",
3163        InterfaceType::Option(_) => "option",
3164        InterfaceType::Result(_) => "result",
3165
3166        InterfaceType::Record(_) => "record",
3167        InterfaceType::Variant(_) => "variant",
3168        InterfaceType::Flags(_) => "flags",
3169        InterfaceType::Enum(_) => "enum",
3170        InterfaceType::Own(_) => "owned resource",
3171        InterfaceType::Borrow(_) => "borrowed resource",
3172        InterfaceType::Future(_) => "future",
3173        InterfaceType::Stream(_) => "stream",
3174        InterfaceType::ErrorContext(_) => "error-context",
3175        InterfaceType::Map(_) => "map",
3176        InterfaceType::FixedLengthList(_) => "list<_, N>",
3177    }
3178}
3179
3180#[cold]
3181#[doc(hidden)]
3182pub fn bad_type_info<T>() -> T {
3183    // NB: should consider something like `unreachable_unchecked` here if this
3184    // becomes a performance bottleneck at some point, but that also comes with
3185    // a tradeoff of propagating a lot of unsafety, so it may not be worth it.
3186    panic!("bad type information detected");
3187}