simple user function

This commit is contained in:
NikVolf
2017-05-15 15:40:08 +03:00
parent 21ff1509f6
commit b7ff4d92d4
6 changed files with 108 additions and 37 deletions

View File

@ -1,7 +1,7 @@
use std::sync::{Arc, Weak};
use std::collections::HashMap;
use builder::module;
use builder::{module, function, export};
use elements::{Module, FunctionType, ExportEntry, Internal, GlobalEntry, GlobalType,
ValueType, InitExpr, Opcode, Opcodes};
use interpreter::Error;
@ -73,13 +73,27 @@ const INDEX_FUNC_MAX: u32 = 10000;
pub type UserFunctions = HashMap<String, UserFunction>;
/// User function closure
pub type UserFunctionClosure = Box<Fn(&CallerContext) -> Result<Option<RuntimeValue>, Error>>;
pub type UserFunctionClosure = Box<UserFunctionInterface>;
/// User-defined function execution interface
pub trait UserFunctionInterface {
fn call(&mut self, context: CallerContext) -> Result<Option<RuntimeValue>, Error>;
}
impl<T> UserFunctionInterface for T where T: FnMut(CallerContext) -> Result<Option<RuntimeValue>, Error> {
fn call(&mut self, context: CallerContext) -> Result<Option<RuntimeValue>, Error> {
(&mut *self)(context)
}
}
/// Signature of user-defined env function
pub struct UserFunction {
params: Vec<ValueType>,
result: Option<ValueType>,
closure: UserFunctionClosure,
/// User function parameters (for signature matching)
pub params: Vec<ValueType>,
/// User function return type (for signature matching)
pub result: Option<ValueType>,
/// Executor of the function
pub closure: UserFunctionClosure,
}
/// Environment parameters.
@ -92,7 +106,7 @@ pub struct EnvParams {
pub allow_memory_growth: bool,
}
type UserFunctionsInternals = HashMap<u32, UserFunctionClosure>;
type UserFunctionsInternals = Vec<::std::cell::RefCell<UserFunctionClosure>>;
pub struct EnvModuleInstance {
_params: EnvParams,
@ -168,20 +182,26 @@ impl ModuleInstanceInterface for EnvModuleInstance {
.map(|g| g.get())
.map(Some),
INDEX_FUNC_MIN_NONUSED ... INDEX_FUNC_MAX => Err(Error::Trap("unimplemented".into())),
idx @ _ if idx == INDEX_FUNC_MAX + 1 => outer.value_stack.pop().map(|_| None), // TODO: `gas(i32) -> None` function
idx @ _ if idx == INDEX_FUNC_MAX + 2 => Ok(Some(RuntimeValue::I32(0))), // TODO: `_storage_size() -> i32` function
idx @ _ if idx == INDEX_FUNC_MAX + 3 => outer.value_stack.pop_triple().map(|_| Some(RuntimeValue::I32(0))), // TODO: `_storage_size(i32,i32,i32) -> i32` function
_ => Err(Error::Trap(format!("trying to call function with index {} in emv module", index))),
idx if idx > INDEX_FUNC_MAX && idx <= INDEX_FUNC_MAX + self.user_functions.len() as u32 => {
// user-defined function
let user_index = idx - (INDEX_FUNC_MAX+1);
let func = self.user_functions.get(user_index as usize).ok_or(Error::Trap(format!("Trying to invoke user-defined function {}", user_index)))?;
func.borrow_mut().call(outer)
},
// idx @ _ if idx == INDEX_FUNC_MAX + 1 => outer.value_stack.pop().map(|_| None), // TODO: `gas(i32) -> None` function
// idx @ _ if idx == INDEX_FUNC_MAX + 2 => Ok(Some(RuntimeValue::I32(0))), // TODO: `_storage_size() -> i32` function
// idx @ _ if idx == INDEX_FUNC_MAX + 3 => outer.value_stack.pop_triple().map(|_| Some(RuntimeValue::I32(0))), // TODO: `_storage_size(i32,i32,i32) -> i32` function
_ => Err(Error::Trap(format!("trying to call function with index {} in env module", index))),
}
}
}
pub fn env_module(user_functions: UserFunctions) -> Result<EnvModuleInstance, Error> {
let mut env_params = EnvParams::default();
let env_params = EnvParams::default();
debug_assert!(env_params.total_stack < env_params.total_memory);
debug_assert!((env_params.total_stack % LINEAR_MEMORY_PAGE_SIZE) == 0);
debug_assert!((env_params.total_memory % LINEAR_MEMORY_PAGE_SIZE) == 0);
let mut module = module()
let mut builder = module()
// memory regions
.memory()
.with_min(env_params.total_memory / LINEAR_MEMORY_PAGE_SIZE)
@ -232,33 +252,31 @@ pub fn env_module(user_functions: UserFunctions) -> Result<EnvModuleInstance, Er
.signature().return_type().i32().build()
.body().with_opcodes(Opcodes::new(vec![Opcode::Unreachable, Opcode::End])).build()
.build()
.with_export(ExportEntry::new("getTotalMemory".into(), Internal::Function(INDEX_FUNC_GET_TOTAL_MEMORY)))
.build();
// non-standard functions (TODO: pass as parameters to EnvModuleInstance)
// .function()
// .signature().param().i32().build()
// .body().with_opcodes(Opcodes::new(vec![Opcode::Unreachable, Opcode::End])).build()
// .build()
// .with_export(ExportEntry::new("gas".into(), Internal::Function(INDEX_FUNC_MAX + 1)))
// .function()
// .signature().return_type().i32().build()
// .body().with_opcodes(Opcodes::new(vec![Opcode::Unreachable, Opcode::End])).build()
// .build()
// .with_export(ExportEntry::new("_storage_size".into(), Internal::Function(INDEX_FUNC_MAX + 2)))
// .function()
// .signature().param().i32().param().i32().param().i32().return_type().i32().build()
// .body().with_opcodes(Opcodes::new(vec![Opcode::Unreachable, Opcode::End])).build()
// .build()
// .with_export(ExportEntry::new("_storage_write".into(), Internal::Function(INDEX_FUNC_MAX + 3)))
// .build();
.with_export(ExportEntry::new("getTotalMemory".into(), Internal::Function(INDEX_FUNC_GET_TOTAL_MEMORY)));
let mut funcs = user_functions;
let internals = HashMap::new();
let mut internals = UserFunctionsInternals::new();
let mut index = INDEX_FUNC_MAX + 1;
for (func_name, func) in funcs.drain() {
let _location = builder.push_function(
function()
.signature().with_params(func.params).with_return_type(func.result).build()
.build()
);
let _export_idx = builder.push_export(
export()
.field(&func_name)
.internal().func(index)
.build()
);
internals.push(::std::cell::RefCell::new(func.closure));
index += 1;
}
EnvModuleInstance::new(env_params, internals, module)
EnvModuleInstance::new(env_params, internals, builder.build())
}
impl Default for EnvParams {