use std::{fs, io}; use crate::EX_OK; use std::io::Write; use crate::astprinter::ASTPrinter; use crate::expr::ExprVisitor; use crate::parser::Parser; use crate::scanner::Scanner; pub struct RLoxInterpreter; impl RLoxInterpreter { pub fn new() -> Self { RLoxInterpreter } pub fn run_file(&self, file_path: &str ) -> i32 { let contents = fs::read_to_string(file_path) .expect(&format!("Should have been able to read the file {file_path}")); self.run(contents) } pub fn run_prompt(&self) -> 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 = self.run(line); } exit_code } fn run(&self, src: String) -> i32 { let mut scanner = Scanner::new( src ); scanner.scan_tokens(); let mut parser = Parser::new( scanner.tokens ); match parser.parse() { Some(expr) => { let mut printer = ASTPrinter { depth: 0 }; printer.visit_expr(&expr); println!(); }, None => println!("An error occurred while parsing expression.") } EX_OK } }