NativeModuleInstance

This commit is contained in:
Svyatoslav Nikolsky
2017-05-18 15:08:55 +03:00
parent 3fb35f29b2
commit 977df55323
10 changed files with 524 additions and 415 deletions

View File

@ -1,10 +1,9 @@
use std::sync::Arc;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use parking_lot::RwLock;
use elements::Module;
use interpreter::Error;
use interpreter::env::{self, env_module};
use interpreter::env::env_module;
use interpreter::module::{ModuleInstance, ModuleInstanceInterface};
/// Program instance. Program is a set of instantiated modules.
@ -27,24 +26,12 @@ impl ProgramInstance {
})
}
/// Create new program instance with predefined user-defined functions
pub fn with_functions(funcs: env::UserFunctions) -> Result<Self, Error> {
Ok(ProgramInstance {
essence: Arc::new(ProgramInstanceEssence::with_functions(funcs)?),
})
}
/// Instantiate module.
pub fn add_module(&self, name: &str, module: Module) -> Result<Arc<ModuleInstance>, Error> {
let module_instance = Arc::new(ModuleInstance::new(Arc::downgrade(&self.essence), module)?);
let mut modules = self.essence.modules.write();
match modules.entry(name.into()) {
Entry::Occupied(_) => Err(Error::Program(format!("module {} already instantiated", name))),
Entry::Vacant(entry) => {
entry.insert(module_instance.clone());
Ok(module_instance)
},
}
// replace existing module with the same name with new one
self.essence.modules.write().insert(name.into(), module_instance.clone());
Ok(module_instance)
}
/// Get one of the modules by name
@ -56,13 +43,8 @@ impl ProgramInstance {
impl ProgramInstanceEssence {
/// Create new program essence.
pub fn new() -> Result<Self, Error> {
ProgramInstanceEssence::with_functions(HashMap::with_capacity(0))
}
/// Create new program essence with provided user-defined functions
pub fn with_functions(funcs: env::UserFunctions) -> Result<Self, Error> {
let mut modules = HashMap::new();
let env_module: Arc<ModuleInstanceInterface> = Arc::new(env_module(funcs)?);
let env_module: Arc<ModuleInstanceInterface> = Arc::new(env_module()?);
modules.insert("env".into(), env_module);
Ok(ProgramInstanceEssence {
modules: RwLock::new(modules),