interpreter in rust

This commit is contained in:
Sebastian Hugentobler 2025-02-11 11:19:56 +01:00
parent ac2621e431
commit 860eb6dfa4
2 changed files with 153 additions and 10 deletions

View file

@ -11,6 +11,7 @@ use tracing::{error, info};
pub mod cli;
pub mod expression;
pub mod interpreter;
pub mod keywords;
pub mod parser;
pub mod scanner;
@ -30,11 +31,7 @@ pub mod tokenizer {
/// Read the source code in a file and scan it to tokens.
pub fn compile(source: &Path) -> Result<(), io::Error> {
let input = fs::read_to_string(source)?;
let tokens = scanner::tokenize(&input);
match parser::generate_ast(tokens) {
Ok(ast) => info!("{ast:?}"),
Err(e) => error!("{e}"),
}
run(&input);
Ok(())
}
@ -51,10 +48,18 @@ pub fn repl() {
Err(e) => error!("{}", e),
}
let input = input.trim().to_string();
let tokens = scanner::tokenize(&input);
match parser::generate_ast(tokens) {
Ok(ast) => info!("{ast:?}"),
Err(e) => error!("{e}"),
}
run(&input);
}
}
/// Evaluate a Lox input string and print errors or output.
fn run(input: &str) {
let tokens = scanner::tokenize(input);
match parser::generate_ast(tokens) {
Ok(ast) => match interpreter::evaluate(ast) {
Ok(value) => info!("{value:?}"),
Err(e) => error!("{e}"),
},
Err(e) => error!("{e}"),
}
}