A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fixed-length lists, host side (#12315)
Christof Petig30ea2ab5b415
diff --git a/crates/c-api/src/component/types/val.rs b/crates/c-api/src/component/types/val.rsindex c3e4f1630b..80076d34f1 100644--- a/crates/c-api/src/component/types/val.rs+++ b/crates/c-api/src/component/types/val.rs@@ -32,6 +32,7 @@ pub enum wasmtime_component_valtype_t {Stream(Box<wasmtime_component_stream_type_t>),ErrorContext,Map(Box<wasmtime_component_map_type_t>),+ FixedLengthList(Box<wasmtime_component_fixed_length_list_type_t>),}impl From<Type> for wasmtime_component_valtype_t {@@ -63,6 +64,7 @@ impl From<Type> for wasmtime_component_valtype_t {Type::Future(ty) => Self::Future(Box::new(ty.into())),Type::Stream(ty) => Self::Stream(Box::new(ty.into())),Type::Map(ty) => Self::Map(Box::new(ty.into())),+ Type::FixedLengthList(ty) => Self::FixedLengthList(Box::new(ty.into())),Type::ErrorContext => Self::ErrorContext,}}@@ -110,6 +112,25 @@ pub extern "C" fn wasmtime_component_list_type_element(type_ret.write(ty.ty.ty().into());}+type_wrapper! {+ #[derive(PartialEq)]+ pub struct wasmtime_component_fixed_length_list_type_t {+ pub(crate) ty: FixedLengthList,+ }++ clone: wasmtime_component_fixed_length_list_type_clone,+ delete: wasmtime_component_fixed_length_list_type_delete,+ equal: wasmtime_component_fixed_length_list_type_equal,+}++#[unsafe(no_mangle)]+pub extern "C" fn wasmtime_component_fixed_length_list_type_element(+ ty: &wasmtime_component_fixed_length_list_type_t,+ type_ret: &mut MaybeUninit<wasmtime_component_valtype_t>,+) {+ type_ret.write(ty.ty.ty().into());+}+type_wrapper! {#[derive(PartialEq)]pub struct wasmtime_component_map_type_t {diff --git a/crates/c-api/src/component/val.rs b/crates/c-api/src/component/val.rsindex 98bbaef070..c57365493f 100644--- a/crates/c-api/src/component/val.rs+++ b/crates/c-api/src/component/val.rs@@ -274,6 +274,7 @@ pub enum wasmtime_component_val_t {Flags(wasmtime_component_valflags_t),Resource(Box<wasmtime_component_resource_any_t>),Map(wasmtime_component_valmap_t),+ FixedLengthList(wasmtime_component_vallist_t),}// Safety: the C API async contract (documented in async.h) guarantees that@@ -321,6 +322,7 @@ impl From<&wasmtime_component_val_t> for Val {wasmtime_component_val_t::Flags(x) => Val::Flags(x.into()),wasmtime_component_val_t::Map(x) => Val::Map(x.into()),wasmtime_component_val_t::Resource(x) => Val::Resource(x.resource),+ wasmtime_component_val_t::FixedLengthList(x) => Val::FixedLengthList(x.into()),}}}@@ -363,6 +365,9 @@ impl From<&Val> for wasmtime_component_val_t {Val::Future(_) => todo!(),Val::Stream(_) => todo!(),Val::ErrorContext(_) => todo!(),+ Val::FixedLengthList(ty) => wasmtime_component_val_t::FixedLengthList(+ wasmtime_component_vallist_t::from(ty.as_ref()),+ ),}}}diff --git a/crates/core/src/array.rs b/crates/core/src/array.rsnew file mode 100644index 0000000000..c17cf01013--- /dev/null+++ b/crates/core/src/array.rs@@ -0,0 +1,147 @@+//! Not yet stable array functions needed by fixed length list++use core::mem::MaybeUninit;++// See https://doc.rust-lang.org/core/array/fn.try_from_fn.html for the not yet stable original+//+/// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.+/// Unlike [`core::array::from_fn`], where the element creation can't fail, this version will return an error+/// if any element creation was unsuccessful.+///+/// The return type of this function depends on the return type of the closure.+/// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.+///+/// Note: Unlike the unstable core implementation this function only supports a closure returning a Result.+///+/// # Arguments+///+/// * `cb`: Callback where the passed argument is the current array index.+///+/// # Example+///+/// ```rust+/// use wasmtime_internal_core::array::array_try_from_fn;+///+/// let array: Result<[u8; 5], _> = array_try_from_fn(|i| i.try_into());+/// assert_eq!(array, Ok([0, 1, 2, 3, 4]));+///+/// let array: Result<[i8; 200], _> = array_try_from_fn(|i| i.try_into());+/// assert!(array.is_err());+/// ```+//+// this is a reimplementation of array::try_from_fn, replace once that became stable+pub fn array_try_from_fn<E, T, const N: usize>(+ mut cb: impl FnMut(usize) -> Result<T, E>,+) -> Result<[T; N], E> {+ let mut result: MaybeUninit<[T; N]> = MaybeUninit::uninit();+ {+ struct DropGuard<'a, T> {+ slice: &'a mut [MaybeUninit<T>],+ initialized: usize,+ }+ impl<T> Drop for DropGuard<'_, T> {+ fn drop(&mut self) {+ for slot in self.slice[..self.initialized].iter_mut() {+ // SAFETY: self.initialized is the number of valid elements at all time+ // we can assume init and drop them directly+ unsafe {+ slot.assume_init_drop();+ }+ }+ }+ }+ let mut guard = DropGuard {+ // Note .as_mut() would be ideal but requires 1.95, so we work around it+ // SAFETY: We cast from an uninitialized ptr to an array of T to an array of uninitialized T+ // The bit pattern is identical, and unstable provides the safe function transpose for this+ // Turning a pointer to uninitialized memory into a mutable reference to uninitialized memory is a valid op+ slice: unsafe { &mut *(result.as_mut_ptr().cast::<[MaybeUninit<T>; N]>()) },+ initialized: 0,+ };+ for (i, slot) in guard.slice.iter_mut().enumerate() {+ slot.write(cb(i)?);+ guard.initialized = i + 1;+ }+ // don't drop valid elements+ guard.initialized = 0;+ }+ // SAFETY: All N elements have been successfully written to here+ unsafe { Ok(result.assume_init()) }+}++#[cfg(test)]+mod test {+ use super::array_try_from_fn;+ use core::cell::Cell;+ use std_alloc::rc::Rc;+ use std_alloc::string::{String, ToString};++ // original test from the documentation+ #[test]+ fn array_try_from_fn_test() {+ let array: Result<[u8; 5], _> = array_try_from_fn(|i| i.try_into());+ assert_eq!(array, Ok([0, 1, 2, 3, 4]));++ let array: Result<[i8; 200], _> = array_try_from_fn(|i| i.try_into());+ assert!(array.is_err());+ }++ #[test]+ fn smoke_try_from_fn() {+ let arr = array_try_from_fn(|i| Ok::<_, ()>(i * 2)).unwrap();+ assert_eq!(arr, [0, 2, 4, 6, 8]);+ assert_eq!(+ array_try_from_fn::<_, _, 3>(|i| if i == 0 { Ok(0) } else { Err(1) }).unwrap_err(),+ 1+ )+ }++ #[test]+ fn try_from_fn_dont_drop_on_success() {+ let arr = array_try_from_fn(|i| Ok::<_, String>(i.to_string())).unwrap();+ assert_eq!(arr, ["0", "1"]);+ }++ #[test]+ fn try_from_fn_drop_on_failure() {+ let drops = Rc::new(Cell::new(0));++ struct DropCounter(Rc<Cell<usize>>);+ impl Drop for DropCounter {+ fn drop(&mut self) {+ self.0.set(self.0.get() + 1);+ }+ }++ let err = array_try_from_fn::<_, _, 10>(|i| match i {+ 0..=4 => Ok(DropCounter(drops.clone())),+ _ => Err("error".to_string()),+ })+ .err()+ .unwrap();+ assert_eq!(err, "error");+ assert_eq!(drops.get(), 5);+ }++ #[test]+ #[cfg(feature = "std")]+ fn try_from_fn_drop_on_panic() {+ let drops = Rc::new(Cell::new(0));++ struct DropCounter(Rc<Cell<usize>>);+ impl Drop for DropCounter {+ fn drop(&mut self) {+ self.0.set(self.0.get() + 1);+ }+ }++ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ array_try_from_fn::<_, _, 10>(|i| match i {+ 0..=4 => Ok::<_, String>(DropCounter(drops.clone())),+ _ => panic!("hi"),+ })+ }));+ assert!(result.is_err());+ assert_eq!(drops.get(), 5);+ }+}diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rsindex 09cd072bdd..9935de01b1 100644--- a/crates/core/src/lib.rs+++ b/crates/core/src/lib.rs@@ -19,6 +19,7 @@ extern crate alloc as std_alloc;extern crate std;pub mod alloc;+pub mod array;pub mod error;pub mod math;pub mod mpk;diff --git a/crates/environ/src/component/types.rs b/crates/environ/src/component/types.rsindex 1400159cbe..56c2874fa8 100644--- a/crates/environ/src/component/types.rs+++ b/crates/environ/src/component/types.rs@@ -751,6 +751,48 @@ impl CanonicalAbiInfo {return ret;}+ /// Returns the abi for a fixed length list+ pub const fn fixed_length_list_static(+ element: &CanonicalAbiInfo,+ count: usize,+ ) -> CanonicalAbiInfo {+ if count <= u32::MAX as usize {+ let count = count as u32;+ CanonicalAbiInfo {+ size32: element.size32.saturating_mul(count),+ align32: element.align32,+ size64: element.size64.saturating_mul(count),+ align64: element.align64,++ flat_count: match element.flat_count {+ None => None,+ Some(c) =>+ // .and_then(|c| u8::try_from(c).ok()) is not yet const+ {+ match count.checked_mul(c as u32) {+ Some(product) => {+ if product as usize > MAX_FLAT_TYPES || product > u8::MAX as u32 {+ None+ } else {+ Some(product as u8)+ }+ }+ None => None,+ }+ }+ },+ }+ } else {+ CanonicalAbiInfo {+ size32: u32::MAX,+ align32: element.align32,+ size64: u32::MAX,+ align64: element.align64,+ flat_count: None,+ }+ }+ }+/// Returns the delta from the current value of `offset` to align properly/// and read the next record field of type `abi` for 32-bit memories.pub fn next_field32(&self, offset: &mut u32) -> u32 {diff --git a/crates/environ/src/component/types_builder.rs b/crates/environ/src/component/types_builder.rsindex d6cd8ec85b..a9822ea1af 100644--- a/crates/environ/src/component/types_builder.rs+++ b/crates/environ/src/component/types_builder.rs@@ -584,14 +584,10 @@ impl ComponentTypesBuilder {size: u32,) -> TypeFixedLengthListIndex {let element_abi = self.component_types.canonical_abi(&element);- let mut abi = element_abi.clone();- // this assumes that size32 is already rounded up to alignment- abi.size32 = element_abi.size32.saturating_mul(size);- abi.size64 = element_abi.size64.saturating_mul(size);- abi.flat_count = element_abi- .flat_count- .zip(u8::try_from(size).ok())- .and_then(|(flat_count, size)| flat_count.checked_mul(size));+ let abi = CanonicalAbiInfo::fixed_length_list_static(+ element_abi,+ size.try_into().expect("size should fit into usize"),+ );self.add_fixed_length_list_type(TypeFixedLengthList { element, size, abi })}diff --git a/crates/fuzzing/src/oracles/component_api.rs b/crates/fuzzing/src/oracles/component_api.rsindex ed904756a5..24ab9a1be7 100644--- a/crates/fuzzing/src/oracles/component_api.rs+++ b/crates/fuzzing/src/oracles/component_api.rs@@ -138,6 +138,11 @@ fn arbitrary_val(}).collect::<arbitrary::Result<_>>()?,),+ Type::FixedLengthList(list) => Val::FixedLengthList(+ (0..list.len())+ .map(|_| arbitrary_val(&list.ty(), fuel, input))+ .collect::<arbitrary::Result<_>>()?,+ ),Type::Map(map) => {let mut pairs = Vec::new();diff --git a/crates/wasmtime/src/runtime/component/func/typed.rs b/crates/wasmtime/src/runtime/component/func/typed.rsindex 3022cf68fb..d8ab37bb98 100644--- a/crates/wasmtime/src/runtime/component/func/typed.rs+++ b/crates/wasmtime/src/runtime/component/func/typed.rs@@ -12,6 +12,7 @@ use core::iter;use core::marker;use core::mem::{self, MaybeUninit};use core::str;+use wasmtime_core::array::array_try_from_fn;use wasmtime_environ::component::{CanonicalAbiInfo, ComponentTypes, InterfaceType, MAX_FLAT_PARAMS, MAX_FLAT_RESULTS,OptionsIndex, StringEncoding, TypeMap, VariantInfo,@@ -2973,6 +2974,99 @@ macro_rules! impl_component_ty_for_tuples {for_each_function_signature!(impl_component_ty_for_tuples);+unsafe impl<T, const N: usize> ComponentType for [T; N]+where+ T: ComponentType,+{+ type Lower = [T::Lower; N];++ #[allow(+ clippy::cast_possible_truncation,+ reason = "there is no fallible const conversion, yet"+ )]+ const ABI: CanonicalAbiInfo = CanonicalAbiInfo::fixed_length_list_static(&T::ABI, N);++ fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {+ match ty {+ InterfaceType::FixedLengthList(t) => T::typecheck(&types.types[*t].element, types),+ other => bail!("expected `list<_, N>` found `{}`", desc(other)),+ }+ }+}++unsafe impl<T, const N: usize> Lower for [T; N]+where+ T: Lower,+{+ fn linear_lower_to_flat<U>(+ &self,+ cx: &mut LowerContext<'_, U>,+ ty: InterfaceType,+ dst: &mut MaybeUninit<Self::Lower>,+ ) -> Result<()> {+ let element = match ty {+ InterfaceType::FixedLengthList(ty) => cx.types[ty].element,+ _ => bad_type_info(),+ };+ for (i, val) in self.iter().enumerate() {+ val.linear_lower_to_flat(cx, element, map_maybe_uninit!(dst[i]))?;+ }+ Ok(())+ }++ fn linear_lower_to_memory<U>(+ &self,+ cx: &mut LowerContext<'_, U>,+ ty: InterfaceType,+ offset: usize,+ ) -> Result<()> {+ debug_assert!(offset % (Self::ALIGN32 as usize) == 0);+ let element = match ty {+ InterfaceType::FixedLengthList(ty) => cx.types[ty].element,+ _ => bad_type_info(),+ };+ for (i, val) in self.iter().enumerate() {+ val.linear_lower_to_memory(cx, element, offset + i * T::SIZE32)?;+ }+ Ok(())+ }+}++unsafe impl<T, const N: usize> Lift for [T; N]+where+ T: Lift + Sized,+{+ fn linear_lift_from_flat(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ src: &Self::Lower,+ ) -> Result<Self> {+ let element = match ty {+ InterfaceType::FixedLengthList(ty) => cx.types[ty].element,+ _ => bad_type_info(),+ };+ array_try_from_fn(|n| T::linear_lift_from_flat(cx, element, &src[n]))+ }++ fn linear_lift_from_memory(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ bytes: &[u8],+ ) -> Result<Self> {+ debug_assert!((bytes.as_ptr() as usize) % (Self::ALIGN32 as usize) == 0);+ let element = match ty {+ InterfaceType::FixedLengthList(ty) => cx.types[ty].element,+ _ => bad_type_info(),+ };+ let mut offset = 0;+ array_try_from_fn(|_n| {+ let res = T::linear_lift_from_memory(cx, element, &bytes[offset..offset + T::SIZE32]);+ offset += T::SIZE32;+ res+ })+ }+}+pub fn desc(ty: &InterfaceType) -> &'static str {match ty {InterfaceType::U8 => "u8",diff --git a/crates/wasmtime/src/runtime/component/types.rs b/crates/wasmtime/src/runtime/component/types.rsindex 94b0ce0231..4f94d17ad1 100644--- a/crates/wasmtime/src/runtime/component/types.rs+++ b/crates/wasmtime/src/runtime/component/types.rs@@ -10,10 +10,11 @@ use core::ops::Deref;use wasmtime_environ::PanicOnOom as _;use wasmtime_environ::component::{ComponentTypes, Export, InterfaceType, ResourceIndex, TypeComponentIndex,- TypeComponentInstanceIndex, TypeDef, TypeEnumIndex, TypeFlagsIndex, TypeFuncIndex,- TypeFutureIndex, TypeFutureTableIndex, TypeListIndex, TypeMapIndex, TypeModuleIndex,- TypeOptionIndex, TypeRecordIndex, TypeResourceTable, TypeResourceTableIndex, TypeResultIndex,- TypeStreamIndex, TypeStreamTableIndex, TypeTupleIndex, TypeVariantIndex, alternate_lookup_key,+ TypeComponentInstanceIndex, TypeDef, TypeEnumIndex, TypeFixedLengthListIndex, TypeFlagsIndex,+ TypeFuncIndex, TypeFutureIndex, TypeFutureTableIndex, TypeListIndex, TypeMapIndex,+ TypeModuleIndex, TypeOptionIndex, TypeRecordIndex, TypeResourceTable, TypeResourceTableIndex,+ TypeResultIndex, TypeStreamIndex, TypeStreamTableIndex, TypeTupleIndex, TypeVariantIndex,+ alternate_lookup_key,};pub use crate::component::resources::ResourceType;@@ -165,7 +166,10 @@ impl TypeChecker<'_> {(InterfaceType::Stream(_), _) => false,(InterfaceType::ErrorContext(_), InterfaceType::ErrorContext(_)) => true,(InterfaceType::ErrorContext(_), _) => false,- (InterfaceType::FixedLengthList(_), _) => todo!(), // FIXME(#12279)+ (InterfaceType::FixedLengthList(t1), InterfaceType::FixedLengthList(t2)) => {+ self.fixed_length_lists_equal(t1, t2)+ }+ (InterfaceType::FixedLengthList(_), _) => false,}}@@ -181,6 +185,19 @@ impl TypeChecker<'_> {self.interface_types_equal(a.key, b.key) && self.interface_types_equal(a.value, b.value)}+ fn fixed_length_lists_equal(+ &self,+ l1: wasmtime_environ::component::TypeFixedLengthListIndex,+ l2: wasmtime_environ::component::TypeFixedLengthListIndex,+ ) -> bool {+ let a = &self.a_types[l1];+ let b = &self.b_types[l2];+ if a.size != b.size {+ return false;+ }+ self.interface_types_equal(a.element, b.element)+ }+fn resources_equal(&self, o1: TypeResourceTableIndex, o2: TypeResourceTableIndex) -> bool {match (&self.a_types[o1], &self.b_types[o2]) {// Concrete resource types are the same if they map back to the@@ -365,6 +382,34 @@ impl Map {Type::from(&self.0.types[self.0.index].value, &self.0.instance())}}+/// A `list` interface type+#[derive(Clone, Debug)]+pub struct FixedLengthList(Handle<TypeFixedLengthListIndex>);++impl PartialEq for FixedLengthList {+ fn eq(&self, other: &Self) -> bool {+ self.0+ .equivalent(&other.0, TypeChecker::fixed_length_lists_equal)+ }+}++impl Eq for FixedLengthList {}++impl FixedLengthList {+ pub(crate) fn from(index: TypeFixedLengthListIndex, ty: &InstanceType<'_>) -> Self {+ FixedLengthList(Handle::new(index, ty))+ }++ /// Retrieve the element type of this `list`.+ pub fn ty(&self) -> Type {+ Type::from(&self.0.types[self.0.index].element, &self.0.instance())+ }++ /// Retrieve the length of this `list`.+ pub fn len(&self) -> u32 {+ self.0.types[self.0.index].size+ }+}/// A field declaration belonging to a `record`#[derive(Debug)]@@ -738,6 +783,7 @@ pub enum Type {Future(FutureType),Stream(StreamType),ErrorContext,+ FixedLengthList(FixedLengthList),}impl Type {@@ -899,7 +945,9 @@ impl Type {InterfaceType::Future(index) => Type::Future(instance.future_type(*index)),InterfaceType::Stream(index) => Type::Stream(instance.stream_type(*index)),InterfaceType::ErrorContext(_) => Type::ErrorContext,- InterfaceType::FixedLengthList(_) => todo!(), // FIXME(#12279)+ InterfaceType::FixedLengthList(index) => {+ Type::FixedLengthList(FixedLengthList::from(*index, instance))+ }}}@@ -932,6 +980,7 @@ impl Type {Type::Future(_) => "future",Type::Stream(_) => "stream",Type::ErrorContext => "error-context",+ Type::FixedLengthList(_) => "list<_, N>",}}}diff --git a/crates/wasmtime/src/runtime/component/values.rs b/crates/wasmtime/src/runtime/component/values.rsindex bee8347a5f..1a94b1bdd7 100644--- a/crates/wasmtime/src/runtime/component/values.rs+++ b/crates/wasmtime/src/runtime/component/values.rs@@ -93,6 +93,7 @@ pub enum Val {Future(FutureAny),Stream(StreamAny),ErrorContext(ErrorContextAny),+ FixedLengthList(Vec<Val>),}impl Val {@@ -220,7 +221,15 @@ impl Val {InterfaceType::ErrorContext(_) => {ErrorContext::linear_lift_from_flat(cx, ty, next(src))?.into_val()}- InterfaceType::FixedLengthList(_) => todo!(), // FIXME(#12279)+ InterfaceType::FixedLengthList(i) => {+ let number_elements = usize::try_from(cx.types[i].size)?;+ cx.consume_fuel_array(number_elements, size_of::<Val>())?;+ Val::FixedLengthList(+ (0..number_elements)+ .map(|_| Self::lift(cx, cx.types[i].element, src))+ .collect::<Result<_>>()?,+ )+ }})}@@ -349,7 +358,28 @@ impl Val {InterfaceType::ErrorContext(_) => {ErrorContext::linear_lift_from_memory(cx, ty, bytes)?.into_val()}- InterfaceType::FixedLengthList(_) => todo!(), // FIXME(#12279)+ InterfaceType::FixedLengthList(i) => {+ let element_type = cx.types[i].element;+ let abi = cx.types.canonical_abi(&element_type);+ let element_size = usize::try_from(abi.size32)?;+ let number_elements = usize::try_from(cx.types[i].size)?;++ match number_elements.checked_mul(element_size) {+ Some(total_size) if total_size <= bytes.len() => {+ cx.consume_fuel_array(number_elements, size_of::<Val>())?;+ Val::Tuple(+ (0..number_elements)+ .map(|n| {+ // the match already checked that the whole array fits into usize+ let offset = element_size.wrapping_mul(n);+ Val::load(cx, element_type, &bytes[offset..][..element_size])+ })+ .collect::<Result<_>>()?,+ )+ }+ _ => bail!("fixed length list out of bounds of memory"),+ }+ }})}@@ -508,7 +538,17 @@ impl Val {)}(InterfaceType::ErrorContext(_), _) => unexpected(ty, self),- (InterfaceType::FixedLengthList(_), _) => todo!(), // FIXME(#12279)+ (InterfaceType::FixedLengthList(ty), Val::FixedLengthList(values)) => {+ let ty = &cx.types[ty];+ if ty.size as usize != values.len() {+ bail!("expected vec of size {}, got {}", ty.size, values.len());+ }+ for value in values {+ value.lower(cx, ty.element, dst)?;+ }+ Ok(())+ }+ (InterfaceType::FixedLengthList(_), _) => unexpected(ty, self),}}@@ -671,7 +711,18 @@ impl Val {)}(InterfaceType::ErrorContext(_), _) => unexpected(ty, self),- (InterfaceType::FixedLengthList(_), _) => todo!(), // FIXME(#12279)+ (InterfaceType::FixedLengthList(ty), Val::FixedLengthList(values)) => {+ let ty = &cx.types[ty];+ if ty.size as usize != values.len() {+ bail!("expected {} types, got {}", ty.size, values.len());+ }+ let elemsize = cx.types.canonical_abi(&ty.element).size32 as usize;+ for (n, value) in values.iter().enumerate() {+ value.store(cx, ty.element, elemsize * n)?;+ }+ Ok(())+ }+ (InterfaceType::FixedLengthList(_), _) => unexpected(ty, self),}}@@ -703,6 +754,7 @@ impl Val {Val::Future(_) => "future",Val::Stream(_) => "stream",Val::ErrorContext(_) => "error-context",+ Val::FixedLengthList(_) => "list<_, N>",}}@@ -789,6 +841,8 @@ impl PartialEq for Val {(Self::Stream(_), _) => false,(Self::ErrorContext(l), Self::ErrorContext(r)) => l == r,(Self::ErrorContext(_), _) => false,+ (Self::FixedLengthList(l), Self::FixedLengthList(r)) => l == r,+ (Self::FixedLengthList(_), _) => false,}}}diff --git a/crates/wasmtime/src/runtime/wave/component.rs b/crates/wasmtime/src/runtime/wave/component.rsindex cc3e8c1b7c..6b795305ed 100644--- a/crates/wasmtime/src/runtime/wave/component.rs+++ b/crates/wasmtime/src/runtime/wave/component.rs@@ -40,6 +40,7 @@ impl WasmType for component::Type {Self::Option(_) => WasmTypeKind::Option,Self::Result(_) => WasmTypeKind::Result,Self::Flags(_) => WasmTypeKind::Flags,+ Self::FixedLengthList(_) => WasmTypeKind::FixedLengthList,Self::Own(_)| Self::Borrow(_)@@ -144,6 +145,7 @@ impl WasmValue for component::Val {| Self::Future(_)| Self::ErrorContext(_)| Self::Map(_) => WasmTypeKind::Unsupported,+ Self::FixedLengthList(_) => WasmTypeKind::FixedLengthList,}}diff --git a/crates/wast/src/component.rs b/crates/wast/src/component.rsindex 06a8f62a77..48843b319a 100644--- a/crates/wast/src/component.rs+++ b/crates/wast/src/component.rs@@ -291,6 +291,7 @@ fn mismatch(expected: &ComponentConst<'_>, actual: &Val) -> Result<()> {Val::Stream(..) => "stream",Val::ErrorContext(..) => "error-context",Val::Map(..) => "map",+ Val::FixedLengthList(..) => "list<_, N>",};bail!("expected `{expected}` got `{actual}`")}diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rsindex 92e2d170bd..8cf75078a6 100644--- a/crates/wit-bindgen/src/lib.rs+++ b/crates/wit-bindgen/src/lib.rs@@ -1798,7 +1798,9 @@ impl<'a> InterfaceGenerator<'a> {TypeDefKind::Resource => self.type_resource(id, name, ty, &ty.docs),TypeDefKind::Map(k, v) => self.type_map(id, name, k, v, &ty.docs),TypeDefKind::Unknown => unreachable!(),- TypeDefKind::FixedLengthList(..) => todo!(),+ TypeDefKind::FixedLengthList(elem, size) => {+ self.type_fixed_length_list(id, name, elem, *size, &ty.docs)+ }}}@@ -1981,6 +1983,29 @@ impl<'a> InterfaceGenerator<'a> {}}+ fn type_fixed_length_list(+ &mut self,+ id: TypeId,+ _name: &str,+ elem: &Type,+ size: u32,+ docs: &Docs,+ ) {+ let info = self.info(id);+ for (name, mode) in self.modes_of(id) {+ let lt = self.lifetime_for(&info, mode);+ self.rustdoc(docs);+ self.push_str(&format!("pub type {name}"));+ self.print_generics(lt);+ self.push_str(" = [");+ self.print_ty(elem, mode);+ self.push_str("; ");+ self.push_str(&size.to_string());+ self.push_str("];\n");+ self.assert_type(id, &name);+ }+ }+fn type_flags(&mut self, id: TypeId, name: &str, flags: &Flags, docs: &Docs) {self.rustdoc(docs);let wt = self.generator.wasmtime_path();@@ -3748,7 +3773,7 @@ fn type_contains_lists(ty: Type, resolve: &Resolve) -> bool {TypeDefKind::Map(k, v) => {type_contains_lists(*k, resolve) || type_contains_lists(*v, resolve)}- TypeDefKind::FixedLengthList(..) => todo!(),+ TypeDefKind::FixedLengthList(elem, ..) => type_contains_lists(*elem, resolve),},// Technically strings are lists too, but we ignore that here becausediff --git a/crates/wit-bindgen/src/rust.rs b/crates/wit-bindgen/src/rust.rsindex d33987812a..e9cafa75e4 100644--- a/crates/wit-bindgen/src/rust.rs+++ b/crates/wit-bindgen/src/rust.rs@@ -126,14 +126,14 @@ pub trait RustGenerator<'a> {| TypeDefKind::Enum(_)| TypeDefKind::Tuple(_)| TypeDefKind::Handle(_)- | TypeDefKind::Resource => true,+ | TypeDefKind::Resource+ | TypeDefKind::FixedLengthList(..) => true,TypeDefKind::Type(Type::Id(t)) => {needs_generics(resolve, &resolve.types[*t].kind)}TypeDefKind::Type(Type::String) => true,TypeDefKind::Type(_) => false,TypeDefKind::Unknown => unreachable!(),- TypeDefKind::FixedLengthList(..) => todo!(),}}}@@ -194,7 +194,9 @@ pub trait RustGenerator<'a> {format!("std::collections::HashMap<{key}, {value}>")}TypeDefKind::Unknown => unreachable!(),- TypeDefKind::FixedLengthList(..) => todo!(),+ TypeDefKind::FixedLengthList(t, size) => {+ format!("[{}; {}]", self.ty(t, mode), size)+ }}}diff --git a/crates/wit-bindgen/src/types.rs b/crates/wit-bindgen/src/types.rsindex 7dd53a86c1..dae923337f 100644--- a/crates/wit-bindgen/src/types.rs+++ b/crates/wit-bindgen/src/types.rs@@ -167,7 +167,9 @@ impl Types {TypeDefKind::Handle(_) => info.has_handle = true,TypeDefKind::Resource => {}TypeDefKind::Unknown => unreachable!(),- TypeDefKind::FixedLengthList(..) => todo!(),+ TypeDefKind::FixedLengthList(ty, _) => {+ info = self.type_info(resolve, ty);+ }}self.type_info.insert(ty, info);infodiff --git a/tests/all/component_model.rs b/tests/all/component_model.rsindex e407806805..f383baa041 100644--- a/tests/all/component_model.rs+++ b/tests/all/component_model.rs@@ -13,6 +13,7 @@ mod async_dynamic;mod bindgen;mod call_hook;mod dynamic;+mod fixed_length_list;mod func;mod import;mod instance;diff --git a/tests/all/component_model/fixed_length_list.rs b/tests/all/component_model/fixed_length_list.rsnew file mode 100644index 0000000000..cbcc624662--- /dev/null+++ b/tests/all/component_model/fixed_length_list.rs@@ -0,0 +1,207 @@+#![cfg(not(miri))]++use wasmtime::component::{Component, Linker};+use wasmtime::{Config, Engine, Result, Store};++#[test]+fn fixed_length_list() -> Result<()> {+ // nested roundtrip returns the parameters in a tuple+ // this is the same component as in tests/misc_testsuite/component-model/fixed_length_lists.wast+ // as this test was compiled from C(++) the assembly is less human readable+ let component = r##"+(component+ (core module $main (;0;)+ (type (;0;) (func (param i32 i32 i32 i32 i32 i32 i32 i32) (result i32)))+ (memory (;0;) 2)+ (global (;0;) (mut i32) i32.const 67248)+ (export "memory" (memory 0))+ (export "test:fixed-length-lists/to-test#nested-roundtrip" (func 0))+ (func (;0;) (type 0) (param i32 i32 i32 i32 i32 i32 i32 i32) (result i32)+ (local i32 i32 i64 i64)+ global.get 0+ i32.const 96+ i32.sub+ local.tee 8+ global.set 0+ local.get 8+ i32.const 56+ i32.add+ local.tee 9+ local.get 2+ i32.store+ local.get 8+ i32.const 40+ i32.add+ local.tee 2+ local.get 6+ i32.store+ local.get 8+ local.get 3+ i32.store offset=60+ local.get 8+ i32.const 16+ i32.add+ local.tee 3+ i32.const 8+ i32.add+ local.tee 6+ local.get 9+ i64.load+ i64.store+ local.get 8+ local.get 7+ i32.store offset=44+ local.get 8+ i32.const 8+ i32.add+ local.tee 7+ local.get 2+ i64.load+ i64.store+ local.get 8+ local.get 0+ i64.extend_i32_u+ local.get 1+ i64.extend_i32_u+ i64.const 32+ i64.shl+ i64.or+ local.tee 10+ i64.store offset=48+ local.get 8+ local.get 4+ i64.extend_i32_u+ local.get 5+ i64.extend_i32_u+ i64.const 32+ i64.shl+ i64.or+ local.tee 11+ i64.store offset=32+ local.get 8+ local.get 10+ i64.store offset=16+ local.get 8+ local.get 11+ i64.store+ local.get 8+ i32.const -64+ i32.sub+ local.tee 0+ local.get 3+ i64.load align=4+ i64.store align=4+ local.get 0+ local.get 8+ i64.load align=4+ i64.store offset=16 align=4+ local.get 0+ i32.const 8+ i32.add+ local.tee 1+ local.get 6+ i64.load align=4+ i64.store align=4+ local.get 0+ i32.const 24+ i32.add+ local.get 7+ i64.load align=4+ i64.store align=4+ i32.const 1064+ local.get 1+ i64.load align=4+ i64.store+ i32.const 1056+ local.get 8+ i64.load offset=64 align=4+ i64.store+ i32.const 1072+ local.get 8+ i64.load offset=80 align=4+ i64.store+ i32.const 1080+ local.get 8+ i32.const 88+ i32.add+ i64.load align=4+ i64.store+ local.get 8+ i32.const 96+ i32.add+ global.set 0+ i32.const 1056+ )+ (data (;0;) (i32.const 1024) "\ff\ff\ff\ff\00\00\02")+ (@producers+ (processed-by "wit-component" "0.243.0")+ )+ )+ (core instance $main (;0;) (instantiate $main))+ (alias core export $main "memory" (core memory $memory (;0;)))+ (type (;0;) (list u32 2))+ (type (;1;) (list 0 2))+ (type (;2;) (list s32 2))+ (type (;3;) (list 2 2))+ (type (;4;) (tuple 1 3))+ (type (;5;) (func (param "a" 1) (param "b" 3) (result 4)))+ (alias core export $main "test:fixed-length-lists/to-test#nested-roundtrip" (core func $test:fixed-length-lists/to-test#nested-roundtrip (;0;)))+ (func $nested-roundtrip (;0;) (type 5) (canon lift (core func $test:fixed-length-lists/to-test#nested-roundtrip) (memory $memory)))+ (component $test:fixed-length-lists/to-test-shim-component (;0;)+ (type (;0;) (list u32 2))+ (type (;1;) (list 0 2))+ (type (;2;) (list s32 2))+ (type (;3;) (list 2 2))+ (type (;4;) (tuple 1 3))+ (type (;5;) (func (param "a" 1) (param "b" 3) (result 4)))+ (import "import-func-nested-roundtrip" (func (;0;) (type 5)))+ (type (;6;) (list u32 2))+ (type (;7;) (list 6 2))+ (type (;8;) (list s32 2))+ (type (;9;) (list 8 2))+ (type (;10;) (tuple 7 9))+ (type (;11;) (func (param "a" 7) (param "b" 9) (result 10)))+ (export (;1;) "nested-roundtrip" (func 0) (func (type 11)))+ )+ (instance $test:fixed-length-lists/to-test-shim-instance (;0;) (instantiate $test:fixed-length-lists/to-test-shim-component+ (with "import-func-nested-roundtrip" (func $nested-roundtrip))+ )+ )+ (export $test:fixed-length-lists/to-test (;1;) "test:fixed-length-lists/to-test" (instance $test:fixed-length-lists/to-test-shim-instance))+ (@producers+ (processed-by "wit-component" "0.243.0")+ )+)+"##;+ wasmtime::component::bindgen!({+ inline: "+ package root:root;++world root {+ export test:fixed-length-lists/to-test;+}+package test:fixed-length-lists {+ interface to-test {+ nested-roundtrip: func(a: list<list<u32, 2>, 2>, b: list<list<s32, 2>, 2>) -> tuple<list<list<u32, 2>, 2>, list<list<s32, 2>, 2>>;+ }+}+",+ imports: {default: trappable},+ });++ let mut config = Config::new();+ config.wasm_component_model_fixed_length_lists(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(&engine, component)?;+ let mut store = Store::new(&engine, 0);+ let linker = Linker::new(&engine);+ let to_test = Root::instantiate(&mut store, &component, &linker)?;+ let inputa: [[u32; 2]; 2] = [[1, 2], [3, 4]];+ let inputb: [[i32; 2]; 2] = [[-1, -2], [-3, -4]];+ let result = to_test+ .interface0+ .call_nested_roundtrip(&mut store, inputa, inputb)+ .expect("no trap");+ assert_eq!(result, ([[1, 2], [3, 4]], [[-1, -2], [-3, -4]]));+ Ok(())+}