Interpreter - Refactored internals out of the node implemntations

This commit is contained in:
Emmanuel BENOîT 2023-01-17 07:23:17 +01:00
parent b01ae10d09
commit 18d9bfb74c

View file

@ -1,7 +1,10 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use crate::{
ast::{ClassDecl, ExprNode, FunDecl, GetExpr, ProgramNode, SetExpr, StmtNode, VariableExpr},
ast::{
ClassDecl, ExprNode, FunDecl, GetExpr, ProgramNode, SetExpr, StmtNode, SuperExpr,
VariableExpr,
},
errors::{ErrorKind, SloxError, SloxResult},
resolver::ResolvedVariables,
tokens::{Token, TokenType},
@ -128,9 +131,9 @@ fn error<T>(token: &Token, message: &str) -> SloxResult<T> {
))
}
/* ----------------------------- *
* INTERPRETER FOR PROGRAM NODES *
* ----------------------------- */
/* -------------------------- *
* ENTRY POINTS FOR AST NODES *
* -------------------------- */
impl Interpretable for ProgramNode {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
@ -141,39 +144,85 @@ impl Interpretable for ProgramNode {
}
}
/* ------------------------------- *
* INTERPRETER FOR STATEMENT NODES *
* ------------------------------- */
impl Interpretable for StmtNode {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
match self {
StmtNode::VarDecl(name, expr) => self.on_var_decl(es, name, expr),
StmtNode::FunDecl(decl) => self.on_fun_decl(es, decl),
StmtNode::ClassDecl(decl) => self.on_class_decl(es, decl),
StmtNode::VarDecl(name, expr) => on_var_decl(es, name, expr),
StmtNode::FunDecl(decl) => on_fun_decl(es, decl),
StmtNode::ClassDecl(decl) => on_class_decl(es, decl),
StmtNode::Expression(expr) => expr.interpret(es),
StmtNode::Print(expr) => self.on_print(es, expr),
StmtNode::Block(statements) => self.on_block(es, statements),
StmtNode::Print(expr) => on_print(es, expr),
StmtNode::Block(statements) => on_block(es, statements),
StmtNode::If {
condition,
then_branch,
else_branch,
} => self.on_if_statement(es, condition, then_branch, else_branch),
} => on_if_statement(es, condition, then_branch, else_branch),
StmtNode::Loop {
label,
condition,
body,
after_body,
} => self.on_loop_statement(es, label, condition, body, after_body),
} => on_loop_statement(es, label, condition, body, after_body),
StmtNode::LoopControl {
is_break,
loop_name,
} => self.on_loop_control_statemement(*is_break, loop_name),
StmtNode::Return { token: _, value } => self.on_return_statement(es, value),
} => on_loop_control_statemement(*is_break, loop_name),
StmtNode::Return { token: _, value } => on_return_statement(es, value),
}
}
}
impl Interpretable for ExprNode {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
match self {
ExprNode::Assignment { name, value, id } => {
let value = value.interpret(es)?.result();
es.assign_var(name, id, value)?;
Ok(InterpreterFlowControl::default())
}
ExprNode::Logical(binary_expr) => on_logic(
es,
&binary_expr.left,
&binary_expr.operator,
&binary_expr.right,
),
ExprNode::Binary(binary_expr) => on_binary(
es,
&binary_expr.left,
&binary_expr.operator,
&binary_expr.right,
),
ExprNode::Unary { operator, right } => on_unary(es, operator, right),
ExprNode::Grouping { expression } => expression.interpret(es),
ExprNode::Litteral { value } => on_litteral(value),
ExprNode::Variable(var_expr) | ExprNode::This(var_expr) => var_expr.interpret(es),
ExprNode::Call {
callee,
right_paren,
arguments,
} => on_call(es, callee, right_paren, arguments),
ExprNode::Lambda { params, body } => {
let lambda = Function::new(None, params, body, es.environment.clone(), false);
Ok(Value::from(lambda).into())
}
ExprNode::Get(get_expr) => on_get_expression(es, get_expr),
ExprNode::Set(set_expr) => on_set_expression(es, set_expr),
ExprNode::Super(super_expr) => on_super(es, super_expr),
}
}
}
impl Interpretable for VariableExpr {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
Ok(es.lookup_var(self)?.into())
}
}
/* --------------------- *
* INTERPRETER INTERNALS *
* --------------------- */
/// Extract members from a class declaration, generating a map of
/// functions.
fn extract_members(
@ -198,9 +247,8 @@ fn extract_members(
.collect()
}
impl StmtNode {
/// Handle the `print` statement.
fn on_print(&self, es: &mut InterpreterState, expr: &ExprNode) -> InterpreterResult {
fn on_print(es: &mut InterpreterState, expr: &ExprNode) -> InterpreterResult {
let value = expr.interpret(es)?.result();
let output = value.to_string();
println!("{}", output);
@ -209,7 +257,6 @@ impl StmtNode {
/// Handle a variable declaration.
fn on_var_decl(
&self,
es: &mut InterpreterState,
name: &Token,
initializer: &Option<ExprNode>,
@ -223,7 +270,7 @@ impl StmtNode {
}
/// Handle a class declaration
fn on_class_decl(&self, es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult {
fn on_class_decl(es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult {
es.environment.borrow_mut().define(&decl.name, None)?;
let class = match &decl.superclass {
None => Class::new(decl.name.lexeme.clone(), None, extract_members(es, decl)),
@ -253,7 +300,7 @@ impl StmtNode {
}
/// Handle a function declaration.
fn on_fun_decl(&self, es: &mut InterpreterState, decl: &FunDecl) -> InterpreterResult {
fn on_fun_decl(es: &mut InterpreterState, decl: &FunDecl) -> InterpreterResult {
let fun = Function::new(
Some(&decl.name),
&decl.params,
@ -268,7 +315,7 @@ impl StmtNode {
}
/// Execute the contents of a block.
fn on_block(&self, es: &mut InterpreterState, stmts: &[StmtNode]) -> InterpreterResult {
fn on_block(es: &mut InterpreterState, stmts: &[StmtNode]) -> InterpreterResult {
let mut child = InterpreterState::create_child(es);
for stmt in stmts.iter() {
let result = stmt.interpret(&mut child)?;
@ -281,7 +328,6 @@ impl StmtNode {
/// Execute an if statement.
fn on_if_statement(
&self,
es: &mut InterpreterState,
condition: &ExprNode,
then_branch: &StmtNode,
@ -298,7 +344,6 @@ impl StmtNode {
/// Execute a while statement.
fn on_loop_statement(
&self,
es: &mut InterpreterState,
label: &Option<Token>,
condition: &ExprNode,
@ -328,11 +373,7 @@ impl StmtNode {
}
/// Execute a loop control statement.
fn on_loop_control_statemement(
&self,
is_break: bool,
label: &Option<Token>,
) -> InterpreterResult {
fn on_loop_control_statemement(is_break: bool, label: &Option<Token>) -> InterpreterResult {
let name = label.as_ref().map(|token| token.lexeme.clone());
if is_break {
Ok(InterpreterFlowControl::Break(name))
@ -342,93 +383,16 @@ impl StmtNode {
}
/// Execute a return statement.
fn on_return_statement(
&self,
es: &mut InterpreterState,
value: &Option<ExprNode>,
) -> InterpreterResult {
fn on_return_statement(es: &mut InterpreterState, value: &Option<ExprNode>) -> InterpreterResult {
let rv = match value {
None => Value::Nil,
Some(expr) => expr.interpret(es)?.result(),
};
Ok(InterpreterFlowControl::Return(rv))
}
}
/* -------------------------------- *
* INTERPRETER FOR EXPRESSION NODES *
* -------------------------------- */
impl Interpretable for ExprNode {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
match self {
ExprNode::Assignment { name, value, id } => {
let value = value.interpret(es)?.result();
es.assign_var(name, id, value)?;
Ok(InterpreterFlowControl::default())
}
ExprNode::Logical(binary_expr) => self.on_logic(
es,
&binary_expr.left,
&binary_expr.operator,
&binary_expr.right,
),
ExprNode::Binary(binary_expr) => self.on_binary(
es,
&binary_expr.left,
&binary_expr.operator,
&binary_expr.right,
),
ExprNode::Unary { operator, right } => self.on_unary(es, operator, right),
ExprNode::Grouping { expression } => expression.interpret(es),
ExprNode::Litteral { value } => self.on_litteral(value),
ExprNode::Variable(var_expr) | ExprNode::This(var_expr) => var_expr.interpret(es),
ExprNode::Call {
callee,
right_paren,
arguments,
} => self.on_call(es, callee, right_paren, arguments),
ExprNode::Lambda { params, body } => {
let lambda = Function::new(None, params, body, es.environment.clone(), false);
Ok(Value::from(lambda).into())
}
ExprNode::Get(get_expr) => self.on_get_expression(es, get_expr),
ExprNode::Set(set_expr) => self.on_set_expression(es, set_expr),
ExprNode::Super(super_expr) => {
let distance = match es.locals.get(&super_expr.keyword.id) {
Some(distance) => *distance,
None => panic!("super environment not found"),
};
assert!(distance > 0);
let obj_ref = es.environment.borrow().get_at(
distance - 1,
&Token {
token_type: TokenType::This,
lexeme: "this".to_owned(),
line: 0,
},
)?;
Ok(obj_ref
.with_property_carrier(
|inst| inst.get_super(es, &super_expr, distance),
|| panic!("'this' didn't contain an instance"),
)?
.into())
}
}
}
}
impl Interpretable for VariableExpr {
fn interpret(&self, es: &mut InterpreterState) -> InterpreterResult {
Ok(es.lookup_var(self)?.into())
}
}
impl ExprNode {
/// Evaluate a logical operator.
fn on_logic(
&self,
es: &mut InterpreterState,
left: &ExprNode,
operator: &Token,
@ -446,7 +410,6 @@ impl ExprNode {
/// Evaluate a binary operator.
fn on_binary(
&self,
es: &mut InterpreterState,
left: &ExprNode,
operator: &Token,
@ -468,9 +431,7 @@ impl ExprNode {
TokenType::Star => match (left_value, right_value) {
(Value::Number(a), Value::Number(b)) => Ok(Value::Number(a * b).into()),
(Value::String(a), Value::Number(b)) => {
Ok(Value::String(a.repeat(b as usize)).into())
}
(Value::String(a), Value::Number(b)) => Ok(Value::String(a.repeat(b as usize)).into()),
_ => error(operator, "type error"),
},
@ -516,12 +477,7 @@ impl ExprNode {
}
/// Evaluate an unary operator.
fn on_unary(
&self,
es: &mut InterpreterState,
operator: &Token,
right: &ExprNode,
) -> InterpreterResult {
fn on_unary(es: &mut InterpreterState, operator: &Token, right: &ExprNode) -> InterpreterResult {
let right_value = right.interpret(es)?.result();
match operator.token_type {
TokenType::Minus => {
@ -542,7 +498,7 @@ impl ExprNode {
}
/// Evaluate a litteral.
fn on_litteral(&self, value: &Token) -> InterpreterResult {
fn on_litteral(value: &Token) -> InterpreterResult {
let out_value = match &value.token_type {
TokenType::Nil => Value::Nil,
TokenType::True => Value::Boolean(true),
@ -556,7 +512,6 @@ impl ExprNode {
/// Evaluate a function call.
fn on_call(
&self,
es: &mut InterpreterState,
callee: &ExprNode,
right_paren: &Token,
@ -591,11 +546,7 @@ impl ExprNode {
}
/// Evaluate a get expression.
fn on_get_expression(
&self,
itpr_state: &mut InterpreterState,
get_expr: &GetExpr,
) -> InterpreterResult {
fn on_get_expression(itpr_state: &mut InterpreterState, get_expr: &GetExpr) -> InterpreterResult {
let instance = get_expr.instance.interpret(itpr_state)?.result();
instance.with_property_carrier(
|inst| inst.get(itpr_state, &get_expr.name).map(|v| v.into()),
@ -604,11 +555,7 @@ impl ExprNode {
}
/// Evaluate a set expression.
fn on_set_expression(
&self,
itpr_state: &mut InterpreterState,
set_expr: &SetExpr,
) -> InterpreterResult {
fn on_set_expression(itpr_state: &mut InterpreterState, set_expr: &SetExpr) -> InterpreterResult {
let instance = set_expr.instance.interpret(itpr_state)?.result();
instance.with_property_carrier(
|instance| {
@ -619,4 +566,26 @@ impl ExprNode {
|| error(&set_expr.name, "this object doesn't have properties"),
)
}
/// Evaluate a reference to a superclass method.
fn on_super(itpr_state: &mut InterpreterState, super_expr: &SuperExpr) -> InterpreterResult {
let distance = match itpr_state.locals.get(&super_expr.keyword.id) {
Some(distance) => *distance,
None => panic!("super environment not found"),
};
assert!(distance > 0);
let obj_ref = itpr_state.environment.borrow().get_at(
distance - 1,
&Token {
token_type: TokenType::This,
lexeme: "this".to_owned(),
line: 0,
},
)?;
Ok(obj_ref
.with_property_carrier(
|inst| inst.get_super(itpr_state, &super_expr, distance),
|| panic!("'this' didn't contain an instance"),
)?
.into())
}