roan_engine/context.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
use crate::{
module::{loaders::ModuleLoader, Module},
vm::VM,
};
use anyhow::Result;
use bon::bon;
use roan_error::print_diagnostic;
use std::{cell::RefCell, fmt::Debug, path::PathBuf, rc::Rc};
use tracing::debug;
/// Struct to interact with the runtime.
///
/// # Example
/// ```rs
/// let ctx = Context::new();
/// let src_code = r#"
/// use { println, eprintln } from "std::io";
///
/// fn add(a: float, b: float) -> float {
/// return a + b;
/// }
///
/// fn main() -> int {
/// let i = 3.14;
/// let j = true;
///
/// if j {
/// i = add(i, 2.0);
/// } else {
/// eprintln("Goodbye, world!");
/// }
///
/// return 0;
/// }
///
/// main();
/// "#;
///
/// let source = Source::from_string(src_code);
/// let module = Module::from_source(source, ctx)?;
///
/// let result = ctx.eval(module);
///
/// assert_eq!(result, Ok(Value::Int(3)));
/// ```
#[derive(Clone, Debug)]
pub struct Context {
pub module_loader: Rc<RefCell<dyn ModuleLoader>>,
pub cwd: PathBuf,
}
#[bon]
impl Context {
/// Create a new context.
#[builder]
pub fn new(
#[builder] module_loader: Rc<RefCell<dyn ModuleLoader>>,
#[builder(default = std::env::current_dir().unwrap())] cwd: PathBuf,
) -> Self {
Self { module_loader, cwd }
}
}
impl Context {
/// Evaluate a module by parsing and interpreting it.
///
/// # Arguments
///
/// * `module` - The module to evaluate.
/// * `vm` - The virtual machine instance.
///
/// # Returns
///
/// The result of the evaluation.
pub fn eval(&mut self, module: &mut Module, vm: &mut VM) -> Result<()> {
self.parse(module)?;
self.interpret(module, vm)?;
Ok(())
}
/// Parse a module to prepare it for interpretation.
///
/// # Arguments
///
/// * `module` - The module to parse.
///
/// # Returns
///
/// An empty result if successful, otherwise returns an error.
pub fn parse(&mut self, module: &mut Module) -> Result<()> {
match module.parse() {
Ok(_) => Ok(()),
Err(e) => {
print_diagnostic(e, Some(module.source().content()));
std::process::exit(1);
}
}
}
/// Interpret a parsed module in the virtual machine.
///
/// # Arguments
///
/// * `module` - The module to interpret.
/// * `vm` - The virtual machine instance.
///
/// # Returns
///
/// An empty result if successful, otherwise returns an error.
pub fn interpret(&mut self, module: &mut Module, vm: &mut VM) -> Result<()> {
match module.interpret(self, vm) {
Ok(_) => Ok(()),
Err(e) => {
print_diagnostic(e, Some(module.source().content()));
std::process::exit(1);
}
}
}
/// Insert a module into the context.
///
/// # Arguments
/// - `name` - The name of the module.
/// - `module` - The module to insert.
pub fn insert_module(&mut self, name: String, module: Module) {
debug!("Inserting module: {}", name);
self.module_loader.borrow_mut().insert(name, module);
}
/// Query a module from the context.
///
/// # Arguments
/// - `name` - The name of the module to query.
pub fn query_module(&self, name: &str) -> Option<Module> {
self.module_loader.borrow().get(name)
}
/// Load a module from the context.
///
/// This function is different from `query_module` in that it will attempt to load the module from the cache
/// if it is not found it will try to resolve the path and load the module.
///
/// # Arguments
/// - `referrer` - The module that is requesting the module.
/// - `spec` - The name of the module to load.
pub fn load_module(&mut self, referrer: &Module, spec: &str) -> Result<Module> {
Ok(self.module_loader.borrow_mut().load(referrer, spec, self)?)
}
pub fn module_keys(&self) -> Vec<String> {
self.module_loader.borrow().keys()
}
/// Inserts or updates a module in the context.
pub fn upsert_module(&mut self, name: String, module: Module) {
debug!("Upserting module: {}", name);
self.module_loader.borrow_mut().insert(name, module);
}
}