Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d59e748bf | ||
|
|
956446c170 | ||
|
|
52f0a5b8f1 | ||
|
|
84a7bf453f | ||
|
|
2c3267e8a4 | ||
|
|
2498b3b345 | ||
|
|
b93a1394cd | ||
|
|
842216729b | ||
|
|
9f15a00b98 | ||
|
|
d40fe2a550 | ||
|
|
ef8abda048 | ||
|
|
29c86d278d |
Executable → Regular
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rlox"
|
name = "rlox"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
Executable
+78
@@ -0,0 +1,78 @@
|
|||||||
|
#+title: README
|
||||||
|
|
||||||
|
* Syntax example:
|
||||||
|
#+begin_src
|
||||||
|
#this is what a struct delcaration shoul lool like
|
||||||
|
Point :: struct{
|
||||||
|
x: Numeric, # btw Numeric in my imagination is a Interface/Trai/Contrato comune to all numberic type
|
||||||
|
y: Numeric,
|
||||||
|
}
|
||||||
|
|
||||||
|
Point.new :: fn(x:Numeric, y:Numeric) Self:
|
||||||
|
return Point{x,y}
|
||||||
|
|
||||||
|
|
||||||
|
Point.sum :: fn(self, other: Point) Self:
|
||||||
|
return Point{x: self.x+other.x, y: self.y+self.y}
|
||||||
|
|
||||||
|
|
||||||
|
@(entrypoint)
|
||||||
|
main :: fn(parametro1: Numeric, parametro2: String) Void :
|
||||||
|
a := Point.new(67, 420)
|
||||||
|
b := Point.new(42, 47)
|
||||||
|
a = a.sum(b)
|
||||||
|
|
||||||
|
print("par: {},{}", touple(parametro1, parametro2))
|
||||||
|
if parametro1 == 0:
|
||||||
|
print("What do you epexted to happen?")
|
||||||
|
else if parametro1 > 0:
|
||||||
|
for i in range(0,parametro1,1):
|
||||||
|
print("{}", parametro2)
|
||||||
|
else:
|
||||||
|
for i in range(0,parametro1,-1):
|
||||||
|
print("{}", parametro2)
|
||||||
|
range_gen := precook(range, args: [0,parametro1]);
|
||||||
|
match parametro1 is:
|
||||||
|
== 0 => print("{}", parametro2),
|
||||||
|
> 0 => forEach(range_gen(1), |x| print("{}", parametro2)),
|
||||||
|
< 0 => forEach(range_gen(-1), |x| print("{}", parametro2)),
|
||||||
|
_ => panic()
|
||||||
|
match a is:
|
||||||
|
Point(x > 100, y) => print("YEAAA :)"),
|
||||||
|
_ => print("NAIH :(")
|
||||||
|
#+end_src
|
||||||
|
|
||||||
|
* Planning:
|
||||||
|
allora quello che devo fare è:
|
||||||
|
** TODO Controllare se ho finito la questione del return:label
|
||||||
|
** TODO Complete the use os source slice inside parser (many node has synthetic source slice or badly wrapped)
|
||||||
|
** TODO implement struct:
|
||||||
|
#+begin_src rlox
|
||||||
|
Cosa :: struct{
|
||||||
|
field1: Numeric
|
||||||
|
}
|
||||||
|
#+end_src
|
||||||
|
*** TODO update lexer
|
||||||
|
*** TODO update ast
|
||||||
|
*** TODO update parser
|
||||||
|
** TODO implement partial function ...
|
||||||
|
#+begin_src rlox
|
||||||
|
cosa := Cosa{feld1: 42}
|
||||||
|
function :: fn(self:Cosa, b: Numeric) -> Numeric
|
||||||
|
res := function(cosa,44)
|
||||||
|
#+end_src
|
||||||
|
*** TODO ... to undirectly create method
|
||||||
|
#+begin_src rlox
|
||||||
|
res := cosa.function(44);
|
||||||
|
#+end_src
|
||||||
|
*** TODO ... to make pipeline
|
||||||
|
#+begin_src rlox
|
||||||
|
res := cosa |> function(44);
|
||||||
|
#+end_src
|
||||||
|
** TODO Understand what is a type system
|
||||||
|
** TODO implement struct method:
|
||||||
|
#+begin_src rlox
|
||||||
|
Cosa.new :: fn(field1: Numeric):Self #+begin_src do
|
||||||
|
return Self{ field1 };
|
||||||
|
end;
|
||||||
|
#+end_src
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
|
|
||||||
closure :: fn() do
|
closure :: fn(): Any do
|
||||||
value := "Closure";
|
value := "Closure";
|
||||||
internal :: fn() do
|
internal :: fn(): String do
|
||||||
print value;
|
print value;
|
||||||
return value;
|
return value;
|
||||||
end
|
end;
|
||||||
return internal;
|
return internal;
|
||||||
end
|
end;
|
||||||
|
|
||||||
internal := closure();
|
internal := closure();
|
||||||
internal();
|
internal();
|
||||||
@@ -17,9 +17,9 @@ c := b;
|
|||||||
c = b = a;
|
c = b = a;
|
||||||
d := c = b = a;
|
d := c = b = a;
|
||||||
do
|
do
|
||||||
showA :: fn() do
|
showA :: fn(): Nil do
|
||||||
print a;
|
print a;
|
||||||
end
|
end;
|
||||||
|
|
||||||
showA();
|
showA();
|
||||||
a := "Local";
|
a := "Local";
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// address: String,
|
// address: String,
|
||||||
// }
|
// }
|
||||||
//func_name :: fn(param: Number, param2: String) {param is Int} do
|
//func_name :: fn(param: Number, param2: String) {param is Int} do
|
||||||
func_name :: fn(param: Int, param2: String) do
|
func_name :: fn(param: Int, param2: String): Any do
|
||||||
print param;
|
print param;
|
||||||
print param2;
|
print param2;
|
||||||
while param < param2 do
|
while param < param2 do
|
||||||
@@ -26,6 +26,6 @@ func_name :: fn(param: Int, param2: String) do
|
|||||||
end
|
end
|
||||||
|
|
||||||
return False or True;
|
return False or True;
|
||||||
end
|
end;
|
||||||
|
|
||||||
func_name(1,20)
|
func_name(1,20);
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
|
|
||||||
function :: fn() do
|
function :: fn(): Nil do
|
||||||
print "Function";
|
print "Function";
|
||||||
end
|
end;
|
||||||
|
|
||||||
|
|
||||||
function_factory :: fn() do
|
function_factory :: fn(): Any do
|
||||||
print "Function Factory";
|
print "Function Factory";
|
||||||
function
|
function;
|
||||||
end
|
end;
|
||||||
|
|
||||||
function_fatcoty_factory :: fn() do
|
function_fatcoty_factory :: fn(): Any do
|
||||||
print "Function Factory Factory";
|
print "Function Factory Factory";
|
||||||
return function_factory;
|
return function_factory;
|
||||||
end
|
end;
|
||||||
|
|
||||||
//function();
|
//function();
|
||||||
//function_factory()();
|
//function_factory()();
|
||||||
//function_fatcoty_factory()()();
|
//function_fatcoty_factory()()();
|
||||||
clock()
|
clock();
|
||||||
|
|
||||||
closure :: fn() do
|
closure :: fn(): Any do
|
||||||
value = "Closure";
|
value := "Closure";
|
||||||
internal :: fn() do
|
internal :: fn(): Nil do
|
||||||
print value;
|
print value;
|
||||||
end
|
end;
|
||||||
return internal;
|
return internal;
|
||||||
end
|
end;
|
||||||
|
|
||||||
closure()
|
closure();
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
|
||||||
|
Data :: struct {
|
||||||
|
number: Number,
|
||||||
|
string: String,
|
||||||
|
bool: Bool
|
||||||
|
};
|
||||||
|
|
||||||
|
Data.new :: fn(number: Number, string: String, bool: Bool) -> Self
|
||||||
|
do
|
||||||
|
return Self {
|
||||||
|
number: number,
|
||||||
|
string: string,
|
||||||
|
bool: bool
|
||||||
|
};
|
||||||
|
end;
|
||||||
|
|
||||||
|
Data.function :: fn(
|
||||||
|
self,
|
||||||
|
number: Number,
|
||||||
|
string: String,
|
||||||
|
bool: Bool,)
|
||||||
|
{number == 42} : Nil
|
||||||
|
do
|
||||||
|
self.number = number;
|
||||||
|
self.string = string;
|
||||||
|
self.bool = bool;
|
||||||
|
end;
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
|
||||||
|
statement -> print_statement
|
||||||
|
| return_statement
|
||||||
|
| break_statement
|
||||||
|
| block_statement
|
||||||
|
| var_statement
|
||||||
|
| if_statement
|
||||||
|
| while_statement
|
||||||
|
| for_statement
|
||||||
|
| expression_statement
|
||||||
|
|
||||||
|
print_statement -> "print" expression ";"
|
||||||
|
return_statement -> "return" expression? ";"
|
||||||
|
break_statement -> "break" ";"
|
||||||
|
block_statement -> "do" statement* "end"
|
||||||
|
expression_statement -> expression ";"?
|
||||||
|
|
||||||
|
; leading "var" optional; the ":" is required
|
||||||
|
var_statement -> "var"? IDENTIFIER ":" IDENTIFIER?
|
||||||
|
( variable_declaration
|
||||||
|
| function_declaration
|
||||||
|
| struct_declaration ) ; struct = WIP
|
||||||
|
variable_declaration -> ( "=" expression )? ";"
|
||||||
|
function_declaration -> ":" "fn" "(" parameters? ")" ( "{" expression "}" )? statement
|
||||||
|
parameters -> IDENTIFIER ( ":" IDENTIFIER )?
|
||||||
|
( "," IDENTIFIER ( ":" IDENTIFIER )? )*
|
||||||
|
|
||||||
|
if_statement -> "if" expression "then" statement
|
||||||
|
( "elif" expression "then" statement )*
|
||||||
|
( "else" statement )?
|
||||||
|
while_statement -> "while" expression statement
|
||||||
|
for_statement -> "for" var_statement expression ";" expression_statement statement
|
||||||
|
|
||||||
|
; ---------- expressions (lowest -> highest precedence) ----------
|
||||||
|
expression -> assignment
|
||||||
|
assignment -> IDENTIFIER "=" assignment ; right-associative
|
||||||
|
| pipe
|
||||||
|
pipe -> logic ( "|>" logic )* ; left-assoc; x |> f(a) == f(x, a)
|
||||||
|
logic -> is ( ( "or" | "and" ) is )*
|
||||||
|
is -> equality ( "is" equality )*
|
||||||
|
equality -> comparison ( ( "==" | "!=" ) comparison )*
|
||||||
|
comparison -> term ( ( ">" | ">=" | "<" | "<=" ) term )*
|
||||||
|
term -> factor ( ( "+" | "-" ) factor )*
|
||||||
|
factor -> unary ( ( "*" | "/" ) unary )*
|
||||||
|
unary -> ( "!" | "-" ) unary | call
|
||||||
|
call -> primary ( "(" arguments? ")" )*
|
||||||
|
arguments -> expression ( "," expression )*
|
||||||
|
primary -> NUMBER | STRING | "true" | "false" | "nil"
|
||||||
|
| "(" expression ")" | IDENTIFIER
|
||||||
|
| dictionary | list | ATOM ; WIP
|
||||||
|
|
||||||
|
; ---------- work in progress (lexed; parser support being added) ----------
|
||||||
|
struct_declaration -> "struct" "{" field* "}"
|
||||||
|
field -> IDENTIFIER ( ":" IDENTIFIER )? ";"
|
||||||
|
dictionary -> "dict" "(" IDENTIFIER ":" expression
|
||||||
|
( "," IDENTIFIER ":" expression )* ")"
|
||||||
|
list -> "list" "(" expression ( "," expression )* ")"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "nightly"
|
||||||
@@ -48,7 +48,7 @@ impl<T: Clone + Debug + PartialEq> EnvironmentStack<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
runtime_error(
|
runtime_error(
|
||||||
SourceSlice::default(), // todo change this to the actual source slice
|
SourceSlice::synthetic(), // todo change this to the actual source slice
|
||||||
format!("Undefined variable '{}'", name),
|
format!("Undefined variable '{}'", name),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -58,6 +58,38 @@ impl<T: Clone + Debug + PartialEq> EnvironmentStack<T> {
|
|||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read a variable at a known scope `distance` from the innermost scope
|
||||||
|
/// (0 = innermost). Used with resolver-computed distances.
|
||||||
|
pub fn get_at(&self, distance: usize, name: &str) -> LoxResult<T> {
|
||||||
|
let index = self.stack.len().checked_sub(distance + 1);
|
||||||
|
match index
|
||||||
|
.and_then(|i| self.stack.get(i))
|
||||||
|
.and_then(|s| s.get(name))
|
||||||
|
{
|
||||||
|
Some(value) => Ok(value.clone()),
|
||||||
|
None => runtime_error(
|
||||||
|
SourceSlice::synthetic(),
|
||||||
|
format!("Undefined variable '{}'", name),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assign to a variable at a known scope `distance` from the innermost
|
||||||
|
/// scope (0 = innermost).
|
||||||
|
pub fn assign_at(&mut self, distance: usize, name: String, value: T) -> LoxResult<T> {
|
||||||
|
let index = self.stack.len().checked_sub(distance + 1);
|
||||||
|
match index {
|
||||||
|
Some(i) if i < self.stack.len() => {
|
||||||
|
self.stack[i].insert(name, value.clone());
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
_ => runtime_error(
|
||||||
|
SourceSlice::synthetic(),
|
||||||
|
format!("Undefined variable '{}'", name),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set(&mut self, name: String, value: T) -> LoxResult<T> {
|
pub fn set(&mut self, name: String, value: T) -> LoxResult<T> {
|
||||||
let size = self.stack.len();
|
let size = self.stack.len();
|
||||||
|
|
||||||
@@ -75,7 +107,7 @@ impl<T: Clone + Debug + PartialEq> EnvironmentStack<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
runtime_error(
|
runtime_error(
|
||||||
SourceSlice::default(), // todo change this to the actual source slice
|
SourceSlice::synthetic(), // todo change this to the actual source slice
|
||||||
format!("Undefined variable '{}'", name),
|
format!("Undefined variable '{}'", name),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+184
-180
@@ -1,79 +1,30 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
backend::environment::EnvironmentStack,
|
backend::environment::EnvironmentStack,
|
||||||
common::{
|
common::{
|
||||||
ast::{AstNode, AstNodeKind, Expr, Stmt},
|
ast::{AstNode, Expr, NodeId},
|
||||||
base_value::{BaseValue, NativeFunction, Number, Truthy},
|
base_value::{BaseValue, NativeFunction, Number, Struct, Truthy},
|
||||||
lox_result::{runtime_error, LoxError, LoxResult},
|
lox_result::{LoxError, LoxResult, runtime_error},
|
||||||
|
types::Type,
|
||||||
},
|
},
|
||||||
frontend::{source_registry::SourceSlice, tokens::TokenType},
|
frontend::{source_registry::SourceSlice, tokens::TokenType},
|
||||||
};
|
};
|
||||||
use std::fmt::{Debug, Display};
|
use std::collections::HashMap;
|
||||||
|
|
||||||
pub struct Interpreter {
|
pub struct Interpreter {
|
||||||
enviorment: EnvironmentStack<BaseValue>,
|
enviorment: EnvironmentStack<BaseValue>,
|
||||||
|
/// Per-reference scope distances from the resolver. Empty means "no
|
||||||
|
/// resolution pass was run", in which case lookups fall back to a dynamic
|
||||||
|
/// search of the scope chain.
|
||||||
|
locals: HashMap<NodeId, usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait EvaluateInterpreter<T> {
|
pub trait EvaluateInterpreter<T> {
|
||||||
fn evaluate(&mut self, stmt: T) -> LoxResult<BaseValue>;
|
fn evaluate(&mut self, stmt: T) -> LoxResult<BaseValue>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: AstNodeKind + Clone + Debug + Display> EvaluateInterpreter<AstNode<R>> for Interpreter
|
impl EvaluateInterpreter<AstNode> for Interpreter {
|
||||||
where
|
fn evaluate(&mut self, node: AstNode) -> LoxResult<BaseValue> {
|
||||||
Interpreter: EvaluateInterpreter<R>,
|
self.eval_expr(&node)
|
||||||
{
|
|
||||||
fn evaluate(&mut self, stmt: AstNode<R>) -> LoxResult<BaseValue> {
|
|
||||||
match self.evaluate(stmt.node.clone()) {
|
|
||||||
Ok(value) => Ok(value),
|
|
||||||
Err(err) => runtime_error(stmt.source_slice, err.get_message()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Direct Expr evaluation to avoid infinite recursion
|
|
||||||
impl EvaluateInterpreter<Expr> for Interpreter {
|
|
||||||
fn evaluate(&mut self, expr: Expr) -> LoxResult<BaseValue> {
|
|
||||||
match expr {
|
|
||||||
Expr::Literal { value } => match value {
|
|
||||||
BaseValue::Function(mut func) => {
|
|
||||||
func.closure = Some(self.enviorment.clone());
|
|
||||||
Ok(BaseValue::Function(func))
|
|
||||||
}
|
|
||||||
_ => Ok(value),
|
|
||||||
},
|
|
||||||
Expr::Identifier { name } => self.enviorment.get(&name),
|
|
||||||
Expr::Binary {
|
|
||||||
left,
|
|
||||||
operator,
|
|
||||||
right,
|
|
||||||
} => {
|
|
||||||
let left_val = self.evaluate(*left)?;
|
|
||||||
let right_val = self.evaluate(*right)?;
|
|
||||||
self.evaluate_binary(left_val, operator, right_val)
|
|
||||||
}
|
|
||||||
Expr::Unary { operator, operand } => {
|
|
||||||
let operand_val = self.evaluate(*operand)?;
|
|
||||||
self.evaluate_unary(operator, operand_val)
|
|
||||||
}
|
|
||||||
Expr::Grouping { expression } => self.evaluate(*expression),
|
|
||||||
Expr::Call { callee, arguments } => self.evaluate_call(callee, arguments),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EvaluateInterpreter<AstNode<Stmt>> for Interpreter {
|
|
||||||
fn evaluate(&mut self, node: AstNode<Stmt>) -> LoxResult<BaseValue> {
|
|
||||||
let stmt = node.node;
|
|
||||||
let result = self.interpret_stmt_inner(stmt);
|
|
||||||
match result {
|
|
||||||
Ok(value) => Ok(value),
|
|
||||||
Err(LoxError::RuntimeError {
|
|
||||||
message,
|
|
||||||
source_slice,
|
|
||||||
}) if source_slice == SourceSlice::default() => {
|
|
||||||
runtime_error(node.source_slice.clone(), message)
|
|
||||||
}
|
|
||||||
Err(err) => Err(err),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,36 +33,166 @@ impl Interpreter {
|
|||||||
let mut env = EnvironmentStack::new();
|
let mut env = EnvironmentStack::new();
|
||||||
let _ = env.declare(
|
let _ = env.declare(
|
||||||
"clock".to_string(),
|
"clock".to_string(),
|
||||||
BaseValue::NativeFunction(NativeFunction::new(Vec::default(), |_args| {
|
BaseValue::NativeFunction(Box::new(NativeFunction::new(Vec::default(), |_args| {
|
||||||
BaseValue::Number(Number::U128(
|
BaseValue::Number(Number::U128(
|
||||||
std::time::SystemTime::now()
|
std::time::SystemTime::now()
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.as_millis(),
|
.as_millis(),
|
||||||
))
|
))
|
||||||
})),
|
}))),
|
||||||
);
|
);
|
||||||
Self { enviorment: env }
|
Self {
|
||||||
|
enviorment: env,
|
||||||
|
locals: HashMap::new(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fn evaluate_call(
|
|
||||||
|
/// Install the resolver's per-reference scope distances.
|
||||||
|
pub fn set_locals(&mut self, locals: HashMap<NodeId, usize>) {
|
||||||
|
self.locals = locals;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluate an expression node, threading its `NodeId` so resolved
|
||||||
|
/// variables and assignments can use their precomputed scope distance.
|
||||||
|
fn eval_expr(&mut self, node: &AstNode) -> LoxResult<BaseValue> {
|
||||||
|
let result = match &node.node {
|
||||||
|
Expr::Literal { value } => match &**value {
|
||||||
|
BaseValue::Function(func) => {
|
||||||
|
let mut func = func.clone();
|
||||||
|
func.closure = Some(self.enviorment.clone());
|
||||||
|
Ok(BaseValue::Function(func))
|
||||||
|
}
|
||||||
|
other => Ok(other.clone()),
|
||||||
|
},
|
||||||
|
Expr::Identifier { name } => self.look_up_variable(name, node.id),
|
||||||
|
Expr::Binary {
|
||||||
|
left,
|
||||||
|
operator,
|
||||||
|
right,
|
||||||
|
} => {
|
||||||
|
let left_val = self.eval_expr(left)?;
|
||||||
|
let right_val = self.eval_expr(right)?;
|
||||||
|
self.evaluate_binary(left_val, operator.clone(), right_val)
|
||||||
|
}
|
||||||
|
Expr::Unary { operator, operand } => {
|
||||||
|
let operand_val = self.eval_expr(operand)?;
|
||||||
|
self.evaluate_unary(operator.clone(), operand_val)
|
||||||
|
}
|
||||||
|
Expr::Grouping { expression } => self.eval_expr(expression),
|
||||||
|
Expr::Call { callee, arguments } => self.evaluate_call(callee, arguments),
|
||||||
|
Expr::Assign { name, value } => {
|
||||||
|
let value = self.eval_expr(value)?;
|
||||||
|
self.assign_variable(name, node.id, value)
|
||||||
|
}
|
||||||
|
Expr::Print { expression } => {
|
||||||
|
let value = self.eval_expr(expression)?;
|
||||||
|
println!("{}", value);
|
||||||
|
Ok(BaseValue::Nil)
|
||||||
|
}
|
||||||
|
Expr::VarDeclaration {
|
||||||
|
name, initializer, ..
|
||||||
|
} => {
|
||||||
|
let value = match initializer {
|
||||||
|
Some(expr_node) => self.eval_expr(expr_node)?,
|
||||||
|
None => BaseValue::Nil,
|
||||||
|
};
|
||||||
|
self.enviorment.declare(name.clone(), value)
|
||||||
|
}
|
||||||
|
Expr::Return { expression, .. } => self.eval_expr(expression),
|
||||||
|
Expr::Block { statements, .. } => self.evaluate_block(statements),
|
||||||
|
Expr::If {
|
||||||
|
condition,
|
||||||
|
then_branch,
|
||||||
|
elif_branches,
|
||||||
|
else_branch,
|
||||||
|
} => self.evaluate_if(condition, then_branch, elif_branches, else_branch),
|
||||||
|
Expr::While { condition, body } => {
|
||||||
|
let mut ret = BaseValue::Nil;
|
||||||
|
while self.eval_expr(condition)?.is_truthy() {
|
||||||
|
match self.eval_expr(body) {
|
||||||
|
Ok(val) => ret = val,
|
||||||
|
Err(LoxError::Return { value, .. }) => {
|
||||||
|
ret = *value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(err) => return Err(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(ret)
|
||||||
|
}
|
||||||
|
Expr::For {
|
||||||
|
variable,
|
||||||
|
condition,
|
||||||
|
increment,
|
||||||
|
body,
|
||||||
|
} => {
|
||||||
|
let source_slice = variable.source_slice.clone();
|
||||||
|
let val = self.eval_expr(variable)?;
|
||||||
|
if !matches!(val, BaseValue::Number(..)) {
|
||||||
|
return runtime_error(source_slice, "Expected number literal");
|
||||||
|
}
|
||||||
|
let mut ret = BaseValue::Nil;
|
||||||
|
while self.eval_expr(condition)?.is_truthy() {
|
||||||
|
match self.eval_expr(body) {
|
||||||
|
Ok(val) => ret = val,
|
||||||
|
Err(LoxError::Return { value, .. }) => {
|
||||||
|
ret = *value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(err) => return Err(err),
|
||||||
|
};
|
||||||
|
self.eval_expr(increment)?;
|
||||||
|
}
|
||||||
|
Ok(ret)
|
||||||
|
}
|
||||||
|
Expr::Struct { fields } => {
|
||||||
|
let fields: Vec<(String, Type)> = fields
|
||||||
|
.iter()
|
||||||
|
.map(|(name, ty)| (name.clone(), ty.clone()))
|
||||||
|
.collect();
|
||||||
|
Ok(BaseValue::Struct(Box::new(Struct { fields })))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Give location-less runtime errors this node's span.
|
||||||
|
match result {
|
||||||
|
Err(LoxError::RuntimeError {
|
||||||
|
message,
|
||||||
|
source_slice,
|
||||||
|
}) if source_slice.is_synthetic() => runtime_error(node.source_slice.clone(), message),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Look up a variable: by resolved distance if known, else dynamically.
|
||||||
|
fn look_up_variable(&self, name: &str, id: NodeId) -> LoxResult<BaseValue> {
|
||||||
|
match self.locals.get(&id) {
|
||||||
|
Some(&distance) => self.enviorment.get_at(distance, name),
|
||||||
|
None => self.enviorment.get(name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assign a variable: at its resolved distance if known, else dynamically.
|
||||||
|
fn assign_variable(
|
||||||
&mut self,
|
&mut self,
|
||||||
callee: Box<AstNode<Expr>>,
|
name: &str,
|
||||||
arguments: Vec<AstNode<Expr>>,
|
id: NodeId,
|
||||||
|
value: BaseValue,
|
||||||
) -> LoxResult<BaseValue> {
|
) -> LoxResult<BaseValue> {
|
||||||
|
match self.locals.get(&id) {
|
||||||
|
Some(&distance) => self.enviorment.assign_at(distance, name.to_string(), value),
|
||||||
|
None => self.enviorment.set(name.to_string(), value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evaluate_call(&mut self, callee: &AstNode, arguments: &[AstNode]) -> LoxResult<BaseValue> {
|
||||||
let source_slice = callee.source_slice.clone();
|
let source_slice = callee.source_slice.clone();
|
||||||
|
|
||||||
// Estrai il nome della variabile se il callee è un identificatore
|
// A bare identifier callee resolves through `locals`; anything else is
|
||||||
let function_name = match &callee.node {
|
// evaluated as a general expression.
|
||||||
Expr::Identifier { name } => Some(name.clone()),
|
let function = match &callee.node {
|
||||||
_ => None,
|
Expr::Identifier { name } => self.look_up_variable(name, callee.id)?,
|
||||||
};
|
_ => self.eval_expr(callee)?,
|
||||||
|
|
||||||
let function = if let Some(name) = function_name {
|
|
||||||
// Se abbiamo un nome di variabile, ottieni la funzione dall'ambiente
|
|
||||||
self.enviorment.get(&name)?
|
|
||||||
} else {
|
|
||||||
// Altrimenti valuta l'espressione callee (per casi più complessi)
|
|
||||||
self.evaluate(*callee)?
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if !function.is_callable() {
|
if !function.is_callable() {
|
||||||
@@ -120,7 +201,7 @@ impl Interpreter {
|
|||||||
|
|
||||||
let evaluated_arguments = arguments
|
let evaluated_arguments = arguments
|
||||||
.iter()
|
.iter()
|
||||||
.map(|arg| self.evaluate(arg.clone()))
|
.map(|arg| self.eval_expr(arg))
|
||||||
.collect::<Result<Vec<BaseValue>, LoxError>>()?;
|
.collect::<Result<Vec<BaseValue>, LoxError>>()?;
|
||||||
|
|
||||||
match function {
|
match function {
|
||||||
@@ -142,9 +223,9 @@ impl Interpreter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Execute the function body
|
// Execute the function body
|
||||||
let result = match self.evaluate(func.body) {
|
let result = match self.eval_expr(&func.body) {
|
||||||
Ok(value) => Ok(value),
|
Ok(value) => Ok(value),
|
||||||
Err(LoxError::Return { value, .. }) => Ok(value),
|
Err(LoxError::Return { value, .. }) => Ok(*value),
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -180,7 +261,7 @@ impl Interpreter {
|
|||||||
TokenType::And => Ok(BaseValue::Boolean(left.is_truthy() && right.is_truthy())),
|
TokenType::And => Ok(BaseValue::Boolean(left.is_truthy() && right.is_truthy())),
|
||||||
TokenType::Or => Ok(BaseValue::Boolean(left.is_truthy() || right.is_truthy())),
|
TokenType::Or => Ok(BaseValue::Boolean(left.is_truthy() || right.is_truthy())),
|
||||||
_ => Err(LoxError::RuntimeError {
|
_ => Err(LoxError::RuntimeError {
|
||||||
source_slice: SourceSlice::default(),
|
source_slice: SourceSlice::synthetic(),
|
||||||
message: format!("Unsupported binary operator: {:?}", operator),
|
message: format!("Unsupported binary operator: {:?}", operator),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
@@ -191,114 +272,39 @@ impl Interpreter {
|
|||||||
TokenType::Minus => match operand {
|
TokenType::Minus => match operand {
|
||||||
BaseValue::Number(n) => Ok(BaseValue::Number(n.neg())),
|
BaseValue::Number(n) => Ok(BaseValue::Number(n.neg())),
|
||||||
_ => Err(LoxError::RuntimeError {
|
_ => Err(LoxError::RuntimeError {
|
||||||
source_slice: SourceSlice::default(),
|
source_slice: SourceSlice::synthetic(),
|
||||||
message: "Cannot negate non-numeric value".to_string(),
|
message: "Cannot negate non-numeric value".to_string(),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
TokenType::Bang => Ok(!operand),
|
TokenType::Bang => Ok(!operand),
|
||||||
_ => Err(LoxError::RuntimeError {
|
_ => Err(LoxError::RuntimeError {
|
||||||
source_slice: SourceSlice::default(),
|
source_slice: SourceSlice::synthetic(),
|
||||||
message: format!("Unsupported unary operator: {:?}", operator),
|
message: format!("Unsupported unary operator: {:?}", operator),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn interpret_stmt_inner(&mut self, stmt: Stmt) -> LoxResult<BaseValue> {
|
|
||||||
match stmt {
|
|
||||||
Stmt::Expression { expression, .. } => self.evaluate(*expression),
|
|
||||||
Stmt::Print { expression, .. } => {
|
|
||||||
let value = self.evaluate(*expression)?;
|
|
||||||
println!("{}", value);
|
|
||||||
Ok(BaseValue::Nil)
|
|
||||||
}
|
|
||||||
Stmt::Block { statements, .. } => self.evaluate_block(*statements),
|
|
||||||
Stmt::Return { expression, .. } => self.evaluate(*expression),
|
|
||||||
Stmt::VarDeclaration {
|
|
||||||
name, initializer, ..
|
|
||||||
} => {
|
|
||||||
let value = match initializer {
|
|
||||||
Some(expr_node) => self.evaluate(*expr_node)?,
|
|
||||||
None => BaseValue::Nil,
|
|
||||||
};
|
|
||||||
self.enviorment.declare(name.clone(), value)
|
|
||||||
}
|
|
||||||
Stmt::VarAssigment { name, value, .. } => {
|
|
||||||
let result = self.evaluate(*value)?;
|
|
||||||
self.enviorment.set(name.clone(), result)
|
|
||||||
}
|
|
||||||
Stmt::If {
|
|
||||||
condition,
|
|
||||||
then_branch,
|
|
||||||
elif_branch,
|
|
||||||
else_branch,
|
|
||||||
..
|
|
||||||
} => self.evaluate_if(condition, then_branch, elif_branch, else_branch),
|
|
||||||
Stmt::While {
|
|
||||||
condition, body, ..
|
|
||||||
} => {
|
|
||||||
let mut ret = BaseValue::Nil;
|
|
||||||
while self.evaluate(*condition.clone())?.is_truthy() {
|
|
||||||
match self.evaluate(*body.clone()) {
|
|
||||||
Ok(val) => ret = val,
|
|
||||||
Err(LoxError::Return { value, .. }) => {
|
|
||||||
ret = value;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(err) => return Err(err),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Ok(ret)
|
|
||||||
}
|
|
||||||
Stmt::For {
|
|
||||||
variable,
|
|
||||||
condition,
|
|
||||||
increment,
|
|
||||||
body,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
let source_slice = variable.source_slice.clone();
|
|
||||||
let val = self.evaluate(*variable)?;
|
|
||||||
if !matches!(val, BaseValue::Number(..)) {
|
|
||||||
return runtime_error(source_slice, "Expected number literal");
|
|
||||||
}
|
|
||||||
let mut ret = BaseValue::Nil;
|
|
||||||
while self.evaluate(*condition.clone())?.is_truthy() {
|
|
||||||
match self.evaluate(*body.clone()) {
|
|
||||||
Ok(val) => ret = val,
|
|
||||||
Err(LoxError::Return { value, .. }) => {
|
|
||||||
ret = value;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(err) => return Err(err),
|
|
||||||
};
|
|
||||||
self.evaluate(*increment.clone())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(ret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn evaluate_if(
|
fn evaluate_if(
|
||||||
&mut self,
|
&mut self,
|
||||||
condition: Box<AstNode<Expr>>,
|
condition: &AstNode,
|
||||||
then_branch: Box<AstNode<Stmt>>,
|
then_branch: &AstNode,
|
||||||
elif_branch: Vec<(Box<AstNode<Expr>>, Box<AstNode<Stmt>>)>,
|
elif_branch: &[(Box<AstNode>, Box<AstNode>)],
|
||||||
else_branch: Option<Box<AstNode<Stmt>>>,
|
else_branch: &Option<Box<AstNode>>,
|
||||||
) -> LoxResult<BaseValue> {
|
) -> LoxResult<BaseValue> {
|
||||||
let condition = self.evaluate(*condition)?;
|
let condition = self.eval_expr(condition)?;
|
||||||
match condition {
|
match condition {
|
||||||
BaseValue::Boolean(true) => self.evaluate(*then_branch),
|
BaseValue::Boolean(true) => self.eval_expr(then_branch),
|
||||||
BaseValue::Boolean(false) => {
|
BaseValue::Boolean(false) => {
|
||||||
for (elif_condition, elif_then_branch) in elif_branch {
|
for (elif_condition, elif_then_branch) in elif_branch {
|
||||||
let condition = self.evaluate(*elif_condition)?;
|
let condition = self.eval_expr(elif_condition)?;
|
||||||
match condition {
|
match condition {
|
||||||
BaseValue::Boolean(true) => {
|
BaseValue::Boolean(true) => {
|
||||||
return self.evaluate(*elif_then_branch);
|
return self.eval_expr(elif_then_branch);
|
||||||
}
|
}
|
||||||
BaseValue::Boolean(false) => continue,
|
BaseValue::Boolean(false) => continue,
|
||||||
_ => {
|
_ => {
|
||||||
return Err(LoxError::TypeMismatch {
|
return Err(LoxError::TypeMismatch {
|
||||||
source_slice: SourceSlice::default(), // todo change this to the actual source slice
|
source_slice: SourceSlice::synthetic(), // todo change this to the actual source slice
|
||||||
expected: "boolean".to_string(),
|
expected: "boolean".to_string(),
|
||||||
found: condition.to_string(),
|
found: condition.to_string(),
|
||||||
});
|
});
|
||||||
@@ -306,38 +312,36 @@ impl Interpreter {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
if let Some(else_block) = else_branch {
|
if let Some(else_block) = else_branch {
|
||||||
self.evaluate(*else_block)
|
self.eval_expr(else_block)
|
||||||
} else {
|
} else {
|
||||||
Ok(BaseValue::Nil)
|
Ok(BaseValue::Nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Err(LoxError::TypeMismatch {
|
_ => Err(LoxError::TypeMismatch {
|
||||||
source_slice: SourceSlice::default(), // todo change this to the actual source slice
|
source_slice: SourceSlice::synthetic(), // todo change this to the actual source slice
|
||||||
expected: "boolean".to_string(),
|
expected: "boolean".to_string(),
|
||||||
found: condition.to_string(),
|
found: condition.to_string(),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn evaluate_block(&mut self, statements: Vec<AstNode<Stmt>>) -> LoxResult<BaseValue> {
|
fn evaluate_block(&mut self, statements: &[AstNode]) -> LoxResult<BaseValue> {
|
||||||
self.enviorment.push_new_scope();
|
self.enviorment.push_new_scope();
|
||||||
|
|
||||||
// Ora elements è sempre disponibile
|
|
||||||
let mut result = Ok(BaseValue::Nil);
|
let mut result = Ok(BaseValue::Nil);
|
||||||
for statement in statements.iter() {
|
for statement in statements.iter() {
|
||||||
let node = statement.node.clone();
|
match &statement.node {
|
||||||
match node {
|
Expr::Return { expression, .. } => {
|
||||||
Stmt::Return { expression, .. } => {
|
let value = self.eval_expr(expression)?;
|
||||||
let value = self.evaluate(*expression)?;
|
|
||||||
|
|
||||||
result = Err(LoxError::Return {
|
result = Err(LoxError::Return {
|
||||||
source_slice: statement.source_slice.clone(),
|
source_slice: statement.source_slice.clone(),
|
||||||
value: value,
|
value: Box::new(value),
|
||||||
return_label: "Hi".to_string(),
|
return_label: "Hi".to_string(),
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
_ => result = self.evaluate((*statement).clone()),
|
_ => result = self.eval_expr(statement),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
self.enviorment.pop_scope();
|
self.enviorment.pop_scope();
|
||||||
@@ -460,7 +464,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn defines_and_calls_a_function() {
|
fn defines_and_calls_a_function() {
|
||||||
let src = "add :: fn (a, b) do return a + b; end add(2, 3);";
|
let src = "add :: fn (a, b): Number do return a + b; end; add(2, 3);";
|
||||||
assert_eq!(eval(src).unwrap().to_string(), "5");
|
assert_eq!(eval(src).unwrap().to_string(), "5");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+138
-346
@@ -1,65 +1,93 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
common::base_value::BaseValue,
|
common::{base_value::BaseValue, types::Type},
|
||||||
frontend::{source_registry::SourceSlice, tokens::TokenType},
|
frontend::{source_registry::SourceSlice, tokens::TokenType},
|
||||||
};
|
};
|
||||||
use std::fmt::{Debug, Display};
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
/*
|
use std::{
|
||||||
* grammar:
|
collections::HashMap,
|
||||||
* program -> statement* EOF
|
fmt::{Debug, Display},
|
||||||
* statement -> expression_statement
|
};
|
||||||
* | print_statement
|
|
||||||
* | var_statement
|
/// A unique identity for an AST node, assigned once at construction.
|
||||||
* | block_statement
|
///
|
||||||
* | assignment_statement
|
/// Unlike a [`SourceSlice`] (which describes *where* a node is, for
|
||||||
* | if_statement
|
/// diagnostics), a `NodeId` describes *which* node it is. It is stable across
|
||||||
*
|
/// clones, so analyses such as the resolver can key per-reference data on it
|
||||||
* expression_statement -> expression ";"
|
/// without relying on source positions being unique.
|
||||||
* print_statement -> "print" expression ";"
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
* var_statement -> ("var"|"dyn"|"mut")? IDENTIFIER (":" IDENTIFIER)? (("=" expression)? ";")| function_declaration
|
pub struct NodeId(pub usize);
|
||||||
* function_declaration -> "::" "(" parameters? ")" ("->" IDENTIFIER)? block_statement
|
|
||||||
* parameters -> ( IDENTIFIER (":" IDENTIFIER)? ("," IDENTIFIER (":" IDENTIFIER)? )* )
|
static NEXT_NODE_ID: AtomicUsize = AtomicUsize::new(0);
|
||||||
* assignment_statement -> IDENTIFIER "=" expression ";"
|
|
||||||
* block_statement -> "do" statement* "end"
|
impl NodeId {
|
||||||
* if_statement -> "if" expression "then" statement ("elif" expression "then" statement)* ("else" statement)? "end"
|
/// Allocate the next globally-unique node id.
|
||||||
* while_statement -> "while" expression "do" statement "end"
|
pub fn next() -> Self {
|
||||||
*
|
NodeId(NEXT_NODE_ID.fetch_add(1, Ordering::Relaxed))
|
||||||
* expression -> assignment
|
}
|
||||||
* assignment -> IDENTIFIER "=" assignment | logical_or
|
}
|
||||||
* logical_or -> logical_and (("or" logical_and)*
|
|
||||||
* logical_and -> logical_is (("and" logical_is)*
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
* logical_is -> equality (("is" equality)*
|
|
||||||
* equality -> comparison (("==" | "!=") comparison)*
|
|
||||||
* comparison -> term ((">" | ">=" | "<" | "<=") term)*
|
|
||||||
* term -> factor (("+" | "-") factor)*
|
|
||||||
* factor -> unary (("*" | "/") unary)*
|
|
||||||
* unary -> ("!" | "-") unary | call
|
|
||||||
* call -> primary ("(" arguments ")")*
|
|
||||||
* arguments -> expression ("," expression)*
|
|
||||||
* primary -> NUMBER | STRING | "true" | "false" | "nil" | "(" expression ")" | IDENTIFIER
|
|
||||||
*/
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
pub enum Expr {
|
pub enum Expr {
|
||||||
Literal {
|
Literal {
|
||||||
value: BaseValue,
|
value: Box<BaseValue>,
|
||||||
},
|
},
|
||||||
Binary {
|
Binary {
|
||||||
left: Box<AstNode<Expr>>,
|
left: Box<AstNode>,
|
||||||
operator: TokenType,
|
operator: TokenType,
|
||||||
right: Box<AstNode<Expr>>,
|
right: Box<AstNode>,
|
||||||
},
|
},
|
||||||
Unary {
|
Unary {
|
||||||
operator: TokenType,
|
operator: TokenType,
|
||||||
operand: Box<AstNode<Expr>>,
|
operand: Box<AstNode>,
|
||||||
},
|
},
|
||||||
Grouping {
|
Grouping {
|
||||||
expression: Box<AstNode<Expr>>,
|
expression: Box<AstNode>,
|
||||||
},
|
},
|
||||||
Identifier {
|
Identifier {
|
||||||
name: String,
|
name: String,
|
||||||
},
|
},
|
||||||
Call {
|
Call {
|
||||||
callee: Box<AstNode<Expr>>,
|
callee: Box<AstNode>,
|
||||||
arguments: Vec<AstNode<Expr>>,
|
arguments: Vec<AstNode>,
|
||||||
|
},
|
||||||
|
Assign {
|
||||||
|
name: String,
|
||||||
|
value: Box<AstNode>,
|
||||||
|
},
|
||||||
|
Print {
|
||||||
|
expression: Box<AstNode>,
|
||||||
|
},
|
||||||
|
VarDeclaration {
|
||||||
|
name: String,
|
||||||
|
var_type: Type,
|
||||||
|
initializer: Option<Box<AstNode>>,
|
||||||
|
},
|
||||||
|
Return {
|
||||||
|
expression: Box<AstNode>,
|
||||||
|
label: String,
|
||||||
|
},
|
||||||
|
Block {
|
||||||
|
statements: Box<Vec<AstNode>>,
|
||||||
|
label: String,
|
||||||
|
},
|
||||||
|
If {
|
||||||
|
condition: Box<AstNode>,
|
||||||
|
then_branch: Box<AstNode>,
|
||||||
|
elif_branches: Vec<(Box<AstNode>, Box<AstNode>)>,
|
||||||
|
else_branch: Option<Box<AstNode>>,
|
||||||
|
},
|
||||||
|
While {
|
||||||
|
condition: Box<AstNode>,
|
||||||
|
body: Box<AstNode>,
|
||||||
|
},
|
||||||
|
For {
|
||||||
|
variable: Box<AstNode>,
|
||||||
|
condition: Box<AstNode>,
|
||||||
|
increment: Box<AstNode>,
|
||||||
|
body: Box<AstNode>,
|
||||||
|
},
|
||||||
|
Struct {
|
||||||
|
fields: Box<HashMap<String, Type>>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,8 +102,10 @@ impl std::fmt::Display for Expr {
|
|||||||
right,
|
right,
|
||||||
} => write!(f, "Binary ({} {} {})", left.node, operator, right.node),
|
} => write!(f, "Binary ({} {} {})", left.node, operator, right.node),
|
||||||
Expr::Unary { operator, operand } => write!(f, "Unary ({} {})", operator, operand.node),
|
Expr::Unary { operator, operand } => write!(f, "Unary ({} {})", operator, operand.node),
|
||||||
Expr::Grouping { expression } => write!(f, "Grouping (group {})", expression.node),
|
Expr::Grouping { expression } => write!(f, "Grouping (group {})", expression.node,),
|
||||||
Expr::Identifier { name } => write!(f, "Identifier (variable {})", name),
|
Expr::Identifier { name } => {
|
||||||
|
write!(f, "Identifier (variable {})", name)
|
||||||
|
}
|
||||||
Expr::Call { callee, arguments } => write!(
|
Expr::Call { callee, arguments } => write!(
|
||||||
f,
|
f,
|
||||||
"Call ({}({}))",
|
"Call ({}({}))",
|
||||||
@@ -86,344 +116,92 @@ impl std::fmt::Display for Expr {
|
|||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
),
|
),
|
||||||
}
|
Expr::Assign { name, value } => write!(f, "Assign ({} = {})", name, value.node),
|
||||||
}
|
Expr::If {
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for Expr {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
Expr::Literal { value } => write!(f, "{:?}", value),
|
|
||||||
Expr::Binary {
|
|
||||||
left,
|
|
||||||
operator,
|
|
||||||
right,
|
|
||||||
} => write!(f, "({:?} {:?} {:?})", operator, left.node, right.node),
|
|
||||||
Expr::Unary { operator, operand } => write!(f, "({:?} {:?})", operator, operand.node),
|
|
||||||
Expr::Grouping { expression } => write!(f, "(group {:?})", expression.node),
|
|
||||||
Expr::Identifier { name } => write!(f, "(variable {:?})", name),
|
|
||||||
Expr::Call { callee, arguments } => write!(
|
|
||||||
f,
|
|
||||||
"Call ({}({}))",
|
|
||||||
callee.node,
|
|
||||||
arguments
|
|
||||||
.iter()
|
|
||||||
.map(|arg| arg.node.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
pub enum Stmt {
|
|
||||||
Expression {
|
|
||||||
expression: Box<AstNode<Expr>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
Print {
|
|
||||||
expression: Box<AstNode<Expr>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
VarDeclaration {
|
|
||||||
name: String,
|
|
||||||
initializer: Option<Box<AstNode<Expr>>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
VarAssigment {
|
|
||||||
name: String,
|
|
||||||
value: Box<AstNode<Expr>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
Return {
|
|
||||||
expression: Box<AstNode<Expr>>,
|
|
||||||
label: String,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
Block {
|
|
||||||
statements: Box<Vec<AstNode<Stmt>>>,
|
|
||||||
label: String,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
If {
|
|
||||||
condition: Box<AstNode<Expr>>,
|
|
||||||
then_branch: Box<AstNode<Stmt>>,
|
|
||||||
elif_branch: Vec<(Box<AstNode<Expr>>, Box<AstNode<Stmt>>)>,
|
|
||||||
else_branch: Option<Box<AstNode<Stmt>>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
While {
|
|
||||||
condition: Box<AstNode<Expr>>,
|
|
||||||
body: Box<AstNode<Stmt>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
For {
|
|
||||||
variable: Box<AstNode<Stmt>>,
|
|
||||||
condition: Box<AstNode<Expr>>,
|
|
||||||
increment: Box<AstNode<Stmt>>,
|
|
||||||
body: Box<AstNode<Stmt>>,
|
|
||||||
return_value: Box<BaseValue>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for Stmt {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
Stmt::Expression {
|
|
||||||
expression,
|
|
||||||
return_value,
|
|
||||||
} => write!(f, "Expression ({}) -> {:?}", expression.node, return_value),
|
|
||||||
Stmt::If {
|
|
||||||
condition,
|
condition,
|
||||||
then_branch,
|
then_branch,
|
||||||
elif_branch,
|
elif_branches,
|
||||||
else_branch,
|
else_branch,
|
||||||
return_value,
|
|
||||||
} => {
|
} => {
|
||||||
let mut result = format!("IF ({}) {{\n{}\n}}", condition.node, then_branch.node);
|
let mut result = format!("IF ({}) {{\n{}\n}}", condition.node, then_branch.node);
|
||||||
for (condition, branch) in elif_branch {
|
for (condition, branch) in elif_branches {
|
||||||
result.push_str(&format!(
|
result.push_str(&format!(
|
||||||
" ELIF ({}) {{\n{}\n}} -> {:?}",
|
" ELIF ({}) {{\n{}\n}}",
|
||||||
condition.node, branch.node, return_value
|
condition.node, branch.node,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if let Some(else_branch) = else_branch {
|
if let Some(else_branch) = else_branch {
|
||||||
result.push_str(&format!(
|
result.push_str(&format!(" ELSE {{\n{}\n}}", else_branch.node));
|
||||||
" ELSE {{\n{}\n}} -> {:?}",
|
|
||||||
else_branch.node, return_value
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
write!(f, "IfStmt {}", result)
|
write!(f, "IfStmt {}", result)
|
||||||
}
|
}
|
||||||
Stmt::Print {
|
Expr::Print { expression } => write!(f, "Print({})", expression.node),
|
||||||
expression,
|
Expr::VarDeclaration {
|
||||||
return_value,
|
|
||||||
} => write!(f, "Print({}) -> {:?};", expression.node, return_value),
|
|
||||||
Stmt::VarDeclaration {
|
|
||||||
name,
|
name,
|
||||||
initializer,
|
initializer,
|
||||||
return_value,
|
var_type,
|
||||||
} => match initializer {
|
} => match initializer {
|
||||||
Some(init) => write!(f, "Var({} = {}) -> {:?};", name, init.node, return_value),
|
Some(init) => write!(f, "Var({} : {:?} = {})", name, var_type, init.node),
|
||||||
None => write!(f, "Var({}) -> {:?};", name, return_value),
|
None => write!(f, "Var({} : {:?})", name, var_type),
|
||||||
},
|
},
|
||||||
Stmt::VarAssigment {
|
Expr::Return { expression, label } => {
|
||||||
name,
|
write!(f, "Return({}, {})", expression.node, label)
|
||||||
value,
|
}
|
||||||
return_value,
|
Expr::Block { statements, label } => write!(
|
||||||
} => write!(
|
|
||||||
f,
|
f,
|
||||||
"Assign({} = {}) -> {:?};",
|
"Block [{}] ([\n{}\n])",
|
||||||
name, value.node, return_value
|
|
||||||
),
|
|
||||||
Stmt::Return {
|
|
||||||
expression,
|
|
||||||
return_value,
|
|
||||||
label,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
"Return({}, {}) -> {:?};",
|
|
||||||
expression.node, label, return_value
|
|
||||||
),
|
|
||||||
Stmt::Block {
|
|
||||||
statements,
|
|
||||||
label,
|
|
||||||
return_value,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
"Block [{}] ([\n{}\n]) -> {:?}",
|
|
||||||
label,
|
label,
|
||||||
statements
|
statements
|
||||||
.iter()
|
.iter()
|
||||||
.map(|stmt| format!("\t \t{}", stmt.node))
|
.map(|stmt| format!("\t \t{}", stmt.node))
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("\n"),
|
.join("\n"),
|
||||||
return_value
|
|
||||||
),
|
),
|
||||||
Stmt::While {
|
Expr::While { condition, body } => {
|
||||||
condition,
|
write!(f, "While({}) {{\n{}\n}}", condition.node, body.node)
|
||||||
body,
|
|
||||||
return_value,
|
|
||||||
} => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"While({}) {{\n{}\n}} -> {:?}",
|
|
||||||
condition.node, body.node, return_value
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
Stmt::For {
|
Expr::For {
|
||||||
variable,
|
variable,
|
||||||
condition,
|
condition,
|
||||||
increment,
|
increment,
|
||||||
body,
|
body,
|
||||||
return_value,
|
|
||||||
} => write!(
|
} => write!(
|
||||||
f,
|
f,
|
||||||
"For({} = {} in {}) {{\n{}\n}} -> {:?}",
|
"For({} = {} in {}) {{\n{}\n}}",
|
||||||
variable.node, condition.node, increment.node, body.node, return_value
|
variable.node, condition.node, increment.node, body.node
|
||||||
),
|
),
|
||||||
}
|
Expr::Struct { fields } => {
|
||||||
}
|
let field_strs: Vec<String> = fields
|
||||||
}
|
|
||||||
|
|
||||||
impl Debug for Stmt {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
Stmt::Expression {
|
|
||||||
expression,
|
|
||||||
return_value,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
" Expression ({:?}) -> {:?}",
|
|
||||||
expression.node, return_value
|
|
||||||
),
|
|
||||||
Stmt::If {
|
|
||||||
condition,
|
|
||||||
then_branch,
|
|
||||||
elif_branch,
|
|
||||||
else_branch,
|
|
||||||
return_value,
|
|
||||||
} => {
|
|
||||||
let mut result = format!(
|
|
||||||
"IF ({:?}) {{\n{:?}\n}} -> {:?} ",
|
|
||||||
condition.node, then_branch.node, return_value
|
|
||||||
);
|
|
||||||
for (condition, branch) in elif_branch {
|
|
||||||
result.push_str(&format!(
|
|
||||||
" ELIF ({:?}) {{\n{:?}\n}} -> {:?} ",
|
|
||||||
condition.node, branch.node, return_value
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if let Some(else_branch) = else_branch {
|
|
||||||
result.push_str(&format!(
|
|
||||||
" ELSE {{\n{:?}\n}} -> {:?}",
|
|
||||||
else_branch.node, return_value
|
|
||||||
));
|
|
||||||
}
|
|
||||||
write!(f, "IfStmt {:?}", result)
|
|
||||||
}
|
|
||||||
Stmt::Print {
|
|
||||||
expression,
|
|
||||||
return_value,
|
|
||||||
} => write!(f, "Print({:?}) -> {:?};", expression.node, return_value),
|
|
||||||
Stmt::VarDeclaration {
|
|
||||||
name,
|
|
||||||
initializer,
|
|
||||||
return_value,
|
|
||||||
} => match initializer {
|
|
||||||
Some(init) => write!(
|
|
||||||
f,
|
|
||||||
"Var({:?} = {:?}) -> {:?};",
|
|
||||||
name, init.node, return_value
|
|
||||||
),
|
|
||||||
None => write!(f, "Var({:?}) -> {:?};", name, return_value),
|
|
||||||
},
|
|
||||||
Stmt::VarAssigment {
|
|
||||||
name,
|
|
||||||
value,
|
|
||||||
return_value,
|
|
||||||
} => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"Assign({:?} = {:?}) -> {:?};",
|
|
||||||
name, value.node, return_value
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Stmt::Return {
|
|
||||||
expression,
|
|
||||||
return_value,
|
|
||||||
label,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
"Return({:?}, {}) -> {:?};",
|
|
||||||
expression.node, label, return_value
|
|
||||||
),
|
|
||||||
Stmt::Block {
|
|
||||||
label,
|
|
||||||
statements,
|
|
||||||
return_value,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
"Block [{}] ([\n{:?}\n]) -> {:?}",
|
|
||||||
label,
|
|
||||||
statements
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|stmt| format!("{:?}", stmt.node))
|
.map(|(k, v)| format!("{}: {:?}", k, v))
|
||||||
.collect::<Vec<_>>()
|
.collect();
|
||||||
.join("\t\t\n"),
|
write!(f, "Struct {{ {} }}", field_strs.join(", "))
|
||||||
return_value
|
|
||||||
),
|
|
||||||
Stmt::While {
|
|
||||||
condition,
|
|
||||||
body,
|
|
||||||
return_value,
|
|
||||||
} => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"While({:?}) {{\n{:?}\n}} -> {:?}",
|
|
||||||
condition.node, body.node, return_value
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
Stmt::For {
|
|
||||||
variable,
|
|
||||||
condition,
|
|
||||||
increment,
|
|
||||||
body,
|
|
||||||
return_value,
|
|
||||||
} => write!(
|
|
||||||
f,
|
|
||||||
"For({:?} = {:?} in {:?}) {{\n{:?}\n}} -> {:?}",
|
|
||||||
variable.node, condition.node, increment.node, body.node, return_value
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait AstNodeKind {
|
// Debug is derived on Expr via #[derive(Debug)] above.
|
||||||
fn kind(&self) -> &'static str;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AstNodeKind for Expr {
|
#[derive(Clone)]
|
||||||
fn kind(&self) -> &'static str {
|
pub struct AstNode {
|
||||||
match self {
|
/// Stable identity, assigned at construction and preserved across clones.
|
||||||
Expr::Literal { value: _ } => "literal",
|
pub id: NodeId,
|
||||||
Expr::Binary {
|
pub node: Expr,
|
||||||
left: _,
|
pub is_statement: bool,
|
||||||
operator: _,
|
|
||||||
right: _,
|
|
||||||
} => "binary expression",
|
|
||||||
Expr::Unary { .. } => "unary expression",
|
|
||||||
Expr::Grouping { .. } => "grouping expression",
|
|
||||||
Expr::Identifier { .. } => "variable expression",
|
|
||||||
Expr::Call { .. } => "call expression",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AstNodeKind for Stmt {
|
|
||||||
fn kind(&self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Stmt::Expression { .. } => "expression",
|
|
||||||
Stmt::VarDeclaration { .. } => "variable declaration",
|
|
||||||
Stmt::VarAssigment { .. } => "assignment",
|
|
||||||
Stmt::Return { .. } => "return statement",
|
|
||||||
Stmt::Block { .. } => "block statement",
|
|
||||||
Stmt::If { .. } => "if statement",
|
|
||||||
Stmt::Print { .. } => "print statement",
|
|
||||||
Stmt::While { .. } => "while statement",
|
|
||||||
Stmt::For { .. } => "for statement",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Default)]
|
|
||||||
pub struct AstNode<T: AstNodeKind + Debug + Display> {
|
|
||||||
pub node: T,
|
|
||||||
pub source_slice: SourceSlice,
|
pub source_slice: SourceSlice,
|
||||||
|
pub return_type: Type,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AstNodeKind + Debug + Display> Display for AstNode<T> {
|
// Identity (`id`) deliberately does not participate in equality: two nodes are
|
||||||
|
// equal when their content and location match, regardless of node id.
|
||||||
|
impl PartialEq for AstNode {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.node == other.node && self.source_slice == other.source_slice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for AstNode {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
@@ -433,7 +211,7 @@ impl<T: AstNodeKind + Debug + Display> Display for AstNode<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AstNodeKind + Debug + Display> Debug for AstNode<T> {
|
impl Debug for AstNode {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
@@ -443,8 +221,22 @@ impl<T: AstNodeKind + Debug + Display> Debug for AstNode<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AstNodeKind + Debug + Display> AstNode<T> {
|
impl AstNode {
|
||||||
pub fn new(node: T, source_slice: SourceSlice) -> Self {
|
fn new(node: Expr, source_slice: SourceSlice, type_name: String, is_statement: bool) -> Self {
|
||||||
AstNode { node, source_slice }
|
AstNode {
|
||||||
|
id: NodeId::next(),
|
||||||
|
node,
|
||||||
|
is_statement,
|
||||||
|
source_slice,
|
||||||
|
return_type: Type::Unresolved(type_name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_statement(node: Expr, source_slice: SourceSlice) -> Self {
|
||||||
|
Self::new(node, source_slice, "Nil".to_string(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_expression(node: Expr, source_slice: SourceSlice, type_name: String) -> Self {
|
||||||
|
Self::new(node, source_slice, type_name, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-37
@@ -1,12 +1,13 @@
|
|||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use std::ops::{Add, Div, Mul, Not, Rem, Sub};
|
use std::ops::{Add, Div, Mul, Not, Rem, Sub};
|
||||||
|
use std::ptr::fn_addr_eq;
|
||||||
|
|
||||||
use crate::backend::environment::Environment;
|
use crate::common::lox_result::{LoxResult, runtime_error};
|
||||||
use crate::common::lox_result::{runtime_error, LoxResult};
|
use crate::common::types::Type;
|
||||||
use crate::{
|
use crate::{
|
||||||
backend::environment::EnvironmentStack,
|
backend::environment::EnvironmentStack, common::ast::AstNode,
|
||||||
common::ast::{AstNode, Expr, Stmt},
|
|
||||||
frontend::source_registry::SourceSlice,
|
frontend::source_registry::SourceSlice,
|
||||||
};
|
};
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -270,27 +271,26 @@ pub enum BaseValue {
|
|||||||
Number(Number),
|
Number(Number),
|
||||||
Boolean(bool),
|
Boolean(bool),
|
||||||
Nil,
|
Nil,
|
||||||
Function(LoxFunction),
|
Function(Box<LoxFunction>),
|
||||||
NativeFunction(NativeFunction),
|
NativeFunction(Box<NativeFunction>),
|
||||||
|
Struct(Box<Struct>),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Dict {
|
||||||
|
map: HashMap<String, BaseValue>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ReturnValue {
|
struct ReturnValue {
|
||||||
label: Vec<String>,
|
label: Vec<String>,
|
||||||
value: BaseValue,
|
value: Type,
|
||||||
}
|
|
||||||
|
|
||||||
impl ReturnValue {
|
|
||||||
pub fn new(label: Vec<String>, value: BaseValue) -> Self {
|
|
||||||
Self { label, value }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BaseValue {
|
impl BaseValue {
|
||||||
pub fn is_callable(&self) -> bool {
|
pub fn is_callable(&self) -> bool {
|
||||||
match self {
|
matches!(
|
||||||
BaseValue::Function(..) | BaseValue::NativeFunction(..) => true,
|
self,
|
||||||
_ => false,
|
BaseValue::Function(..) | BaseValue::NativeFunction(..)
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,39 +304,40 @@ impl Display for BaseValue {
|
|||||||
BaseValue::Nil => write!(f, "nil"),
|
BaseValue::Nil => write!(f, "nil"),
|
||||||
BaseValue::Function(..) => write!(f, "<fn lox function>"),
|
BaseValue::Function(..) => write!(f, "<fn lox function>"),
|
||||||
BaseValue::NativeFunction(..) => write!(f, "<native native function>"),
|
BaseValue::NativeFunction(..) => write!(f, "<native native function>"),
|
||||||
|
BaseValue::Struct(_) => write!(f, "<struct>"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct LoxFunction {
|
pub struct LoxFunction {
|
||||||
pub parameters: Vec<(String, String)>,
|
pub parameters: Vec<(String, Type)>,
|
||||||
pub return_type: Option<String>,
|
pub return_type: Type,
|
||||||
pub body: AstNode<Stmt>,
|
pub body: AstNode,
|
||||||
pub closure: Option<EnvironmentStack<BaseValue>>,
|
pub closure: Option<EnvironmentStack<BaseValue>>,
|
||||||
pub guard: Option<Box<AstNode<Expr>>>,
|
pub guard: Option<Box<AstNode>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LoxFunction {
|
impl LoxFunction {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
parameters: Vec<(String, String)>,
|
parameters: Vec<(String, Type)>,
|
||||||
body: AstNode<Stmt>,
|
body: AstNode,
|
||||||
closure: Option<EnvironmentStack<BaseValue>>,
|
closure: Option<EnvironmentStack<BaseValue>>,
|
||||||
guard: Option<Box<AstNode<Expr>>>,
|
guard: Option<Box<AstNode>>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
LoxFunction {
|
LoxFunction {
|
||||||
parameters,
|
parameters,
|
||||||
return_type: None,
|
return_type: Type::Any,
|
||||||
body,
|
body,
|
||||||
closure,
|
closure,
|
||||||
guard,
|
guard,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn anonymous_function(parameters: Vec<(String, String)>, body: AstNode<Stmt>) -> Self {
|
pub fn anonymous_function(parameters: Vec<(String, Type)>, body: AstNode) -> Self {
|
||||||
LoxFunction {
|
LoxFunction {
|
||||||
parameters,
|
parameters,
|
||||||
return_type: None,
|
return_type: Type::Any,
|
||||||
body,
|
body,
|
||||||
closure: None,
|
closure: None,
|
||||||
guard: None,
|
guard: None,
|
||||||
@@ -344,14 +345,19 @@ impl LoxFunction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NativeFunction {
|
pub struct NativeFunction {
|
||||||
pub parameters: Vec<(String, String)>,
|
pub parameters: Vec<(String, Type)>,
|
||||||
pub function: fn(&[BaseValue]) -> BaseValue,
|
pub function: fn(&[BaseValue]) -> BaseValue,
|
||||||
}
|
}
|
||||||
|
impl PartialEq for NativeFunction {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.parameters == other.parameters && fn_addr_eq(self.function, other.function)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl NativeFunction {
|
impl NativeFunction {
|
||||||
pub fn new(parameters: Vec<(String, String)>, function: fn(&[BaseValue]) -> BaseValue) -> Self {
|
pub fn new(parameters: Vec<(String, Type)>, function: fn(&[BaseValue]) -> BaseValue) -> Self {
|
||||||
NativeFunction {
|
NativeFunction {
|
||||||
parameters,
|
parameters,
|
||||||
function,
|
function,
|
||||||
@@ -359,6 +365,11 @@ impl NativeFunction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct Struct {
|
||||||
|
pub fields: Vec<(String, Type)>,
|
||||||
|
}
|
||||||
|
|
||||||
// Trait implementations for BaseValue
|
// Trait implementations for BaseValue
|
||||||
|
|
||||||
pub trait Truthy {
|
pub trait Truthy {
|
||||||
@@ -398,7 +409,7 @@ impl Add for BaseValue {
|
|||||||
Ok(BaseValue::String(format!("{}{}", a, b)))
|
Ok(BaseValue::String(format!("{}{}", a, b)))
|
||||||
}
|
}
|
||||||
_ => runtime_error(
|
_ => runtime_error(
|
||||||
SourceSlice::default(),
|
SourceSlice::synthetic(),
|
||||||
"Cannot add non-numeric values".to_string(),
|
"Cannot add non-numeric values".to_string(),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -428,7 +439,7 @@ impl Sub for BaseValue {
|
|||||||
match (self, other) {
|
match (self, other) {
|
||||||
(BaseValue::Number(a), BaseValue::Number(b)) => Ok(BaseValue::Number(a.sub(b))),
|
(BaseValue::Number(a), BaseValue::Number(b)) => Ok(BaseValue::Number(a.sub(b))),
|
||||||
_ => runtime_error(
|
_ => runtime_error(
|
||||||
SourceSlice::default(),
|
SourceSlice::synthetic(),
|
||||||
"Cannot subtract non-numeric values".to_string(),
|
"Cannot subtract non-numeric values".to_string(),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -442,10 +453,10 @@ impl Div for BaseValue {
|
|||||||
match (self, other) {
|
match (self, other) {
|
||||||
(BaseValue::Number(a), BaseValue::Number(b)) => match a.div(b) {
|
(BaseValue::Number(a), BaseValue::Number(b)) => match a.div(b) {
|
||||||
Some(result) => Ok(BaseValue::Number(result)),
|
Some(result) => Ok(BaseValue::Number(result)),
|
||||||
None => runtime_error(SourceSlice::default(), "Division by zero".to_string()),
|
None => runtime_error(SourceSlice::synthetic(), "Division by zero".to_string()),
|
||||||
},
|
},
|
||||||
_ => runtime_error(
|
_ => runtime_error(
|
||||||
SourceSlice::default(),
|
SourceSlice::synthetic(),
|
||||||
"Cannot divide non-numeric values".to_string(),
|
"Cannot divide non-numeric values".to_string(),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -459,7 +470,7 @@ impl Mul for BaseValue {
|
|||||||
match (self, other) {
|
match (self, other) {
|
||||||
(BaseValue::Number(a), BaseValue::Number(b)) => Ok(BaseValue::Number(a.mul(b))),
|
(BaseValue::Number(a), BaseValue::Number(b)) => Ok(BaseValue::Number(a.mul(b))),
|
||||||
_ => runtime_error(
|
_ => runtime_error(
|
||||||
SourceSlice::default(),
|
SourceSlice::synthetic(),
|
||||||
"Cannot multiply non-numeric values".to_string(),
|
"Cannot multiply non-numeric values".to_string(),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -473,10 +484,10 @@ impl Rem for BaseValue {
|
|||||||
match (self, other) {
|
match (self, other) {
|
||||||
(BaseValue::Number(a), BaseValue::Number(b)) => match a.rem(b) {
|
(BaseValue::Number(a), BaseValue::Number(b)) => match a.rem(b) {
|
||||||
Some(result) => Ok(BaseValue::Number(result)),
|
Some(result) => Ok(BaseValue::Number(result)),
|
||||||
None => runtime_error(SourceSlice::default(), "Division by zero".to_string()),
|
None => runtime_error(SourceSlice::synthetic(), "Division by zero".to_string()),
|
||||||
},
|
},
|
||||||
_ => runtime_error(
|
_ => runtime_error(
|
||||||
SourceSlice::default(),
|
SourceSlice::synthetic(),
|
||||||
"Cannot divide non-numeric values".to_string(),
|
"Cannot divide non-numeric values".to_string(),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ pub enum LoxError {
|
|||||||
},
|
},
|
||||||
Return {
|
Return {
|
||||||
source_slice: SourceSlice,
|
source_slice: SourceSlice,
|
||||||
value: BaseValue,
|
value: Box<BaseValue>,
|
||||||
return_label: String,
|
return_label: String,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -479,3 +479,90 @@ pub fn io_error<T>(message: impl Into<String>) -> LoxResult<T> {
|
|||||||
message: message.into(),
|
message: message.into(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Accumulates diagnostics during a pass instead of bailing on the first one.
|
||||||
|
///
|
||||||
|
/// Static analyses (e.g. the resolver) `report` problems and keep traversing so
|
||||||
|
/// the user sees every error at once, then surface them at the end.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct ErrorSink {
|
||||||
|
errors: Vec<LoxError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrorSink {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record a diagnostic and keep going.
|
||||||
|
pub fn report(&mut self, error: LoxError) {
|
||||||
|
self.errors.push(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_errors(&self) -> bool {
|
||||||
|
!self.errors.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn errors(&self) -> &[LoxError] {
|
||||||
|
&self.errors
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merge another sink's errors into this one (e.g. from a separate pass).
|
||||||
|
pub fn extend(&mut self, other: ErrorSink) {
|
||||||
|
self.errors.extend(other.errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_errors(self) -> Vec<LoxError> {
|
||||||
|
self.errors
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bridge to the single-error [`LoxResult`] API: `Ok` if empty, otherwise
|
||||||
|
/// the first reported error.
|
||||||
|
pub fn into_result(self) -> LoxResult<()> {
|
||||||
|
match self.errors.into_iter().next() {
|
||||||
|
Some(error) => Err(error),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::frontend::source_registry::SourceSlice;
|
||||||
|
|
||||||
|
fn parse_err(message: &str) -> LoxError {
|
||||||
|
LoxError::ParseError {
|
||||||
|
source_slice: SourceSlice::synthetic(),
|
||||||
|
message: message.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_sink_is_ok() {
|
||||||
|
let sink = ErrorSink::new();
|
||||||
|
assert!(!sink.has_errors());
|
||||||
|
assert!(sink.into_result().is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accumulates_multiple_errors() {
|
||||||
|
let mut sink = ErrorSink::new();
|
||||||
|
sink.report(parse_err("first"));
|
||||||
|
sink.report(parse_err("second"));
|
||||||
|
assert!(sink.has_errors());
|
||||||
|
assert_eq!(sink.errors().len(), 2);
|
||||||
|
assert!(sink.into_result().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extend_merges_sinks() {
|
||||||
|
let mut a = ErrorSink::new();
|
||||||
|
a.report(parse_err("a"));
|
||||||
|
let mut b = ErrorSink::new();
|
||||||
|
b.report(parse_err("b1"));
|
||||||
|
b.report(parse_err("b2"));
|
||||||
|
a.extend(b);
|
||||||
|
assert_eq!(a.into_errors().len(), 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod ast;
|
pub mod ast;
|
||||||
pub mod base_value;
|
pub mod base_value;
|
||||||
pub mod lox_result;
|
pub mod lox_result;
|
||||||
|
pub mod types;
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
use std::{fmt::Display, rc::Rc};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Type {
|
||||||
|
Any,
|
||||||
|
Number,
|
||||||
|
String,
|
||||||
|
Boolean,
|
||||||
|
Nil,
|
||||||
|
Function(FunctionType),
|
||||||
|
Struct(Rc<StructType>),
|
||||||
|
Unresolved(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Type {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Type::Any => write!(f, "any"),
|
||||||
|
Type::Number => write!(f, "number"),
|
||||||
|
Type::String => write!(f, "string"),
|
||||||
|
Type::Boolean => write!(f, "boolean"),
|
||||||
|
Type::Nil => write!(f, "nil"),
|
||||||
|
Type::Function(fun) => write!(f, "{}", fun),
|
||||||
|
Type::Struct(struct_) => write!(f, "{}", struct_),
|
||||||
|
Type::Unresolved(name) => write!(f, "{}", name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct FunctionType {
|
||||||
|
pub params: Vec<(String, Box<Type>)>,
|
||||||
|
pub return_type: Box<Type>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for FunctionType {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let rendered_params = self
|
||||||
|
.params
|
||||||
|
.iter()
|
||||||
|
.map(|(name, ty)| format!("{}: {}", name, ty))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
write!(f, "fn({}) -> {}", rendered_params, self.return_type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct StructType {
|
||||||
|
pub fields: Vec<(String, Box<Type>)>,
|
||||||
|
pub methods: Vec<(String, FunctionType)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for StructType {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let rendered_field = self
|
||||||
|
.fields
|
||||||
|
.iter()
|
||||||
|
.map(|(name, ty)| format!("{}: {}", name, ty))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
let rendered_method = self
|
||||||
|
.methods
|
||||||
|
.iter()
|
||||||
|
.map(|(name, ty)| format!("{}: {}", name, ty))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
write!(f, "struct {{ {}, {} }}", rendered_field, rendered_method)
|
||||||
|
}
|
||||||
|
}
|
||||||
+84
-51
@@ -1,12 +1,13 @@
|
|||||||
use crate::common::base_value::{BaseValue, Number};
|
use crate::common::base_value::{BaseValue, Number};
|
||||||
use crate::common::lox_result::{lexical_error, LoxError, LoxResult};
|
use crate::common::lox_result::{LoxError, LoxResult, lexical_error};
|
||||||
use crate::frontend::source_registry::{SourceId, SourcePosition, SourceSlice};
|
use crate::frontend::source_registry::{SourceId, SourcePosition, SourceSlice};
|
||||||
use crate::frontend::tokens::{Token, TokenType};
|
use crate::frontend::tokens::{Token, TokenType};
|
||||||
|
|
||||||
pub struct Lexer {
|
pub struct Lexer {
|
||||||
input: String,
|
input: String,
|
||||||
start_char: usize,
|
// Byte offsets into `input` (not char counts) so slicing is UTF-8 correct.
|
||||||
current_char: usize,
|
start: usize,
|
||||||
|
current: usize,
|
||||||
start_pos: SourcePosition,
|
start_pos: SourcePosition,
|
||||||
end_pos: SourcePosition,
|
end_pos: SourcePosition,
|
||||||
source_id: SourceId,
|
source_id: SourceId,
|
||||||
@@ -15,7 +16,7 @@ pub struct Lexer {
|
|||||||
fn get_keyword_token(word: &str) -> Option<TokenType> {
|
fn get_keyword_token(word: &str) -> Option<TokenType> {
|
||||||
match word {
|
match word {
|
||||||
"and" => Some(TokenType::And),
|
"and" => Some(TokenType::And),
|
||||||
"class" => Some(TokenType::Class),
|
"struct" => Some(TokenType::Struct),
|
||||||
"do" => Some(TokenType::StartBlock),
|
"do" => Some(TokenType::StartBlock),
|
||||||
"end" => Some(TokenType::EndBlock),
|
"end" => Some(TokenType::EndBlock),
|
||||||
"false" => Some(TokenType::False),
|
"false" => Some(TokenType::False),
|
||||||
@@ -48,28 +49,18 @@ impl Lexer {
|
|||||||
pub fn new(input: String, source_id: SourceId) -> Lexer {
|
pub fn new(input: String, source_id: SourceId) -> Lexer {
|
||||||
Lexer {
|
Lexer {
|
||||||
input,
|
input,
|
||||||
start_char: 0,
|
start: 0,
|
||||||
current_char: 0,
|
current: 0,
|
||||||
start_pos: SourcePosition::default(),
|
start_pos: SourcePosition::default(),
|
||||||
end_pos: SourcePosition::default(),
|
end_pos: SourcePosition::default(),
|
||||||
source_id,
|
source_id,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn advance_column(&mut self) {
|
|
||||||
self.current_char += 1;
|
|
||||||
self.end_pos.column += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn advance_line(&mut self) {
|
|
||||||
self.end_pos.line += 1;
|
|
||||||
self.end_pos.column = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn scans_tokens(&mut self) -> LoxResult<Vec<Token>> {
|
pub fn scans_tokens(&mut self) -> LoxResult<Vec<Token>> {
|
||||||
let mut tokens = Vec::new();
|
let mut tokens = Vec::new();
|
||||||
while !self.is_at_end() {
|
while !self.is_at_end() {
|
||||||
self.start_char = self.current_char;
|
self.start = self.current;
|
||||||
self.start_pos = self.end_pos.clone();
|
self.start_pos = self.end_pos.clone();
|
||||||
match self.scan_token() {
|
match self.scan_token() {
|
||||||
Ok(Some(token)) => tokens.push(token),
|
Ok(Some(token)) => tokens.push(token),
|
||||||
@@ -82,50 +73,49 @@ impl Lexer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn is_at_end(&self) -> bool {
|
fn is_at_end(&self) -> bool {
|
||||||
self.current_char >= self.input.len()
|
self.current >= self.input.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn advance(&mut self) -> char {
|
fn advance(&mut self) -> char {
|
||||||
self.advance_column();
|
let c = self.input[self.current..].chars().next().unwrap();
|
||||||
self.input.chars().nth(self.current_char - 1).unwrap()
|
self.current += c.len_utf8();
|
||||||
|
if c == '\n' {
|
||||||
|
self.end_pos.line += 1;
|
||||||
|
self.end_pos.column = 0;
|
||||||
|
} else {
|
||||||
|
self.end_pos.column += 1;
|
||||||
|
}
|
||||||
|
c
|
||||||
}
|
}
|
||||||
|
|
||||||
fn peek(&self) -> char {
|
fn peek(&self) -> char {
|
||||||
if self.is_at_end() {
|
self.input[self.current..].chars().next().unwrap_or('\0')
|
||||||
'\0'
|
|
||||||
} else {
|
|
||||||
self.input.chars().nth(self.current_char).unwrap()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn peek_next(&self) -> char {
|
fn peek_next(&self) -> char {
|
||||||
if self.current_char + 1 >= self.input.len() {
|
self.input[self.current..].chars().nth(1).unwrap_or('\0')
|
||||||
'\0'
|
|
||||||
} else {
|
|
||||||
self.input.chars().nth(self.current_char + 1).unwrap()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_token(&self, token_type: TokenType) -> Token {
|
fn make_token(&self, token_type: TokenType) -> Token {
|
||||||
let text = self.input[self.start_char..self.current_char].to_string();
|
let text = self.input[self.start..self.current].to_string();
|
||||||
Token::new(
|
Token::new(
|
||||||
token_type,
|
token_type,
|
||||||
text,
|
text,
|
||||||
SourceSlice::from_positions(
|
SourceSlice::from_positions(
|
||||||
self.source_id.clone(),
|
self.source_id,
|
||||||
self.start_pos.clone(),
|
self.start_pos.clone(),
|
||||||
self.end_pos.clone(),
|
self.end_pos.clone(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
fn make_token_with_literal(&self, token_type: TokenType, literal: BaseValue) -> Token {
|
fn make_token_with_literal(&self, token_type: TokenType, literal: BaseValue) -> Token {
|
||||||
let text = self.input[self.start_char..self.current_char].to_string();
|
let text = self.input[self.start..self.current].to_string();
|
||||||
Token::new_complete(
|
Token::new_complete(
|
||||||
token_type,
|
token_type,
|
||||||
text,
|
text,
|
||||||
Some(literal),
|
Some(literal),
|
||||||
SourceSlice::from_positions(
|
SourceSlice::from_positions(
|
||||||
self.source_id.clone(),
|
self.source_id,
|
||||||
self.start_pos.clone(),
|
self.start_pos.clone(),
|
||||||
self.end_pos.clone(),
|
self.end_pos.clone(),
|
||||||
),
|
),
|
||||||
@@ -179,15 +169,12 @@ impl Lexer {
|
|||||||
('/', '*') => {
|
('/', '*') => {
|
||||||
// Commento multi-line
|
// Commento multi-line
|
||||||
while (self.peek() != '*' || self.peek_next() != '/') && !self.is_at_end() {
|
while (self.peek() != '*' || self.peek_next() != '/') && !self.is_at_end() {
|
||||||
if self.peek() == '\n' {
|
|
||||||
self.advance_line();
|
|
||||||
}
|
|
||||||
self.advance();
|
self.advance();
|
||||||
}
|
}
|
||||||
if self.is_at_end() {
|
if self.is_at_end() {
|
||||||
return lexical_error(
|
return lexical_error(
|
||||||
SourceSlice::from_positions(
|
SourceSlice::from_positions(
|
||||||
self.source_id.clone(),
|
self.source_id,
|
||||||
self.start_pos.clone(),
|
self.start_pos.clone(),
|
||||||
self.end_pos.clone(),
|
self.end_pos.clone(),
|
||||||
),
|
),
|
||||||
@@ -201,16 +188,13 @@ impl Lexer {
|
|||||||
}
|
}
|
||||||
('/', _) => Ok(Some(self.make_token(TokenType::Slash))),
|
('/', _) => Ok(Some(self.make_token(TokenType::Slash))),
|
||||||
(' ', _) | ('\r', _) | ('\t', _) => Ok(None),
|
(' ', _) | ('\r', _) | ('\t', _) => Ok(None),
|
||||||
('\n', _) => {
|
('\n', _) => Ok(None),
|
||||||
self.advance_line();
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
('"', _) => self.string(),
|
('"', _) => self.string(),
|
||||||
(c, _) if c.is_digit(10) => self.number(),
|
(c, _) if c.is_ascii_digit() => self.number(),
|
||||||
(c, _) if c.is_alphanumeric() || c == '_' => self.identifier(),
|
(c, _) if c.is_alphanumeric() || c == '_' => self.identifier(),
|
||||||
_ => Err(LoxError::LexicalError {
|
_ => Err(LoxError::LexicalError {
|
||||||
source_slice: SourceSlice::from_positions(
|
source_slice: SourceSlice::from_positions(
|
||||||
self.source_id.clone(),
|
self.source_id,
|
||||||
self.start_pos.clone(),
|
self.start_pos.clone(),
|
||||||
self.end_pos.clone(),
|
self.end_pos.clone(),
|
||||||
),
|
),
|
||||||
@@ -226,7 +210,7 @@ impl Lexer {
|
|||||||
if self.is_at_end() {
|
if self.is_at_end() {
|
||||||
return Err(LoxError::LexicalError {
|
return Err(LoxError::LexicalError {
|
||||||
source_slice: SourceSlice::from_positions(
|
source_slice: SourceSlice::from_positions(
|
||||||
self.source_id.clone(),
|
self.source_id,
|
||||||
self.start_pos.clone(),
|
self.start_pos.clone(),
|
||||||
self.end_pos.clone(),
|
self.end_pos.clone(),
|
||||||
),
|
),
|
||||||
@@ -236,20 +220,20 @@ impl Lexer {
|
|||||||
self.advance();
|
self.advance();
|
||||||
Ok(Some(self.make_token_with_literal(
|
Ok(Some(self.make_token_with_literal(
|
||||||
TokenType::String,
|
TokenType::String,
|
||||||
BaseValue::String(self.input[self.start_char..self.current_char].to_string()),
|
BaseValue::String(self.input[self.start..self.current].to_string()),
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn number(&mut self) -> LoxResult<Option<Token>> {
|
fn number(&mut self) -> LoxResult<Option<Token>> {
|
||||||
// Leggi la parte intera
|
// Leggi la parte intera
|
||||||
while self.peek().is_digit(10) {
|
while self.peek().is_ascii_digit() {
|
||||||
self.advance();
|
self.advance();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Controlla se c'è una parte decimale
|
// Controlla se c'è una parte decimale
|
||||||
let has_decimal = if self.peek() == '.' && self.peek_next().is_digit(10) {
|
let has_decimal = if self.peek() == '.' && self.peek_next().is_ascii_digit() {
|
||||||
self.advance(); // consuma il '.'
|
self.advance(); // consuma il '.'
|
||||||
while self.peek().is_digit(10) {
|
while self.peek().is_ascii_digit() {
|
||||||
self.advance();
|
self.advance();
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
@@ -266,7 +250,7 @@ impl Lexer {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let num_str = &self.input[self.start_char..self.current_char];
|
let num_str = &self.input[self.start..self.current];
|
||||||
let num_str_without_suffix = if suffix.is_some() {
|
let num_str_without_suffix = if suffix.is_some() {
|
||||||
&num_str[..num_str.len() - 1]
|
&num_str[..num_str.len() - 1]
|
||||||
} else {
|
} else {
|
||||||
@@ -303,7 +287,7 @@ impl Lexer {
|
|||||||
while self.peek().is_alphanumeric() || self.peek() == '_' {
|
while self.peek().is_alphanumeric() || self.peek() == '_' {
|
||||||
self.advance();
|
self.advance();
|
||||||
}
|
}
|
||||||
let text = self.input[self.start_char..self.current_char].to_string();
|
let text = self.input[self.start..self.current].to_string();
|
||||||
match get_keyword_token(&text) {
|
match get_keyword_token(&text) {
|
||||||
Some(TokenType::True) => Ok(Some(
|
Some(TokenType::True) => Ok(Some(
|
||||||
self.make_token_with_literal(TokenType::True, BaseValue::Boolean(true)),
|
self.make_token_with_literal(TokenType::True, BaseValue::Boolean(true)),
|
||||||
@@ -509,4 +493,53 @@ mod tests {
|
|||||||
let result = Lexer::new("@".to_string(), 0).scans_tokens();
|
let result = Lexer::new("@".to_string(), 0).scans_tokens();
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn handles_multibyte_identifier() {
|
||||||
|
// `é` is two UTF-8 bytes; the old char-counted slicing would panic or
|
||||||
|
// slice mid-codepoint here. Byte offsets make this correct.
|
||||||
|
let tokens = lex("café");
|
||||||
|
assert_eq!(tokens[0].token_type, TokenType::Identifier);
|
||||||
|
assert_eq!(
|
||||||
|
tokens[0].literal,
|
||||||
|
Some(BaseValue::String("café".to_string()))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tracks_line_and_column_across_newlines() {
|
||||||
|
// "1\n22": the second token sits at the start of line 1.
|
||||||
|
let tokens = lex("1\n22");
|
||||||
|
assert_eq!(tokens[1].lexeme, "22");
|
||||||
|
assert_eq!(tokens[1].source_slice.start_position.line, 1);
|
||||||
|
assert_eq!(tokens[1].source_slice.start_position.column, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn handle_struct() {
|
||||||
|
let tokens = lex("Cosa :: struct {field1: Number, field2: String}");
|
||||||
|
let tokens_tyepe: Vec<TokenType> = tokens.iter().map(|x| x.token_type.clone()).collect();
|
||||||
|
let tokent_for_check = vec![
|
||||||
|
TokenType::Identifier,
|
||||||
|
TokenType::Colon,
|
||||||
|
TokenType::Colon,
|
||||||
|
TokenType::Struct,
|
||||||
|
TokenType::LeftBrace,
|
||||||
|
TokenType::Identifier,
|
||||||
|
TokenType::Colon,
|
||||||
|
TokenType::Identifier,
|
||||||
|
TokenType::Comma,
|
||||||
|
TokenType::Identifier,
|
||||||
|
TokenType::Colon,
|
||||||
|
TokenType::Identifier,
|
||||||
|
TokenType::RightBrace,
|
||||||
|
TokenType::Eof,
|
||||||
|
];
|
||||||
|
assert_eq!(tokens_tyepe, tokent_for_check);
|
||||||
|
assert_eq!(tokens[0].lexeme, "Cosa");
|
||||||
|
assert_eq!(tokens[5].lexeme, "field1");
|
||||||
|
assert_eq!(tokens[7].lexeme, "Number");
|
||||||
|
assert_eq!(tokens[9].lexeme, "field2");
|
||||||
|
assert_eq!(tokens[11].lexeme, "String");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,4 +2,3 @@ pub mod lexer;
|
|||||||
pub mod parser;
|
pub mod parser;
|
||||||
pub mod source_registry;
|
pub mod source_registry;
|
||||||
pub mod tokens;
|
pub mod tokens;
|
||||||
pub mod variable_resolution;
|
|
||||||
|
|||||||
+321
-308
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ use std::{
|
|||||||
io::ErrorKind,
|
io::ErrorKind,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::common::lox_result::{io_error, LoxResult};
|
use crate::common::lox_result::{LoxResult, io_error};
|
||||||
|
|
||||||
pub struct SourceRegistry {
|
pub struct SourceRegistry {
|
||||||
pub sources: Vec<SourceFile>,
|
pub sources: Vec<SourceFile>,
|
||||||
@@ -51,7 +51,7 @@ impl SourceFile {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||||
pub struct SourcePosition {
|
pub struct SourcePosition {
|
||||||
pub line: usize,
|
pub line: usize,
|
||||||
pub column: usize,
|
pub column: usize,
|
||||||
@@ -63,7 +63,7 @@ impl Display for SourcePosition {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Default)]
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
pub struct SourceSlice {
|
pub struct SourceSlice {
|
||||||
pub source_id: SourceId,
|
pub source_id: SourceId,
|
||||||
pub start_position: SourcePosition,
|
pub start_position: SourcePosition,
|
||||||
@@ -91,6 +91,25 @@ impl Display for SourceSlice {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SourceSlice {
|
impl SourceSlice {
|
||||||
|
/// An explicit, non-located placeholder span.
|
||||||
|
///
|
||||||
|
/// Use this only when a real span is genuinely unavailable. Unlike the old
|
||||||
|
/// `Default` impl, it is greppable and obviously intentional, so it can't be
|
||||||
|
/// produced by accident.
|
||||||
|
pub fn synthetic() -> Self {
|
||||||
|
Self {
|
||||||
|
source_id: 0,
|
||||||
|
start_position: SourcePosition::default(),
|
||||||
|
end_position: SourcePosition::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this span is the non-located placeholder produced by
|
||||||
|
/// [`SourceSlice::synthetic`].
|
||||||
|
pub fn is_synthetic(&self) -> bool {
|
||||||
|
*self == Self::synthetic()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn from_positions(
|
pub fn from_positions(
|
||||||
source_id: SourceId,
|
source_id: SourceId,
|
||||||
start_position: SourcePosition,
|
start_position: SourcePosition,
|
||||||
@@ -102,6 +121,14 @@ impl SourceSlice {
|
|||||||
end_position,
|
end_position,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn from_source_slices(start_point: SourceSlice, end_point: SourceSlice) -> Self {
|
||||||
|
Self {
|
||||||
|
source_id: start_point.source_id,
|
||||||
|
start_position: start_point.start_position,
|
||||||
|
end_position: end_point.end_position,
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn tree_point(
|
pub fn tree_point(
|
||||||
source_id: SourceId,
|
source_id: SourceId,
|
||||||
column_start: usize,
|
column_start: usize,
|
||||||
@@ -199,3 +226,9 @@ impl SourceRegistry {
|
|||||||
line_of_code
|
line_of_code
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for SourceRegistry {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+10
-2
@@ -5,6 +5,9 @@ use crate::{common::base_value::BaseValue, frontend::source_registry::SourceSlic
|
|||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum TokenType {
|
pub enum TokenType {
|
||||||
// Single character tokens
|
// Single character tokens
|
||||||
|
Space,
|
||||||
|
Tab,
|
||||||
|
NewLine,
|
||||||
LeftParen,
|
LeftParen,
|
||||||
RightParen,
|
RightParen,
|
||||||
LeftBrace,
|
LeftBrace,
|
||||||
@@ -35,11 +38,12 @@ pub enum TokenType {
|
|||||||
Identifier,
|
Identifier,
|
||||||
String,
|
String,
|
||||||
Number,
|
Number,
|
||||||
|
Atom,
|
||||||
|
|
||||||
// Keywords
|
// Keywords
|
||||||
Fn,
|
Fn,
|
||||||
And,
|
And,
|
||||||
Class,
|
Struct,
|
||||||
StartBlock,
|
StartBlock,
|
||||||
EndBlock,
|
EndBlock,
|
||||||
False,
|
False,
|
||||||
@@ -69,6 +73,9 @@ pub enum TokenType {
|
|||||||
impl fmt::Display for TokenType {
|
impl fmt::Display for TokenType {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
|
TokenType::Space => write!(f, "/s"),
|
||||||
|
TokenType::Tab => write!(f, "/t"),
|
||||||
|
TokenType::NewLine => write!(f, "/n"),
|
||||||
TokenType::Bang => write!(f, "!"),
|
TokenType::Bang => write!(f, "!"),
|
||||||
TokenType::BangEqual => write!(f, "!="),
|
TokenType::BangEqual => write!(f, "!="),
|
||||||
TokenType::Equal => write!(f, "="),
|
TokenType::Equal => write!(f, "="),
|
||||||
@@ -80,8 +87,9 @@ impl fmt::Display for TokenType {
|
|||||||
TokenType::Identifier => write!(f, "IDENTIFIER"),
|
TokenType::Identifier => write!(f, "IDENTIFIER"),
|
||||||
TokenType::String => write!(f, "STRING"),
|
TokenType::String => write!(f, "STRING"),
|
||||||
TokenType::Number => write!(f, "NUMBER"),
|
TokenType::Number => write!(f, "NUMBER"),
|
||||||
|
TokenType::Atom => write!(f, "ATOM"),
|
||||||
TokenType::And => write!(f, "and"),
|
TokenType::And => write!(f, "and"),
|
||||||
TokenType::Class => write!(f, "class"),
|
TokenType::Struct => write!(f, "struct"),
|
||||||
TokenType::Else => write!(f, "else"),
|
TokenType::Else => write!(f, "else"),
|
||||||
TokenType::False => write!(f, "false"),
|
TokenType::False => write!(f, "false"),
|
||||||
TokenType::True => write!(f, "true"),
|
TokenType::True => write!(f, "true"),
|
||||||
|
|||||||
@@ -1,204 +0,0 @@
|
|||||||
use crate::{
|
|
||||||
backend::environment::EnvironmentStack,
|
|
||||||
common::{
|
|
||||||
ast::{AstNode, AstNodeKind, Expr, Stmt},
|
|
||||||
lox_result::{runtime_error, LoxError, LoxResult},
|
|
||||||
},
|
|
||||||
frontend::source_registry::SourceSlice,
|
|
||||||
};
|
|
||||||
|
|
||||||
use std::fmt::{Debug, Display};
|
|
||||||
struct Resolver {
|
|
||||||
scopes: EnvironmentStack<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resolver {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Resolver {
|
|
||||||
scopes: EnvironmentStack::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn declare(&mut self, name: &String) {
|
|
||||||
if self.scopes.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let _ = self.scopes.set(name.clone(), false);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn define(&mut self, name: &String) {
|
|
||||||
if self.scopes.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let _ = self.scopes.set(name.clone(), true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait StaticAnalyzer<T> {
|
|
||||||
fn resolve(&mut self, node: &T) -> LoxResult<bool>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<R: AstNodeKind + Clone + Debug + Display> StaticAnalyzer<AstNode<R>> for Resolver
|
|
||||||
where
|
|
||||||
Resolver: StaticAnalyzer<R>,
|
|
||||||
{
|
|
||||||
fn resolve(&mut self, node: &AstNode<R>) -> LoxResult<bool> {
|
|
||||||
self.resolve(&node.node)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StaticAnalyzer<Stmt> for Resolver {
|
|
||||||
fn resolve(&mut self, node: &Stmt) -> LoxResult<bool> {
|
|
||||||
match node {
|
|
||||||
Stmt::Expression { expression, .. } => {
|
|
||||||
// Visit the expression
|
|
||||||
self.resolve(expression.as_ref())
|
|
||||||
}
|
|
||||||
Stmt::Print { expression, .. } => {
|
|
||||||
// Visit the expression
|
|
||||||
self.resolve(expression.as_ref())
|
|
||||||
}
|
|
||||||
Stmt::VarDeclaration {
|
|
||||||
initializer, name, ..
|
|
||||||
} => {
|
|
||||||
self.declare(name);
|
|
||||||
// Visit the initializer if present
|
|
||||||
if let Some(init) = initializer {
|
|
||||||
self.resolve(init.as_ref())?;
|
|
||||||
}
|
|
||||||
self.define(name);
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Stmt::VarAssigment { value, name, .. } => {
|
|
||||||
match self.scopes.get(name) {
|
|
||||||
Ok(true) => (),
|
|
||||||
Ok(false) => {
|
|
||||||
return Err(LoxError::RuntimeError {
|
|
||||||
source_slice: SourceSlice::default(),
|
|
||||||
message: "Cant read loac variable in it own lintilizer".to_string(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(err) => return Err(err),
|
|
||||||
}
|
|
||||||
self.resolve(value.as_ref())
|
|
||||||
}
|
|
||||||
Stmt::Return { expression, .. } => {
|
|
||||||
// Visit the return expression
|
|
||||||
self.resolve(expression.as_ref())
|
|
||||||
}
|
|
||||||
Stmt::Block { statements, .. } => {
|
|
||||||
self.scopes.push_new_scope();
|
|
||||||
// Visit all statements in the block
|
|
||||||
for stmt in statements.iter() {
|
|
||||||
self.resolve(stmt)?;
|
|
||||||
}
|
|
||||||
self.scopes.pop_scope();
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Stmt::If {
|
|
||||||
condition,
|
|
||||||
then_branch,
|
|
||||||
elif_branch,
|
|
||||||
else_branch,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
// Visit the condition
|
|
||||||
self.resolve(condition.as_ref())?;
|
|
||||||
|
|
||||||
// Visit the then branch
|
|
||||||
self.resolve(then_branch.as_ref())?;
|
|
||||||
|
|
||||||
// Visit all elif branches
|
|
||||||
for (elif_condition, elif_stmt) in elif_branch.iter() {
|
|
||||||
self.resolve(elif_condition.as_ref())?;
|
|
||||||
self.resolve(elif_stmt.as_ref())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Visit the else branch if present
|
|
||||||
if let Some(else_stmt) = else_branch {
|
|
||||||
self.resolve(else_stmt.as_ref())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Stmt::While {
|
|
||||||
condition, body, ..
|
|
||||||
} => {
|
|
||||||
// Visit the condition
|
|
||||||
self.resolve(condition.as_ref())?;
|
|
||||||
|
|
||||||
// Visit the body
|
|
||||||
self.resolve(body.as_ref())?;
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Stmt::For {
|
|
||||||
variable,
|
|
||||||
condition,
|
|
||||||
increment,
|
|
||||||
body,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
// Visit the variable initialization
|
|
||||||
self.resolve(variable.as_ref())?;
|
|
||||||
|
|
||||||
// Visit the condition
|
|
||||||
self.resolve(condition.as_ref())?;
|
|
||||||
|
|
||||||
// Visit the increment
|
|
||||||
self.resolve(increment.as_ref())?;
|
|
||||||
|
|
||||||
// Visit the body
|
|
||||||
self.resolve(body.as_ref())?;
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StaticAnalyzer<Expr> for Resolver {
|
|
||||||
fn resolve(&mut self, node: &Expr) -> LoxResult<bool> {
|
|
||||||
match node {
|
|
||||||
Expr::Literal { .. } => {
|
|
||||||
// Leaf node - no children to visit
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Expr::Binary { left, right, .. } => {
|
|
||||||
// Visit left operand
|
|
||||||
self.resolve(left.as_ref())?;
|
|
||||||
|
|
||||||
// Visit right operand
|
|
||||||
self.resolve(right.as_ref())
|
|
||||||
}
|
|
||||||
Expr::Unary { operand, .. } => {
|
|
||||||
// Visit the operand
|
|
||||||
self.resolve(operand.as_ref())
|
|
||||||
}
|
|
||||||
Expr::Grouping { expression } => {
|
|
||||||
// Visit the grouped expression
|
|
||||||
self.resolve(expression.as_ref())
|
|
||||||
}
|
|
||||||
Expr::Identifier { name, .. } => {
|
|
||||||
if !self.scopes.is_empty() && self.scopes.get(name).is_ok() {
|
|
||||||
return Err(LoxError::ParseError {
|
|
||||||
source_slice: SourceSlice::default(),
|
|
||||||
message: "Cant read local varialbe in it own initializer".to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Expr::Call {
|
|
||||||
callee, arguments, ..
|
|
||||||
} => {
|
|
||||||
// Visit the callee
|
|
||||||
self.resolve(callee.as_ref())?;
|
|
||||||
|
|
||||||
// Visit all arguments
|
|
||||||
for arg in arguments.iter() {
|
|
||||||
self.resolve(arg)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod backend;
|
pub mod backend;
|
||||||
pub mod common;
|
pub mod common;
|
||||||
pub mod frontend;
|
pub mod frontend;
|
||||||
|
pub mod logging;
|
||||||
pub mod middleend;
|
pub mod middleend;
|
||||||
|
|||||||
+52
-81
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
use std::fmt::{self, Write};
|
use std::fmt::{self, Write};
|
||||||
|
|
||||||
use crate::common::ast::{AstNode, AstNodeKind, Expr, Stmt};
|
use crate::common::ast::{AstNode, Expr};
|
||||||
|
|
||||||
/// Configuration for pretty printing output
|
/// Configuration for pretty printing output
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -117,7 +117,7 @@ impl PrettyContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn should_truncate(&self) -> bool {
|
fn should_truncate(&self) -> bool {
|
||||||
self.config.max_depth.map_or(false, |max| self.depth >= max)
|
self.config.max_depth.is_some_and(|max| self.depth >= max)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,6 +234,20 @@ impl PrettyPrint for Expr {
|
|||||||
write!(f, "{}Identifier {{ name: {:?} }}", indent, name)
|
write!(f, "{}Identifier {{ name: {:?} }}", indent, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Expr::Assign { name, value } => {
|
||||||
|
if ctx.config.compact {
|
||||||
|
let value_str =
|
||||||
|
pretty_print_with_config(value.as_ref(), &PrettyConfig::compact());
|
||||||
|
write!(f, "{} = {}", name, value_str)
|
||||||
|
} else {
|
||||||
|
writeln!(f, "{}Assign {{", indent)?;
|
||||||
|
writeln!(f, "{}name: {:?},", ctx.child_context(false).indent(), name)?;
|
||||||
|
write!(f, "{}value: ", ctx.child_context(true).indent())?;
|
||||||
|
value.pretty_print(&ctx.child_context(true), f)?;
|
||||||
|
writeln!(f)?;
|
||||||
|
write!(f, "{}}}", indent)
|
||||||
|
}
|
||||||
|
}
|
||||||
Expr::Call { callee, arguments } => {
|
Expr::Call { callee, arguments } => {
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
write!(f, "{}", callee)
|
write!(f, "{}", callee)
|
||||||
@@ -250,33 +264,7 @@ impl PrettyPrint for Expr {
|
|||||||
write!(f, "] }}")
|
write!(f, "] }}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
Expr::Print { expression } => {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PrettyPrint for Stmt {
|
|
||||||
fn pretty_print(&self, ctx: &PrettyContext, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
if ctx.should_truncate() {
|
|
||||||
return write!(f, "{}...", ctx.indent());
|
|
||||||
}
|
|
||||||
|
|
||||||
let indent = ctx.indent();
|
|
||||||
|
|
||||||
match self {
|
|
||||||
Stmt::Expression { expression, .. } => {
|
|
||||||
if ctx.config.compact {
|
|
||||||
let expr_str =
|
|
||||||
pretty_print_with_config(expression.as_ref(), &PrettyConfig::compact());
|
|
||||||
write!(f, "{};", expr_str)
|
|
||||||
} else {
|
|
||||||
writeln!(f, "{}Expression {{", indent)?;
|
|
||||||
write!(f, "{}expression: ", ctx.child_context(true).indent())?;
|
|
||||||
expression.pretty_print(&ctx.child_context(true), f)?;
|
|
||||||
writeln!(f)?;
|
|
||||||
write!(f, "{}}}", indent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Stmt::Print { expression, .. } => {
|
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
let expr_str =
|
let expr_str =
|
||||||
pretty_print_with_config(expression.as_ref(), &PrettyConfig::compact());
|
pretty_print_with_config(expression.as_ref(), &PrettyConfig::compact());
|
||||||
@@ -289,7 +277,7 @@ impl PrettyPrint for Stmt {
|
|||||||
write!(f, "{}}}", indent)
|
write!(f, "{}}}", indent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Stmt::VarDeclaration {
|
Expr::VarDeclaration {
|
||||||
name, initializer, ..
|
name, initializer, ..
|
||||||
} => {
|
} => {
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
@@ -317,21 +305,7 @@ impl PrettyPrint for Stmt {
|
|||||||
write!(f, "{}}}", indent)
|
write!(f, "{}}}", indent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Stmt::VarAssigment { name, value, .. } => {
|
Expr::Return { expression, .. } => {
|
||||||
if ctx.config.compact {
|
|
||||||
let value_str =
|
|
||||||
pretty_print_with_config(value.as_ref(), &PrettyConfig::compact());
|
|
||||||
write!(f, "{} = {};", name, value_str)
|
|
||||||
} else {
|
|
||||||
writeln!(f, "{}Assign {{", indent)?;
|
|
||||||
writeln!(f, "{}name: {:?},", ctx.child_context(false).indent(), name)?;
|
|
||||||
write!(f, "{}value: ", ctx.child_context(true).indent())?;
|
|
||||||
value.pretty_print(&ctx.child_context(true), f)?;
|
|
||||||
writeln!(f)?;
|
|
||||||
write!(f, "{}}}", indent)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Stmt::Return { expression, .. } => {
|
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
let expr_str =
|
let expr_str =
|
||||||
pretty_print_with_config(expression.as_ref(), &PrettyConfig::compact());
|
pretty_print_with_config(expression.as_ref(), &PrettyConfig::compact());
|
||||||
@@ -344,9 +318,7 @@ impl PrettyPrint for Stmt {
|
|||||||
write!(f, "{}}}", indent)
|
write!(f, "{}}}", indent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Stmt::Block {
|
Expr::Block { statements, label } => {
|
||||||
statements, label, ..
|
|
||||||
} => {
|
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
write!(f, "{{ ... [{}] ({} statements) }}", label, statements.len())
|
write!(f, "{{ ... [{}] ({} statements) }}", label, statements.len())
|
||||||
} else {
|
} else {
|
||||||
@@ -365,12 +337,11 @@ impl PrettyPrint for Stmt {
|
|||||||
write!(f, "{}}}", indent)
|
write!(f, "{}}}", indent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Stmt::If {
|
Expr::If {
|
||||||
condition,
|
condition,
|
||||||
then_branch,
|
then_branch,
|
||||||
elif_branch,
|
elif_branches,
|
||||||
else_branch,
|
else_branch,
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
if ctx.config.compact {
|
if ctx.config.compact {
|
||||||
let cond_str =
|
let cond_str =
|
||||||
@@ -385,10 +356,10 @@ impl PrettyPrint for Stmt {
|
|||||||
then_branch.pretty_print(&ctx.child_context(false), f)?;
|
then_branch.pretty_print(&ctx.child_context(false), f)?;
|
||||||
writeln!(f, ",")?;
|
writeln!(f, ",")?;
|
||||||
|
|
||||||
if !elif_branch.is_empty() {
|
if !elif_branches.is_empty() {
|
||||||
writeln!(f, "{}elif_branches: [", ctx.child_context(false).indent())?;
|
writeln!(f, "{}elif_branches: [", ctx.child_context(false).indent())?;
|
||||||
for (i, (cond, branch)) in elif_branch.iter().enumerate() {
|
for (i, (cond, branch)) in elif_branches.iter().enumerate() {
|
||||||
let is_last = i == elif_branch.len() - 1;
|
let is_last = i == elif_branches.len() - 1;
|
||||||
let child_ctx = ctx.child_context(false).child_context(is_last);
|
let child_ctx = ctx.child_context(false).child_context(is_last);
|
||||||
writeln!(f, "{}(", child_ctx.indent())?;
|
writeln!(f, "{}(", child_ctx.indent())?;
|
||||||
write!(f, "{}condition: ", child_ctx.child_context(false).indent())?;
|
write!(f, "{}condition: ", child_ctx.child_context(false).indent())?;
|
||||||
@@ -420,21 +391,18 @@ impl PrettyPrint for Stmt {
|
|||||||
write!(f, "{}}}", indent)
|
write!(f, "{}}}", indent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Stmt::While {
|
Expr::While { condition, body } => {
|
||||||
condition, body, ..
|
|
||||||
} => {
|
|
||||||
write!(f, "{}while (", ctx.child_context(true).indent())?;
|
write!(f, "{}while (", ctx.child_context(true).indent())?;
|
||||||
condition.pretty_print(&ctx.child_context(true), f)?;
|
condition.pretty_print(&ctx.child_context(true), f)?;
|
||||||
writeln!(f, ") {{")?;
|
writeln!(f, ") {{")?;
|
||||||
body.pretty_print(&ctx.child_context(true), f)?;
|
body.pretty_print(&ctx.child_context(true), f)?;
|
||||||
writeln!(f, "{}}}", ctx.child_context(true).indent())
|
writeln!(f, "{}}}", ctx.child_context(true).indent())
|
||||||
}
|
}
|
||||||
Stmt::For {
|
Expr::For {
|
||||||
variable,
|
variable,
|
||||||
condition,
|
condition,
|
||||||
increment,
|
increment,
|
||||||
body,
|
body,
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
write!(f, "{}for (", ctx.child_context(true).indent())?;
|
write!(f, "{}for (", ctx.child_context(true).indent())?;
|
||||||
variable.pretty_print(&ctx.child_context(true), f)?;
|
variable.pretty_print(&ctx.child_context(true), f)?;
|
||||||
@@ -446,11 +414,32 @@ impl PrettyPrint for Stmt {
|
|||||||
body.pretty_print(&ctx.child_context(true), f)?;
|
body.pretty_print(&ctx.child_context(true), f)?;
|
||||||
writeln!(f, "{}}}", ctx.child_context(true).indent())
|
writeln!(f, "{}}}", ctx.child_context(true).indent())
|
||||||
}
|
}
|
||||||
|
Expr::Struct { fields } => {
|
||||||
|
if ctx.config.compact {
|
||||||
|
let field_strs: Vec<String> = fields
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| format!("{}: {:?}", k, v))
|
||||||
|
.collect();
|
||||||
|
write!(f, "struct {{ {} }}", field_strs.join(", "))
|
||||||
|
} else {
|
||||||
|
writeln!(f, "{}Struct {{", indent)?;
|
||||||
|
for (name, ty) in fields.iter() {
|
||||||
|
writeln!(
|
||||||
|
f,
|
||||||
|
"{}{}: {:?},",
|
||||||
|
ctx.child_context(false).indent(),
|
||||||
|
name,
|
||||||
|
ty
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
write!(f, "{}}}", indent)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AstNodeKind + fmt::Debug + fmt::Display + PrettyPrint> PrettyPrint for AstNode<T> {
|
impl PrettyPrint for AstNode {
|
||||||
fn pretty_print(&self, ctx: &PrettyContext, f: &mut fmt::Formatter) -> fmt::Result {
|
fn pretty_print(&self, ctx: &PrettyContext, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let indent = ctx.indent();
|
let indent = ctx.indent();
|
||||||
|
|
||||||
@@ -462,9 +451,9 @@ impl<T: AstNodeKind + fmt::Debug + fmt::Display + PrettyPrint> PrettyPrint for A
|
|||||||
if ctx.config.show_types {
|
if ctx.config.show_types {
|
||||||
writeln!(
|
writeln!(
|
||||||
f,
|
f,
|
||||||
"{}kind: {:?},",
|
"{}type: {},",
|
||||||
ctx.child_context(false).indent(),
|
ctx.child_context(false).indent(),
|
||||||
self.node.kind()
|
self.return_type
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,25 +507,7 @@ impl PrettyPrintExt for Expr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PrettyPrintExt for Stmt {
|
impl PrettyPrintExt for AstNode {
|
||||||
fn pretty(&self) -> String {
|
|
||||||
pretty_print(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pretty_compact(&self) -> String {
|
|
||||||
pretty_print_with_config(self, &PrettyConfig::compact())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pretty_tree(&self) -> String {
|
|
||||||
pretty_print_with_config(self, &PrettyConfig::tree())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pretty_with_config(&self, config: &PrettyConfig) -> String {
|
|
||||||
pretty_print_with_config(self, config)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: AstNodeKind + fmt::Debug + fmt::Display + PrettyPrint> PrettyPrintExt for AstNode<T> {
|
|
||||||
fn pretty(&self) -> String {
|
fn pretty(&self) -> String {
|
||||||
pretty_print(self)
|
pretty_print(self)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,17 +102,17 @@ impl Token {
|
|||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
if config.colored {
|
if config.colored {
|
||||||
format!("{}", self.colored_type())
|
self.colored_type().to_string()
|
||||||
} else {
|
} else {
|
||||||
format!("{}", self.token_type_symbol())
|
self.token_type_symbol().to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if config.colored {
|
if config.colored {
|
||||||
format!("{}", self.colored_type())
|
self.colored_type().to_string()
|
||||||
} else {
|
} else {
|
||||||
format!("{}", self.token_type_symbol())
|
self.token_type_symbol().to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -148,6 +148,9 @@ impl Token {
|
|||||||
|
|
||||||
fn token_type_symbol(&self) -> &'static str {
|
fn token_type_symbol(&self) -> &'static str {
|
||||||
match self.token_type {
|
match self.token_type {
|
||||||
|
TokenType::Space => "SPC",
|
||||||
|
TokenType::Tab => "TAB",
|
||||||
|
TokenType::NewLine => "NEL",
|
||||||
TokenType::LeftParen => "(",
|
TokenType::LeftParen => "(",
|
||||||
TokenType::RightParen => ")",
|
TokenType::RightParen => ")",
|
||||||
TokenType::LeftBrace => "{",
|
TokenType::LeftBrace => "{",
|
||||||
@@ -174,7 +177,8 @@ impl Token {
|
|||||||
TokenType::String => "STR",
|
TokenType::String => "STR",
|
||||||
TokenType::Number => "NUM",
|
TokenType::Number => "NUM",
|
||||||
TokenType::And => "AND",
|
TokenType::And => "AND",
|
||||||
TokenType::Class => "CLASS",
|
TokenType::Struct => "STRUCT",
|
||||||
|
TokenType::Atom => "ATOM",
|
||||||
TokenType::StartBlock => "DO",
|
TokenType::StartBlock => "DO",
|
||||||
TokenType::EndBlock => "END",
|
TokenType::EndBlock => "END",
|
||||||
TokenType::False => "FALSE",
|
TokenType::False => "FALSE",
|
||||||
@@ -219,7 +223,7 @@ impl Token {
|
|||||||
| TokenType::Less
|
| TokenType::Less
|
||||||
| TokenType::LessEqual => ("\x1b[31m", self.token_type_symbol()),
|
| TokenType::LessEqual => ("\x1b[31m", self.token_type_symbol()),
|
||||||
TokenType::And
|
TokenType::And
|
||||||
| TokenType::Class
|
| TokenType::Struct
|
||||||
| TokenType::False
|
| TokenType::False
|
||||||
| TokenType::True
|
| TokenType::True
|
||||||
| TokenType::Fun
|
| TokenType::Fun
|
||||||
@@ -239,6 +243,7 @@ impl Token {
|
|||||||
| TokenType::Var
|
| TokenType::Var
|
||||||
| TokenType::Fn
|
| TokenType::Fn
|
||||||
| TokenType::Is
|
| TokenType::Is
|
||||||
|
| TokenType::Atom
|
||||||
| TokenType::Val => ("\x1b[34m", self.token_type_symbol()),
|
| TokenType::Val => ("\x1b[34m", self.token_type_symbol()),
|
||||||
TokenType::Identifier | TokenType::String | TokenType::Number => {
|
TokenType::Identifier | TokenType::String | TokenType::Number => {
|
||||||
("\x1b[32m", self.token_type_symbol())
|
("\x1b[32m", self.token_type_symbol())
|
||||||
@@ -254,7 +259,9 @@ impl Token {
|
|||||||
| TokenType::Dot
|
| TokenType::Dot
|
||||||
| TokenType::Semicolon => ("\x1b[37m", self.token_type_symbol()),
|
| TokenType::Semicolon => ("\x1b[37m", self.token_type_symbol()),
|
||||||
TokenType::StartBlock | TokenType::EndBlock => ("\x1b[35m", self.token_type_symbol()),
|
TokenType::StartBlock | TokenType::EndBlock => ("\x1b[35m", self.token_type_symbol()),
|
||||||
TokenType::Eof => ("\x1b[33m", self.token_type_symbol()),
|
TokenType::Eof | TokenType::Space | TokenType::Tab | TokenType::NewLine => {
|
||||||
|
("\x1b[33m", self.token_type_symbol())
|
||||||
|
}
|
||||||
TokenType::In => ("\x1b[36m", self.token_type_symbol()),
|
TokenType::In => ("\x1b[36m", self.token_type_symbol()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+42
-32
@@ -1,13 +1,12 @@
|
|||||||
mod backend;
|
pub mod backend;
|
||||||
mod common;
|
pub mod common;
|
||||||
mod frontend;
|
pub mod frontend;
|
||||||
mod logging;
|
pub mod logging;
|
||||||
mod middleend;
|
pub mod middleend;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
backend::interpreter::{EvaluateInterpreter, Interpreter},
|
backend::interpreter::{EvaluateInterpreter, Interpreter},
|
||||||
common::{
|
common::{
|
||||||
ast::{AstNode, Stmt},
|
ast::AstNode,
|
||||||
lox_result::{LoxError, LoxResult},
|
lox_result::{LoxError, LoxResult},
|
||||||
},
|
},
|
||||||
frontend::{
|
frontend::{
|
||||||
@@ -15,6 +14,7 @@ use crate::{
|
|||||||
parser::Parser,
|
parser::Parser,
|
||||||
source_registry::{SourceId, SourceRegistry},
|
source_registry::{SourceId, SourceRegistry},
|
||||||
},
|
},
|
||||||
|
middleend::variable_resolution::Resolver,
|
||||||
};
|
};
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -33,12 +33,10 @@ fn main() -> LoxResult<()> {
|
|||||||
println!("running {file_path:?}");
|
println!("running {file_path:?}");
|
||||||
let mut lox = LoxInterpreter::new(debug);
|
let mut lox = LoxInterpreter::new(debug);
|
||||||
|
|
||||||
let res = match file_path {
|
match file_path {
|
||||||
Some(path) => lox.run_file(&path, stage),
|
Some(path) => lox.run_file(&path, stage),
|
||||||
None => lox.run_prompt(stage),
|
None => lox.run_prompt(stage),
|
||||||
};
|
}
|
||||||
|
|
||||||
res
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_args(args: &[String]) -> (ExecutionStage, Option<String>, bool) {
|
fn parse_args(args: &[String]) -> (ExecutionStage, Option<String>, bool) {
|
||||||
@@ -140,13 +138,12 @@ impl LoxInterpreter {
|
|||||||
|
|
||||||
match self.source_registry.add_source_string(line.to_string()) {
|
match self.source_registry.add_source_string(line.to_string()) {
|
||||||
Ok(source_id) => {
|
Ok(source_id) => {
|
||||||
match self.process_source(source_id, stage, self.debug) {
|
if let Ok(result) = self.process_source(source_id, stage, self.debug) {
|
||||||
Ok(result) => match stage {
|
match stage {
|
||||||
ExecutionStage::Tokens => println!("Tokens: {}", result),
|
ExecutionStage::Tokens => println!("Tokens: {}", result),
|
||||||
ExecutionStage::Ast => println!("AST: {}", result),
|
ExecutionStage::Ast => println!("AST: {}", result),
|
||||||
ExecutionStage::Full => println!("Result: {}", result),
|
ExecutionStage::Full => println!("Result: {}", result),
|
||||||
},
|
}
|
||||||
Err(_) => {} // Errore già stampato in process_source
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => eprintln!("Error: {}", e),
|
Err(e) => eprintln!("Error: {}", e),
|
||||||
@@ -167,34 +164,35 @@ impl LoxInterpreter {
|
|||||||
let source_content = self.source_registry.get_by_id(source_id).content.clone();
|
let source_content = self.source_registry.get_by_id(source_id).content.clone();
|
||||||
let mut lexer = Lexer::new(source_content, source_id);
|
let mut lexer = Lexer::new(source_content, source_id);
|
||||||
|
|
||||||
lexer.scans_tokens().or_else(|err| {
|
lexer.scans_tokens().inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Funzione per parsare fino all'AST
|
// Funzione per parsare fino all'AST
|
||||||
fn parse_to_ast(&self, source_id: SourceId) -> LoxResult<Vec<AstNode<Stmt>>> {
|
fn parse_to_ast(&self, source_id: SourceId) -> LoxResult<Vec<AstNode>> {
|
||||||
let tokens = self.tokenize(source_id)?;
|
let tokens = self.tokenize(source_id)?;
|
||||||
|
|
||||||
Parser::new(tokens).parse().or_else(|err| {
|
Parser::new(tokens).parse().inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Funzione per eseguire l'AST
|
// Funzione per eseguire l'AST
|
||||||
fn execute_ast(&self, ast: Vec<AstNode<Stmt>>, debug: bool) -> LoxResult<String> {
|
fn execute_ast(&self, ast: Vec<AstNode>, debug: bool) -> LoxResult<String> {
|
||||||
|
// Static resolution pass: compute variable scope distances and report
|
||||||
|
// any resolution errors before executing.
|
||||||
|
let locals = self.resolve(&ast)?;
|
||||||
let mut interpreter = Interpreter::new();
|
let mut interpreter = Interpreter::new();
|
||||||
|
interpreter.set_locals(locals);
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
|
|
||||||
for (index, stmt) in ast.iter().enumerate() {
|
for (index, stmt) in ast.iter().enumerate() {
|
||||||
if debug {
|
if debug {
|
||||||
println!("Executing statement {}: {:?}", index, stmt);
|
println!("Executing statement {}: {:?}", index, stmt);
|
||||||
}
|
}
|
||||||
result = Some(interpreter.evaluate(stmt.clone()).or_else(|err| {
|
result = Some(interpreter.evaluate(stmt.clone()).inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})?);
|
})?);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,6 +202,19 @@ impl LoxInterpreter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Static variable resolution; prints and returns the first error, if any.
|
||||||
|
fn resolve(
|
||||||
|
&self,
|
||||||
|
ast: &[AstNode],
|
||||||
|
) -> LoxResult<std::collections::HashMap<crate::common::ast::NodeId, usize>> {
|
||||||
|
Resolver::resolve_program(ast).map_err(|errors| {
|
||||||
|
for err in &errors {
|
||||||
|
err.print_with_context(&self.source_registry);
|
||||||
|
}
|
||||||
|
errors.into_iter().next().unwrap()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn process_source(
|
fn process_source(
|
||||||
&self,
|
&self,
|
||||||
source_id: SourceId,
|
source_id: SourceId,
|
||||||
@@ -214,9 +225,8 @@ impl LoxInterpreter {
|
|||||||
let mut lexer = Lexer::new(source_content, source_id);
|
let mut lexer = Lexer::new(source_content, source_id);
|
||||||
|
|
||||||
// Stage 1: Tokenization
|
// Stage 1: Tokenization
|
||||||
let tokens = lexer.scans_tokens().or_else(|err| {
|
let tokens = lexer.scans_tokens().inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// Se debug è attivo, mostra sempre i tokens
|
// Se debug è attivo, mostra sempre i tokens
|
||||||
@@ -230,9 +240,8 @@ impl LoxInterpreter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Stage 2: Parsing
|
// Stage 2: Parsing
|
||||||
let ast = Parser::new(tokens).parse().or_else(|err| {
|
let ast = Parser::new(tokens).parse().inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// Se debug è attivo, mostra sempre l'AST
|
// Se debug è attivo, mostra sempre l'AST
|
||||||
@@ -245,17 +254,18 @@ impl LoxInterpreter {
|
|||||||
return Ok(format_ast(&ast));
|
return Ok(format_ast(&ast));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stage 3: Interpretation
|
// Stage 3: Resolution + Interpretation
|
||||||
|
let locals = self.resolve(&ast)?;
|
||||||
let mut interpreter = Interpreter::new();
|
let mut interpreter = Interpreter::new();
|
||||||
|
interpreter.set_locals(locals);
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
|
|
||||||
for (index, stmt) in ast.iter().enumerate() {
|
for (index, stmt) in ast.iter().enumerate() {
|
||||||
if debug {
|
if debug {
|
||||||
println!("Executing statement {}: {:?}", index, stmt);
|
println!("Executing statement {}: {:?}", index, stmt);
|
||||||
}
|
}
|
||||||
result = Some(interpreter.evaluate(stmt.clone()).or_else(|err| {
|
result = Some(interpreter.evaluate(stmt.clone()).inspect_err(|err| {
|
||||||
err.print_with_context(&self.source_registry);
|
err.print_with_context(&self.source_registry);
|
||||||
Err(err)
|
|
||||||
})?);
|
})?);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,8 +285,8 @@ fn format_tokens(tokens: &[crate::frontend::tokens::Token]) -> String {
|
|||||||
.join("\n")
|
.join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_ast(ast: &[AstNode<Stmt>]) -> String {
|
fn format_ast(ast: &[AstNode]) -> String {
|
||||||
use crate::logging::display_ast::{pretty_print_with_config, PrettyConfig};
|
use crate::logging::display_ast::{PrettyConfig, pretty_print_with_config};
|
||||||
|
|
||||||
let config = PrettyConfig {
|
let config = PrettyConfig {
|
||||||
indent: " ".to_string(),
|
indent: " ".to_string(),
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
|
pub mod scope_stack;
|
||||||
pub mod variable_resolution;
|
pub mod variable_resolution;
|
||||||
pub mod visit_ast;
|
pub mod visit_ast;
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
//! A reusable lexical-scope stack for static analyses.
|
||||||
|
//!
|
||||||
|
//! Unlike [`EnvironmentStack`](crate::backend::environment::EnvironmentStack),
|
||||||
|
//! which stores runtime *values*, this stores per-binding *analysis state*
|
||||||
|
//! (for the resolver, a `bool` meaning "defined yet?"). It is generic over that
|
||||||
|
//! state so other passes (a type checker, an unused-variable lint, ...) can
|
||||||
|
//! reuse the same machinery.
|
||||||
|
//!
|
||||||
|
//! It starts **empty**: the global scope is intentionally untracked, so
|
||||||
|
//! [`ScopeStack::resolve`] returning `None` means "not local — assume global".
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ScopeStack<T> {
|
||||||
|
scopes: Vec<HashMap<String, T>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Default for ScopeStack<T> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> ScopeStack<T> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
ScopeStack { scopes: Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn begin_scope(&mut self) {
|
||||||
|
self.scopes.push(HashMap::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn end_scope(&mut self) {
|
||||||
|
self.scopes.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.scopes.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn depth(&self) -> usize {
|
||||||
|
self.scopes.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Insert `name` with `state` into the innermost scope (no-op at global).
|
||||||
|
pub fn declare(&mut self, name: impl Into<String>, state: T) {
|
||||||
|
if let Some(scope) = self.scopes.last_mut() {
|
||||||
|
scope.insert(name.into(), state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update an existing binding in the innermost scope (no-op if absent).
|
||||||
|
pub fn set_local(&mut self, name: &str, state: T) {
|
||||||
|
if let Some(scope) = self.scopes.last_mut()
|
||||||
|
&& let Some(slot) = scope.get_mut(name)
|
||||||
|
{
|
||||||
|
*slot = state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Look up `name` in the innermost scope only.
|
||||||
|
pub fn get_local(&self, name: &str) -> Option<&T> {
|
||||||
|
self.scopes.last().and_then(|scope| scope.get(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the innermost scope already declares `name`.
|
||||||
|
pub fn declared_in_current(&self, name: &str) -> bool {
|
||||||
|
self.scopes
|
||||||
|
.last()
|
||||||
|
.is_some_and(|scope| scope.contains_key(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Distance (in scopes) from the innermost scope to the one declaring
|
||||||
|
/// `name`, or `None` if it isn't in any scope (i.e. global).
|
||||||
|
pub fn resolve(&self, name: &str) -> Option<usize> {
|
||||||
|
self.scopes
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.enumerate()
|
||||||
|
.find_map(|(distance, scope)| scope.contains_key(name).then_some(distance))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn declare_and_get_local() {
|
||||||
|
let mut scopes: ScopeStack<bool> = ScopeStack::new();
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("a", false);
|
||||||
|
assert_eq!(scopes.get_local("a"), Some(&false));
|
||||||
|
scopes.set_local("a", true);
|
||||||
|
assert_eq!(scopes.get_local("a"), Some(&true));
|
||||||
|
assert_eq!(scopes.get_local("missing"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_returns_distance_from_innermost() {
|
||||||
|
let mut scopes: ScopeStack<bool> = ScopeStack::new();
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("a", true);
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("b", true);
|
||||||
|
assert_eq!(scopes.resolve("b"), Some(0));
|
||||||
|
assert_eq!(scopes.resolve("a"), Some(1));
|
||||||
|
assert_eq!(scopes.resolve("missing"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shadowing_and_end_scope() {
|
||||||
|
let mut scopes: ScopeStack<bool> = ScopeStack::new();
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("a", true);
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("a", false);
|
||||||
|
assert_eq!(scopes.get_local("a"), Some(&false));
|
||||||
|
assert_eq!(scopes.resolve("a"), Some(0));
|
||||||
|
scopes.end_scope();
|
||||||
|
assert_eq!(scopes.get_local("a"), Some(&true));
|
||||||
|
assert_eq!(scopes.resolve("a"), Some(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn declared_in_current_checks_only_innermost() {
|
||||||
|
let mut scopes: ScopeStack<bool> = ScopeStack::new();
|
||||||
|
scopes.begin_scope();
|
||||||
|
scopes.declare("a", true);
|
||||||
|
scopes.begin_scope();
|
||||||
|
assert!(!scopes.declared_in_current("a"));
|
||||||
|
scopes.declare("a", true);
|
||||||
|
assert!(scopes.declared_in_current("a"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn global_scope_is_untracked() {
|
||||||
|
let mut scopes: ScopeStack<bool> = ScopeStack::new();
|
||||||
|
// No scope pushed: declarations are no-ops and nothing resolves locally.
|
||||||
|
scopes.declare("a", true);
|
||||||
|
assert!(scopes.is_empty());
|
||||||
|
assert_eq!(scopes.resolve("a"), None);
|
||||||
|
assert_eq!(scopes.get_local("a"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,99 +1,258 @@
|
|||||||
|
//! Static variable resolution (Crafting Interpreters, chapter 11).
|
||||||
|
//!
|
||||||
|
//! Walks the AST with the shared [`Visitor`] traversal, tracking lexical scopes
|
||||||
|
//! in a [`ScopeStack`], and records for every variable *reference* how many
|
||||||
|
//! scopes up its declaration lives (`locals: NodeId -> distance`). It also
|
||||||
|
//! reports the resolution errors from chapter 11:
|
||||||
|
//!
|
||||||
|
//! * reading a local variable in its own initializer (`var a = a;`),
|
||||||
|
//! * declaring two variables with the same name in one local scope,
|
||||||
|
//! * `return` outside of any function.
|
||||||
|
//!
|
||||||
|
//! Diagnostics accumulate in an [`ErrorSink`] so a single pass surfaces them
|
||||||
|
//! all. The produced `locals` map is keyed by [`NodeId`] (stable identity),
|
||||||
|
//! ready for the interpreter to consume via distance-based lookup.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
backend::environment::EnvironmentStack,
|
|
||||||
common::{
|
common::{
|
||||||
ast::{AstNode, Expr, Stmt},
|
ast::{AstNode, Expr, NodeId},
|
||||||
lox_result::{LoxError, LoxResult},
|
base_value::{BaseValue, LoxFunction},
|
||||||
|
lox_result::{ErrorSink, LoxError, LoxResult},
|
||||||
|
},
|
||||||
|
middleend::{
|
||||||
|
scope_stack::ScopeStack,
|
||||||
|
visit_ast::{walk_expr, walk_function, Visitor},
|
||||||
},
|
},
|
||||||
frontend::source_registry::SourceSlice,
|
|
||||||
middleend::visit_ast::{walk_expr, walk_stmt, Visitor},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Resolver {
|
/// Tracks whether resolution is currently inside a function body, so a
|
||||||
scopes: EnvironmentStack<bool>,
|
/// top-level `return` can be reported.
|
||||||
locals: HashMap<SourceSlice, usize>,
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
enum FunctionType {
|
||||||
|
None,
|
||||||
|
Function,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Resolver {
|
||||||
|
scopes: ScopeStack<bool>,
|
||||||
|
locals: HashMap<NodeId, usize>,
|
||||||
|
errors: ErrorSink,
|
||||||
|
current_function: FunctionType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Resolver {
|
impl Resolver {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Resolver {
|
Resolver {
|
||||||
scopes: EnvironmentStack::new(),
|
scopes: ScopeStack::new(),
|
||||||
locals: HashMap::new(),
|
locals: HashMap::new(),
|
||||||
|
errors: ErrorSink::new(),
|
||||||
|
current_function: FunctionType::None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn declare(&mut self, name: &String) {
|
/// Resolve a whole program, returning the per-reference scope distances or
|
||||||
|
/// the accumulated resolution errors.
|
||||||
|
pub fn resolve_program(
|
||||||
|
statements: &[AstNode],
|
||||||
|
) -> Result<HashMap<NodeId, usize>, Vec<LoxError>> {
|
||||||
|
let mut resolver = Resolver::new();
|
||||||
|
for statement in statements {
|
||||||
|
// Visiting only fails for fatal/internal errors, which this pass
|
||||||
|
// never produces; user-facing diagnostics go to `errors`.
|
||||||
|
let _ = resolver.visit_expr(statement);
|
||||||
|
}
|
||||||
|
if resolver.errors.has_errors() {
|
||||||
|
Err(resolver.errors.into_errors())
|
||||||
|
} else {
|
||||||
|
Ok(resolver.locals)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declare(&mut self, name: &str, slice: &crate::frontend::source_registry::SourceSlice) {
|
||||||
|
if self.scopes.is_empty() {
|
||||||
|
return; // global scope is untracked
|
||||||
|
}
|
||||||
|
if self.scopes.declared_in_current(name) {
|
||||||
|
self.errors.report(LoxError::ParseError {
|
||||||
|
source_slice: slice.clone(),
|
||||||
|
message: format!("Already a variable named '{}' in this scope.", name),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.scopes.declare(name.to_string(), false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn define(&mut self, name: &str) {
|
||||||
if self.scopes.is_empty() {
|
if self.scopes.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let _ = self.scopes.set(name.clone(), false);
|
self.scopes.set_local(name, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn define(&mut self, name: &String) {
|
fn resolve_local(&mut self, id: NodeId, name: &str) {
|
||||||
if self.scopes.is_empty() {
|
if let Some(distance) = self.scopes.resolve(name) {
|
||||||
return;
|
self.locals.insert(id, distance);
|
||||||
}
|
}
|
||||||
let _ = self.scopes.set(name.clone(), true);
|
// Not found locally: assume global, record nothing.
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn resolve_local(&mut self, name: &String) {
|
impl Default for Resolver {
|
||||||
let depth = self.scopes.depth();
|
fn default() -> Self {
|
||||||
for i in (0..depth).rev() {
|
Self::new()
|
||||||
if self.scopes.scope_contains(i, name) {
|
|
||||||
self.locals.insert(, i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Visitor for Resolver {
|
impl Visitor for Resolver {
|
||||||
fn visit_stmt(&mut self, stmt: &AstNode<Stmt>) -> LoxResult<()> {
|
fn visit_expr(&mut self, expr: &AstNode) -> LoxResult<()> {
|
||||||
match &stmt.node {
|
|
||||||
Stmt::VarDeclaration { name, .. } => {
|
|
||||||
self.declare(name);
|
|
||||||
// `walk_stmt` resolves the initializer (if present).
|
|
||||||
walk_stmt(self, stmt)?;
|
|
||||||
self.define(name);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Stmt::VarAssigment { name, .. } => {
|
|
||||||
match self.scopes.get(name) {
|
|
||||||
Ok(true) => (),
|
|
||||||
Ok(false) => {
|
|
||||||
return Err(LoxError::RuntimeError {
|
|
||||||
source_slice: SourceSlice::default(),
|
|
||||||
message: "Cant read local variable in it own lintilizer".to_string(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(err) => return Err(err),
|
|
||||||
}
|
|
||||||
// `walk_stmt` resolves the assigned value.
|
|
||||||
walk_stmt(self, stmt)
|
|
||||||
}
|
|
||||||
Stmt::Block { .. } => {
|
|
||||||
self.scopes.push_new_scope();
|
|
||||||
walk_stmt(self, stmt)?;
|
|
||||||
self.scopes.pop_scope();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
// Expression, Print, Return, If, While, For: default traversal.
|
|
||||||
_ => walk_stmt(self, stmt),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_expr(&mut self, expr: &AstNode<Expr>) -> LoxResult<()> {
|
|
||||||
match &expr.node {
|
match &expr.node {
|
||||||
Expr::Identifier { name, .. } => {
|
Expr::Identifier { name } => {
|
||||||
if !self.scopes.is_empty() && self.scopes.get(name).is_ok() {
|
if self.scopes.get_local(name) == Some(&false) {
|
||||||
return Err(LoxError::ParseError {
|
self.errors.report(LoxError::ParseError {
|
||||||
source_slice: SourceSlice::default(),
|
source_slice: expr.source_slice.clone(),
|
||||||
message: "Cant read local varialbe in it own initializer".to_string(),
|
message: "Can't read local variable in its own initializer.".to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
self.resolve_local(expr.id, name);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Expr::Assign { name, .. } => {
|
||||||
|
walk_expr(self, expr)?; // resolve the assigned value first
|
||||||
|
self.resolve_local(expr.id, name);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::VarDeclaration {
|
||||||
|
name, initializer, ..
|
||||||
|
} => {
|
||||||
|
// A function declaration is a var bound to a function literal.
|
||||||
|
// Define its name *before* resolving the body so it can recurse;
|
||||||
|
// a plain variable is defined *after* its initializer so that
|
||||||
|
// `var a = a;` is caught.
|
||||||
|
let is_function = matches!(
|
||||||
|
initializer.as_deref().map(|node| &node.node),
|
||||||
|
Some(Expr::Literal { value }) if matches!(**value, BaseValue::Function(_))
|
||||||
|
);
|
||||||
|
self.declare(name, &expr.source_slice);
|
||||||
|
if is_function {
|
||||||
|
self.define(name);
|
||||||
|
walk_expr(self, expr)?;
|
||||||
|
} else {
|
||||||
|
walk_expr(self, expr)?; // resolves the initializer, if any
|
||||||
|
self.define(name);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::Block { .. } => {
|
||||||
|
self.scopes.begin_scope();
|
||||||
|
walk_expr(self, expr)?;
|
||||||
|
self.scopes.end_scope();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::Return { .. } => {
|
||||||
|
if self.current_function == FunctionType::None {
|
||||||
|
self.errors.report(LoxError::ParseError {
|
||||||
|
source_slice: expr.source_slice.clone(),
|
||||||
|
message: "Can't return from top-level code.".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
walk_expr(self, expr) // resolve the returned expression
|
||||||
|
}
|
||||||
_ => walk_expr(self, expr),
|
_ => walk_expr(self, expr),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn visit_function(&mut self, function: &LoxFunction) -> LoxResult<()> {
|
||||||
|
let enclosing = std::mem::replace(&mut self.current_function, FunctionType::Function);
|
||||||
|
self.scopes.begin_scope();
|
||||||
|
// Parameters carry no source slice of their own; use the body's.
|
||||||
|
let param_slice = function.body.source_slice.clone();
|
||||||
|
for (param, _ty) in &function.parameters {
|
||||||
|
self.declare(param, ¶m_slice);
|
||||||
|
self.define(param);
|
||||||
|
}
|
||||||
|
walk_function(self, function)?; // resolves guard + body
|
||||||
|
self.scopes.end_scope();
|
||||||
|
self.current_function = enclosing;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::frontend::lexer::Lexer;
|
||||||
|
use crate::frontend::parser::Parser;
|
||||||
|
|
||||||
|
fn parse(src: &str) -> Vec<AstNode> {
|
||||||
|
let tokens = Lexer::new(src.to_string(), 0)
|
||||||
|
.scans_tokens()
|
||||||
|
.expect("source should lex");
|
||||||
|
Parser::new(tokens).parse().expect("source should parse")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve(src: &str) -> Result<HashMap<NodeId, usize>, Vec<LoxError>> {
|
||||||
|
Resolver::resolve_program(&parse(src))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn global_variables_are_not_resolved() {
|
||||||
|
// Top-level (global) scope is untracked, so nothing is recorded.
|
||||||
|
let locals = resolve("x := 1; print x;").expect("should resolve");
|
||||||
|
assert!(locals.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_read_resolves_to_distance_zero() {
|
||||||
|
let locals = resolve("do x := 1; print x; end").expect("should resolve");
|
||||||
|
assert_eq!(locals.len(), 1);
|
||||||
|
assert_eq!(*locals.values().next().unwrap(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nested_scope_resolves_to_outer_distance() {
|
||||||
|
let src = "do x := 1; do print x; end end";
|
||||||
|
let locals = resolve(src).expect("should resolve");
|
||||||
|
assert_eq!(locals.len(), 1);
|
||||||
|
// `x` is read one scope above where it is read from.
|
||||||
|
assert_eq!(*locals.values().next().unwrap(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reading_a_variable_in_its_own_initializer_is_an_error() {
|
||||||
|
let errors = resolve("do x := x; end").expect_err("should fail");
|
||||||
|
assert!(errors
|
||||||
|
.iter()
|
||||||
|
.any(|e| e.get_message().contains("its own initializer")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_declaration_in_same_scope_is_an_error() {
|
||||||
|
let errors = resolve("do x := 1; x := 2; end").expect_err("should fail");
|
||||||
|
assert!(errors
|
||||||
|
.iter()
|
||||||
|
.any(|e| e.get_message().contains("Already a variable")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn return_at_top_level_is_an_error() {
|
||||||
|
let errors = resolve("return 1;").expect_err("should fail");
|
||||||
|
assert!(errors.iter().any(|e| e.get_message().contains("top-level")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn return_inside_a_function_is_allowed() {
|
||||||
|
let locals = resolve("f :: fn (n): Number do return n; end;").expect("should resolve");
|
||||||
|
// `n` resolves from the body block up to the parameter scope.
|
||||||
|
assert_eq!(locals.len(), 1);
|
||||||
|
assert_eq!(*locals.values().next().unwrap(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assignment_target_is_resolved() {
|
||||||
|
let locals = resolve("do x := 1; x = 2; end").expect("should resolve");
|
||||||
|
// Both the assignment target and... only the target is a reference here.
|
||||||
|
assert!(locals.values().all(|&d| d == 0));
|
||||||
|
assert!(!locals.is_empty());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+73
-91
@@ -23,7 +23,7 @@
|
|||||||
//! struct IdentifierCounter { count: usize }
|
//! struct IdentifierCounter { count: usize }
|
||||||
//!
|
//!
|
||||||
//! impl Visitor for IdentifierCounter {
|
//! impl Visitor for IdentifierCounter {
|
||||||
//! fn visit_expr(&mut self, expr: &AstNode<Expr>) -> LoxResult<()> {
|
//! fn visit_expr(&mut self, expr: &AstNode) -> LoxResult<()> {
|
||||||
//! if let Expr::Identifier { .. } = &expr.node {
|
//! if let Expr::Identifier { .. } = &expr.node {
|
||||||
//! self.count += 1;
|
//! self.count += 1;
|
||||||
//! }
|
//! }
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::common::{
|
use crate::common::{
|
||||||
ast::{AstNode, Expr, Stmt},
|
ast::{AstNode, Expr},
|
||||||
base_value::{BaseValue, LoxFunction},
|
base_value::{BaseValue, LoxFunction},
|
||||||
lox_result::LoxResult,
|
lox_result::LoxResult,
|
||||||
};
|
};
|
||||||
@@ -43,13 +43,8 @@ use crate::common::{
|
|||||||
/// Every hook has a default implementation that performs the standard
|
/// Every hook has a default implementation that performs the standard
|
||||||
/// recursive traversal, so implementors only override the cases they need.
|
/// recursive traversal, so implementors only override the cases they need.
|
||||||
pub trait Visitor: Sized {
|
pub trait Visitor: Sized {
|
||||||
/// Visit a statement node. Defaults to [`walk_stmt`].
|
|
||||||
fn visit_stmt(&mut self, stmt: &AstNode<Stmt>) -> LoxResult<()> {
|
|
||||||
walk_stmt(self, stmt)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Visit an expression node. Defaults to [`walk_expr`].
|
/// Visit an expression node. Defaults to [`walk_expr`].
|
||||||
fn visit_expr(&mut self, expr: &AstNode<Expr>) -> LoxResult<()> {
|
fn visit_expr(&mut self, expr: &AstNode) -> LoxResult<()> {
|
||||||
walk_expr(self, expr)
|
walk_expr(self, expr)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,71 +57,13 @@ pub trait Visitor: Sized {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recurse into the children of `stmt`, calling back into `visitor`.
|
|
||||||
pub fn walk_stmt<V: Visitor>(visitor: &mut V, stmt: &AstNode<Stmt>) -> LoxResult<()> {
|
|
||||||
match &stmt.node {
|
|
||||||
Stmt::Expression { expression, .. } => visitor.visit_expr(expression),
|
|
||||||
Stmt::Print { expression, .. } => visitor.visit_expr(expression),
|
|
||||||
Stmt::VarDeclaration { initializer, .. } => {
|
|
||||||
if let Some(initializer) = initializer {
|
|
||||||
visitor.visit_expr(initializer)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Stmt::VarAssigment { value, .. } => visitor.visit_expr(value),
|
|
||||||
Stmt::Return { expression, .. } => visitor.visit_expr(expression),
|
|
||||||
Stmt::Block { statements, .. } => {
|
|
||||||
for statement in statements.iter() {
|
|
||||||
visitor.visit_stmt(statement)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Stmt::If {
|
|
||||||
condition,
|
|
||||||
then_branch,
|
|
||||||
elif_branch,
|
|
||||||
else_branch,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
visitor.visit_expr(condition)?;
|
|
||||||
visitor.visit_stmt(then_branch)?;
|
|
||||||
for (elif_condition, elif_body) in elif_branch.iter() {
|
|
||||||
visitor.visit_expr(elif_condition)?;
|
|
||||||
visitor.visit_stmt(elif_body)?;
|
|
||||||
}
|
|
||||||
if let Some(else_body) = else_branch {
|
|
||||||
visitor.visit_stmt(else_body)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Stmt::While {
|
|
||||||
condition, body, ..
|
|
||||||
} => {
|
|
||||||
visitor.visit_expr(condition)?;
|
|
||||||
visitor.visit_stmt(body)
|
|
||||||
}
|
|
||||||
Stmt::For {
|
|
||||||
variable,
|
|
||||||
condition,
|
|
||||||
increment,
|
|
||||||
body,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
visitor.visit_stmt(variable)?;
|
|
||||||
visitor.visit_expr(condition)?;
|
|
||||||
visitor.visit_stmt(increment)?;
|
|
||||||
visitor.visit_stmt(body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recurse into the children of `expr`, calling back into `visitor`.
|
/// Recurse into the children of `expr`, calling back into `visitor`.
|
||||||
pub fn walk_expr<V: Visitor>(visitor: &mut V, expr: &AstNode<Expr>) -> LoxResult<()> {
|
pub fn walk_expr<V: Visitor>(visitor: &mut V, expr: &AstNode) -> LoxResult<()> {
|
||||||
match &expr.node {
|
match &expr.node {
|
||||||
// A function literal carries an entire sub-tree (its body), so it is
|
// A function literal carries an entire sub-tree (its body), so it is
|
||||||
// not a leaf: hand it to the dedicated function hook.
|
// not a leaf: hand it to the dedicated function hook.
|
||||||
Expr::Literal { value } => {
|
Expr::Literal { value } => {
|
||||||
if let BaseValue::Function(function) = value {
|
if let BaseValue::Function(function) = &**value {
|
||||||
visitor.visit_function(function)?;
|
visitor.visit_function(function)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -137,6 +74,7 @@ pub fn walk_expr<V: Visitor>(visitor: &mut V, expr: &AstNode<Expr>) -> LoxResult
|
|||||||
visitor.visit_expr(right)
|
visitor.visit_expr(right)
|
||||||
}
|
}
|
||||||
Expr::Unary { operand, .. } => visitor.visit_expr(operand),
|
Expr::Unary { operand, .. } => visitor.visit_expr(operand),
|
||||||
|
Expr::Assign { value, .. } => visitor.visit_expr(value),
|
||||||
Expr::Grouping { expression } => visitor.visit_expr(expression),
|
Expr::Grouping { expression } => visitor.visit_expr(expression),
|
||||||
Expr::Call {
|
Expr::Call {
|
||||||
callee, arguments, ..
|
callee, arguments, ..
|
||||||
@@ -147,6 +85,59 @@ pub fn walk_expr<V: Visitor>(visitor: &mut V, expr: &AstNode<Expr>) -> LoxResult
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Expr::Print { expression, .. } => visitor.visit_expr(expression),
|
||||||
|
Expr::VarDeclaration { initializer, .. } => {
|
||||||
|
if let Some(initializer) = initializer {
|
||||||
|
visitor.visit_expr(initializer)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::Return { expression, .. } => visitor.visit_expr(expression),
|
||||||
|
Expr::Block { statements, .. } => {
|
||||||
|
for statement in statements.iter() {
|
||||||
|
visitor.visit_expr(statement)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::If {
|
||||||
|
condition,
|
||||||
|
then_branch,
|
||||||
|
elif_branches,
|
||||||
|
else_branch,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
visitor.visit_expr(condition)?;
|
||||||
|
visitor.visit_expr(then_branch)?;
|
||||||
|
for (elif_condition, elif_body) in elif_branches.iter() {
|
||||||
|
visitor.visit_expr(elif_condition)?;
|
||||||
|
visitor.visit_expr(elif_body)?;
|
||||||
|
}
|
||||||
|
if let Some(else_body) = else_branch {
|
||||||
|
visitor.visit_expr(else_body)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Expr::While {
|
||||||
|
condition, body, ..
|
||||||
|
} => {
|
||||||
|
visitor.visit_expr(condition)?;
|
||||||
|
visitor.visit_expr(body)
|
||||||
|
}
|
||||||
|
Expr::For {
|
||||||
|
variable,
|
||||||
|
condition,
|
||||||
|
increment,
|
||||||
|
body,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
visitor.visit_expr(variable)?;
|
||||||
|
visitor.visit_expr(condition)?;
|
||||||
|
visitor.visit_expr(increment)?;
|
||||||
|
visitor.visit_expr(body)
|
||||||
|
}
|
||||||
|
// Struct declarations carry only type information, no child expressions.
|
||||||
|
Expr::Struct { .. } => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,7 +146,7 @@ pub fn walk_function<V: Visitor>(visitor: &mut V, function: &LoxFunction) -> Lox
|
|||||||
if let Some(guard) = &function.guard {
|
if let Some(guard) = &function.guard {
|
||||||
visitor.visit_expr(guard)?;
|
visitor.visit_expr(guard)?;
|
||||||
}
|
}
|
||||||
visitor.visit_stmt(&function.body)
|
visitor.visit_expr(&function.body)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -165,7 +156,7 @@ mod tests {
|
|||||||
use crate::frontend::lexer::Lexer;
|
use crate::frontend::lexer::Lexer;
|
||||||
use crate::frontend::parser::Parser;
|
use crate::frontend::parser::Parser;
|
||||||
|
|
||||||
fn parse(src: &str) -> Vec<AstNode<Stmt>> {
|
fn parse(src: &str) -> Vec<AstNode> {
|
||||||
let tokens = Lexer::new(src.to_string(), 0)
|
let tokens = Lexer::new(src.to_string(), 0)
|
||||||
.scans_tokens()
|
.scans_tokens()
|
||||||
.expect("source should lex");
|
.expect("source should lex");
|
||||||
@@ -173,29 +164,23 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A visitor that relies entirely on the default traversal and just counts
|
/// A visitor that relies entirely on the default traversal and just counts
|
||||||
/// how many statement and expression nodes it sees.
|
/// how many nodes it sees.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Counter {
|
struct Counter {
|
||||||
stmts: usize,
|
nodes: usize,
|
||||||
exprs: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Visitor for Counter {
|
impl Visitor for Counter {
|
||||||
fn visit_stmt(&mut self, stmt: &AstNode<Stmt>) -> LoxResult<()> {
|
fn visit_expr(&mut self, node: &AstNode) -> LoxResult<()> {
|
||||||
self.stmts += 1;
|
self.nodes += 1;
|
||||||
walk_stmt(self, stmt)
|
walk_expr(self, node)
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_expr(&mut self, expr: &AstNode<Expr>) -> LoxResult<()> {
|
|
||||||
self.exprs += 1;
|
|
||||||
walk_expr(self, expr)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn count(src: &str) -> Counter {
|
fn count(src: &str) -> Counter {
|
||||||
let mut counter = Counter::default();
|
let mut counter = Counter::default();
|
||||||
for stmt in parse(src).iter() {
|
for stmt in parse(src).iter() {
|
||||||
counter.visit_stmt(stmt).unwrap();
|
counter.visit_expr(stmt).unwrap();
|
||||||
}
|
}
|
||||||
counter
|
counter
|
||||||
}
|
}
|
||||||
@@ -204,19 +189,16 @@ mod tests {
|
|||||||
fn counts_every_node_via_default_traversal() {
|
fn counts_every_node_via_default_traversal() {
|
||||||
// 1 + 2 * 3 => Binary(+){ Literal, Binary(*){ Literal, Literal } }
|
// 1 + 2 * 3 => Binary(+){ Literal, Binary(*){ Literal, Literal } }
|
||||||
let counter = count("1 + 2 * 3;");
|
let counter = count("1 + 2 * 3;");
|
||||||
assert_eq!(counter.stmts, 1);
|
assert_eq!(counter.nodes, 5);
|
||||||
assert_eq!(counter.exprs, 5);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn descends_into_function_bodies() {
|
fn descends_into_function_bodies() {
|
||||||
// The function body must be traversed through `visit_function`, so the
|
// The function body must be traversed through `visit_function`, so the
|
||||||
// `return a;` inside it should contribute to the counts.
|
// `return a;` inside it should contribute to the counts.
|
||||||
let counter = count("f :: fn (a) do return a; end");
|
let counter = count("f :: fn (a): Number do return a; end;");
|
||||||
// VarDeclaration + Block + Return
|
// VarDeclaration + Function literal + Block + Return + identifier `a`
|
||||||
assert_eq!(counter.stmts, 3);
|
assert_eq!(counter.nodes, 5);
|
||||||
// Function literal + identifier `a`
|
|
||||||
assert_eq!(counter.exprs, 2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A visitor that aborts as soon as it sees an identifier, used to check
|
/// A visitor that aborts as soon as it sees an identifier, used to check
|
||||||
@@ -224,7 +206,7 @@ mod tests {
|
|||||||
struct FailOnIdentifier;
|
struct FailOnIdentifier;
|
||||||
|
|
||||||
impl Visitor for FailOnIdentifier {
|
impl Visitor for FailOnIdentifier {
|
||||||
fn visit_expr(&mut self, expr: &AstNode<Expr>) -> LoxResult<()> {
|
fn visit_expr(&mut self, expr: &AstNode) -> LoxResult<()> {
|
||||||
if let Expr::Identifier { .. } = &expr.node {
|
if let Expr::Identifier { .. } = &expr.node {
|
||||||
return runtime_error(expr.source_slice.clone(), "found an identifier");
|
return runtime_error(expr.source_slice.clone(), "found an identifier");
|
||||||
}
|
}
|
||||||
@@ -238,7 +220,7 @@ mod tests {
|
|||||||
let mut visitor = FailOnIdentifier;
|
let mut visitor = FailOnIdentifier;
|
||||||
let mut result = Ok(());
|
let mut result = Ok(());
|
||||||
for stmt in stmts.iter() {
|
for stmt in stmts.iter() {
|
||||||
result = visitor.visit_stmt(stmt);
|
result = visitor.visit_expr(stmt);
|
||||||
if result.is_err() {
|
if result.is_err() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
//! End-to-end frontend tests: source text -> lexer -> parser -> AST.
|
||||||
|
//!
|
||||||
|
//! These exercise the lexer and parser together through the public API and
|
||||||
|
//! assert on the resulting AST, complementing the per-module unit tests inside
|
||||||
|
//! `src/frontend/{lexer,parser}.rs`.
|
||||||
|
|
||||||
|
use rlox::common::ast::{AstNode, Expr};
|
||||||
|
use rlox::common::base_value::{BaseValue, Number};
|
||||||
|
use rlox::frontend::lexer::Lexer;
|
||||||
|
use rlox::frontend::parser::Parser;
|
||||||
|
use rlox::frontend::tokens::TokenType;
|
||||||
|
|
||||||
|
/// Run the full frontend pipeline on `src`.
|
||||||
|
fn parse(src: &str) -> Result<Vec<AstNode>, String> {
|
||||||
|
let tokens = Lexer::new(src.to_string(), 0)
|
||||||
|
.scans_tokens()
|
||||||
|
.map_err(|e| format!("lex error: {e}"))?;
|
||||||
|
Parser::new(tokens)
|
||||||
|
.parse()
|
||||||
|
.map_err(|e| format!("parse error: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `src`, panicking if the frontend reports any error.
|
||||||
|
fn parse_ok(src: &str) -> Vec<AstNode> {
|
||||||
|
parse(src).expect("expected source to lex and parse")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `src` and return the single node it should produce.
|
||||||
|
///
|
||||||
|
/// Statements and expressions share the unified `Expr`/`AstNode` type, so this
|
||||||
|
/// simply returns the node of the sole top-level statement.
|
||||||
|
fn single_stmt(src: &str) -> Expr {
|
||||||
|
let mut stmts = parse_ok(src);
|
||||||
|
assert_eq!(stmts.len(), 1, "expected exactly one statement for {src:?}");
|
||||||
|
stmts.remove(0).node
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `src` and return its single expression-statement's expression.
|
||||||
|
///
|
||||||
|
/// Expression statements aren't wrapped in a dedicated variant anymore; the
|
||||||
|
/// node itself is the expression.
|
||||||
|
fn single_expr(src: &str) -> Expr {
|
||||||
|
single_stmt(src)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Expressions
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lexes_and_parses_number_literal() {
|
||||||
|
match single_expr("42;") {
|
||||||
|
Expr::Literal { value } => assert_eq!(*value, BaseValue::Number(Number::I32(42))),
|
||||||
|
other => panic!("expected literal, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_string_and_boolean_literals() {
|
||||||
|
assert!(matches!(single_expr("true;"), Expr::Literal { .. }));
|
||||||
|
assert!(matches!(single_expr("\"hi\";"), Expr::Literal { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiplication_binds_tighter_than_addition() {
|
||||||
|
// 1 + 2 * 3 => (+ 1 (* 2 3))
|
||||||
|
match single_expr("1 + 2 * 3;") {
|
||||||
|
Expr::Binary {
|
||||||
|
operator, right, ..
|
||||||
|
} => {
|
||||||
|
assert_eq!(operator, TokenType::Plus);
|
||||||
|
assert!(matches!(
|
||||||
|
right.node,
|
||||||
|
Expr::Binary {
|
||||||
|
operator: TokenType::Star,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
other => panic!("expected binary, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grouping_overrides_precedence() {
|
||||||
|
// (1 + 2) * 3 => (* (group (+ 1 2)) 3)
|
||||||
|
match single_expr("(1 + 2) * 3;") {
|
||||||
|
Expr::Binary { operator, left, .. } => {
|
||||||
|
assert_eq!(operator, TokenType::Star);
|
||||||
|
assert!(matches!(left.node, Expr::Grouping { .. }));
|
||||||
|
}
|
||||||
|
other => panic!("expected binary, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_unary_operators() {
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("-5;"),
|
||||||
|
Expr::Unary {
|
||||||
|
operator: TokenType::Minus,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("!true;"),
|
||||||
|
Expr::Unary {
|
||||||
|
operator: TokenType::Bang,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_comparison_and_equality() {
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("1 < 2;"),
|
||||||
|
Expr::Binary {
|
||||||
|
operator: TokenType::Less,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("1 == 2;"),
|
||||||
|
Expr::Binary {
|
||||||
|
operator: TokenType::EqualEqual,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_logical_operators() {
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("true or false;"),
|
||||||
|
Expr::Binary {
|
||||||
|
operator: TokenType::Or,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
single_expr("true and false;"),
|
||||||
|
Expr::Binary {
|
||||||
|
operator: TokenType::And,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_call_with_arguments() {
|
||||||
|
match single_expr("add(1, 2);") {
|
||||||
|
Expr::Call { callee, arguments } => {
|
||||||
|
assert!(matches!(callee.node, Expr::Identifier { .. }));
|
||||||
|
assert_eq!(arguments.len(), 2);
|
||||||
|
}
|
||||||
|
other => panic!("expected call, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Assignment (now an expression)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assignment_is_an_expression_statement() {
|
||||||
|
match single_expr("x = 5;") {
|
||||||
|
Expr::Assign { name, .. } => assert_eq!(name, "x"),
|
||||||
|
other => panic!("expected assign, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assignment_is_right_associative() {
|
||||||
|
// a = b = c => (assign a (assign b c))
|
||||||
|
match single_expr("a = b = c;") {
|
||||||
|
Expr::Assign { name, value } => {
|
||||||
|
assert_eq!(name, "a");
|
||||||
|
match value.node {
|
||||||
|
Expr::Assign { name, .. } => assert_eq!(name, "b"),
|
||||||
|
other => panic!("expected nested assign, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => panic!("expected assign, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assignment_to_non_identifier_is_an_error() {
|
||||||
|
assert!(parse("1 = 2;").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Statements
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_var_declaration() {
|
||||||
|
match single_stmt("x := 5;") {
|
||||||
|
Expr::VarDeclaration {
|
||||||
|
name, initializer, ..
|
||||||
|
} => {
|
||||||
|
assert_eq!(name, "x");
|
||||||
|
assert!(initializer.is_some());
|
||||||
|
}
|
||||||
|
other => panic!("expected var declaration, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_print_statement() {
|
||||||
|
assert!(matches!(single_stmt("print 1;"), Expr::Print { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_block_with_multiple_statements() {
|
||||||
|
match single_stmt("do print 1; print 2; end") {
|
||||||
|
Expr::Block { statements, .. } => assert_eq!(statements.len(), 2),
|
||||||
|
other => panic!("expected block, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_if_else() {
|
||||||
|
match single_stmt("if true then print 1; else print 2;") {
|
||||||
|
Expr::If {
|
||||||
|
else_branch: Some(_),
|
||||||
|
..
|
||||||
|
} => {}
|
||||||
|
other => panic!("expected if/else, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_while_loop() {
|
||||||
|
assert!(matches!(
|
||||||
|
single_stmt("while true do print 1; end"),
|
||||||
|
Expr::While { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_for_loop_with_assignment_increment() {
|
||||||
|
match single_stmt("for i := 0; i <= 2; i = i + 1; do print i; end") {
|
||||||
|
Expr::For { increment, .. } => {
|
||||||
|
// The increment is an assignment expression.
|
||||||
|
assert!(matches!(increment.node, Expr::Assign { .. }))
|
||||||
|
}
|
||||||
|
other => panic!("expected for loop, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_function_declaration() {
|
||||||
|
match single_stmt("add :: fn (a, b): Number do return a + b; end;") {
|
||||||
|
Expr::VarDeclaration {
|
||||||
|
name, initializer, ..
|
||||||
|
} => {
|
||||||
|
assert_eq!(name, "add");
|
||||||
|
match initializer {
|
||||||
|
Some(init) => assert!(matches!(
|
||||||
|
&init.node,
|
||||||
|
Expr::Literal { value } if matches!(&**value, BaseValue::Function(_))
|
||||||
|
)),
|
||||||
|
None => panic!("expected a function initializer"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => panic!("expected function declaration, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Whole-program / error handling
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_a_multi_statement_program() {
|
||||||
|
let stmts = parse_ok("x := 1; y := 2; print x + y;");
|
||||||
|
assert_eq!(stmts.len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lexer_errors_surface_through_the_frontend() {
|
||||||
|
// Unterminated string is a lexical error reported by the lexer stage.
|
||||||
|
assert!(parse("\"unterminated;").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_semicolon_is_a_parse_error() {
|
||||||
|
assert!(parse("print 1").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unclosed_grouping_is_a_parse_error() {
|
||||||
|
assert!(parse("(1 + 2;").is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! End-to-end pipeline tests: lexer -> parser -> resolver -> interpreter.
|
||||||
|
//!
|
||||||
|
//! These verify chapter-11 resolution wired into execution: a variable's
|
||||||
|
//! resolved scope distance is used for lookup (`get_at`), and resolution errors
|
||||||
|
//! abort before running.
|
||||||
|
|
||||||
|
use rlox::backend::interpreter::{EvaluateInterpreter, Interpreter};
|
||||||
|
use rlox::common::base_value::BaseValue;
|
||||||
|
use rlox::frontend::lexer::Lexer;
|
||||||
|
use rlox::frontend::parser::Parser;
|
||||||
|
use rlox::middleend::variable_resolution::Resolver;
|
||||||
|
|
||||||
|
/// Run the whole pipeline, returning the value of the last statement.
|
||||||
|
fn run(src: &str) -> Result<BaseValue, String> {
|
||||||
|
let tokens = Lexer::new(src.to_string(), 0)
|
||||||
|
.scans_tokens()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let ast = Parser::new(tokens).parse().map_err(|e| e.to_string())?;
|
||||||
|
let locals = Resolver::resolve_program(&ast)
|
||||||
|
.map_err(|errors| errors.into_iter().next().unwrap().to_string())?;
|
||||||
|
let mut interpreter = Interpreter::new();
|
||||||
|
interpreter.set_locals(locals);
|
||||||
|
let mut last = BaseValue::Nil;
|
||||||
|
for stmt in ast {
|
||||||
|
last = interpreter.evaluate(stmt).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(last)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn block_local_variables_evaluate() {
|
||||||
|
assert_eq!(run("do x := 10; x + 5; end").unwrap().to_string(), "15");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolved_nested_closure_reads_captured_local() {
|
||||||
|
// `count` is read from inside a nested function, two scopes up; the
|
||||||
|
// resolver records distance 2 and the interpreter uses `get_at(2, ..)`.
|
||||||
|
let src = "\
|
||||||
|
make :: fn (): Any do
|
||||||
|
count := 10;
|
||||||
|
get :: fn (): Number do
|
||||||
|
return count;
|
||||||
|
end;
|
||||||
|
return get;
|
||||||
|
end;
|
||||||
|
g := make();
|
||||||
|
g();
|
||||||
|
";
|
||||||
|
assert_eq!(run(src).unwrap().to_string(), "10");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn use_before_initializer_is_rejected() {
|
||||||
|
let err = run("do x := x; end").expect_err("should be a resolution error");
|
||||||
|
assert!(err.contains("its own initializer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn top_level_return_is_rejected() {
|
||||||
|
let err = run("return 1;").expect_err("should be a resolution error");
|
||||||
|
assert!(err.contains("top-level"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_declaration_in_block_is_rejected() {
|
||||||
|
let err = run("do x := 1; x := 2; end").expect_err("should be a resolution error");
|
||||||
|
assert!(err.contains("Already a variable"));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user