[wasmtime-api] reduce examples complexity: hostref for store/engine (#489)

* reduce amount of store.clone()

* use HostRef Engine as ref / use Engine::default()
This commit is contained in:
Yury Delendik
2019-11-07 11:39:23 -06:00
committed by GitHub
parent 55eb06ecc2
commit 6632a7da37
13 changed files with 76 additions and 88 deletions

View File

@@ -270,14 +270,14 @@ fn main() -> Result<()> {
strategy,
);
let engine = HostRef::new(Engine::new(config));
let store = HostRef::new(Store::new(engine));
let store = HostRef::new(Store::new(&engine));
let mut module_registry = HashMap::new();
// Make spectest available by default.
module_registry.insert(
"spectest".to_owned(),
Instance::from_handle(store.clone(), instantiate_spectest()?)?,
Instance::from_handle(&store, instantiate_spectest()?)?,
);
// Make wasi available by default.
@@ -301,36 +301,36 @@ fn main() -> Result<()> {
module_registry.insert(
"wasi_unstable".to_owned(),
Instance::from_handle(store.clone(), wasi.clone())?,
Instance::from_handle(&store, wasi.clone())?,
);
module_registry.insert(
"wasi_unstable_preview0".to_owned(),
Instance::from_handle(store.clone(), wasi)?,
Instance::from_handle(&store, wasi)?,
);
// Load the preload wasm modules.
for filename in &args.flag_preload {
let path = Path::new(&filename);
instantiate_module(store.clone(), &module_registry, path)
instantiate_module(&store, &module_registry, path)
.with_context(|| format!("failed to process preload at `{}`", path.display()))?;
}
// Load the main wasm module.
let path = Path::new(&args.arg_file);
handle_module(store, &module_registry, &args, path)
handle_module(&store, &module_registry, &args, path)
.with_context(|| format!("failed to process main module `{}`", path.display()))?;
Ok(())
}
fn instantiate_module(
store: HostRef<Store>,
store: &HostRef<Store>,
module_registry: &HashMap<String, (Instance, HashMap<String, usize>)>,
path: &Path,
) -> Result<(HostRef<Instance>, HostRef<Module>, Vec<u8>)> {
// Read the wasm module binary either as `*.wat` or a raw binary
let data = wat::parse_file(path.to_path_buf())?;
let module = HostRef::new(Module::new(store.clone(), &data)?);
let module = HostRef::new(Module::new(store, &data)?);
// Resolve import using module_registry.
let imports = module
@@ -356,18 +356,18 @@ fn instantiate_module(
})
.collect::<Result<Vec<_>, _>>()?;
let instance = HostRef::new(Instance::new(store.clone(), module.clone(), &imports)?);
let instance = HostRef::new(Instance::new(store, &module, &imports)?);
Ok((instance, module, data))
}
fn handle_module(
store: HostRef<Store>,
store: &HostRef<Store>,
module_registry: &HashMap<String, (Instance, HashMap<String, usize>)>,
args: &Args,
path: &Path,
) -> Result<()> {
let (instance, _module, data) = instantiate_module(store.clone(), module_registry, path)?;
let (instance, _module, data) = instantiate_module(store, module_registry, path)?;
// If a function to invoke was given, invoke it.
if let Some(f) = &args.flag_invoke {
@@ -379,7 +379,7 @@ fn handle_module(
}
fn invoke_export(
store: HostRef<Store>,
store: &HostRef<Store>,
instance: HostRef<Instance>,
data: &ModuleData,
name: &str,

View File

@@ -10,10 +10,10 @@ fn main() -> Result<()> {
// Instantiate engine and store.
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(engine));
let store = HostRef::new(Store::new(&engine));
// Load a module.
let module = HostRef::new(Module::new(store.clone(), &wasm)?);
let module = HostRef::new(Module::new(&store, &wasm)?);
// Find index of the `gcd` export.
let gcd_index = module
@@ -26,7 +26,7 @@ fn main() -> Result<()> {
.0;
// Instantiate the module.
let instance = HostRef::new(Instance::new(store.clone(), module, &[])?);
let instance = HostRef::new(Instance::new(&store, &module, &[])?);
// Invoke `gcd` export
let gcd = instance.borrow().exports()[gcd_index]

View File

@@ -21,8 +21,8 @@ impl Callable for HelloCallback {
fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::new(Config::default()));
let store = HostRef::new(Store::new(engine));
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));
// Load binary.
println!("Loading binary...");
@@ -30,19 +30,18 @@ fn main() -> Result<()> {
// Compile.
println!("Compiling module...");
let module =
HostRef::new(Module::new(store.clone(), &binary).context("> Error compiling module!")?);
let module = HostRef::new(Module::new(&store, &binary).context("> Error compiling module!")?);
// Create external print functions.
println!("Creating callback...");
let hello_type = FuncType::new(Box::new([]), Box::new([]));
let hello_func = HostRef::new(Func::new(store.clone(), hello_type, Rc::new(HelloCallback)));
let hello_func = HostRef::new(Func::new(&store, hello_type, Rc::new(HelloCallback)));
// Instantiate.
println!("Instantiating module...");
let imports = vec![hello_func.into()];
let instance = HostRef::new(
Instance::new(store.clone(), module, imports.as_slice())
Instance::new(&store, &module, imports.as_slice())
.context("> Error instantiating module!")?,
);

View File

@@ -64,8 +64,8 @@ macro_rules! call {
fn main() -> Result<(), Error> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::new(Config::default()));
let store = HostRef::new(Store::new(engine));
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));
// Load binary.
println!("Loading binary...");
@@ -73,14 +73,12 @@ fn main() -> Result<(), Error> {
// Compile.
println!("Compiling module...");
let module =
HostRef::new(Module::new(store.clone(), &binary).context("> Error compiling module!")?);
let module = HostRef::new(Module::new(&store, &binary).context("> Error compiling module!")?);
// Instantiate.
println!("Instantiating module...");
let instance = HostRef::new(
Instance::new(store.clone(), module, &[]).context("> Error instantiating module!")?,
);
let instance =
HostRef::new(Instance::new(&store, &module, &[]).context("> Error instantiating module!")?);
// Extract export.
println!("Extracting export...");
@@ -141,7 +139,7 @@ fn main() -> Result<(), Error> {
// TODO(wasm+): Once Wasm allows multiple memories, turn this into import.
println!("Creating stand-alone memory...");
let memorytype = MemoryType::new(Limits::new(5, 5));
let mut memory2 = Memory::new(store.clone(), memorytype);
let mut memory2 = Memory::new(&store, memorytype);
check!(memory2.size(), 5u32);
check!(memory2.grow(1), false);
check!(memory2.grow(0), true);

View File

@@ -24,8 +24,8 @@ impl Callable for Callback {
fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::new(Config::default()));
let store = HostRef::new(Store::new(engine));
let engine = HostRef::new(Engine::default());
let store = HostRef::new(Store::new(&engine));
// Load binary.
println!("Loading binary...");
@@ -33,8 +33,7 @@ fn main() -> Result<()> {
// Compile.
println!("Compiling module...");
let module =
HostRef::new(Module::new(store.clone(), &binary).context("Error compiling module!")?);
let module = HostRef::new(Module::new(&store, &binary).context("Error compiling module!")?);
// Create external print functions.
println!("Creating callback...");
@@ -42,13 +41,13 @@ fn main() -> Result<()> {
Box::new([ValType::I32, ValType::I64]),
Box::new([ValType::I64, ValType::I32]),
);
let callback_func = HostRef::new(Func::new(store.clone(), callback_type, Rc::new(Callback)));
let callback_func = HostRef::new(Func::new(&store, callback_type, Rc::new(Callback)));
// Instantiate.
println!("Instantiating module...");
let imports = vec![callback_func.into()];
let instance = HostRef::new(
Instance::new(store.clone(), module, imports.as_slice())
Instance::new(&store, &module, imports.as_slice())
.context("Error instantiating module!")?,
);

View File

@@ -34,9 +34,9 @@ pub(crate) struct WasmtimeFn {
}
impl WasmtimeFn {
pub fn new(store: HostRef<Store>, instance: InstanceHandle, export: Export) -> WasmtimeFn {
pub fn new(store: &HostRef<Store>, instance: InstanceHandle, export: Export) -> WasmtimeFn {
WasmtimeFn {
store,
store: store.clone(),
instance,
export,
}

View File

@@ -66,7 +66,7 @@ impl Extern {
}
pub(crate) fn from_wasmtime_export(
store: HostRef<Store>,
store: &HostRef<Store>,
instance_handle: InstanceHandle,
export: wasmtime_runtime::Export,
) -> Extern {
@@ -118,18 +118,18 @@ pub struct Func {
}
impl Func {
pub fn new(store: HostRef<Store>, ty: FuncType, callable: Rc<dyn Callable + 'static>) -> Self {
pub fn new(store: &HostRef<Store>, ty: FuncType, callable: Rc<dyn Callable + 'static>) -> Self {
let callable = Rc::new(NativeCallable::new(callable, &ty, &store));
Func::from_wrapped(store, ty, callable)
}
fn from_wrapped(
store: HostRef<Store>,
store: &HostRef<Store>,
r#type: FuncType,
callable: Rc<dyn WrappedCallable + 'static>,
) -> Func {
Func {
_store: store,
_store: store.clone(),
callable,
r#type,
}
@@ -159,7 +159,7 @@ impl Func {
pub(crate) fn from_wasmtime_function(
export: wasmtime_runtime::Export,
store: HostRef<Store>,
store: &HostRef<Store>,
instance_handle: InstanceHandle,
) -> Self {
let ty = if let wasmtime_runtime::Export::Function { signature, .. } = &export {
@@ -167,7 +167,7 @@ impl Func {
} else {
panic!("expected function export")
};
let callable = WasmtimeFn::new(store.clone(), instance_handle, export.clone());
let callable = WasmtimeFn::new(store, instance_handle, export.clone());
Func::from_wrapped(store, ty, Rc::new(callable))
}
}
@@ -187,11 +187,11 @@ pub struct Global {
}
impl Global {
pub fn new(store: HostRef<Store>, r#type: GlobalType, val: Val) -> Global {
pub fn new(store: &HostRef<Store>, r#type: GlobalType, val: Val) -> Global {
let (wasmtime_export, wasmtime_state) =
generate_global_export(&r#type, val).expect("generated global");
Global {
_store: store,
_store: store.clone(),
r#type,
wasmtime_export,
wasmtime_state: Some(wasmtime_state),
@@ -248,7 +248,7 @@ impl Global {
pub(crate) fn from_wasmtime_global(
export: wasmtime_runtime::Export,
store: HostRef<Store>,
store: &HostRef<Store>,
) -> Global {
let global = if let wasmtime_runtime::Export::Global { ref global, .. } = export {
global
@@ -257,7 +257,7 @@ impl Global {
};
let ty = GlobalType::from_cranelift_global(global.clone());
Global {
_store: store,
_store: store.clone(),
r#type: ty,
wasmtime_export: export,
wasmtime_state: None,
@@ -302,7 +302,7 @@ fn set_table_item(
}
impl Table {
pub fn new(store: HostRef<Store>, r#type: TableType, init: Val) -> Table {
pub fn new(store: &HostRef<Store>, r#type: TableType, init: Val) -> Table {
match r#type.element() {
ValType::FuncRef => (),
_ => panic!("table is not for funcref"),
@@ -317,7 +317,7 @@ impl Table {
let len = unsafe { (*definition).current_elements };
for i in 0..len {
let _success =
set_table_item(&mut wasmtime_handle, &store, index, i, init.clone());
set_table_item(&mut wasmtime_handle, store, index, i, init.clone());
assert!(_success);
}
}
@@ -325,7 +325,7 @@ impl Table {
}
Table {
store,
store: store.clone(),
r#type,
wasmtime_handle,
wasmtime_export,
@@ -387,7 +387,7 @@ impl Table {
pub(crate) fn from_wasmtime_table(
export: wasmtime_runtime::Export,
store: HostRef<Store>,
store: &HostRef<Store>,
instance_handle: wasmtime_runtime::InstanceHandle,
) -> Table {
let table = if let wasmtime_runtime::Export::Table { ref table, .. } = export {
@@ -397,7 +397,7 @@ impl Table {
};
let ty = TableType::from_cranelift_table(table.table.clone());
Table {
store,
store: store.clone(),
r#type: ty,
wasmtime_handle: instance_handle,
wasmtime_export: export,
@@ -413,11 +413,11 @@ pub struct Memory {
}
impl Memory {
pub fn new(store: HostRef<Store>, r#type: MemoryType) -> Memory {
pub fn new(store: &HostRef<Store>, r#type: MemoryType) -> Memory {
let (wasmtime_handle, wasmtime_export) =
generate_memory_export(&r#type).expect("generated memory");
Memory {
_store: store,
_store: store.clone(),
r#type,
wasmtime_handle,
wasmtime_export,
@@ -471,7 +471,7 @@ impl Memory {
pub(crate) fn from_wasmtime_memory(
export: wasmtime_runtime::Export,
store: HostRef<Store>,
store: &HostRef<Store>,
instance_handle: wasmtime_runtime::InstanceHandle,
) -> Memory {
let memory = if let wasmtime_runtime::Export::Memory { ref memory, .. } = export {
@@ -481,7 +481,7 @@ impl Memory {
};
let ty = MemoryType::from_cranelift_memory(memory.memory.clone());
Memory {
_store: store,
_store: store.clone(),
r#type: ty,
wasmtime_handle: instance_handle,
wasmtime_export: export,

View File

@@ -61,8 +61,8 @@ pub struct Instance {
impl Instance {
pub fn new(
store: HostRef<Store>,
module: HostRef<Module>,
store: &HostRef<Store>,
module: &HostRef<Module>,
externs: &[Extern],
) -> Result<Instance> {
let context = store.borrow_mut().context().clone();
@@ -84,7 +84,7 @@ impl Instance {
let name = export.name().to_string();
let export = instance_handle.lookup(&name).expect("export");
exports.push(Extern::from_wasmtime_export(
store.clone(),
store,
instance_handle.clone(),
export,
));
@@ -103,7 +103,7 @@ impl Instance {
}
pub fn from_handle(
store: HostRef<Store>,
store: &HostRef<Store>,
instance_handle: InstanceHandle,
) -> Result<(Instance, HashMap<String, usize>)> {
let contexts = HashSet::new();
@@ -121,7 +121,7 @@ impl Instance {
}
export_names_map.insert(name.to_owned(), exports.len());
exports.push(Extern::from_wasmtime_export(
store.clone(),
store,
instance_handle.clone(),
export.clone(),
));

View File

@@ -182,10 +182,10 @@ pub struct Module {
}
impl Module {
pub fn new(store: HostRef<Store>, binary: &[u8]) -> Result<Module> {
pub fn new(store: &HostRef<Store>, binary: &[u8]) -> Result<Module> {
let (imports, exports) = read_imports_and_exports(binary)?;
Ok(Module {
store,
store: store.clone(),
binary: binary.into(),
imports,
exports,

View File

@@ -102,13 +102,13 @@ pub struct Store {
}
impl Store {
pub fn new(engine: HostRef<Engine>) -> Store {
pub fn new(engine: &HostRef<Engine>) -> Store {
let flags = engine.borrow().config().flags().clone();
let features = engine.borrow().config().features().clone();
let debug_info = engine.borrow().config().debug_info();
let strategy = engine.borrow().config().strategy();
Store {
engine,
engine: engine.clone(),
context: Context::create(flags, features, debug_info, strategy),
global_exports: Rc::new(RefCell::new(HashMap::new())),
signature_cache: HashMap::new(),

View File

@@ -230,6 +230,6 @@ pub(crate) fn from_checked_anyfunc(
signature,
vmctx: item.vmctx,
};
let f = Func::from_wasmtime_function(export, store.clone(), instance_handle);
let f = Func::from_wasmtime_function(export, store, instance_handle);
Val::FuncRef(HostRef::new(f))
}

View File

@@ -609,7 +609,7 @@ pub unsafe extern "C" fn wasm_func_new(
ty: *const wasm_functype_t,
callback: wasm_func_callback_t,
) -> *mut wasm_func_t {
let store = (*store).store.clone();
let store = &(*store).store;
let ty = (*ty).functype.clone();
let callback = Rc::new(callback);
let func = Box::new(wasm_func_t {
@@ -663,13 +663,13 @@ pub unsafe extern "C" fn wasm_instance_new(
imports: *const *const wasm_extern_t,
result: *mut *mut wasm_trap_t,
) -> *mut wasm_instance_t {
let store = (*store).store.clone();
let store = &(*store).store;
let mut externs: Vec<Extern> = Vec::with_capacity((*module).imports.len());
for i in 0..(*module).imports.len() {
let import = *imports.offset(i as isize);
externs.push((*import).ext.clone());
}
let module = (*module).module.clone();
let module = &(*module).module;
match Instance::new(store, module, &externs) {
Ok(instance) => {
let instance = Box::new(wasm_instance_t {
@@ -731,7 +731,7 @@ pub unsafe extern "C" fn wasm_module_new(
binary: *const wasm_byte_vec_t,
) -> *mut wasm_module_t {
let binary = (*binary).as_slice();
let store = (*store).store.clone();
let store = &(*store).store;
let module = Module::new(store, binary).expect("module");
let imports = module
.imports()
@@ -766,9 +766,9 @@ pub unsafe extern "C" fn wasm_store_delete(store: *mut wasm_store_t) {
#[no_mangle]
pub unsafe extern "C" fn wasm_store_new(engine: *mut wasm_engine_t) -> *mut wasm_store_t {
let engine = (*engine).engine.clone();
let engine = &(*engine).engine;
let store = Box::new(wasm_store_t {
store: HostRef::new(Store::new(engine)),
store: HostRef::new(Store::new(&engine)),
});
Box::into_raw(store)
}
@@ -804,7 +804,7 @@ pub unsafe extern "C" fn wasm_func_new_with_env(
env: *mut ::core::ffi::c_void,
finalizer: ::core::option::Option<unsafe extern "C" fn(arg1: *mut ::core::ffi::c_void)>,
) -> *mut wasm_func_t {
let store = (*store).store.clone();
let store = &(*store).store;
let ty = (*ty).functype.clone();
let callback = Rc::new(CallbackWithEnv {
callback,
@@ -1327,7 +1327,7 @@ pub unsafe extern "C" fn wasm_global_new(
val: *const wasm_val_t,
) -> *mut wasm_global_t {
let global = HostRef::new(Global::new(
(*store).store.clone(),
&(*store).store,
(*gt).globaltype.clone(),
(*val).val(),
));
@@ -1446,10 +1446,7 @@ pub unsafe extern "C" fn wasm_memory_new(
store: *mut wasm_store_t,
mt: *const wasm_memorytype_t,
) -> *mut wasm_memory_t {
let memory = HostRef::new(Memory::new(
(*store).store.clone(),
(*mt).memorytype.clone(),
));
let memory = HostRef::new(Memory::new(&(*store).store, (*mt).memorytype.clone()));
let m = Box::new(wasm_memory_t { memory, ext: None });
Box::into_raw(m)
}
@@ -1537,11 +1534,7 @@ pub unsafe extern "C" fn wasm_table_new(
Val::AnyRef(AnyRef::Null)
};
let t = Box::new(wasm_table_t {
table: HostRef::new(Table::new(
(*store).store.clone(),
(*tt).tabletype.clone(),
init,
)),
table: HostRef::new(Table::new(&(*store).store, (*tt).tabletype.clone(), init)),
ext: None,
});
Box::into_raw(t)

View File

@@ -25,10 +25,10 @@ fn test_import_calling_export() {
}
let engine = HostRef::new(Engine::new(Config::default()));
let store = HostRef::new(Store::new(engine));
let store = HostRef::new(Store::new(&engine));
let module = HostRef::new(
Module::new(
store.clone(),
&store,
&read("tests/import_calling_export.wasm").expect("failed to read wasm file"),
)
.expect("failed to create module"),
@@ -39,15 +39,14 @@ fn test_import_calling_export() {
});
let callback_func = HostRef::new(Func::new(
store.clone(),
&store,
FuncType::new(Box::new([]), Box::new([])),
callback.clone(),
));
let imports = vec![callback_func.into()];
let instance = HostRef::new(
Instance::new(store.clone(), module, imports.as_slice())
.expect("failed to instantiate module"),
Instance::new(&store, &module, imports.as_slice()).expect("failed to instantiate module"),
);
let exports = Ref::map(instance.borrow(), |instance| instance.exports());