-
Notifications
You must be signed in to change notification settings - Fork 824
/
function.rs
1382 lines (1252 loc) · 49 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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub use self::inner::{FromToNativeWasmType, HostFunction, WasmTypeList};
use crate::js::context::{
AsContextMut, AsContextRef, ContextHandle, ContextInner, ContextMut, InternalContextHandle,
};
use crate::js::exports::{ExportError, Exportable};
use crate::js::externals::Extern;
use crate::js::types::param_from_js; // AsJs}; /* ValFuncRef */
use crate::js::FunctionType;
use crate::js::RuntimeError;
use crate::js::TypedFunction;
use crate::js::Value;
use js_sys::{Array, Function as JSFunction};
use std::iter::FromIterator;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use crate::js::export::VMFunction;
use std::fmt;
#[repr(C)]
pub struct VMFunctionBody(u8);
#[inline]
fn result_to_js(val: &Value) -> JsValue {
match val {
Value::I32(i) => JsValue::from_f64(*i as _),
Value::I64(i) => JsValue::from_f64(*i as _),
Value::F32(f) => JsValue::from_f64(*f as _),
Value::F64(f) => JsValue::from_f64(*f),
val => unimplemented!(
"The value `{:?}` is not yet supported in the JS Function API",
val
),
}
}
#[inline]
fn results_to_js_array(values: &[Value]) -> Array {
Array::from_iter(values.iter().map(result_to_js))
}
/// A WebAssembly `function` instance.
///
/// A function instance is the runtime representation of a function.
/// It effectively is a closure of the original function (defined in either
/// the host or the WebAssembly module) over the runtime `Instance` of its
/// originating `Module`.
///
/// The module instance is used to resolve references to other definitions
/// during execution of the function.
///
/// Spec: <https://webassembly.github.io/spec/core/exec/runtime.html#function-instances>
///
/// # Panics
/// - Closures (functions with captured environments) are not currently supported
/// with native functions. Attempting to create a native `Function` with one will
/// result in a panic.
/// [Closures as host functions tracking issue](https://github.com/wasmerio/wasmer/issues/1840)
#[derive(Clone, PartialEq)]
pub struct Function {
pub(crate) handle: ContextHandle<VMFunction>,
}
impl Function {
/// Creates a new host `Function` (dynamic) with the provided signature.
///
/// If you know the signature of the host function at compile time,
/// consider using [`Function::new_native`] for less runtime overhead.
///
/// # Examples
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// #
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
///
/// let f = Function::new(&store, &signature, |args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
/// ```
///
/// With constant signature:
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// #
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
///
/// let f = Function::new(&store, I32_I32_TO_I32, |args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new<FT, F, T>(ctx: &mut impl AsContextMut<Data = T>, ty: FT, func: F) -> Self
where
FT: Into<FunctionType>,
F: Fn(ContextMut<'_, T>, &[Value]) -> Result<Vec<Value>, RuntimeError>
+ 'static
+ Send
+ Sync,
{
let mut ctx = ctx.as_context_mut();
let function_type = ty.into();
let func_ty = function_type.clone();
let raw_ctx = ctx.as_raw() as *mut u8;
let wrapped_func: JsValue = match function_type.results().len() {
0 => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32)))
.collect::<Vec<_>>();
let _results = func(ctx.as_context_mut(), &wasm_arguments)?;
Ok(())
})
as Box<dyn FnMut(&Array) -> Result<(), JsValue>>)
.into_js_value(),
1 => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32)))
.collect::<Vec<_>>();
let results = func(ctx.as_context_mut(), &wasm_arguments)?;
return Ok(result_to_js(&results[0]));
})
as Box<dyn FnMut(&Array) -> Result<JsValue, JsValue>>)
.into_js_value(),
_n => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32)))
.collect::<Vec<_>>();
let results = func(ctx.as_context_mut(), &wasm_arguments)?;
return Ok(results_to_js_array(&results));
})
as Box<dyn FnMut(&Array) -> Result<Array, JsValue>>)
.into_js_value(),
};
let dyn_func =
JSFunction::new_with_args("f", "return f(Array.prototype.slice.call(arguments, 1))");
let binded_func = dyn_func.bind1(&JsValue::UNDEFINED, &wrapped_func);
let vm_function = VMFunction::new(binded_func, func_ty);
Self::from_vm_export(&mut ctx, vm_function)
}
/// Creates a new host `Function` (dynamic) with the provided signature and environment.
///
/// If you know the signature of the host function at compile time,
/// consider using [`Function::new_native_with_env`] for less runtime
/// overhead.
///
/// # Examples
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// #
/// #[derive(Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
///
/// let f = Function::new_with_env(&store, &signature, env, |env, args| {
/// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
/// Ok(vec![Value::I32(result)])
/// });
/// ```
///
/// With constant signature:
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # let store = Store::default();
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
///
/// #[derive(Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// let f = Function::new_with_env(&store, I32_I32_TO_I32, env, |env, args| {
/// let result = env.multiplier * (args[0].unwrap_i32() + args[1].unwrap_i32());
/// Ok(vec![Value::I32(result)])
/// });
/// ```
#[allow(clippy::cast_ptr_alignment)]
pub fn new_with_env<T, F, FT>(ctx: &mut impl AsContextMut<Data = T>, ty: FT, func: F) -> Self
where
FT: Into<FunctionType>,
F: Fn(ContextMut<'_, T>, &[Value]) -> Result<Vec<Value>, RuntimeError>
+ 'static
+ Send
+ Sync,
{
let mut ctx = ctx.as_context_mut();
let function_type = ty.into();
let func_ty = function_type.clone();
let raw_ctx = ctx.as_raw() as *mut u8;
let wrapped_func: JsValue = match function_type.results().len() {
0 => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1)))
.collect::<Vec<_>>();
let _results = func(ctx.as_context_mut(), &wasm_arguments)?;
Ok(())
})
as Box<dyn FnMut(&Array) -> Result<(), JsValue>>)
.into_js_value(),
1 => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1)))
.collect::<Vec<_>>();
let results = func(ctx.as_context_mut(), &wasm_arguments)?;
return Ok(result_to_js(&results[0]));
})
as Box<dyn FnMut(&Array) -> Result<JsValue, JsValue>>)
.into_js_value(),
_n => Closure::wrap(Box::new(move |args: &Array| {
let mut ctx = unsafe { ContextMut::from_raw(raw_ctx as *mut ContextInner<T>) };
let wasm_arguments = function_type
.params()
.iter()
.enumerate()
.map(|(i, param)| param_from_js(param, &args.get(i as u32 + 1)))
.collect::<Vec<_>>();
let results = func(ctx.as_context_mut(), &wasm_arguments)?;
return Ok(results_to_js_array(&results));
})
as Box<dyn FnMut(&Array) -> Result<Array, JsValue>>)
.into_js_value(),
};
let dyn_func =
JSFunction::new_with_args("f", "return f(Array.prototype.slice.call(arguments, 1))");
let binded_func = dyn_func.bind2(
&JsValue::UNDEFINED,
&wrapped_func,
&JsValue::from_f64(&*ctx.data() as *const T as *const u8 as usize as f64),
);
let vm_function = VMFunction::new(binded_func, func_ty);
Self::from_vm_export(&mut ctx, vm_function)
}
/// Creates a new host `Function` from a native function.
///
/// The function signature is automatically retrieved using the
/// Rust typing system.
///
/// # Example
///
/// ```
/// # use wasmer::{Store, Function};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// ```
pub fn new_native<T, F, Args, Rets>(ctx: &mut impl AsContextMut<Data = T>, func: F) -> Self
where
F: HostFunction<T, Args, Rets>,
Args: WasmTypeList,
Rets: WasmTypeList,
{
let mut ctx = ctx.as_context_mut();
if std::mem::size_of::<F>() != 0 {
Self::closures_unsupported_panic();
}
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address() as usize as u32;
let ft = wasm_bindgen::function_table();
let as_table = ft.unchecked_ref::<js_sys::WebAssembly::Table>();
let func = as_table.get(address).unwrap();
let binded_func = func.bind1(&JsValue::UNDEFINED, &JsValue::UNDEFINED);
let ty = function.ty();
let vm_function = VMFunction::new(binded_func, ty);
Self {
handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function),
}
}
/// Creates a new host `Function` from a native function and a provided environment.
///
/// The function signature is automatically retrieved using the
/// Rust typing system.
///
/// # Example
///
/// ```
/// # use wasmer::{Store, Function};
/// # let store = Store::default();
/// #
/// #[derive(Clone)]
/// struct Env {
/// multiplier: i32,
/// };
/// let env = Env { multiplier: 2 };
///
/// fn sum_and_multiply(env: &Env, a: i32, b: i32) -> i32 {
/// (a + b) * env.multiplier
/// }
///
/// let f = Function::new_native_with_env(&store, env, sum_and_multiply);
/// ```
pub fn new_native_with_env<T, F, Args, Rets>(
ctx: &mut impl AsContextMut<Data = T>,
func: F,
) -> Self
where
F: HostFunction<T, Args, Rets>,
Args: WasmTypeList,
Rets: WasmTypeList,
{
return Self::new_native(ctx, func);
/*
if std::mem::size_of::<F>() != 0 {
Self::closures_unsupported_panic();
}
let function = inner::Function::<Args, Rets>::new(func);
let address = function.address() as usize as u32;
let ft = wasm_bindgen::function_table();
let as_table = ft.unchecked_ref::<js_sys::WebAssembly::Table>();
let func = as_table.get(address).unwrap();
let ty = function.ty();
let binded_func = func.bind1(&JsValue::UNDEFINED, &JsValue::UNDEFINED);
let vm_function = VMFunction::new(binded_func, ty);
// panic!("Function env {:?}", environment.type_id());
Self {
handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function),
}
*/
}
/// Returns the [`FunctionType`] of the `Function`.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]);
/// assert_eq!(f.ty().results(), vec![Type::I32]);
/// ```
pub fn ty<'context>(&self, ctx: &'context impl AsContextRef) -> &'context FunctionType {
&self.handle.get(ctx.as_context_ref().objects()).ty
}
/// Returns the number of parameters that this function takes.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.param_arity(), 2);
/// ```
pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).params().len()
}
/// Returns the number of results this function produces.
///
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # let store = Store::default();
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
///
/// assert_eq!(f.result_arity(), 1);
/// ```
pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).results().len()
}
/// Call the `Function` function.
///
/// Depending on where the Function is defined, it will call it.
/// 1. If the function is defined inside a WebAssembly, it will call the trampoline
/// for the function signature.
/// 2. If the function is defined in the host (in a native way), it will
/// call the trampoline.
///
/// # Examples
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
/// ```
pub fn call(
&self,
_ctx: &mut impl AsContextMut,
_params: &[Value],
) -> Result<Box<[Value]>, RuntimeError> {
unimplemented!("Can't call functions with ContextMut as first parameter yet.");
/*
let arr = js_sys::Array::new_with_length(params.len() as u32);
for (i, param) in params.iter().enumerate() {
let js_value = param.as_jsvalue(&ctx.as_context_ref());
arr.set(i as u32, js_value);
}
let result = js_sys::Reflect::apply(
&self.handle.get(ctx.as_context_ref().objects()).function,
&wasm_bindgen::JsValue::NULL,
&arr,
)?;
let result_types = self.handle.get(ctx.as_context_ref().objects()).ty.results();
match result_types.len() {
0 => Ok(Box::new([])),
1 => {
let value = param_from_js(&result_types[0], &result);
Ok(vec![value].into_boxed_slice())
}
_n => {
let result_array: Array = result.into();
Ok(result_array
.iter()
.enumerate()
.map(|(i, js_val)| param_from_js(&result_types[i], &js_val))
.collect::<Vec<_>>()
.into_boxed_slice())
}
}
*/
}
pub(crate) fn from_vm_export(ctx: &mut impl AsContextMut, vm_function: VMFunction) -> Self {
Self {
handle: ContextHandle::new(ctx.as_context_mut().objects_mut(), vm_function),
}
}
pub(crate) fn from_vm_extern(
ctx: &mut impl AsContextMut,
internal: InternalContextHandle<VMFunction>,
) -> Self {
Self {
handle: unsafe {
ContextHandle::from_internal(ctx.as_context_ref().objects().id(), internal)
},
}
}
/// Transform this WebAssembly function into a function with the
/// native ABI. See [`TypedFunction`] to learn more.
///
/// # Examples
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
/// let sum_native = sum.native::<(i32, i32), i32>().unwrap();
///
/// assert_eq!(sum_native.call(1, 2).unwrap(), 3);
/// ```
///
/// # Errors
///
/// If the `Args` generic parameter does not match the exported function
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i64, i64), i32>().unwrap();
/// ```
///
/// If the `Rets` generic parameter does not match the exported function
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # let store = Store::default();
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
/// # local.get $x
/// # local.get $y
/// # i32.add
/// # ))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i32, i32), i64>().unwrap();
/// ```
pub fn native<Args, Rets>(
&self,
ctx: &impl AsContextRef,
) -> Result<TypedFunction<Args, Rets>, RuntimeError>
where
Args: WasmTypeList,
Rets: WasmTypeList,
{
let vm_function = self.handle.get(ctx.as_context_ref().objects());
// type check
{
let expected = vm_function.ty.params();
let given = Args::wasm_types();
if expected != given {
return Err(RuntimeError::new(format!(
"given types (`{:?}`) for the function arguments don't match the actual types (`{:?}`)",
given,
expected,
)));
}
}
{
let expected = vm_function.ty.results();
let given = Rets::wasm_types();
if expected != given {
// todo: error result types don't match
return Err(RuntimeError::new(format!(
"given types (`{:?}`) for the function results don't match the actual types (`{:?}`)",
given,
expected,
)));
}
}
Ok(TypedFunction::from_handle(self.clone()))
}
#[track_caller]
fn closures_unsupported_panic() -> ! {
unimplemented!("Closures (functions with captured environments) are currently unsupported with native functions. See: https://github.com/wasmerio/wasmer/issues/1840")
}
/// Checks whether this `Function` can be used with the given context.
pub fn is_from_context(&self, ctx: &impl AsContextRef) -> bool {
self.handle.context_id() == ctx.as_context_ref().objects().id()
}
}
impl<'a> Exportable<'a> for Function {
fn get_self_from_extern(
_ctx: &impl AsContextRef,
_extern: &'a Extern,
) -> Result<&'a Self, ExportError> {
match _extern {
Extern::Function(func) => Ok(func),
_ => Err(ExportError::IncompatibleType),
}
}
}
impl fmt::Debug for Function {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.debug_struct("Function").finish()
}
}
/// This private inner module contains the low-level implementation
/// for `Function` and its siblings.
mod inner {
use super::RuntimeError;
use super::VMFunctionBody;
use crate::js::context::{AsContextMut, ContextInner, ContextMut};
use crate::js::NativeWasmTypeInto;
use std::array::TryFromSliceError;
use std::convert::{Infallible, TryInto};
use std::error::Error;
use std::marker::PhantomData;
use std::panic::{self, AssertUnwindSafe};
use wasmer_types::{FunctionType, NativeWasmType, Type};
// use wasmer::{raise_user_trap, resume_panic};
/// A trait to convert a Rust value to a `WasmNativeType` value,
/// or to convert `WasmNativeType` value to a Rust value.
///
/// This trait should ideally be split into two traits:
/// `FromNativeWasmType` and `ToNativeWasmType` but it creates a
/// non-negligible complexity in the `WasmTypeList`
/// implementation.
pub unsafe trait FromToNativeWasmType
where
Self: Sized,
{
/// Native Wasm type.
type Native: NativeWasmTypeInto;
/// Convert a value of kind `Self::Native` to `Self`.
///
/// # Panics
///
/// This method panics if `native` cannot fit in the `Self`
/// type`.
fn from_native(native: Self::Native) -> Self;
/// Convert self to `Self::Native`.
///
/// # Panics
///
/// This method panics if `self` cannot fit in the
/// `Self::Native` type.
fn to_native(self) -> Self::Native;
}
macro_rules! from_to_native_wasm_type {
( $( $type:ty => $native_type:ty ),* ) => {
$(
#[allow(clippy::use_self)]
unsafe impl FromToNativeWasmType for $type {
type Native = $native_type;
#[inline]
fn from_native(native: Self::Native) -> Self {
native as Self
}
#[inline]
fn to_native(self) -> Self::Native {
self as Self::Native
}
}
)*
};
}
macro_rules! from_to_native_wasm_type_same_size {
( $( $type:ty => $native_type:ty ),* ) => {
$(
#[allow(clippy::use_self)]
unsafe impl FromToNativeWasmType for $type {
type Native = $native_type;
#[inline]
fn from_native(native: Self::Native) -> Self {
Self::from_ne_bytes(Self::Native::to_ne_bytes(native))
}
#[inline]
fn to_native(self) -> Self::Native {
Self::Native::from_ne_bytes(Self::to_ne_bytes(self))
}
}
)*
};
}
from_to_native_wasm_type!(
i8 => i32,
u8 => i32,
i16 => i32,
u16 => i32
);
from_to_native_wasm_type_same_size!(
i32 => i32,
u32 => i32,
i64 => i64,
u64 => i64,
f32 => f32,
f64 => f64
);
mod test_from_to_native_wasm_type {
use super::*;
#[test]
fn test_to_native() {
assert_eq!(7i8.to_native(), 7i32);
assert_eq!(7u8.to_native(), 7i32);
assert_eq!(7i16.to_native(), 7i32);
assert_eq!(7u16.to_native(), 7i32);
assert_eq!(u32::MAX.to_native(), -1);
}
#[test]
fn test_to_native_same_size() {
assert_eq!(7i32.to_native(), 7i32);
assert_eq!(7u32.to_native(), 7i32);
assert_eq!(7i64.to_native(), 7i64);
assert_eq!(7u64.to_native(), 7i64);
assert_eq!(7f32.to_native(), 7f32);
assert_eq!(7f64.to_native(), 7f64);
}
}
/// The `WasmTypeList` trait represents a tuple (list) of Wasm
/// typed values. It is used to get low-level representation of
/// such a tuple.
pub trait WasmTypeList
where
Self: Sized,
{
/// The C type (a struct) that can hold/represent all the
/// represented values.
type CStruct;
/// The array type that can hold all the represented values.
///
/// Note that all values are stored in their binary form.
type Array: AsMut<[f64]>;
/// The size of the array
fn size() -> u32;
/// Constructs `Self` based on an array of values.
///
/// # Safety
unsafe fn from_array(ctx: &mut impl AsContextMut, array: Self::Array) -> Self;
/// Constructs `Self` based on a slice of values.
///
/// `from_slice` returns a `Result` because it is possible
/// that the slice doesn't have the same size than
/// `Self::Array`, in which circumstance an error of kind
/// `TryFromSliceError` will be returned.
///
/// # Safety
unsafe fn from_slice(
ctx: &mut impl AsContextMut,
slice: &[f64],
) -> Result<Self, TryFromSliceError>;
/// Builds and returns an array of type `Array` from a tuple
/// (list) of values.
///
/// # Safety
unsafe fn into_array(self, ctx: &mut impl AsContextMut) -> Self::Array;
/// Allocates and return an empty array of type `Array` that
/// will hold a tuple (list) of values, usually to hold the
/// returned values of a WebAssembly function call.
fn empty_array() -> Self::Array;
/// Builds a tuple (list) of values from a C struct of type
/// `CStruct`.
///
/// # Safety
unsafe fn from_c_struct(ctx: &mut impl AsContextMut, c_struct: Self::CStruct) -> Self;
/// Builds and returns a C struct of type `CStruct` from a
/// tuple (list) of values.
///
/// # Safety
unsafe fn into_c_struct(self, ctx: &mut impl AsContextMut) -> Self::CStruct;
/// Writes the contents of a C struct to an array of `f64`.
///
/// # Safety
unsafe fn write_c_struct_to_ptr(c_struct: Self::CStruct, ptr: *mut f64);
/// Get the Wasm types for the tuple (list) of currently
/// represented values.
fn wasm_types() -> &'static [Type];
}
/// The `IntoResult` trait turns a `WasmTypeList` into a
/// `Result<WasmTypeList, Self::Error>`.
///
/// It is mostly used to turn result values of a Wasm function
/// call into a `Result`.
pub trait IntoResult<T>
where
T: WasmTypeList,
{
/// The error type for this trait.
type Error: Error + Sync + Send + 'static;
/// Transforms `Self` into a `Result`.
fn into_result(self) -> Result<T, Self::Error>;
}
impl<T> IntoResult<T> for T
where
T: WasmTypeList,
{
// `T` is not a `Result`, it's already a value, so no error
// can be built.
type Error = Infallible;
fn into_result(self) -> Result<Self, Infallible> {
Ok(self)
}
}
impl<T, E> IntoResult<T> for Result<T, E>
where
T: WasmTypeList,
E: Error + Sync + Send + 'static,
{
type Error = E;
fn into_result(self) -> Self {
self
}
}
#[cfg(test)]
mod test_into_result {
use super::*;
use std::convert::Infallible;
fn test_into_result_over_t() {
let x: i32 = 42;
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x.unwrap(), x);
}
fn test_into_result_over_result() {
{
let x: Result<i32, Infallible> = Ok(42);
let result_of_x: Result<i32, Infallible> = x.into_result();
assert_eq!(result_of_x, x);
}
{
use std::{error, fmt};
#[derive(Debug, PartialEq)]
struct E;
impl fmt::Display for E {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "E")
}
}
impl error::Error for E {}
let x: Result<Infallible, E> = Err(E);
let result_of_x: Result<Infallible, E> = x.into_result();
assert_eq!(result_of_x.unwrap_err(), E);
}
}
}
/// The `HostFunction` trait represents the set of functions that
/// can be used as host function. To uphold this statement, it is
/// necessary for a function to be transformed into a pointer to
/// `VMFunctionBody`.
pub trait HostFunction<T, Args, Rets>
where
Args: WasmTypeList,
Rets: WasmTypeList,
T: Sized,
Self: Sized,
{
/// Get the pointer to the function body.
fn function_body_ptr(self) -> *const VMFunctionBody;
}
/// Represents a low-level Wasm static host function. See
/// `super::Function::new_native` to learn more.
pub(crate) struct StaticFunction<F> {
pub(crate) raw_ctx: *mut u8,
pub(crate) func: F,
}
/// Represents a low-level Wasm static host function. See
/// `super::Function::new` and `super::Function::new_env` to learn
/// more.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Function<Args = (), Rets = ()> {
address: *const VMFunctionBody,
_phantom: PhantomData<(Args, Rets)>,
}
unsafe impl<Args, Rets> Send for Function<Args, Rets> {}
impl<Args, Rets> Function<Args, Rets>
where
Args: WasmTypeList,
Rets: WasmTypeList,
{
/// Creates a new `Function`.
#[allow(dead_code)]
pub fn new<F, T>(function: F) -> Self
where
F: HostFunction<T, Args, Rets>,
T: Sized,
{
Self {
address: function.function_body_ptr(),
_phantom: PhantomData,
}
}
/// Get the function type of this `Function`.
#[allow(dead_code)]
pub fn ty(&self) -> FunctionType {
FunctionType::new(Args::wasm_types(), Rets::wasm_types())
}
/// Get the address of this `Function`.
#[allow(dead_code)]
pub fn address(&self) -> *const VMFunctionBody {
self.address
}
}