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
+11 -51
View File
@@ -1,5 +1,5 @@
use crate::frontend::{
source_registry::{SourceId, SourcePosition, SourceSlice},
source_registry::SourceSlice,
tokens::{LiteralValue, TokenType},
};
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)
impl std::fmt::Display for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -294,28 +266,16 @@ impl AstNodeKind for Expr {
impl AstNodeKind for Stmt {
fn kind(&self) -> &'static str {
match self {
Stmt::Expression { expression: _ } => "expression",
Stmt::Var {
name: _,
initializer: _,
} => "variable declaration",
Stmt::Assign { name: _, value: _ } => "assignment",
Stmt::Return { expression: _ } => "return statement",
Stmt::Block { statements: _ } => "block statement",
Stmt::If {
condition: _,
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",
Stmt::Expression { .. } => "expression",
Stmt::Var { .. } => "variable declaration",
Stmt::Assign { .. } => "assignment",
Stmt::Return { .. } => "return statement",
Stmt::Block { .. } => "block statement",
Stmt::If { .. } => "if statement",
Stmt::Print { .. } => "print statement",
Stmt::Stmt { .. } => "statement",
Stmt::While { .. } => "while statement",
Stmt::For { .. } => "for statement",
}
}
}