use std::cell::RefCell;
use std::rc::Rc;
use crate::modules;
use crate::{Engine, Error, Table, Task, Value};
type Defined = Rc<RefCell<Vec<(Rc<str>, rhue_types::Type)>>>;
#[derive(Clone, Debug)]
pub struct Environment {
table: Table,
types: Defined,
}
impl Environment {
pub fn globals(&self) -> &Table {
&self.table
}
}
impl Engine {
pub fn create_environment(&mut self) -> Environment {
Environment {
table: self.context().new_table(),
types: Rc::default(),
}
}
pub fn compile_in(
&mut self,
env: &Environment,
name: &str,
source: &str,
) -> Result<Rc<crate::Proto>, Error> {
let own = env.types.borrow().clone();
let shared = crate::type_env(&mut self.vm).swap_script_globals(Vec::new());
let layered = shared.iter().cloned().chain(own).collect();
crate::type_env(&mut self.vm).swap_script_globals(layered);
let result = modules::compile_typed(&mut self.vm, name, source);
crate::type_env(&mut self.vm).swap_script_globals(shared);
let compiled = result?;
let mut types = env.types.borrow_mut();
for (n, t) in compiled.globals {
match types.iter_mut().find(|(m, _)| *m == n) {
Some(slot) => slot.1 = t,
None => types.push((n, t)),
}
}
Ok(compiled.proto)
}
pub fn run_in(
&mut self,
env: &Environment,
proto: &Rc<crate::Proto>,
) -> Result<Vec<Value>, Error> {
self.verify(proto)?;
let table = self.context().table_ref_of(&env.table);
let values = self
.vm
.execute_in(proto, table)
.map_err(|e| Error::from_runtime(&e))?;
let cx = self.context();
Ok(values.into_iter().map(|v| cx.lift(v)).collect())
}
pub fn eval_in(&mut self, env: &Environment, source: &str) -> Result<Vec<Value>, Error> {
let proto = self.compile_in(env, "<eval>", source)?;
self.run_in(env, &proto)
}
pub fn spawn_in(&mut self, env: &Environment, name: &str, source: &str) -> Result<Task, Error> {
let proto = self.compile_in(env, name, source)?;
self.verify(&proto)?;
let table = self.context().table_ref_of(&env.table);
let f = self.vm.load_in(&proto, table);
let crate::Value::Function(f) = self.context().lift(f) else {
unreachable!("loading a chunk gives a function")
};
self.spawn_function(&f, Vec::new())
}
}