about summary refs log tree commit diff
path: root/users/tazjin/rlox/src/main.rs
diff options
context:
space:
mode:
authorVincent Ambo <mail@tazj.in>2020-12-31T10·27+0300
committertazjin <mail@tazj.in>2020-12-31T11·19+0000
commit8ab66f1689dade7c346d5a3b51b87194716e03a7 (patch)
tree8a6601dbb3fb1b718d4ac192a599c3b1e7009b73 /users/tazjin/rlox/src/main.rs
parent78355d3c0b91e5b952be6244f23c14a2d596d05f (diff)
refactor(tazjin/rlox): Retain interpreter state in REPL r/2032
Change-Id: Id60760e241ad0e45871b48e499f58e9831d57316
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2298
Tested-by: BuildkiteCI
Reviewed-by: tazjin <mail@tazj.in>
Diffstat (limited to 'users/tazjin/rlox/src/main.rs')
-rw-r--r--users/tazjin/rlox/src/main.rs29
1 files changed, 27 insertions, 2 deletions
diff --git a/users/tazjin/rlox/src/main.rs b/users/tazjin/rlox/src/main.rs
index 5caac3f1ae03..c56d345862c9 100644
--- a/users/tazjin/rlox/src/main.rs
+++ b/users/tazjin/rlox/src/main.rs
@@ -25,12 +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");
-    interpreter::run(&contents);
+    let mut lox = interpreter::Interpreter::default();
+    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();
 
     loop {
         print!("> ");
@@ -38,7 +40,30 @@ fn run_prompt() {
         io::stdin()
             .read_line(&mut line)
             .expect("failed to read user input");
-        interpreter::run(&line);
+        run(&mut lox, &line);
         line.clear();
     }
 }
+
+fn run(lox: &mut interpreter::Interpreter, code: &str) {
+    let chars: Vec<char> = code.chars().collect();
+
+    match scanner::scan(&chars) {
+        Ok(tokens) => match parser::parse(tokens) {
+            Ok(program) => {
+                println!("Program:\n{:?}", program);
+                if let Err(err) = lox.interpret(&program) {
+                    println!("Error in program: {:?}", err);
+                }
+            }
+            Err(errors) => report_errors(errors),
+        },
+        Err(errors) => report_errors(errors),
+    }
+}
+
+fn report_errors(errors: Vec<errors::Error>) {
+    for error in errors {
+        errors::report(&error);
+    }
+}