1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use super::{
    super::engine::{FuncFinished, FuncParams, FuncResults},
    TrampolineEntity,
};
use crate::{
    core::{DecodeUntypedSlice, EncodeUntypedSlice, UntypedVal, ValType, F32, F64},
    Caller,
    Error,
    ExternRef,
    FuncRef,
    FuncType,
};
use core::{array, iter::FusedIterator};

/// Closures and functions that can be used as host functions.
pub trait IntoFunc<T, Params, Results>: Send + Sync + 'static {
    /// The parameters of the host function.
    #[doc(hidden)]
    type Params: WasmTyList;
    /// The results of the host function.
    #[doc(hidden)]
    type Results: WasmTyList;

    /// Converts the function into its Wasmi signature and its trampoline.
    #[doc(hidden)]
    fn into_func(self) -> (FuncType, TrampolineEntity<T>);
}

macro_rules! impl_into_func {
    ( $n:literal $( $tuple:ident )* ) => {
        impl<T, F, $($tuple,)* R> IntoFunc<T, ($($tuple,)*), R> for F
        where
            F: Fn($($tuple),*) -> R,
            F: Send + Sync + 'static,
            $(
                $tuple: WasmTy,
            )*
            R: WasmRet,
        {
            type Params = ($($tuple,)*);
            type Results = <R as WasmRet>::Ok;

            #[allow(non_snake_case)]
            fn into_func(self) -> (FuncType, TrampolineEntity<T>) {
                IntoFunc::into_func(
                    move |
                        _: Caller<'_, T>,
                        $(
                            $tuple: $tuple,
                        )*
                    | {
                        (self)($($tuple),*)
                    }
                )
            }
        }

        impl<T, F, $($tuple,)* R> IntoFunc<T, (Caller<'_, T>, $($tuple),*), R> for F
        where
            F: Fn(Caller<T>, $($tuple),*) -> R,
            F: Send + Sync + 'static,
            $(
                $tuple: WasmTy,
            )*
            R: WasmRet,
        {
            type Params = ($($tuple,)*);
            type Results = <R as WasmRet>::Ok;

            #[allow(non_snake_case)]
            fn into_func(self) -> (FuncType, TrampolineEntity<T>) {
                let signature = FuncType::new(
                    <Self::Params as WasmTyList>::types(),
                    <Self::Results as WasmTyList>::types(),
                );
                let trampoline = TrampolineEntity::new(
                    move |caller: Caller<T>, params_results: FuncParams| -> Result<FuncFinished, Error> {
                        let (($($tuple,)*), func_results): (Self::Params, FuncResults) = params_results.decode_params();
                        let results: Self::Results =
                            (self)(caller, $($tuple),*).into_fallible()?;
                        Ok(func_results.encode_results(results))
                    },
                );
                (signature, trampoline)
            }
        }
    };
}
for_each_tuple!(impl_into_func);

/// Types and type sequences that can be used as return values of host functions.
pub trait WasmRet {
    #[doc(hidden)]
    type Ok: WasmTyList;

    #[doc(hidden)]
    fn into_fallible(self) -> Result<<Self as WasmRet>::Ok, Error>;
}

impl<T1> WasmRet for T1
where
    T1: WasmTy,
{
    type Ok = T1;

    #[inline]
    fn into_fallible(self) -> Result<Self::Ok, Error> {
        Ok(self)
    }
}

impl<T1> WasmRet for Result<T1, Error>
where
    T1: WasmTy,
{
    type Ok = T1;

    #[inline]
    fn into_fallible(self) -> Result<<Self as WasmRet>::Ok, Error> {
        self
    }
}

macro_rules! impl_wasm_return_type {
    ( $n:literal $( $tuple:ident )* ) => {
        impl<$($tuple),*> WasmRet for ($($tuple,)*)
        where
            $(
                $tuple: WasmTy
            ),*
        {
            type Ok = ($($tuple,)*);

            #[inline]
            fn into_fallible(self) -> Result<Self::Ok, Error> {
                Ok(self)
            }
        }

        impl<$($tuple),*> WasmRet for Result<($($tuple,)*), Error>
        where
            $(
                $tuple: WasmTy
            ),*
        {
            type Ok = ($($tuple,)*);

            #[inline]
            fn into_fallible(self) -> Result<<Self as WasmRet>::Ok, Error> {
                self
            }
        }
    };
}
for_each_tuple!(impl_wasm_return_type);

/// Types that can be used as parameters or results of host functions.
pub trait WasmTy: From<UntypedVal> + Into<UntypedVal> + Send {
    /// Returns the value type of the Wasm type.
    #[doc(hidden)]
    fn ty() -> ValType;
}

macro_rules! impl_wasm_type {
    ( $( type $rust_type:ty = $wasmi_type:ident );* $(;)? ) => {
        $(
            impl WasmTy for $rust_type {
                #[inline]
                fn ty() -> ValType {
                    ValType::$wasmi_type
                }
            }
        )*
    };
}
impl_wasm_type! {
    type u32 = I32;
    type u64 = I64;
    type i32 = I32;
    type i64 = I64;
    type F32 = F32;
    type F64 = F64;
    type f32 = F32;
    type f64 = F64;
    type FuncRef = FuncRef;
    type ExternRef = ExternRef;
}

/// A list of [`WasmTy`] types.
///
/// # Note
///
/// This is a convenience trait that allows to:
///
/// - Read host function parameters from a region of the value stack.
/// - Write host function results into a region of the value stack.
/// - Iterate over the value types of the Wasm type sequence
///     - This is useful to construct host function signatures.
pub trait WasmTyList: DecodeUntypedSlice + EncodeUntypedSlice + Sized + Send {
    /// The number of Wasm types in the list.
    #[doc(hidden)]
    const LEN: usize;

    /// The [`ValType`] sequence as array.
    #[doc(hidden)]
    type Types: IntoIterator<IntoIter = Self::TypesIter, Item = ValType>
        + AsRef<[ValType]>
        + AsMut<[ValType]>
        + Copy
        + Clone;

    /// The iterator type of the sequence of [`ValType`].
    #[doc(hidden)]
    type TypesIter: ExactSizeIterator<Item = ValType> + DoubleEndedIterator + FusedIterator;

    /// The [`UntypedVal`] sequence as array.
    #[doc(hidden)]
    type Values: IntoIterator<IntoIter = Self::ValuesIter, Item = UntypedVal>
        + AsRef<[UntypedVal]>
        + AsMut<[UntypedVal]>
        + Copy
        + Clone;

    /// The iterator type of the sequence of [`Val`].
    ///
    /// [`Val`]: [`crate::core::Value`]
    #[doc(hidden)]
    type ValuesIter: ExactSizeIterator<Item = UntypedVal> + DoubleEndedIterator + FusedIterator;

    /// Returns an array representing the [`ValType`] sequence of `Self`.
    #[doc(hidden)]
    fn types() -> Self::Types;

    /// Returns an array representing the [`UntypedVal`] sequence of `self`.
    #[doc(hidden)]
    fn values(self) -> Self::Values;

    /// Consumes the [`UntypedVal`] iterator and creates `Self` if possible.
    ///
    /// Returns `None` if construction of `Self` is impossible.
    #[doc(hidden)]
    fn from_values(values: &[UntypedVal]) -> Option<Self>;
}

impl<T1> WasmTyList for T1
where
    T1: WasmTy,
{
    const LEN: usize = 1;

    type Types = [ValType; 1];
    type TypesIter = array::IntoIter<ValType, 1>;
    type Values = [UntypedVal; 1];
    type ValuesIter = array::IntoIter<UntypedVal, 1>;

    #[inline]
    fn types() -> Self::Types {
        [<T1 as WasmTy>::ty()]
    }

    #[inline]
    fn values(self) -> Self::Values {
        [<T1 as Into<UntypedVal>>::into(self)]
    }

    #[inline]
    fn from_values(values: &[UntypedVal]) -> Option<Self> {
        if let [value] = *values {
            return Some(value.into());
        }
        None
    }
}

macro_rules! impl_wasm_type_list {
    ( $n:literal $( $tuple:ident )* ) => {
        impl<$($tuple),*> WasmTyList for ($($tuple,)*)
        where
            $(
                $tuple: WasmTy
            ),*
        {
            const LEN: usize = $n;

            type Types = [ValType; $n];
            type TypesIter = array::IntoIter<ValType, $n>;
            type Values = [UntypedVal; $n];
            type ValuesIter = array::IntoIter<UntypedVal, $n>;

            #[inline]
            fn types() -> Self::Types {
                [$(
                    <$tuple as WasmTy>::ty()
                ),*]
            }

            #[inline]
            #[allow(non_snake_case)]
            fn values(self) -> Self::Values {
                let ($($tuple,)*) = self;
                [$(
                    <$tuple as Into<UntypedVal>>::into($tuple)
                ),*]
            }

            #[inline]
            #[allow(non_snake_case)]
            fn from_values(values: &[UntypedVal]) -> Option<Self> {
                if let [$($tuple),*] = *values {
                    return Some(
                        ( $( Into::into($tuple), )* )
                    )
                }
                None
            }
        }
    };
}
for_each_tuple!(impl_wasm_type_list);

#[cfg(test)]
mod tests {
    use super::*;
    use std::string::String;

    /// Utility struct helper for the `implements_wasm_results` macro.
    pub struct ImplementsWasmRet<T> {
        marker: core::marker::PhantomData<fn() -> T>,
    }
    /// Utility trait for the fallback case of the `implements_wasm_results` macro.
    #[allow(dead_code)] // TODO: somehow the tests work without this which is strange.
    pub trait ImplementsWasmRetFallback {
        const VALUE: bool = false;
    }
    impl<T> ImplementsWasmRetFallback for ImplementsWasmRet<T> {}
    /// Utility trait impl for the `true` case of the `implements_wasm_results` macro.
    impl<T> ImplementsWasmRet<T>
    where
        T: WasmRet,
    {
        // We need to allow for dead code at this point because
        // the Rust compiler thinks this function is unused even
        // though it acts as the specialized case for detection.
        #[allow(dead_code)]
        pub const VALUE: bool = true;
    }
    /// Returns `true` if the given type `T` implements the `WasmRet` trait.
    #[macro_export]
    #[doc(hidden)]
    macro_rules! implements_wasm_results {
        ( $T:ty $(,)? ) => {{
            #[allow(unused_imports)]
            use ImplementsWasmRetFallback as _;
            ImplementsWasmRet::<$T>::VALUE
        }};
    }

    #[test]
    fn into_func_trait_impls() {
        assert!(!implements_wasm_results!(String));
        assert!(!implements_wasm_results!(Option<i32>));
        assert!(implements_wasm_results!(()));
        assert!(implements_wasm_results!(i32));
        assert!(implements_wasm_results!((i32,)));
        assert!(implements_wasm_results!((i32, u32, i64, u64, F32, F64)));
        assert!(implements_wasm_results!(Result<(), Error>));
        assert!(implements_wasm_results!(Result<i32, Error>));
        assert!(implements_wasm_results!(Result<(i32,), Error>));
        assert!(implements_wasm_results!(Result<(i32, u32, i64, u64, F32, F64), Error>));
    }
}