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
23pub struct TypedFunc<Params, Return> {
38 func: Func,
39
40 _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 pub unsafe fn new_unchecked(func: Func) -> TypedFunc<Params, Return> {
86 TypedFunc {
87 _marker: marker::PhantomData,
88 func,
89 }
90 }
91
92 pub fn func(&self) -> &Func {
95 &self.func
96 }
97
98 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 #[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 let dst: &mut MaybeUninit<Params::Lower> = unsafe { slice_to_storage_mut(dst) };
206 Self::lower_stack_args(cx, ¶ms, ty, dst)
207 } else {
208 Self::lower_heap_args(cx, ¶ms, 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 let result = unsafe {
240 #[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, ¶ms)
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, ¶ms)
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 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 fn lower_heap_args<T>(
304 cx: &mut LowerContext<'_, T>,
305 params: &Params,
306 ty: InterfaceType,
307 dst: &mut MaybeUninit<ValRaw>,
308 ) -> Result<()> {
309 let ptr = cx.realloc(0, 0, Params::ALIGN32, Params::SIZE32)?;
317 params.linear_lower_to_memory(cx, ty, ptr)?;
318
319 dst.write(ValRaw::i64(ptr as i64));
330
331 Ok(())
332 }
333
334 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 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 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
385pub unsafe trait ComponentNamedList: ComponentType {}
402
403pub unsafe trait ComponentType: Send + Sync {
511 #[doc(hidden)]
519 type Lower: Copy;
520
521 #[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 #[doc(hidden)]
541 const MAY_REQUIRE_REALLOC: bool = true;
542
543 #[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 #[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
567pub unsafe trait Lower: ComponentType {
586 #[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 #[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 #[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
666pub unsafe trait Lift: Sized + ComponentType {
683 #[doc(hidden)]
700 fn linear_lift_from_flat(
701 cx: &mut LiftContext<'_>,
702 ty: InterfaceType,
703 src: &Self::Lower,
704 ) -> Result<Self>;
705
706 #[doc(hidden)]
721 fn linear_lift_from_memory(
722 cx: &mut LiftContext<'_>,
723 ty: InterfaceType,
724 bytes: &[u8],
725 ) -> Result<Self>;
726
727 #[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 #[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
762macro_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 #[cfg(feature = "component-model-bytes")]
897 () bytes::BytesMut => WasmList<u8> (via bytes::Bytes),
898}
899
900macro_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 assert!((Self::ALIGN32 as usize) >= mem::align_of::<Self>());
958
959 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 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 assert!((Self::ALIGN32 as usize) >= mem::align_of::<Self>());
1086
1087 let dst = cx.slice_range_mut(offset, items.len() * Self::SIZE32);
1092 assert!(dst.as_ptr().cast::<Self>().is_aligned());
1093
1094 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 let byte_size = list.len * mem::size_of::<Self>();
1124 let bytes = &cx.memory()[list.ptr..][..byte_size];
1125
1126 assert!(bytes.as_ptr().cast::<Self>().is_aligned());
1129
1130 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 let _ = cx; 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 let _ = cx; 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 let _ = cx; 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 *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
1325const UTF16_TAG: usize = 1 << 31;
1327const MAX_STRING_BYTE_LENGTH: usize = (1 << 31) - 1;
1328
1329unsafe 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 match cx.options().string_encoding {
1388 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 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 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 if let Ok(byte) = u8::try_from(u32::from(ch)) {
1441 dst[result] = byte;
1442 result += 1;
1443 continue;
1444 }
1445
1446 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 for i in (0..result).rev() {
1461 dst[2 * i] = dst[i];
1462 dst[2 * i + 1] = 0;
1463 }
1464
1465 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
1488pub 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 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 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 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 Ok(encoding_rs::mem::decode_latin1(
1624 &memory[self.ptr..][..self.len],
1625 ))
1626 }
1627}
1628
1629unsafe 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
1721fn 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
1754pub 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 #[inline]
1808 pub fn len(&self) -> usize {
1809 self.len
1810 }
1811
1812 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 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 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 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 let byte_size = self.len * mem::size_of::<$i>();
1891 let bytes = &all_of_memory[self.ptr..][..byte_size];
1892
1893 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
1919unsafe 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
1960fn 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
1995forward_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 <K as Lower>::linear_lower_to_memory(key, cx, map.key, entry_offset)?;
2139 <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
2152trait LiftMap<K, V>: Sized {
2154 fn with_capacity(len: usize) -> Result<Self>;
2156
2157 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 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
2249fn 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
2274pub 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
2308pub 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
2354pub 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
2385pub 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
2416pub 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 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
2606pub 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 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 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#[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 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 panic!("bad type information detected");
3187}