-
Notifications
You must be signed in to change notification settings - Fork 25
/
function.rs
309 lines (263 loc) · 10.3 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
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
/*
* 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::JsInstance;
use crate::JsWasmBackend;
use crate::JsImportCallContext;
use crate::JsContext;
use crate::JsContextMut;
use crate::js_conversions::js_array_from_wval_array;
use crate::js_conversions::wval_array_from_js_array;
use crate::js_conversions::wval_from_js;
use crate::js_conversions::wval_to_i32;
use crate::store::JsStoreInner;
use crate::store::FunctionHandle;
use marine_wasm_backend_traits::impl_for_each_function_signature;
use marine_wasm_backend_traits::replace_with;
use marine_wasm_backend_traits::prelude::*;
use anyhow::anyhow;
use js_sys::Array;
use wasm_bindgen::prelude::*;
// Safety: this is safe because its intended to run in single thread
unsafe impl Send for HostImportFunction {}
unsafe impl Sync for HostImportFunction {}
unsafe impl Send for WasmExportFunction {}
unsafe impl Sync for WasmExportFunction {}
#[derive(Clone)]
pub struct HostImportFunction {
pub(crate) store_handle: FunctionHandle,
}
#[derive(Clone)]
pub struct WasmExportFunction {
pub(crate) store_handle: FunctionHandle,
/// Instance this export is extracted from.
pub(crate) bound_instance: JsInstance,
}
pub(crate) struct StoredFunction {
pub(crate) js_function: js_sys::Function,
pub(crate) signature: FuncSig,
}
impl StoredFunction {
pub(crate) fn new(js_function: js_sys::Function, signature: FuncSig) -> Self {
Self {
js_function,
signature,
}
}
}
impl WasmExportFunction {
pub(crate) fn new_stored(
ctx: &mut impl AsContextMut<JsWasmBackend>,
instance: JsInstance,
func: js_sys::Function,
signature: FuncSig,
) -> Self {
let handle = ctx
.as_context_mut()
.inner
.store_function(StoredFunction::new(func, signature));
Self {
store_handle: handle,
bound_instance: instance,
}
}
pub(crate) fn stored_mut<'store>(
&self,
ctx: JsContextMut<'store>,
) -> &'store mut StoredFunction {
&mut ctx.inner.functions[self.store_handle]
}
fn call_inner(
&self,
store: &mut impl AsContextMut<JsWasmBackend>,
args: &[WValue],
) -> RuntimeResult<Vec<WValue>> {
let params = js_array_from_wval_array(args);
let stored_func = self.stored_mut(store.as_context_mut());
let result = js_sys::Reflect::apply(&stored_func.js_function, &JsValue::NULL, ¶ms)
.map_err(|e| {
web_sys::console::log_2(&"failed to apply func".into(), &e);
RuntimeError::Other(anyhow!("Failed to apply func"))
})?;
extract_function_results(result, stored_func.signature.returns())
}
}
fn extract_function_results(result: JsValue, result_types: &[WType]) -> RuntimeResult<Vec<WValue>> {
match result_types.len() {
0 => Ok(vec![]),
1 => {
// Single value returned as is.
let value = wval_from_js(&result_types[0], &result);
Ok(vec![value])
}
results_number => {
// Multiple return values are returned as JS array of values.
let result_array: Array = result.into();
if result_array.length() as usize != results_number {
Err(RuntimeError::IncorrectResultsNumber {
expected: results_number,
actual: result_array.length() as usize,
})
} else {
Ok(wval_array_from_js_array(&result_array, result_types.iter()))
}
}
}
}
impl HostImportFunction {
pub(crate) fn stored<'store>(&self, ctx: &JsContext<'store>) -> &'store StoredFunction {
&ctx.inner.functions[self.store_handle]
}
pub(crate) fn stored_mut<'store>(
&self,
ctx: JsContextMut<'store>,
) -> &'store mut StoredFunction {
&mut ctx.inner.functions[self.store_handle]
}
}
impl HostFunction<JsWasmBackend> for HostImportFunction {
fn new<F>(store: &mut impl AsContextMut<JsWasmBackend>, signature: FuncSig, func: F) -> Self
where
F: for<'c> Fn(&'c [WValue]) -> anyhow::Result<Vec<WValue>> + Sync + Send + 'static,
{
let with_caller = move |_, args: &'_ [WValue]| func(args);
Self::new_with_caller(store, signature, with_caller)
}
fn new_with_caller<F>(
store: &mut impl AsContextMut<JsWasmBackend>,
signature: FuncSig,
func: F,
) -> Self
where
F: for<'c> Fn(JsImportCallContext, &[WValue]) -> anyhow::Result<Vec<WValue>>
+ Sync
+ Send
+ 'static,
{
// Safety: JsStoreInner is stored inside a Box and the Store is required by wasm-backend traits contract
// to be valid for function execution. So it is safe to capture this ptr into closure and deference there
let store_inner_ptr = store.as_context_mut().inner as *mut JsStoreInner;
let wrapped = wrap_raw_host_fn(signature.clone(), store_inner_ptr, func);
let closure = prepare_js_closure(wrapped);
let handle = store
.as_context_mut()
.inner
.store_function(StoredFunction::new(closure, signature));
Self {
store_handle: handle,
}
}
fn new_typed<Params, Results, Env>(
store: &mut impl AsContextMut<JsWasmBackend>,
func: impl IntoFunc<JsWasmBackend, Params, Results, Env>,
) -> Self {
func.into_func(store)
}
fn signature(&self, store: &mut impl AsContextMut<JsWasmBackend>) -> FuncSig {
self.stored_mut(store.as_context_mut()).signature.clone()
}
}
fn wrap_raw_host_fn<F>(
signature: FuncSig,
store_inner_ptr: *mut JsStoreInner,
raw_host_function: F,
) -> Box<dyn FnMut(&Array) -> Array>
where
F: for<'c> Fn(JsImportCallContext, &[WValue]) -> anyhow::Result<Vec<WValue>>
+ Sync
+ Send
+ 'static,
{
let func = move |args: &js_sys::Array| -> js_sys::Array {
log::debug!(
"function produced by JsFunction:::new_with_caller call, signature: {:?}",
signature
);
let store_inner = unsafe { &mut *store_inner_ptr };
let caller_instance = store_inner.wasm_call_stack.last().cloned().expect(
"Import cannot be called outside of an export call, when wasm_call_stack is empty",
);
let caller = JsImportCallContext {
store_inner,
caller_instance,
};
let args = wval_array_from_js_array(args, signature.params().iter());
let result = raw_host_function(caller, &args).unwrap_throw(); // TODO is it right?
js_array_from_wval_array(&result)
};
Box::new(func)
}
fn prepare_js_closure(func: Box<dyn FnMut(&Array) -> Array>) -> js_sys::Function {
let closure = Closure::wrap(func).into_js_value();
// Make a function that converts function args into array and wrap our func with it.
// Otherwise our closure will get only first argument.
let wrapper = js_sys::Function::new_with_args(
"wrapped_func",
"return wrapped_func(Array.prototype.slice.call(arguments, 1))",
);
wrapper.bind1(&JsValue::UNDEFINED, &closure)
}
impl ExportFunction<JsWasmBackend> for WasmExportFunction {
fn signature(&self, store: &mut impl AsContextMut<JsWasmBackend>) -> FuncSig {
self.stored_mut(store.as_context_mut()).signature.clone()
}
fn call(
&self,
store: &mut impl AsContextMut<JsWasmBackend>,
args: &[WValue],
) -> RuntimeResult<Vec<WValue>> {
store
.as_context_mut()
.inner
.wasm_call_stack
.push(self.bound_instance.clone());
let result = self.call_inner(store, args);
store.as_context_mut().inner.wasm_call_stack.pop();
result
}
}
/// 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: JsContextMut<'_>, func: F) -> HostImportFunction
where F: Fn(JsImportCallContext, $(replace_with!($args -> i32),)*) + Send + Sync + 'static {
let func = move |caller: JsImportCallContext, args: &[WValue]| -> anyhow::Result<Vec<WValue>> {
let [$($args,)*] = args else { todo!() }; // TODO: Safety: explain why it will never fire
func(caller, $(wval_to_i32($args),)*);
Ok(vec![])
};
let arg_ty = vec![WType::I32; $num];
let ret_ty = vec![];
let signature = FuncSig::new(arg_ty, ret_ty);
HostImportFunction::new_with_caller(&mut ctx, signature, func)
}
fn [< new_typed_with_env_ $num _r>] <F>(mut ctx: JsContextMut<'_>, func: F) -> HostImportFunction
where F: Fn(JsImportCallContext, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static {
let func = move |caller: JsImportCallContext, args: &[WValue]| -> anyhow::Result<Vec<WValue>> {
let [$($args,)*] = args else { panic!("args do not match signature") }; // Safety: signature should b
let res = func(caller, $(wval_to_i32(&$args),)*);
Ok(vec![WValue::I32(res)])
};
let arg_ty = vec![WType::I32; $num];
let ret_ty = vec![WType::I32];
let signature = FuncSig::new(arg_ty, ret_ty);
HostImportFunction::new_with_caller(&mut ctx, signature, func)
}
});
}
impl FuncConstructor<JsWasmBackend> for HostImportFunction {
impl_for_each_function_signature!(impl_func_construction);
}