-
Notifications
You must be signed in to change notification settings - Fork 25
/
function.rs
189 lines (160 loc) · 6.48 KB
/
function.rs
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
/*
* Copyright 2023 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::WasmtimeContextMut;
use crate::WasmtimeWasmBackend;
use crate::WasmtimeImportCallContext;
use crate::val_to_wvalue;
use crate::StoreState;
use crate::sig_to_fn_ty;
use crate::wvalue_to_val;
use crate::utils::fn_ty_to_sig;
use crate::utils::inspect_call_error;
use marine_wasm_backend_traits::prelude::*;
use marine_wasm_backend_traits::impl_for_each_function_signature;
use marine_wasm_backend_traits::replace_with;
use anyhow::anyhow;
#[derive(Clone)]
pub struct WasmtimeFunction {
pub(crate) inner: wasmtime::Func,
}
impl HostFunction<WasmtimeWasmBackend> for WasmtimeFunction {
fn new<F>(store: &mut impl AsContextMut<WasmtimeWasmBackend>, sig: FuncSig, func: F) -> Self
where
F: for<'c> Fn(&[WValue]) -> anyhow::Result<Vec<WValue>> + Sync + Send + 'static,
{
let ty = sig_to_fn_ty(&sig);
let func = move |_: wasmtime::Caller<'_, StoreState>,
args: &[wasmtime::Val],
results_out: &mut [wasmtime::Val]|
-> Result<(), anyhow::Error> {
let args = process_func_args(args).map_err(|e| anyhow!(e))?; // TODO move earlier
let results = func(&args)?;
process_func_results(&results, results_out).map_err(|e| anyhow!(e))
};
let func = wasmtime::Func::new(store.as_context_mut().inner, ty, func);
WasmtimeFunction { inner: func }
}
fn new_with_caller<F>(
store: &mut impl AsContextMut<WasmtimeWasmBackend>,
sig: FuncSig,
func: F,
) -> Self
where
F: for<'c> Fn(
<WasmtimeWasmBackend as WasmBackend>::ImportCallContext<'c>,
&[WValue],
) -> anyhow::Result<Vec<WValue>>
+ Sync
+ Send
+ 'static,
{
let ty = sig_to_fn_ty(&sig);
let func = move |caller: wasmtime::Caller<'_, StoreState>,
args: &[wasmtime::Val],
results_out: &mut [wasmtime::Val]|
-> Result<(), anyhow::Error> {
let caller = WasmtimeImportCallContext { inner: caller };
let args = process_func_args(args).map_err(|e| anyhow!(e))?;
let results = func(caller, &args)?;
process_func_results(&results, results_out).map_err(|e| anyhow!(e))
};
let func = wasmtime::Func::new(store.as_context_mut().inner, ty, func);
WasmtimeFunction { inner: func }
}
fn new_typed<Params, Results, Env>(
store: &mut impl marine_wasm_backend_traits::AsContextMut<WasmtimeWasmBackend>,
func: impl IntoFunc<WasmtimeWasmBackend, Params, Results, Env>,
) -> Self {
func.into_func(store)
}
fn signature<'c>(&self, store: &mut impl AsContextMut<WasmtimeWasmBackend>) -> FuncSig {
let ty = self.inner.ty(store.as_context_mut());
fn_ty_to_sig(&ty)
}
}
impl ExportFunction<WasmtimeWasmBackend> for WasmtimeFunction {
fn signature<'c>(&self, store: &mut impl AsContextMut<WasmtimeWasmBackend>) -> FuncSig {
let ty = self.inner.ty(store.as_context_mut());
fn_ty_to_sig(&ty)
}
fn call<'c>(
&self,
store: &mut impl AsContextMut<WasmtimeWasmBackend>,
args: &[WValue],
) -> RuntimeResult<Vec<WValue>> {
let args = args.iter().map(wvalue_to_val).collect::<Vec<_>>();
let results_count = self.inner.ty(store.as_context_mut()).results().len();
let mut results = vec![wasmtime::Val::null(); results_count];
self.inner
.call(store.as_context_mut().inner, &args, &mut results)
.map_err(inspect_call_error)?;
results
.iter()
.map(val_to_wvalue)
.collect::<Result<Vec<_>, _>>()
}
}
/// Generates a function that accepts a Fn with $num template parameters and turns it into WasmtimeFunction.
/// Needed to allow users to pass almost any function to `Function::new_typed` without worrying about signature.
macro_rules! impl_func_construction {
($num:tt $($args:ident)*) => (paste::paste!{
fn [< new_typed_with_env_ $num >] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction
where F: Fn(WasmtimeImportCallContext<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static {
let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| {
let caller = WasmtimeImportCallContext {inner: caller};
func(caller, $($args,)*)
};
let func = wasmtime::Func::wrap(&mut ctx.inner, func);
WasmtimeFunction {
inner: func
}
}
fn [< new_typed_with_env_ $num _r>] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction
where F: Fn(WasmtimeImportCallContext<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static {
let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| -> i32{
let caller = WasmtimeImportCallContext {inner: caller};
func(caller, $($args,)*)
};
let func = wasmtime::Func::wrap(&mut ctx.inner, func);
WasmtimeFunction {
inner: func
}
}
});
}
impl FuncConstructor<WasmtimeWasmBackend> for WasmtimeFunction {
impl_for_each_function_signature!(impl_func_construction);
}
fn process_func_args(args: &[wasmtime::Val]) -> RuntimeResult<Vec<WValue>> {
args.iter()
.map(val_to_wvalue)
.collect::<RuntimeResult<Vec<_>>>()
}
fn process_func_results(
results_in: &[WValue],
results_out: &mut [wasmtime::Val],
) -> RuntimeResult<()> {
if results_in.len() != results_out.len() {
return Err(RuntimeError::IncorrectResultsNumber {
expected: results_out.len(),
actual: results_in.len(),
});
}
for id in 0..results_in.len() {
results_out[id] = wvalue_to_val(&results_in[id]);
}
Ok(())
}