feat(wasm-backend)!: split Function trait, improve naming (#347)

split function interface, improve naming
This commit is contained in:
Valery Antopol
2023-07-25 18:23:54 +03:00
committed by GitHub
parent 974f5931ab
commit 0f9979ae11
21 changed files with 113 additions and 87 deletions

14
Cargo.lock generated
View File

@@ -1096,9 +1096,9 @@ dependencies = [
[[package]] [[package]]
name = "erased-serde" name = "erased-serde"
version = "0.3.27" version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f94c0e13118e7d7533271f754a168ae8400e6a1cc043f2bfd53cc7290f1a1de3" checksum = "da96524cc884f6558f1769b6c46686af2fe8e8b4cd253bd5a3cdba8181b8e070"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@@ -3373,9 +3373,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_bytes" name = "serde_bytes"
version = "0.11.11" version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a16be4fe5320ade08736447e3198294a5ea9a6d44dde6f35f0a5e06859c427a" checksum = "ab33ec92f677585af6d88c65593ae2375adde54efdbf16d597f2cbc7a6d368ff"
dependencies = [ dependencies = [
"serde", "serde",
] ]
@@ -4117,7 +4117,7 @@ dependencies = [
"leb128", "leb128",
"log", "log",
"walrus-macro", "walrus-macro",
"wasmparser 0.77.0", "wasmparser 0.77.1",
] ]
[[package]] [[package]]
@@ -4567,9 +4567,9 @@ checksum = "aeb1956b19469d1c5e63e459d29e7b5aa0f558d9f16fcef09736f8a265e6c10a"
[[package]] [[package]]
name = "wasmparser" name = "wasmparser"
version = "0.77.0" version = "0.77.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b35c86d22e720a07d954ebbed772d01180501afe7d03d464f413bb5f8914a8d6" checksum = "5fe3d5405e9ea6c1317a656d6e0820912d8b7b3607823a7596117c8f666daf6f"
[[package]] [[package]]
name = "wasmparser" name = "wasmparser"

View File

@@ -31,14 +31,14 @@ const DEFAULT_HEAP_PAGES_COUNT: u32 = 1600;
pub type ErrorHandler = pub type ErrorHandler =
Option<Box<dyn Fn(&HostImportError) -> Option<IValue> + Sync + Send + 'static>>; Option<Box<dyn Fn(&HostImportError) -> Option<IValue> + Sync + Send + 'static>>;
pub type HostExportedFunc<WB> = Box< pub type HostExportedFunc<WB> = Box<
dyn for<'c> Fn(&mut <WB as WasmBackend>::Caller<'c>, Vec<IValue>) -> Option<IValue> dyn for<'c> Fn(&mut <WB as WasmBackend>::ImportCallContext<'c>, Vec<IValue>) -> Option<IValue>
+ Sync + Sync
+ Send + Send
+ 'static, + 'static,
>; >;
pub type RawImportCreator<WB> = pub type RawImportCreator<WB> =
Box<dyn FnOnce(<WB as WasmBackend>::ContextMut<'_>) -> <WB as WasmBackend>::Function>; Box<dyn FnOnce(<WB as WasmBackend>::ContextMut<'_>) -> <WB as WasmBackend>::HostFunction>;
pub struct HostImportDescriptor<WB: WasmBackend> { pub struct HostImportDescriptor<WB: WasmBackend> {
/// This closure will be invoked for corresponding import. /// This closure will be invoked for corresponding import.

View File

@@ -41,16 +41,18 @@ pub(crate) fn create_host_import_func<WB: WasmBackend>(
store: &mut <WB as WasmBackend>::Store, store: &mut <WB as WasmBackend>::Store,
descriptor: HostImportDescriptor<WB>, descriptor: HostImportDescriptor<WB>,
record_types: Arc<MRecordTypes>, record_types: Arc<MRecordTypes>,
) -> <WB as WasmBackend>::Function { ) -> <WB as WasmBackend>::HostFunction {
let raw_args = itypes_args_to_wtypes(&descriptor.argument_types); let raw_args = itypes_args_to_wtypes(&descriptor.argument_types);
let raw_output = let raw_output =
itypes_output_to_wtypes(&output_type_to_types(descriptor.output_type.as_ref())); itypes_output_to_wtypes(&output_type_to_types(descriptor.output_type.as_ref()));
let func = move |caller: <WB as WasmBackend>::Caller<'_>, inputs: &[WValue]| -> Vec<WValue> { let func = move |call_cotnext: <WB as WasmBackend>::ImportCallContext<'_>,
call_host_import(caller, inputs, &descriptor, record_types.clone()) inputs: &[WValue]|
-> Vec<WValue> {
call_host_import(call_cotnext, inputs, &descriptor, record_types.clone())
}; };
<WB as WasmBackend>::Function::new_with_caller( <WB as WasmBackend>::HostFunction::new_with_caller(
&mut store.as_context_mut(), &mut store.as_context_mut(),
FuncSig::new(raw_args, raw_output), FuncSig::new(raw_args, raw_output),
func, func,
@@ -58,7 +60,7 @@ pub(crate) fn create_host_import_func<WB: WasmBackend>(
} }
fn call_host_import<WB: WasmBackend>( fn call_host_import<WB: WasmBackend>(
mut caller: <WB as WasmBackend>::Caller<'_>, mut caller: <WB as WasmBackend>::ImportCallContext<'_>,
inputs: &[WValue], inputs: &[WValue],
descriptor: &HostImportDescriptor<WB>, descriptor: &HostImportDescriptor<WB>,
record_types: Arc<MRecordTypes>, record_types: Arc<MRecordTypes>,
@@ -95,7 +97,7 @@ fn call_host_import<WB: WasmBackend>(
} }
fn lift_inputs<WB: WasmBackend>( fn lift_inputs<WB: WasmBackend>(
caller: &mut <WB as WasmBackend>::Caller<'_>, caller: &mut <WB as WasmBackend>::ImportCallContext<'_>,
memory: <WB as WasmBackend>::Memory, memory: <WB as WasmBackend>::Memory,
record_types: Arc<MRecordTypes>, record_types: Arc<MRecordTypes>,
inputs: &[WValue], inputs: &[WValue],
@@ -113,7 +115,7 @@ fn lift_inputs<WB: WasmBackend>(
} }
fn lower_outputs<WB: WasmBackend>( fn lower_outputs<WB: WasmBackend>(
caller: &mut <WB as WasmBackend>::Caller<'_>, caller: &mut <WB as WasmBackend>::ImportCallContext<'_>,
memory: <WB as WasmBackend>::Memory, memory: <WB as WasmBackend>::Memory,
output: Option<IValue>, output: Option<IValue>,
) -> Vec<WValue> { ) -> Vec<WValue> {

View File

@@ -303,9 +303,9 @@ impl<WB: WasmBackend> MModule<WB> {
inputs: I1, inputs: I1,
outputs: I2, outputs: I2,
raw_import: F, raw_import: F,
) -> <WB as WasmBackend>::Function ) -> <WB as WasmBackend>::HostFunction
where where
F: for<'c> Fn(<WB as WasmBackend>::Caller<'c>, &[WValue]) -> Vec<WValue> F: for<'c> Fn(<WB as WasmBackend>::ImportCallContext<'c>, &[WValue]) -> Vec<WValue>
+ Sync + Sync
+ Send + Send
+ 'static, + 'static,
@@ -317,7 +317,7 @@ impl<WB: WasmBackend> MModule<WB> {
let inputs = inputs.map(itype_to_wtype).collect::<Vec<_>>(); let inputs = inputs.map(itype_to_wtype).collect::<Vec<_>>();
let outputs = outputs.map(itype_to_wtype).collect::<Vec<_>>(); let outputs = outputs.map(itype_to_wtype).collect::<Vec<_>>();
<WB as WasmBackend>::Function::new_with_caller( <WB as WasmBackend>::HostFunction::new_with_caller(
&mut store.as_context_mut(), &mut store.as_context_mut(),
FuncSig::new(inputs, outputs), FuncSig::new(inputs, outputs),
raw_import, raw_import,
@@ -330,11 +330,13 @@ impl<WB: WasmBackend> MModule<WB> {
interpreter: ITInterpreter<WB>, interpreter: ITInterpreter<WB>,
import_namespace: String, import_namespace: String,
import_name: String, import_name: String,
) -> impl for<'c> Fn(<WB as WasmBackend>::Caller<'c>, &[WValue]) -> Vec<WValue> ) -> impl for<'c> Fn(<WB as WasmBackend>::ImportCallContext<'c>, &[WValue]) -> Vec<WValue>
+ Sync + Sync
+ Send + Send
+ 'static { + 'static {
move |mut ctx: <WB as WasmBackend>::Caller<'_>, inputs: &[WValue]| -> Vec<WValue> { move |mut ctx: <WB as WasmBackend>::ImportCallContext<'_>,
inputs: &[WValue]|
-> Vec<WValue> {
use wasmer_it::interpreter::stack::Stackable; use wasmer_it::interpreter::stack::Stackable;
use super::type_converters::wval_to_ival; use super::type_converters::wval_to_ival;

View File

@@ -24,7 +24,7 @@ use crate::MResult;
use marine_wasm_backend_traits::DelayedContextLifetime; use marine_wasm_backend_traits::DelayedContextLifetime;
use marine_wasm_backend_traits::WasmBackend; use marine_wasm_backend_traits::WasmBackend;
use marine_wasm_backend_traits::WValue; use marine_wasm_backend_traits::WValue;
use marine_wasm_backend_traits::Function; use marine_wasm_backend_traits::ExportFunction;
use wasmer_it::interpreter::wasm; use wasmer_it::interpreter::wasm;
@@ -33,7 +33,7 @@ use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
enum WITFunctionInner<WB: WasmBackend> { enum WITFunctionInner<WB: WasmBackend> {
Export { Export {
func: Arc<<WB as WasmBackend>::Function>, func: Arc<<WB as WasmBackend>::ExportFunction>,
}, },
Import { Import {
// TODO: use dyn Callable here // TODO: use dyn Callable here
@@ -54,7 +54,7 @@ impl<WB: WasmBackend> WITFunction<WB> {
/// Creates functions from a "usual" (not IT) module export. /// Creates functions from a "usual" (not IT) module export.
pub(super) fn from_export( pub(super) fn from_export(
store: &mut <WB as WasmBackend>::Store, store: &mut <WB as WasmBackend>::Store,
dyn_func: <WB as WasmBackend>::Function, dyn_func: <WB as WasmBackend>::ExportFunction,
name: String, name: String,
) -> MResult<Self> { ) -> MResult<Self> {
use super::type_converters::wtype_to_itype; use super::type_converters::wtype_to_itype;

View File

@@ -18,10 +18,10 @@ use crate::AsContextMut;
use crate::FuncGetter; use crate::FuncGetter;
use crate::WasmBackend; use crate::WasmBackend;
/// `Caller` is a structure used to pass context to imports. /// `ImportCallContext` is a structure used to pass context to imports.
/// It serves as a handle to `Store`, and also provides access to `Memory` and export functions /// It serves as a handle to `Store`, and also provides access to `Memory` and export functions
/// from the caller instance, if there is one. /// from the caller instance, if there is one.
pub trait Caller<WB: WasmBackend>: pub trait ImportCallContext<WB: WasmBackend>:
FuncGetter<WB, (i32, i32), i32> FuncGetter<WB, (i32, i32), i32>
+ FuncGetter<WB, (i32, i32), ()> + FuncGetter<WB, (i32, i32), ()>
+ FuncGetter<WB, i32, i32> + FuncGetter<WB, i32, i32>

View File

@@ -24,7 +24,7 @@ use crate::WasmBackend;
#[derive(Clone)] #[derive(Clone)]
pub enum Export<WB: WasmBackend> { pub enum Export<WB: WasmBackend> {
Memory(<WB as WasmBackend>::Memory), Memory(<WB as WasmBackend>::Memory),
Function(<WB as WasmBackend>::Function), Function(<WB as WasmBackend>::ExportFunction),
Other, Other,
} }

View File

@@ -21,9 +21,9 @@ use crate::RuntimeResult;
use crate::WasmBackend; use crate::WasmBackend;
use crate::WValue; use crate::WValue;
/// A Wasm function handle, it can be either a function from a host or an export from an `Instance`. /// A host function ready to be used as an import for instantiating a module.
/// As it is only a handle to an object in `Store`, cloning is cheap /// As it is only a handle to an object in `Store`, cloning is cheap.
pub trait Function<WB: WasmBackend>: Send + Sync + Clone { pub trait HostFunction<WB: WasmBackend>: Send + Sync + Clone {
/// Creates a new function with dynamic signature. /// Creates a new function with dynamic signature.
/// The signature check is performed at runtime. /// The signature check is performed at runtime.
fn new<F>(store: &mut impl AsContextMut<WB>, sig: FuncSig, func: F) -> Self fn new<F>(store: &mut impl AsContextMut<WB>, sig: FuncSig, func: F) -> Self
@@ -33,7 +33,7 @@ pub trait Function<WB: WasmBackend>: Send + Sync + Clone {
/// Creates a new function with dynamic signature that needs a context. /// Creates a new function with dynamic signature that needs a context.
fn new_with_caller<F>(store: &mut impl AsContextMut<WB>, sig: FuncSig, func: F) -> Self fn new_with_caller<F>(store: &mut impl AsContextMut<WB>, sig: FuncSig, func: F) -> Self
where where
F: for<'c> Fn(<WB as WasmBackend>::Caller<'c>, &[WValue]) -> Vec<WValue> F: for<'c> Fn(<WB as WasmBackend>::ImportCallContext<'c>, &[WValue]) -> Vec<WValue>
+ Sync + Sync
+ Send + Send
+ 'static; + 'static;
@@ -49,6 +49,15 @@ pub trait Function<WB: WasmBackend>: Send + Sync + Clone {
/// The signature is constructed each time this function is called, so /// The signature is constructed each time this function is called, so
/// it is not recommended to use this function extensively. /// it is not recommended to use this function extensively.
fn signature(&self, store: &mut impl AsContextMut<WB>) -> FuncSig; fn signature(&self, store: &mut impl AsContextMut<WB>) -> FuncSig;
}
/// A Wasm function handle, it can be either a function from a host or an export from an `Instance`.
/// As it is only a handle to an object in `Store`, cloning is cheap
pub trait ExportFunction<WB: WasmBackend>: Send + Sync + Clone {
/// Returns the signature of the function.
/// The signature is constructed each time this function is called, so
/// it is not recommended to use this function extensively.
fn signature(&self, store: &mut impl AsContextMut<WB>) -> FuncSig;
/// Calls the wasm function. /// Calls the wasm function.
/// # Panics: /// # Panics:
@@ -66,17 +75,17 @@ pub trait Function<WB: WasmBackend>: Send + Sync + Clone {
/// Should not be implemented by users. /// Should not be implemented by users.
/// Implemented for all functions that meet the following criteria: /// Implemented for all functions that meet the following criteria:
/// * implement Send + Sync + 'static /// * implement Send + Sync + 'static
/// * take or not take Caller as first parameter /// * take or not take ImportCallContext as first parameter
/// * take from 0 to 16 i32 parameters /// * take from 0 to 16 i32 parameters
/// * return () or i32 /// * return () or i32
pub trait IntoFunc<WB: WasmBackend, Params, Results, Env> { pub trait IntoFunc<WB: WasmBackend, Params, Results, Env> {
fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::Function; fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::HostFunction;
} }
/// An indicator of using Caller argument. /// An indicator of using ImportCallContext argument.
pub struct WithEnv {} pub struct WithEnv {}
/// An indicator of using Caller argument. /// An indicator of using ImportCallContext argument.
pub struct WithoutEnv {} pub struct WithoutEnv {}
#[macro_export] #[macro_export]
@@ -94,8 +103,8 @@ macro_rules! impl_into_func {
WB: WasmBackend, WB: WasmBackend,
F: Fn($(replace_with!($args -> i32),)*) + Send + Sync + 'static, F: Fn($(replace_with!($args -> i32),)*) + Send + Sync + 'static,
{ {
fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::Function { fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::HostFunction {
<WB as WasmBackend>::Function:: [< new_typed_ $num >] (ctx.as_context_mut(), self) <WB as WasmBackend>::HostFunction:: [< new_typed_ $num >] (ctx.as_context_mut(), self)
} }
} }
@@ -103,10 +112,10 @@ macro_rules! impl_into_func {
impl<WB, F> IntoFunc<WB, ($(replace_with!($args -> i32),)*), (), WithEnv> for F impl<WB, F> IntoFunc<WB, ($(replace_with!($args -> i32),)*), (), WithEnv> for F
where where
WB: WasmBackend, WB: WasmBackend,
F: Fn(<WB as WasmBackend>::Caller<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static, F: Fn(<WB as WasmBackend>::ImportCallContext<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static,
{ {
fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::Function { fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::HostFunction {
<WB as WasmBackend>::Function:: [< new_typed_with_env_ $num >] (ctx.as_context_mut(), self) <WB as WasmBackend>::HostFunction:: [< new_typed_with_env_ $num >] (ctx.as_context_mut(), self)
} }
} }
@@ -116,8 +125,8 @@ macro_rules! impl_into_func {
WB: WasmBackend, WB: WasmBackend,
F: Fn($(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static, F: Fn($(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static,
{ {
fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::Function { fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::HostFunction {
<WB as WasmBackend>::Function:: [< new_typed_ $num _r >] (ctx.as_context_mut(), self) <WB as WasmBackend>::HostFunction:: [< new_typed_ $num _r >] (ctx.as_context_mut(), self)
} }
} }
@@ -125,10 +134,10 @@ macro_rules! impl_into_func {
impl<WB, F> IntoFunc<WB, ($(replace_with!($args -> i32),)*), i32, WithEnv> for F impl<WB, F> IntoFunc<WB, ($(replace_with!($args -> i32),)*), i32, WithEnv> for F
where where
WB: WasmBackend, WB: WasmBackend,
F: Fn(<WB as WasmBackend>::Caller<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static, F: Fn(<WB as WasmBackend>::ImportCallContext<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static,
{ {
fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::Function { fn into_func(self, ctx: &mut impl AsContextMut<WB>) -> <WB as WasmBackend>::HostFunction {
<WB as WasmBackend>::Function:: [< new_typed_with_env_ $num _r >] (ctx.as_context_mut(), self) <WB as WasmBackend>::HostFunction:: [< new_typed_with_env_ $num _r >] (ctx.as_context_mut(), self)
} }
} }
}); });
@@ -139,28 +148,28 @@ impl_for_each_function_signature!(impl_into_func);
macro_rules! declare_func_construction { macro_rules! declare_func_construction {
($num:tt $($args:ident)*) => (paste::paste!{ ($num:tt $($args:ident)*) => (paste::paste!{
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn [< new_typed_ $num >]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::Function fn [< new_typed_ $num >]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::HostFunction
where F: Fn($(replace_with!($args -> i32),)*) + Send + Sync + 'static where F: Fn($(replace_with!($args -> i32),)*) + Send + Sync + 'static
{ {
let func = move |_: <WB as WasmBackend>::Caller<'_>, $($args,)*| { func($($args,)*)}; let func = move |_: <WB as WasmBackend>::ImportCallContext<'_>, $($args,)*| { func($($args,)*)};
Self:: [< new_typed_with_env_ $num >] (ctx, func) Self:: [< new_typed_with_env_ $num >] (ctx, func)
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn [< new_typed_with_env_ $num >]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::Function fn [< new_typed_with_env_ $num >]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::HostFunction
where F: Fn(<WB as WasmBackend>::Caller<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static; where F: Fn(<WB as WasmBackend>::ImportCallContext<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static;
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn [< new_typed_ $num _r>]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::Function fn [< new_typed_ $num _r>]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::HostFunction
where F: Fn($(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static where F: Fn($(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static
{ {
let func = move |_: <WB as WasmBackend>::Caller<'_>, $($args,)*| -> i32 { func($($args,)*)}; let func = move |_: <WB as WasmBackend>::ImportCallContext<'_>, $($args,)*| -> i32 { func($($args,)*)};
Self:: [< new_typed_with_env_ $num _r >] (ctx, func) Self:: [< new_typed_with_env_ $num _r >] (ctx, func)
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn [< new_typed_with_env_ $num _r>]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::Function fn [< new_typed_with_env_ $num _r>]<F>(ctx: <WB as WasmBackend>::ContextMut<'_>, func: F) -> <WB as WasmBackend>::HostFunction
where F: Fn(<WB as WasmBackend>::Caller<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static; where F: Fn(<WB as WasmBackend>::ImportCallContext<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static;
}); });
} }

View File

@@ -36,7 +36,7 @@ pub trait Imports<WB: WasmBackend>: Clone {
store: &impl AsContext<WB>, store: &impl AsContext<WB>,
module: impl Into<String>, module: impl Into<String>,
name: impl Into<String>, name: impl Into<String>,
func: <WB as WasmBackend>::Function, func: <WB as WasmBackend>::HostFunction,
) -> Result<(), ImportError>; ) -> Result<(), ImportError>;
/// Inserts several named functions to the same namespace `module` at once, an equivalent to multiple calls of `insert`. /// Inserts several named functions to the same namespace `module` at once, an equivalent to multiple calls of `insert`.
@@ -51,7 +51,7 @@ pub trait Imports<WB: WasmBackend>: Clone {
) -> Result<(), ImportError> ) -> Result<(), ImportError>
where where
S: Into<String>, S: Into<String>,
I: IntoIterator<Item = (String, <WB as WasmBackend>::Function)>; I: IntoIterator<Item = (String, <WB as WasmBackend>::HostFunction)>;
} }
/// A type representing function signature. /// A type representing function signature.
@@ -82,7 +82,7 @@ impl FuncSig {
} }
} }
pub type FuncFromCaller<WB, Args, Rets> = Box< pub type FuncFromImportCallContext<WB, Args, Rets> = Box<
dyn FnMut(&mut <WB as WasmBackend>::ContextMut<'_>, Args) -> RuntimeResult<Rets> dyn FnMut(&mut <WB as WasmBackend>::ContextMut<'_>, Args) -> RuntimeResult<Rets>
+ Sync + Sync
+ Send + Send
@@ -91,5 +91,5 @@ pub type FuncFromCaller<WB, Args, Rets> = Box<
pub trait FuncGetter<WB: WasmBackend, Args, Rets> { pub trait FuncGetter<WB: WasmBackend, Args, Rets> {
/// Gets an export function from the calling instance. /// Gets an export function from the calling instance.
fn get_func(&mut self, name: &str) -> ResolveResult<FuncFromCaller<WB, Args, Rets>>; fn get_func(&mut self, name: &str) -> ResolveResult<FuncFromImportCallContext<WB, Args, Rets>>;
} }

View File

@@ -52,5 +52,5 @@ pub trait Instance<WB: WasmBackend>: Clone {
&self, &self,
store: &mut impl AsContextMut<WB>, store: &mut impl AsContextMut<WB>,
name: &str, name: &str,
) -> ResolveResult<<WB as WasmBackend>::Function>; ) -> ResolveResult<<WB as WasmBackend>::ExportFunction>;
} }

View File

@@ -69,9 +69,11 @@ pub trait WasmBackend: Clone + Default + 'static {
/// A temporary mutable handle to `Store` /// A temporary mutable handle to `Store`
type ContextMut<'c>: ContextMut<Self>; type ContextMut<'c>: ContextMut<Self>;
/// A type that is used to pass context to imports. /// A type that is used to pass context to imports.
type Caller<'c>: Caller<Self>; type ImportCallContext<'c>: ImportCallContext<Self>;
/// A function contained in `Store`, either host one or from wasm. /// A host function prepared to be used as import for instantiating a module, contained in `Store`.
type Function: Function<Self> + FuncConstructor<Self>; type HostFunction: HostFunction<Self> + FuncConstructor<Self>;
/// An export function from a wasm instance, contained in `Store`
type ExportFunction: ExportFunction<Self>;
/// A wasm memory. /// A wasm memory.
type Memory: Memory<Self>; type Memory: Memory<Self>;
/// A view to the wasm memory. /// A view to the wasm memory.

View File

@@ -25,11 +25,11 @@ use marine_wasm_backend_traits::prelude::*;
use wasmtime::AsContext as WasmtimeAsContext; use wasmtime::AsContext as WasmtimeAsContext;
use wasmtime::AsContextMut as WasmtimeAsContextMut; use wasmtime::AsContextMut as WasmtimeAsContextMut;
pub struct WasmtimeCaller<'c> { pub struct WasmtimeImportCallContext<'c> {
pub(crate) inner: wasmtime::Caller<'c, StoreState>, pub(crate) inner: wasmtime::Caller<'c, StoreState>,
} }
impl<'c> Caller<WasmtimeWasmBackend> for WasmtimeCaller<'c> { impl<'c> ImportCallContext<WasmtimeWasmBackend> for WasmtimeImportCallContext<'c> {
fn memory(&mut self, _memory_index: u32) -> Option<WasmtimeMemory> { fn memory(&mut self, _memory_index: u32) -> Option<WasmtimeMemory> {
let memory = self let memory = self
.inner .inner
@@ -40,7 +40,7 @@ impl<'c> Caller<WasmtimeWasmBackend> for WasmtimeCaller<'c> {
} }
} }
impl<'c> AsContext<WasmtimeWasmBackend> for WasmtimeCaller<'c> { impl<'c> AsContext<WasmtimeWasmBackend> for WasmtimeImportCallContext<'c> {
fn as_context(&self) -> WasmtimeContext<'_> { fn as_context(&self) -> WasmtimeContext<'_> {
WasmtimeContext { WasmtimeContext {
inner: self.inner.as_context(), inner: self.inner.as_context(),
@@ -48,7 +48,7 @@ impl<'c> AsContext<WasmtimeWasmBackend> for WasmtimeCaller<'c> {
} }
} }
impl<'c> AsContextMut<WasmtimeWasmBackend> for WasmtimeCaller<'c> { impl<'c> AsContextMut<WasmtimeWasmBackend> for WasmtimeImportCallContext<'c> {
fn as_context_mut(&mut self) -> <WasmtimeWasmBackend as WasmBackend>::ContextMut<'_> { fn as_context_mut(&mut self) -> <WasmtimeWasmBackend as WasmBackend>::ContextMut<'_> {
WasmtimeContextMut { WasmtimeContextMut {
inner: self.inner.as_context_mut(), inner: self.inner.as_context_mut(),
@@ -60,7 +60,7 @@ impl<'c> AsContextMut<WasmtimeWasmBackend> for WasmtimeCaller<'c> {
/// Later `get_func` variant will be statically chosen based on types. /// Later `get_func` variant will be statically chosen based on types.
macro_rules! impl_func_getter { macro_rules! impl_func_getter {
($args:ty, $rets:ty) => { ($args:ty, $rets:ty) => {
impl<'c> FuncGetter<WasmtimeWasmBackend, $args, $rets> for WasmtimeCaller<'c> { impl<'c> FuncGetter<WasmtimeWasmBackend, $args, $rets> for WasmtimeImportCallContext<'c> {
fn get_func( fn get_func(
&mut self, &mut self,
name: &str, name: &str,

View File

@@ -16,7 +16,7 @@
use crate::WasmtimeContextMut; use crate::WasmtimeContextMut;
use crate::WasmtimeWasmBackend; use crate::WasmtimeWasmBackend;
use crate::WasmtimeCaller; use crate::WasmtimeImportCallContext;
use crate::val_to_wvalue; use crate::val_to_wvalue;
use crate::StoreState; use crate::StoreState;
use crate::sig_to_fn_ty; use crate::sig_to_fn_ty;
@@ -35,7 +35,7 @@ pub struct WasmtimeFunction {
pub(crate) inner: wasmtime::Func, pub(crate) inner: wasmtime::Func,
} }
impl Function<WasmtimeWasmBackend> for WasmtimeFunction { impl HostFunction<WasmtimeWasmBackend> for WasmtimeFunction {
fn new<F>(store: &mut impl AsContextMut<WasmtimeWasmBackend>, sig: FuncSig, func: F) -> Self fn new<F>(store: &mut impl AsContextMut<WasmtimeWasmBackend>, sig: FuncSig, func: F) -> Self
where where
F: for<'c> Fn(&[WValue]) -> Vec<WValue> + Sync + Send + 'static, F: for<'c> Fn(&[WValue]) -> Vec<WValue> + Sync + Send + 'static,
@@ -60,7 +60,10 @@ impl Function<WasmtimeWasmBackend> for WasmtimeFunction {
func: F, func: F,
) -> Self ) -> Self
where where
F: for<'c> Fn(<WasmtimeWasmBackend as WasmBackend>::Caller<'c>, &[WValue]) -> Vec<WValue> F: for<'c> Fn(
<WasmtimeWasmBackend as WasmBackend>::ImportCallContext<'c>,
&[WValue],
) -> Vec<WValue>
+ Sync + Sync
+ Send + Send
+ 'static, + 'static,
@@ -71,7 +74,7 @@ impl Function<WasmtimeWasmBackend> for WasmtimeFunction {
args: &[wasmtime::Val], args: &[wasmtime::Val],
results_out: &mut [wasmtime::Val]| results_out: &mut [wasmtime::Val]|
-> Result<(), anyhow::Error> { -> Result<(), anyhow::Error> {
let caller = WasmtimeCaller { inner: caller }; let caller = WasmtimeImportCallContext { inner: caller };
let args = process_func_args(args).map_err(|e| anyhow!(e))?; let args = process_func_args(args).map_err(|e| anyhow!(e))?;
let results = func(caller, &args); let results = func(caller, &args);
process_func_results(&results, results_out).map_err(|e| anyhow!(e)) process_func_results(&results, results_out).map_err(|e| anyhow!(e))
@@ -92,6 +95,13 @@ impl Function<WasmtimeWasmBackend> for WasmtimeFunction {
let ty = self.inner.ty(store.as_context_mut()); let ty = self.inner.ty(store.as_context_mut());
fn_ty_to_sig(&ty) 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>( fn call<'c>(
&self, &self,
@@ -119,10 +129,10 @@ impl Function<WasmtimeWasmBackend> for WasmtimeFunction {
macro_rules! impl_func_construction { macro_rules! impl_func_construction {
($num:tt $($args:ident)*) => (paste::paste!{ ($num:tt $($args:ident)*) => (paste::paste!{
fn [< new_typed_with_env_ $num >] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction fn [< new_typed_with_env_ $num >] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction
where F: Fn(WasmtimeCaller<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static { where F: Fn(WasmtimeImportCallContext<'_>, $(replace_with!($args -> i32),)*) + Send + Sync + 'static {
let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| { let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| {
let caller = WasmtimeCaller {inner: caller}; let caller = WasmtimeImportCallContext {inner: caller};
func(caller, $($args,)*) func(caller, $($args,)*)
}; };
@@ -134,10 +144,10 @@ macro_rules! impl_func_construction {
} }
fn [< new_typed_with_env_ $num _r>] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction fn [< new_typed_with_env_ $num _r>] <F>(mut ctx: WasmtimeContextMut<'_>, func: F) -> WasmtimeFunction
where F: Fn(WasmtimeCaller<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static { where F: Fn(WasmtimeImportCallContext<'_>, $(replace_with!($args -> i32),)*) -> i32 + Send + Sync + 'static {
let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| -> i32{ let func = move |caller: wasmtime::Caller<'_, StoreState>, $($args,)*| -> i32{
let caller = WasmtimeCaller {inner: caller}; let caller = WasmtimeImportCallContext {inner: caller};
func(caller, $($args,)*) func(caller, $($args,)*)
}; };

View File

@@ -38,7 +38,7 @@ impl Imports<WasmtimeWasmBackend> for WasmtimeImports {
store: &impl AsContext<WasmtimeWasmBackend>, store: &impl AsContext<WasmtimeWasmBackend>,
module: impl Into<String>, module: impl Into<String>,
name: impl Into<String>, name: impl Into<String>,
func: <WasmtimeWasmBackend as WasmBackend>::Function, func: <WasmtimeWasmBackend as WasmBackend>::HostFunction,
) -> Result<(), ImportError> { ) -> Result<(), ImportError> {
let module = module.into(); let module = module.into();
let name = name.into(); let name = name.into();

View File

@@ -76,7 +76,7 @@ impl Instance<WasmtimeWasmBackend> for WasmtimeInstance {
&self, &self,
store: &mut impl AsContextMut<WasmtimeWasmBackend>, store: &mut impl AsContextMut<WasmtimeWasmBackend>,
name: &str, name: &str,
) -> ResolveResult<<WasmtimeWasmBackend as WasmBackend>::Function> { ) -> ResolveResult<<WasmtimeWasmBackend as WasmBackend>::ExportFunction> {
let func = self let func = self
.inner .inner
.get_export(&mut store.as_context_mut().inner, name) .get_export(&mut store.as_context_mut().inner, name)

View File

@@ -50,8 +50,9 @@ impl WasmBackend for WasmtimeWasmBackend {
type Instance = WasmtimeInstance; type Instance = WasmtimeInstance;
type Context<'c> = WasmtimeContext<'c>; type Context<'c> = WasmtimeContext<'c>;
type ContextMut<'c> = WasmtimeContextMut<'c>; type ContextMut<'c> = WasmtimeContextMut<'c>;
type Caller<'c> = WasmtimeCaller<'c>; type ImportCallContext<'c> = WasmtimeImportCallContext<'c>;
type Function = WasmtimeFunction; type HostFunction = WasmtimeFunction;
type ExportFunction = WasmtimeFunction;
type Memory = WasmtimeMemory; type Memory = WasmtimeMemory;
type MemoryView = WasmtimeMemory; type MemoryView = WasmtimeMemory;
type Wasi = WasmtimeWasi; type Wasi = WasmtimeWasi;

View File

@@ -82,7 +82,7 @@ fn add_wasi_to_linker(
linker: &mut WasmtimeImports, linker: &mut WasmtimeImports,
wasi_ctx: wasmtime_wasi::WasiCtx, wasi_ctx: wasmtime_wasi::WasiCtx,
) -> Result<(), WasiError> { ) -> Result<(), WasiError> {
// wasmtime-wasi gets its context from Caller<T>, which can hold any user info // wasmtime-wasi gets its context from ImportCallContext<T>, which can hold any user info
// the only convenient method is to be provided with a closure that extracts context // the only convenient method is to be provided with a closure that extracts context
// from used-defined type. // from used-defined type.
// So, here each module has its own wasi context which is stored in a vector in store. // So, here each module has its own wasi context which is stored in a vector in store.

View File

@@ -25,7 +25,7 @@ use crate::host_imports::create_call_parameters_import;
use marine_core::generic::HostImportDescriptor; use marine_core::generic::HostImportDescriptor;
use marine_core::generic::MModuleConfig; use marine_core::generic::MModuleConfig;
use marine_wasm_backend_traits::Function; use marine_wasm_backend_traits::HostFunction;
use marine_wasm_backend_traits::WasmBackend; use marine_wasm_backend_traits::WasmBackend;
use marine_utils::bytes_to_wasm_pages_ceil; use marine_utils::bytes_to_wasm_pages_ceil;
@@ -191,7 +191,7 @@ impl<WB: WasmBackend> MModuleConfigBuilder<WB> {
let creator = move |mut store: <WB as WasmBackend>::ContextMut<'_>| { let creator = move |mut store: <WB as WasmBackend>::ContextMut<'_>| {
let logging_mask = logging_mask; let logging_mask = logging_mask;
<WB as WasmBackend>::Function::new_typed( <WB as WasmBackend>::HostFunction::new_typed(
&mut store, &mut store,
log_utf8_string_closure::<WB>(logging_mask, module_name), log_utf8_string_closure::<WB>(logging_mask, module_name),
) )

View File

@@ -30,7 +30,7 @@ use std::sync::Arc;
pub(crate) fn create_call_parameters_import<WB: WasmBackend>( pub(crate) fn create_call_parameters_import<WB: WasmBackend>(
call_parameters: Arc<Mutex<marine_rs_sdk::CallParameters>>, // TODO try to avoid using mutex call_parameters: Arc<Mutex<marine_rs_sdk::CallParameters>>, // TODO try to avoid using mutex
) -> HostImportDescriptor<WB> { ) -> HostImportDescriptor<WB> {
let call_parameters_closure = move |_ctx: &mut <WB as WasmBackend>::Caller<'_>, let call_parameters_closure = move |_ctx: &mut <WB as WasmBackend>::ImportCallContext<'_>,
_args: Vec<IValue>| { _args: Vec<IValue>| {
let result = { let result = {
// a separate code block to unlock the mutex ASAP and to avoid double locking // a separate code block to unlock the mutex ASAP and to avoid double locking

View File

@@ -15,7 +15,7 @@
*/ */
use marine_wasm_backend_traits::AsContextMut; use marine_wasm_backend_traits::AsContextMut;
use marine_wasm_backend_traits::Caller; use marine_wasm_backend_traits::ImportCallContext;
use marine_wasm_backend_traits::WasmBackend; use marine_wasm_backend_traits::WasmBackend;
use it_memory_traits::Memory; use it_memory_traits::Memory;
@@ -24,7 +24,7 @@ use it_memory_traits::MemoryReadable;
pub(crate) fn log_utf8_string_closure<WB: WasmBackend>( pub(crate) fn log_utf8_string_closure<WB: WasmBackend>(
logging_mask: i32, logging_mask: i32,
module: String, module: String,
) -> impl Fn(<WB as WasmBackend>::Caller<'_>, i32, i32, i32, i32) { ) -> impl Fn(<WB as WasmBackend>::ImportCallContext<'_>, i32, i32, i32, i32) {
move |ctx, level, target, msg_offset, msg_size| { move |ctx, level, target, msg_offset, msg_size| {
if target == 0 || target & logging_mask != 0 { if target == 0 || target & logging_mask != 0 {
log_utf8_string::<WB>(&module, ctx, level, msg_offset, msg_size) log_utf8_string::<WB>(&module, ctx, level, msg_offset, msg_size)
@@ -34,7 +34,7 @@ pub(crate) fn log_utf8_string_closure<WB: WasmBackend>(
pub(crate) fn log_utf8_string<WB: WasmBackend>( pub(crate) fn log_utf8_string<WB: WasmBackend>(
module: &str, module: &str,
mut ctx: <WB as WasmBackend>::Caller<'_>, mut ctx: <WB as WasmBackend>::ImportCallContext<'_>,
level: i32, level: i32,
msg_offset: i32, msg_offset: i32,
msg_size: i32, msg_size: i32,
@@ -57,7 +57,7 @@ pub(crate) fn log_utf8_string<WB: WasmBackend>(
#[inline] #[inline]
fn read_string<WB: WasmBackend>( fn read_string<WB: WasmBackend>(
ctx: &mut <WB as WasmBackend>::Caller<'_>, ctx: &mut <WB as WasmBackend>::ImportCallContext<'_>,
offset: i32, offset: i32,
size: i32, size: i32,
) -> Option<String> { ) -> Option<String> {

View File

@@ -28,7 +28,7 @@ use std::path::PathBuf;
pub(crate) fn create_mounted_binary_import<WB: WasmBackend>( pub(crate) fn create_mounted_binary_import<WB: WasmBackend>(
mounted_binary_path: PathBuf, mounted_binary_path: PathBuf,
) -> HostImportDescriptor<WB> { ) -> HostImportDescriptor<WB> {
let host_cmd_closure = move |_ctx: &mut <WB as WasmBackend>::Caller<'_>, let host_cmd_closure = move |_ctx: &mut <WB as WasmBackend>::ImportCallContext<'_>,
raw_args: Vec<IValue>| { raw_args: Vec<IValue>| {
let result = let result =
mounted_binary_import_impl(&mounted_binary_path, raw_args).unwrap_or_else(Into::into); mounted_binary_import_impl(&mounted_binary_path, raw_args).unwrap_or_else(Into::into);