use super::marine_module::MModule;
use super::{IType, IFunctionArg, IValue, WValue};
use super::marine_module::Callable;
use crate::MResult;
use wasmer_it::interpreter::wasm;
use wasmer_core::instance::DynFunc;
use std::rc::Rc;
#[derive(Clone)]
enum WITFunctionInner {
Export {
func: Rc<DynFunc<'static>>,
},
Import {
callable: Rc<Callable>,
},
}
#[derive(Clone)]
pub(super) struct WITFunction {
name: String,
arguments: Rc<Vec<IFunctionArg>>,
outputs: Rc<Vec<IType>>,
inner: WITFunctionInner,
}
impl WITFunction {
pub(super) fn from_export(dyn_func: DynFunc<'static>, name: String) -> MResult<Self> {
use super::type_converters::wtype_to_itype;
let signature = dyn_func.signature();
let arguments = signature
.params()
.iter()
.map(|wtype| IFunctionArg {
name: String::new(),
ty: wtype_to_itype(wtype),
})
.collect::<Vec<_>>();
let outputs = signature
.returns()
.iter()
.map(wtype_to_itype)
.collect::<Vec<_>>();
let inner = WITFunctionInner::Export {
func: Rc::new(dyn_func),
};
let arguments = Rc::new(arguments);
let outputs = Rc::new(outputs);
Ok(Self {
name,
arguments,
outputs,
inner,
})
}
pub(super) fn from_import(
wit_module: &MModule,
module_name: &str,
function_name: &str,
arguments: Rc<Vec<IFunctionArg>>,
outputs: Rc<Vec<IType>>,
) -> MResult<Self> {
let callable = wit_module.get_callable(module_name, function_name)?;
let inner = WITFunctionInner::Import { callable };
let name = function_name.to_string();
Ok(Self {
name,
arguments,
outputs,
inner,
})
}
}
impl wasm::structures::LocalImport for WITFunction {
fn name(&self) -> &str {
self.name.as_str()
}
fn inputs_cardinality(&self) -> usize {
self.arguments.len()
}
fn outputs_cardinality(&self) -> usize {
self.outputs.len()
}
fn arguments(&self) -> &[IFunctionArg] {
&self.arguments
}
fn outputs(&self) -> &[IType] {
&self.outputs
}
fn call(&self, arguments: &[IValue]) -> std::result::Result<Vec<IValue>, ()> {
use super::type_converters::{ival_to_wval, wval_to_ival};
match &self.inner {
WITFunctionInner::Export { func, .. } => func
.as_ref()
.call(&arguments.iter().map(ival_to_wval).collect::<Vec<WValue>>())
.map(|result| result.iter().map(wval_to_ival).collect())
.map_err(|_| ()),
WITFunctionInner::Import { callable, .. } => Rc::make_mut(&mut callable.clone())
.call(arguments)
.map_err(|_| ()),
}
}
}