Refactor environment to use stack-based scoping

The commit rewrites the environment to use a stack of hash maps for
managing variable scopes. This replaces the old parent-reference
approach with a simpler and more efficient stack-based model.

Key changes: - Rename Environment to EnvironmentStack - Store scopes in
a Vec of HashMaps - Add push/pop scope operations for block handling -
Update interpreter to properly manage scope lifetimes - Clean up error
handling with helper functions
This commit is contained in:
Giulio Agostini
2025-10-04 21:05:00 +02:00
parent 41253e932a
commit 827349cbad
11 changed files with 165 additions and 243 deletions
+2 -1
View File
@@ -13,10 +13,11 @@ do
cavallo cavallo
end end
do do
var cavallo = 0;
print "cavallo"; print "cavallo";
while cavallo < 10 do while cavallo < 10 do
print "loop: " + cavallo;
cavallo = cavallo + 1; cavallo = cavallo + 1;
print cavallo;
end end
89 89
end end
+23 -22
View File
@@ -2,43 +2,44 @@ use std::collections::HashMap;
use crate::{ use crate::{
frontend::{source_registry::SourceSlice, tokens::LiteralValue}, frontend::{source_registry::SourceSlice, tokens::LiteralValue},
result::{LoxError, LoxResult}, result::{runtime_error, LoxResult},
}; };
pub struct Environment<'a> { #[derive(Debug, Clone)]
values: HashMap<String, LiteralValue>, pub struct EnvironmentStack {
parent: Option<&'a Environment<'a>>, stack: Vec<HashMap<String, LiteralValue>>,
} }
impl<'a> Environment<'a> { impl EnvironmentStack {
pub fn new() -> Self { pub fn new() -> Self {
Environment { EnvironmentStack {
values: HashMap::new(), stack: vec![HashMap::new()],
parent: None,
} }
} }
pub fn new_with_parent(parent: &'a Environment<'a>) -> Self { pub fn push_new_scope(&mut self) {
Environment { self.stack.push(HashMap::new());
values: HashMap::new(),
parent: Some(parent),
} }
pub fn pop_scope(&mut self) {
self.stack.pop();
} }
pub fn get(&self, name: &str) -> LoxResult<LiteralValue> { pub fn get(&self, name: &str) -> LoxResult<LiteralValue> {
match self.values.get(name) { let size = self.stack.len();
Some(value) => Ok(value.clone()),
None => match self.parent { for i in (0..size).rev() {
Some(parent) => parent.get(name), if let Some(value) = self.stack[i].get(name) {
None => Err(LoxError::RuntimeError { return Ok(value.clone());
source_slice: SourceSlice::default(), // todo change this to the actual source slice
message: format!("Undefined variable '{}'", name),
}),
},
} }
} }
runtime_error(
SourceSlice::default(), // todo change this to the actual source slice
format!("Undefined variable '{}'", name),
)
}
pub fn set(&mut self, name: String, value: LiteralValue) { pub fn set(&mut self, name: String, value: LiteralValue) {
self.values.insert(name, value); self.stack.last_mut().unwrap().insert(name, value);
} }
} }
+50 -80
View File
@@ -1,5 +1,5 @@
use crate::{ use crate::{
backend::environment::Environment, backend::environment::EnvironmentStack,
frontend::{ frontend::{
ast::{AstNode, AstNodeKind, Expr, Stmt}, ast::{AstNode, AstNodeKind, Expr, Stmt},
source_registry::SourceSlice, source_registry::SourceSlice,
@@ -8,7 +8,7 @@ use crate::{
result::{LoxError, LoxResult}, result::{LoxError, LoxResult},
}; };
use std::{ use std::{
fmt::{format, Debug, Display}, fmt::{Debug, Display},
ops::{Add, Div, Mul, Neg, Not, Rem, Sub}, ops::{Add, Div, Mul, Neg, Not, Rem, Sub},
}; };
@@ -169,59 +169,17 @@ impl From<LiteralValue> for bool {
} }
} }
pub struct Interpreter<'a> { pub struct Interpreter {
enviorment: &'a mut Environment<'a>, enviorment: EnvironmentStack,
}
impl<'a> Interpreter<'a> {
pub fn new(env: &'a mut Environment<'a>) -> Self {
Self { enviorment: env }
}
fn interpret_binary(
&mut self,
left: AstNode<Expr>,
operator: TokenType,
right: AstNode<Expr>,
source_slice: SourceSlice,
) -> LoxResult<LiteralValue> {
let left_value = self.interpret(left)?;
let right_value = self.interpret(right)?;
match operator {
TokenType::Minus => left_value - right_value,
TokenType::Plus => left_value.add_with_source(right_value, source_slice.clone()),
TokenType::Slash => left_value / right_value,
TokenType::Star => left_value * right_value,
TokenType::EqualEqual => Ok(LiteralValue::Boolean(left_value == right_value)),
TokenType::BangEqual => Ok(LiteralValue::Boolean(left_value != right_value)),
TokenType::Greater => Ok(LiteralValue::Boolean(left_value > right_value)),
TokenType::GreaterEqual => Ok(LiteralValue::Boolean(left_value >= right_value)),
TokenType::Less => Ok(LiteralValue::Boolean(left_value < right_value)),
TokenType::LessEqual => Ok(LiteralValue::Boolean(left_value <= right_value)),
TokenType::Percent => left_value % right_value,
TokenType::And => Ok(LiteralValue::Boolean(
left_value.is_truthy() && right_value.is_truthy(),
)),
TokenType::Or => Ok(LiteralValue::Boolean(
left_value.is_truthy() || right_value.is_truthy(),
)),
_ => Err(LoxError::RuntimeError {
source_slice: SourceSlice::default(), // todo change this to the actual source slice
message: format!("Unsupported binary operator {}", operator),
}),
}
}
} }
pub trait EvaluateInterpreter<T> { pub trait EvaluateInterpreter<T> {
fn interpret(&mut self, stmt: T) -> LoxResult<LiteralValue>; fn interpret(&mut self, stmt: T) -> LoxResult<LiteralValue>;
} }
impl<'a, R: AstNodeKind + Clone + Debug + Display> EvaluateInterpreter<AstNode<R>> impl<'a, R: AstNodeKind + Clone + Debug + Display> EvaluateInterpreter<AstNode<R>> for Interpreter
for Interpreter<'a>
where where
Interpreter<'a>: EvaluateInterpreter<R>, Interpreter: EvaluateInterpreter<R>,
{ {
fn interpret(&mut self, stmt: AstNode<R>) -> LoxResult<LiteralValue> { fn interpret(&mut self, stmt: AstNode<R>) -> LoxResult<LiteralValue> {
match self.interpret(stmt.node.clone()) { match self.interpret(stmt.node.clone()) {
@@ -235,7 +193,7 @@ where
} }
// Direct Expr evaluation to avoid infinite recursion // Direct Expr evaluation to avoid infinite recursion
impl<'a> EvaluateInterpreter<Expr> for Interpreter<'a> { impl EvaluateInterpreter<Expr> for Interpreter {
fn interpret(&mut self, expr: Expr) -> LoxResult<LiteralValue> { fn interpret(&mut self, expr: Expr) -> LoxResult<LiteralValue> {
match expr { match expr {
Expr::Literal { value } => Ok(value), Expr::Literal { value } => Ok(value),
@@ -258,7 +216,7 @@ impl<'a> EvaluateInterpreter<Expr> for Interpreter<'a> {
} }
} }
impl<'a> EvaluateInterpreter<AstNode<Stmt>> for Interpreter<'a> { impl EvaluateInterpreter<AstNode<Stmt>> for Interpreter {
fn interpret(&mut self, node: AstNode<Stmt>) -> LoxResult<LiteralValue> { fn interpret(&mut self, node: AstNode<Stmt>) -> LoxResult<LiteralValue> {
let stmt = node.node; let stmt = node.node;
let _source_slice = node.source_slice; let _source_slice = node.source_slice;
@@ -266,7 +224,13 @@ impl<'a> EvaluateInterpreter<AstNode<Stmt>> for Interpreter<'a> {
} }
} }
impl<'a> Interpreter<'a> { impl Interpreter {
pub fn new() -> Self {
Self {
enviorment: EnvironmentStack::new(),
}
}
fn evaluate_binary( fn evaluate_binary(
&mut self, &mut self,
left: LiteralValue, left: LiteralValue,
@@ -311,30 +275,7 @@ impl<'a> Interpreter<'a> {
println!("print interpreter: \t{}", value); println!("print interpreter: \t{}", value);
Ok(LiteralValue::Nil) Ok(LiteralValue::Nil)
} }
Stmt::Block { statements } => { Stmt::Block { statements } => self.evaluate_block(*statements),
let (elements, final_expr) = match statements.split_last() {
Some((stmt, body)) => match &stmt.node {
Stmt::Expression { expression } => (body, Some(expression)),
Stmt::Return { expression } => (body, Some(expression)),
_ => (statements.as_slice(), None),
},
None => {
(&[][..], None) // Blocco vuoto
}
};
// Ora elements è sempre disponibile
for statement in elements.iter() {
self.interpret((*statement).clone())?;
}
// Gestisci l'espressione finale se presente
match final_expr {
Some(expr) => self.interpret(*expr.clone()),
None => Ok(LiteralValue::Nil),
}
}
Stmt::Stmt { expression } => self.interpret(*expression.clone()), Stmt::Stmt { expression } => self.interpret(*expression.clone()),
Stmt::Return { expression } => self.interpret(*expression), Stmt::Return { expression } => self.interpret(*expression),
Stmt::Var { name, initializer } => { Stmt::Var { name, initializer } => {
@@ -396,11 +337,40 @@ impl<'a> Interpreter<'a> {
} }
Ok(LiteralValue::Nil) Ok(LiteralValue::Nil)
} }
Stmt::For { Stmt::For { .. } => todo!(),
variable, }
iterable, }
body,
} => todo!(), fn evaluate_block(&mut self, statements: Vec<AstNode<Stmt>>) -> LoxResult<LiteralValue> {
self.enviorment.push_new_scope();
let (elements, final_expr) = match statements.split_last() {
Some((stmt, body)) => match &stmt.node {
Stmt::Expression { expression } => (body, Some(expression)),
Stmt::Return { expression } => (body, Some(expression)),
_ => (statements.as_slice(), None),
},
None => {
(&[][..], None) // Blocco vuoto
}
};
// Ora elements è sempre disponibile
for statement in elements.iter() {
self.interpret((*statement).clone())?;
}
// Gestisci l'espressione finale se presente
match final_expr {
Some(expr) => {
let res = self.interpret(*expr.clone());
self.enviorment.pop_scope();
res
}
None => {
self.enviorment.pop_scope();
Ok(LiteralValue::Nil)
}
} }
} }
} }
+11 -51
View File
@@ -1,5 +1,5 @@
use crate::frontend::{ use crate::frontend::{
source_registry::{SourceId, SourcePosition, SourceSlice}, source_registry::SourceSlice,
tokens::{LiteralValue, TokenType}, tokens::{LiteralValue, TokenType},
}; };
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
@@ -54,34 +54,6 @@ pub enum Expr {
}, },
} }
pub trait ExprPrint {
fn print(&self) -> String;
}
impl ExprPrint for Expr {
fn print(&self) -> String {
match self {
Expr::Literal { value } => format!("Literal {}", value),
Expr::Binary {
left,
operator,
right,
} => {
format!("Binary ({} {} {})", left.node, operator, right.node)
}
Expr::Unary { operator, operand } => {
format!("Unary ({} {})", operator, operand.node)
}
Expr::Grouping { expression } => {
format!("Grouping (group {})", expression.node)
}
Expr::Variable { name } => {
format!("Variable (variable {})", name)
}
}
}
}
// Implementazione Display per Expr (per debugging) // Implementazione Display per Expr (per debugging)
impl std::fmt::Display for Expr { impl std::fmt::Display for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -294,28 +266,16 @@ impl AstNodeKind for Expr {
impl AstNodeKind for Stmt { impl AstNodeKind for Stmt {
fn kind(&self) -> &'static str { fn kind(&self) -> &'static str {
match self { match self {
Stmt::Expression { expression: _ } => "expression", Stmt::Expression { .. } => "expression",
Stmt::Var { Stmt::Var { .. } => "variable declaration",
name: _, Stmt::Assign { .. } => "assignment",
initializer: _, Stmt::Return { .. } => "return statement",
} => "variable declaration", Stmt::Block { .. } => "block statement",
Stmt::Assign { name: _, value: _ } => "assignment", Stmt::If { .. } => "if statement",
Stmt::Return { expression: _ } => "return statement", Stmt::Print { .. } => "print statement",
Stmt::Block { statements: _ } => "block statement", Stmt::Stmt { .. } => "statement",
Stmt::If { Stmt::While { .. } => "while statement",
condition: _, Stmt::For { .. } => "for statement",
then_branch: _,
elif_branch: _,
else_branch: _,
} => "if statement",
Stmt::Print { expression: _ } => "print statement",
Stmt::Stmt { expression: _ } => "statement",
Stmt::While { condition, body } => "while statement",
Stmt::For {
variable,
iterable,
body,
} => "for statement",
} }
} }
} }
+2
View File
@@ -26,6 +26,7 @@ fn get_keyword_token(word: &str) -> Option<TokenType> {
"elif" => Some(TokenType::Elif), "elif" => Some(TokenType::Elif),
"else" => Some(TokenType::Else), "else" => Some(TokenType::Else),
"or" => Some(TokenType::Or), "or" => Some(TokenType::Or),
"in" => Some(TokenType::In),
"print" => Some(TokenType::Print), "print" => Some(TokenType::Print),
"return" => Some(TokenType::Return), "return" => Some(TokenType::Return),
"super" => Some(TokenType::Super), "super" => Some(TokenType::Super),
@@ -146,6 +147,7 @@ impl Lexer {
('+', _) => Ok(Some(self.make_token(TokenType::Plus))), ('+', _) => Ok(Some(self.make_token(TokenType::Plus))),
(';', _) => Ok(Some(self.make_token(TokenType::Semicolon))), (';', _) => Ok(Some(self.make_token(TokenType::Semicolon))),
('*', _) => Ok(Some(self.make_token(TokenType::Star))), ('*', _) => Ok(Some(self.make_token(TokenType::Star))),
('%', _) => Ok(Some(self.make_token(TokenType::Percent))),
('!', '=') => { ('!', '=') => {
self.advance(); // consuma il '=' self.advance(); // consuma il '='
Ok(Some(self.make_token(TokenType::BangEqual))) Ok(Some(self.make_token(TokenType::BangEqual)))
+44 -1
View File
@@ -5,7 +5,7 @@ use crate::{
tokens::{LiteralValue, Token, TokenType}, tokens::{LiteralValue, Token, TokenType},
}, },
logging::display_ast::{pretty_print_with_config, PrettyConfig}, logging::display_ast::{pretty_print_with_config, PrettyConfig},
result::{LoxError, LoxResult}, result::{parse_error, LoxError, LoxResult},
}; };
pub struct Parser { pub struct Parser {
@@ -65,10 +65,53 @@ impl Parser {
(TokenType::Identifier, TokenType::Equal) => self.assignment_statement(), (TokenType::Identifier, TokenType::Equal) => self.assignment_statement(),
(TokenType::If, _) => self.if_statement(), (TokenType::If, _) => self.if_statement(),
(TokenType::While, _) => self.while_statement(), (TokenType::While, _) => self.while_statement(),
(TokenType::For, _) => self.for_statement(),
_ => self.expression_statement(), _ => self.expression_statement(),
} }
} }
fn for_statement(&mut self) -> LoxResult<AstNode<Stmt>> {
let start_slice = self.peek().source_slice.clone();
self.advance();
let variable = if let Token {
token_type: TokenType::Identifier,
literal: Some(variable_name),
source_slice,
..
} = self.peek()
{
AstNode {
node: Expr::Literal {
value: variable_name.clone(),
},
source_slice: source_slice.clone(),
}
} else {
return parse_error(
self.peek().source_slice.clone(),
"Expect variable name after 'for' keyword.",
);
};
self.advance();
self.consume(TokenType::In, "Expect 'in' after for variable.")?;
let iterable = self.expression()?;
let body = self.statement()?;
let end_slice = body.source_slice.clone();
let combined_slice = SourceSlice::from_positions(
start_slice.source_id,
start_slice.start_position,
end_slice.end_position,
);
Ok(AstNode::new(
Stmt::For {
variable: Box::new(variable),
iterable: Box::new(iterable),
body: Box::new(body),
},
combined_slice,
))
}
fn while_statement(&mut self) -> LoxResult<AstNode<Stmt>> { fn while_statement(&mut self) -> LoxResult<AstNode<Stmt>> {
let start_slice = self.peek().source_slice.clone(); let start_slice = self.peek().source_slice.clone();
self.advance(); self.advance();
+2
View File
@@ -72,6 +72,7 @@ pub enum TokenType {
Else, Else,
Nil, Nil,
Or, Or,
In,
Print, Print,
Return, Return,
Super, Super,
@@ -132,6 +133,7 @@ impl fmt::Display for TokenType {
TokenType::Elif => write!(f, "elif"), TokenType::Elif => write!(f, "elif"),
TokenType::Val => write!(f, "val"), TokenType::Val => write!(f, "val"),
TokenType::Percent => write!(f, "%"), TokenType::Percent => write!(f, "%"),
TokenType::In => write!(f, "in"),
} }
} }
} }
+3 -25
View File
@@ -3,10 +3,7 @@
//! This module provides elegant and functional printing capabilities for AST objects, //! This module provides elegant and functional printing capabilities for AST objects,
//! inspired by Rust's debug formatting but optimized for readability and analysis. //! inspired by Rust's debug formatting but optimized for readability and analysis.
use crate::frontend::{ use crate::frontend::ast::{AstNode, AstNodeKind, Expr, Stmt};
ast::{AstNode, AstNodeKind, Expr, Stmt},
source_registry::SourceSlice,
};
use std::fmt::{self, Write}; use std::fmt::{self, Write};
/// Configuration for pretty printing output /// Configuration for pretty printing output
@@ -39,6 +36,7 @@ impl Default for PrettyConfig {
} }
} }
#[allow(dead_code)]
impl PrettyConfig { impl PrettyConfig {
/// Create a compact configuration /// Create a compact configuration
pub fn compact() -> Self { pub fn compact() -> Self {
@@ -471,6 +469,7 @@ impl<T: AstNodeKind + fmt::Debug + fmt::Display + PrettyPrint> PrettyPrint for A
} }
// Extension trait for convenience methods // Extension trait for convenience methods
#[allow(dead_code)]
pub trait PrettyPrintExt { pub trait PrettyPrintExt {
fn pretty(&self) -> String; fn pretty(&self) -> String;
fn pretty_compact(&self) -> String; fn pretty_compact(&self) -> String;
@@ -531,24 +530,3 @@ impl<T: AstNodeKind + fmt::Debug + fmt::Display + PrettyPrint> PrettyPrintExt fo
pretty_print_with_config(self, config) pretty_print_with_config(self, config)
} }
} }
/// Convenience functions for quick pretty printing
pub fn pretty_expr(expr: &Expr) -> String {
pretty_print(expr)
}
pub fn pretty_stmt(stmt: &Stmt) -> String {
pretty_print(stmt)
}
pub fn pretty_expr_compact(expr: &Expr) -> String {
pretty_print_with_config(expr, &PrettyConfig::compact())
}
pub fn pretty_stmt_compact(stmt: &Stmt) -> String {
pretty_print_with_config(stmt, &PrettyConfig::compact())
}
pub fn pretty_tree<T: PrettyPrint>(item: &T) -> String {
pretty_print_with_config(item, &PrettyConfig::tree())
}
+4 -41
View File
@@ -3,11 +3,7 @@
//! This module provides elegant and functional printing capabilities for Token objects, //! This module provides elegant and functional printing capabilities for Token objects,
//! inspired by Rust's debug formatting but optimized for readability and analysis. //! inspired by Rust's debug formatting but optimized for readability and analysis.
use crate::frontend::{ use crate::frontend::tokens::{Token, TokenType};
source_registry::SourceSlice,
tokens::{LiteralValue, Token, TokenType},
};
use std::fmt;
/// Configuration for pretty printing tokens /// Configuration for pretty printing tokens
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -199,12 +195,12 @@ impl Token {
TokenType::Var => "VAR", TokenType::Var => "VAR",
TokenType::Val => "VAL", TokenType::Val => "VAL",
TokenType::Eof => "EOF", TokenType::Eof => "EOF",
TokenType::In => "IN",
} }
} }
fn colored_type(&self) -> String { fn colored_type(&self) -> String {
let (color_code, symbol) = match self.token_type { let (color_code, symbol) = match self.token_type {
// Operators - Red
TokenType::Plus TokenType::Plus
| TokenType::Minus | TokenType::Minus
| TokenType::Star | TokenType::Star
@@ -218,8 +214,6 @@ impl Token {
| TokenType::GreaterEqual | TokenType::GreaterEqual
| TokenType::Less | TokenType::Less
| TokenType::LessEqual => ("\x1b[31m", self.token_type_symbol()), | TokenType::LessEqual => ("\x1b[31m", self.token_type_symbol()),
// Keywords - Blue
TokenType::And TokenType::And
| TokenType::Class | TokenType::Class
| TokenType::False | TokenType::False
@@ -239,13 +233,9 @@ impl Token {
| TokenType::This | TokenType::This
| TokenType::Var | TokenType::Var
| TokenType::Val => ("\x1b[34m", self.token_type_symbol()), | TokenType::Val => ("\x1b[34m", self.token_type_symbol()),
// Literals - Green
TokenType::Identifier | TokenType::String | TokenType::Number => { TokenType::Identifier | TokenType::String | TokenType::Number => {
("\x1b[32m", self.token_type_symbol()) ("\x1b[32m", self.token_type_symbol())
} }
// Punctuation - Gray
TokenType::LeftParen TokenType::LeftParen
| TokenType::RightParen | TokenType::RightParen
| TokenType::LeftBrace | TokenType::LeftBrace
@@ -255,12 +245,9 @@ impl Token {
| TokenType::Comma | TokenType::Comma
| TokenType::Dot | TokenType::Dot
| TokenType::Semicolon => ("\x1b[37m", self.token_type_symbol()), | TokenType::Semicolon => ("\x1b[37m", self.token_type_symbol()),
// Block delimiters - Magenta
TokenType::StartBlock | TokenType::EndBlock => ("\x1b[35m", self.token_type_symbol()), TokenType::StartBlock | TokenType::EndBlock => ("\x1b[35m", self.token_type_symbol()),
// EOF - Yellow
TokenType::Eof => ("\x1b[33m", self.token_type_symbol()), TokenType::Eof => ("\x1b[33m", self.token_type_symbol()),
TokenType::In => ("\x1b[36m", self.token_type_symbol()),
}; };
format!("{}{}\x1b[0m", color_code, symbol) format!("{}{}\x1b[0m", color_code, symbol)
@@ -298,6 +285,7 @@ pub fn pretty_print_tokens(tokens: &[Token], config: &TokenPrettyConfig) -> Stri
} }
/// Extension trait for convenience methods /// Extension trait for convenience methods
#[allow(dead_code)]
pub trait TokenPrettyPrintExt { pub trait TokenPrettyPrintExt {
fn pretty(&self) -> String; fn pretty(&self) -> String;
fn pretty_compact(&self) -> String; fn pretty_compact(&self) -> String;
@@ -358,28 +346,3 @@ impl TokenPrettyPrintExt for Vec<Token> {
pretty_print_tokens(self, config) pretty_print_tokens(self, config)
} }
} }
/// Convenience functions for quick pretty printing
pub fn pretty_token(token: &Token) -> String {
token.pretty()
}
pub fn pretty_token_compact(token: &Token) -> String {
token.pretty_compact()
}
pub fn pretty_token_minimal(token: &Token) -> String {
token.pretty_minimal()
}
pub fn pretty_tokens(tokens: &[Token]) -> String {
pretty_print_tokens(tokens, &TokenPrettyConfig::default())
}
pub fn pretty_tokens_compact(tokens: &[Token]) -> String {
pretty_print_tokens(tokens, &TokenPrettyConfig::compact())
}
pub fn pretty_tokens_colored(tokens: &[Token]) -> String {
pretty_print_tokens(tokens, &TokenPrettyConfig::colored())
}
+4 -5
View File
@@ -6,19 +6,19 @@ mod result;
use crate::{ use crate::{
backend::{ backend::{
environment::Environment, environment::EnvironmentStack,
interpreter::{EvaluateInterpreter, Interpreter}, interpreter::{EvaluateInterpreter, Interpreter},
}, },
frontend::{ frontend::{
lexer::Lexer, lexer::Lexer,
parser::Parser, parser::Parser,
source_registry::{SourceFile, SourceId, SourcePosition, SourceRegistry, SourceSlice}, source_registry::{SourceId, SourceRegistry, SourceSlice},
}, },
prompt::prompt_lines, prompt::prompt_lines,
result::{LoxError, LoxResult}, result::{LoxError, LoxResult},
}; };
use std::env;
use std::fs; use std::fs;
use std::{env, error::Error};
fn main() -> LoxResult<()> { fn main() -> LoxResult<()> {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
@@ -83,8 +83,7 @@ impl LoxInterpreter {
Ok(asts) Ok(asts)
}) })
.and_then(|stmts| { .and_then(|stmts| {
let mut env = Environment::new(); let mut interpreter = Interpreter::new();
let mut interpreter = Interpreter::new(&mut env);
let mut result = None; let mut result = None;
for (index, stmt) in stmts.iter().enumerate() { for (index, stmt) in stmts.iter().enumerate() {
println!("executing stmt {}: {:?}", index, stmt); println!("executing stmt {}: {:?}", index, stmt);
+19 -16
View File
@@ -402,45 +402,48 @@ impl std::error::Error for LoxError {}
pub type LoxResult<T> = Result<T, LoxError>; pub type LoxResult<T> = Result<T, LoxError>;
/// Helper function to create a lexical error /// Helper function to create a lexical error
pub fn lexical_error(source_slice: SourceSlice, message: impl Into<String>) -> LoxError { pub fn lexical_error<T>(source_slice: SourceSlice, message: impl Into<String>) -> LoxResult<T> {
LoxError::LexicalError { Err(LoxError::LexicalError {
source_slice, source_slice,
message: message.into(), message: message.into(),
} })
} }
/// Helper function to create a parse error /// Helper function to create a parse error
pub fn parse_error(source_slice: SourceSlice, message: impl Into<String>) -> LoxError { pub fn parse_error<T>(source_slice: SourceSlice, message: impl Into<String>) -> LoxResult<T> {
LoxError::ParseError { Err(LoxError::ParseError {
source_slice, source_slice,
message: message.into(), message: message.into(),
} })
} }
/// Helper function to create a runtime error /// Helper function to create a runtime error
pub fn runtime_error(source_slice: SourceSlice, message: impl Into<String>) -> LoxError { #[allow(dead_code)]
LoxError::RuntimeError { pub fn runtime_error<T>(source_slice: SourceSlice, message: impl Into<String>) -> LoxResult<T> {
Err(LoxError::RuntimeError {
source_slice, source_slice,
message: message.into(), message: message.into(),
} })
} }
/// Helper function to create a type mismatch error /// Helper function to create a type mismatch error
pub fn type_mismatch_error( #[allow(dead_code)]
pub fn type_mismatch_error<T>(
source_slice: SourceSlice, source_slice: SourceSlice,
expected: impl Into<String>, expected: impl Into<String>,
found: impl Into<String>, found: impl Into<String>,
) -> LoxError { ) -> LoxResult<T> {
LoxError::TypeMismatch { Err(LoxError::TypeMismatch {
source_slice, source_slice,
expected: expected.into(), expected: expected.into(),
found: found.into(), found: found.into(),
} })
} }
/// Helper function to create an IO error /// Helper function to create an IO error
pub fn io_error(message: impl Into<String>) -> LoxError { #[allow(dead_code)]
LoxError::IoError { pub fn io_error<T>(message: impl Into<String>) -> LoxResult<T> {
Err(LoxError::IoError {
message: message.into(), message: message.into(),
} })
} }