From a03b509fb85ee4fb3b397b3e279ca77d625bc5f6 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Thu, 14 Jan 2021 03:15:25 +0300 Subject: refactor(tazjin/rlox): Constructor for interpreter with globals Change-Id: Id8242c22500c8e2781cc656d3faabb28d9bdf091 Reviewed-on: https://cl.tvl.fyi/c/depot/+/2383 Reviewed-by: tazjin Tested-by: BuildkiteCI --- users/tazjin/rlox/src/interpreter.rs | 20 +++++++++++++++++++- users/tazjin/rlox/src/main.rs | 4 ++-- 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'users') diff --git a/users/tazjin/rlox/src/interpreter.rs b/users/tazjin/rlox/src/interpreter.rs index 2ddbab7e1f29..5944bdfec8d9 100644 --- a/users/tazjin/rlox/src/interpreter.rs +++ b/users/tazjin/rlox/src/interpreter.rs @@ -118,12 +118,30 @@ fn identifier_str<'a>(name: &'a scanner::Token) -> Result<&'a str, Error> { } } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Interpreter { env: Rc>, } impl Interpreter { + /// Create a new interpreter and configure the initial global + /// variable set. + pub fn create() -> Self { + let mut globals = HashMap::new(); + + globals.insert( + "clock".into(), + Value::Callable(Callable::Builtin(&builtins::Clock {})), + ); + + Interpreter { + env: Rc::new(RwLock::new(Environment { + enclosing: None, + values: globals, + })), + } + } + // Environment modification helpers fn define_var(&mut self, name: &scanner::Token, value: Value) -> Result<(), Error> { self.env diff --git a/users/tazjin/rlox/src/main.rs b/users/tazjin/rlox/src/main.rs index c56d345862c9..8970349bfa69 100644 --- a/users/tazjin/rlox/src/main.rs +++ b/users/tazjin/rlox/src/main.rs @@ -25,14 +25,14 @@ fn main() { // Run Lox code from a file and print results to stdout fn run_file(file: &str) { let contents = fs::read_to_string(file).expect("failed to read the input file"); - let mut lox = interpreter::Interpreter::default(); + let mut lox = interpreter::Interpreter::create(); run(&mut lox, &contents); } // Evaluate Lox code interactively in a shitty REPL. fn run_prompt() { let mut line = String::new(); - let mut lox = interpreter::Interpreter::default(); + let mut lox = interpreter::Interpreter::create(); loop { print!("> "); -- cgit 1.4.1