statements in rust

This commit is contained in:
Sebastian Hugentobler 2025-02-12 10:30:51 +01:00
parent 15b331f447
commit a629ddca05
6 changed files with 434 additions and 194 deletions

View file

@ -7,14 +7,17 @@ use std::{
path::Path,
};
use tracing::{error, info};
use interpreter::Interpreter;
use tracing::error;
pub mod cli;
pub mod environment;
pub mod expression;
pub mod interpreter;
pub mod keywords;
pub mod parser;
pub mod scanner;
pub mod statement;
pub mod token;
pub mod tokenizer {
pub mod comment;
@ -32,13 +35,16 @@ pub mod value;
/// 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)?;
run(&input);
let mut interpreter = Interpreter::default();
run(&input, &mut interpreter);
Ok(())
}
/// Run a Lox REPL until SIGINT.
pub fn repl() {
let mut interpreter = Interpreter::default();
loop {
print!("> ");
let _ = io::stdout().flush();
@ -49,16 +55,16 @@ pub fn repl() {
Err(e) => error!("{}", e),
}
let input = input.trim().to_string();
run(&input);
run(&input, &mut interpreter);
}
}
/// Evaluate a Lox input string and print errors or output.
fn run(input: &str) {
fn run(input: &str, interpreter: &mut Interpreter) {
let tokens = scanner::tokenize(input);
match parser::generate_ast(tokens) {
Ok(ast) => match interpreter::evaluate(ast) {
Ok(value) => println!("{value}"),
match parser::ast(tokens) {
Ok(ast) => match interpreter.run(ast) {
Ok(_) => {}
Err(e) => error!("{e}"),
},
Err(e) => error!("{e}"),