Files
parity-wasm/src/interpreter/program.rs

56 lines
1.5 KiB
Rust
Raw Normal View History

2017-12-11 14:58:02 +01:00
2017-04-21 14:35:12 +03:00
use std::collections::HashMap;
use elements::Module;
2017-11-25 22:55:45 +03:00
use interpreter::Error;
2017-12-11 14:58:02 +01:00
use interpreter::store::{Store, ModuleId};
2017-12-11 19:22:45 +01:00
use interpreter::host::HostModule;
2017-04-21 14:35:12 +03:00
/// Program instance. Program is a set of instantiated modules.
2017-11-25 22:55:45 +03:00
pub struct ProgramInstance {
2017-12-11 14:58:02 +01:00
store: Store,
modules: HashMap<String, ModuleId>,
2017-04-21 14:35:12 +03:00
}
2017-11-25 22:55:45 +03:00
impl ProgramInstance {
2017-04-21 14:35:12 +03:00
/// Create new program instance.
2017-11-27 16:11:12 +03:00
pub fn new() -> Self {
ProgramInstance {
2017-12-11 14:58:02 +01:00
store: Store::new(),
modules: HashMap::new(),
2017-11-27 16:11:12 +03:00
}
2017-05-30 17:15:36 +03:00
}
2017-06-07 14:48:02 +03:00
/// Instantiate module with validation.
2017-12-11 16:38:52 +01:00
pub fn add_module<'a, St: 'static>(
2017-12-11 14:58:02 +01:00
&mut self,
name: &str,
module: Module,
2017-12-11 18:38:09 +01:00
state: &mut St,
2017-12-11 14:58:02 +01:00
) -> Result<ModuleId, Error> {
2017-12-11 15:12:46 +01:00
let mut extern_vals = Vec::new();
2017-12-11 14:58:02 +01:00
for import_entry in module.import_section().map(|s| s.entries()).unwrap_or(&[]) {
let module = self.modules[import_entry.module()];
let extern_val = module
.resolve_export(&self.store, import_entry.field())
.ok_or_else(|| Error::Function(format!("Module {} doesn't have export {}", import_entry.module(), import_entry.field())))?;
extern_vals.push(extern_val);
}
2017-12-11 18:38:09 +01:00
let module_id = self.store.instantiate_module(&module, &extern_vals, state)?;
2017-12-11 19:22:45 +01:00
self.modules.insert(name.to_owned(), module_id);
2017-06-13 12:01:59 +03:00
2017-12-11 14:58:02 +01:00
Ok(module_id)
2017-06-07 14:48:02 +03:00
}
2017-12-11 19:22:45 +01:00
pub fn add_host_module(&mut self, name: &str, host_module: HostModule) -> Result<ModuleId, Error> {
let module_id = host_module.allocate(&mut self.store)?;
self.modules.insert(name.to_owned(), module_id);
Ok(module_id)
2017-12-11 16:28:05 +01:00
}
/// Get one of the modules by name
2017-12-11 14:58:02 +01:00
pub fn module(&self, name: &str) -> Option<ModuleId> {
self.modules.get(name).cloned()
2017-04-21 14:35:12 +03:00
}
}