Files
rlox/src/main.rs

107 lines
2.5 KiB
Rust

use std::{env, fs, io};
use std::io::Write;
use std::process;
use crate::astprinter::ASTPrinter;
use crate::interpreter::Interpreter;
use crate::parser::Parser;
mod interpreter;
mod scanner;
mod token;
mod token_type;
mod expr;
mod astprinter;
mod parser;
mod stmt;
mod environment;
use crate::scanner::Scanner;
use crate::stmt::{Statement, StatementVisitor};
// Exit codes from #include <sysexits.h>
const EX_OK: i32 = 0;
//const EX_DATAERR: i32 = 65;
const EX_USAGE : i32 = 66;
//const EX_EXECERR: i32 = 70;
fn main() {
let args: Vec<String> = env::args().collect();
let exit_code = match args.len() {
1 => { run_prompt() } ,
2 => { run_file(&args[1]) },
_ => {
println!("Usage : rlox [script]");
EX_USAGE
}
};
process::exit(exit_code);
}
pub fn run_file(file_path: &str) -> i32 {
let contents = fs::read_to_string(file_path)
.expect(&format!("Should have been able to read the file {file_path}"));
run(contents)
}
pub fn run_prompt() -> i32 {
let mut exit_code = EX_OK;
loop {
print!("> ");
io::stdout().flush().expect("Unable to flush stdout");
let mut line = String::new();
io::stdin()
.read_line(&mut line)
.expect("Failed to read line");
if line.trim().is_empty() {
break;
}
exit_code = run(line);
}
exit_code
}
fn run(src: String) -> i32 {
println!("Scanner");
let mut scanner = Scanner::new( src );
scanner.scan_tokens();
println!("Parser");
let mut parser = Parser::new( scanner.tokens );
let program = parser.parse();
println!("AST");
let mut printer = ASTPrinter { depth: 0 };
for s in program.clone() {
match s {
Statement::Expression(e) => { printer.visit_expr_stmt(&e) }
Statement::Print(p) => { printer.visit_print(&p) }
Statement::Var(v) => { printer.visit_var_stmt(&v) }
}
}
println!("Interpretation");
let mut interpreter = Interpreter::new();
for s in program {
match s {
Statement::Expression(e) => { interpreter.visit_expr_stmt(&e) }
Statement::Print(p) => { interpreter.visit_print(&p) }
Statement::Var(v) => { interpreter.visit_var_stmt(&v) }
}
}
EX_OK
}
// Implémentations de référence :
// https://github.com/munificent/craftinginterpreters/wiki/Lox-implementations#rust
// Pause :
// http://www.craftinginterpreters.com/statements-and-state.html#assignment