implement chapter 11 in rust
This commit is contained in:
parent
8860a1c639
commit
a25b6d1e92
16 changed files with 470 additions and 32 deletions
|
@ -7,7 +7,10 @@ use std::{
|
|||
path::Path,
|
||||
};
|
||||
|
||||
use interpreter::Interpreter;
|
||||
use interpreter::{Interpreter, InterpreterError};
|
||||
use parser::ParserError;
|
||||
use resolver::{Resolver, ResolverError};
|
||||
use thiserror::Error;
|
||||
use tracing::error;
|
||||
|
||||
pub mod callable;
|
||||
|
@ -19,6 +22,7 @@ pub mod interpreter;
|
|||
pub mod keywords;
|
||||
pub mod native_functions;
|
||||
pub mod parser;
|
||||
pub mod resolver;
|
||||
pub mod scanner;
|
||||
pub mod statement;
|
||||
pub mod token;
|
||||
|
@ -35,6 +39,16 @@ pub mod tokenizer {
|
|||
}
|
||||
pub mod value;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum RoxError {
|
||||
#[error("parser failed: {0}")]
|
||||
ParseError(#[from] ParserError),
|
||||
#[error("resolver failed: {0}")]
|
||||
ResolverError(#[from] ResolverError),
|
||||
#[error("interpreter failed: {0}")]
|
||||
InterpreterError(#[from] InterpreterError),
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
|
@ -64,12 +78,18 @@ pub fn repl() {
|
|||
|
||||
/// Evaluate a Lox input string and print errors or output.
|
||||
fn run(input: &str, interpreter: &mut Interpreter) {
|
||||
let tokens = scanner::tokenize(input);
|
||||
match parser::ast(tokens) {
|
||||
Ok(ast) => match interpreter.run(ast) {
|
||||
Ok(_) => {}
|
||||
Err(e) => error!("{e}"),
|
||||
},
|
||||
Err(e) => error!("{e}"),
|
||||
if let Err(e) = run_rox(input, interpreter) {
|
||||
error!("{e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_rox(input: &str, interpreter: &mut Interpreter) -> Result<(), RoxError> {
|
||||
let tokens = scanner::tokenize(input);
|
||||
let mut resolver = Resolver::new(interpreter);
|
||||
|
||||
let ast = parser::ast(tokens)?;
|
||||
resolver.resolve(&ast)?;
|
||||
interpreter.run(ast)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue