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::module::{ExecutionParams};
|
|
|
|
use interpreter::store::{Store, ModuleId};
|
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 14:58:02 +01:00
|
|
|
pub fn add_module<'a>(
|
|
|
|
&mut self,
|
|
|
|
name: &str,
|
|
|
|
module: Module,
|
|
|
|
start_exec_params: ExecutionParams,
|
|
|
|
) -> Result<ModuleId, Error> {
|
|
|
|
let extern_vals = Vec::new();
|
|
|
|
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-05-12 20:45:58 +03:00
|
|
|
|
2017-12-11 14:58:02 +01:00
|
|
|
let module_id = self.store.instantiate_module(&module, &extern_vals, start_exec_params)?;
|
|
|
|
self.modules.insert(name.to_string(), 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-05-12 20:45:58 +03: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
|
|
|
}
|
|
|
|
}
|