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,32 +247,30 @@ fn extract_members(
.collect()
}
impl StmtNode {
/// Handle the `print` statement.
fn on_print(&self, es: &mut InterpreterState, expr: &ExprNode) -> InterpreterResult {
/// Handle the `print` statement.
fn on_print(es: &mut InterpreterState, expr: &ExprNode) -> InterpreterResult {
let value = expr.interpret(es)?.result();
let output = value.to_string();
println!("{}", output);
Ok(InterpreterFlowControl::default())
}
}
/// Handle a variable declaration.
fn on_var_decl(
&self,
/// Handle a variable declaration.
fn on_var_decl(
es: &mut InterpreterState,
name: &Token,
initializer: &Option<ExprNode>,
) -> InterpreterResult {
) -> InterpreterResult {
let variable = match initializer {
Some(expr) => Some(expr.interpret(es)?.result()),
None => None,
};
es.environment.borrow_mut().define(name, variable)?;
Ok(InterpreterFlowControl::default())
}
}
/// Handle a class declaration
fn on_class_decl(&self, es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult {
/// Handle a class declaration
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)),
@ -250,10 +297,10 @@ impl StmtNode {
.borrow_mut()
.assign(&decl.name, class.into())?;
Ok(InterpreterFlowControl::default())
}
}
/// Handle a function declaration.
fn on_fun_decl(&self, es: &mut InterpreterState, decl: &FunDecl) -> InterpreterResult {
/// Handle a function declaration.
fn on_fun_decl(es: &mut InterpreterState, decl: &FunDecl) -> InterpreterResult {
let fun = Function::new(
Some(&decl.name),
&decl.params,
@ -265,10 +312,10 @@ impl StmtNode {
.borrow_mut()
.define(&decl.name, Some(fun.into()))?;
Ok(InterpreterFlowControl::default())
}
}
/// Execute the contents of a block.
fn on_block(&self, es: &mut InterpreterState, stmts: &[StmtNode]) -> InterpreterResult {
/// Execute the contents of a block.
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)?;
@ -277,16 +324,15 @@ impl StmtNode {
}
}
Ok(InterpreterFlowControl::default())
}
}
/// Execute an if statement.
fn on_if_statement(
&self,
/// Execute an if statement.
fn on_if_statement(
es: &mut InterpreterState,
condition: &ExprNode,
then_branch: &StmtNode,
else_branch: &Option<Box<StmtNode>>,
) -> InterpreterResult {
) -> InterpreterResult {
if condition.interpret(es)?.result().is_truthy() {
then_branch.interpret(es)
} else if let Some(else_stmt) = else_branch {
@ -294,17 +340,16 @@ impl StmtNode {
} else {
Ok(InterpreterFlowControl::default())
}
}
}
/// Execute a while statement.
fn on_loop_statement(
&self,
/// Execute a while statement.
fn on_loop_statement(
es: &mut InterpreterState,
label: &Option<Token>,
condition: &ExprNode,
body: &StmtNode,
after_body: &Option<Box<StmtNode>>,
) -> InterpreterResult {
) -> InterpreterResult {
let ln = label.as_ref().map(|token| token.lexeme.clone());
while condition.interpret(es)?.result().is_truthy() {
let result = body.interpret(es)?;
@ -325,115 +370,34 @@ impl StmtNode {
}
}
Ok(InterpreterFlowControl::default())
}
}
/// Execute a loop control statement.
fn on_loop_control_statemement(
&self,
is_break: bool,
label: &Option<Token>,
) -> InterpreterResult {
/// Execute a loop control statement.
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))
} else {
Ok(InterpreterFlowControl::Continue(name))
}
}
}
/// Execute a return statement.
fn on_return_statement(
&self,
es: &mut InterpreterState,
value: &Option<ExprNode>,
) -> InterpreterResult {
/// Execute a return statement.
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,
/// Evaluate a logical operator.
fn on_logic(
es: &mut InterpreterState,
left: &ExprNode,
operator: &Token,
right: &ExprNode,
) -> InterpreterResult {
) -> InterpreterResult {
let left_value = left.interpret(es)?.result();
if operator.token_type == TokenType::Or && left_value.is_truthy()
|| operator.token_type == TokenType::And && !left_value.is_truthy()
@ -442,16 +406,15 @@ impl ExprNode {
} else {
right.interpret(es)
}
}
}
/// Evaluate a binary operator.
fn on_binary(
&self,
/// Evaluate a binary operator.
fn on_binary(
es: &mut InterpreterState,
left: &ExprNode,
operator: &Token,
right: &ExprNode,
) -> InterpreterResult {
) -> InterpreterResult {
let left_value = left.interpret(es)?.result();
let right_value = right.interpret(es)?.result();
match operator.token_type {
@ -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"),
},
@ -513,15 +474,10 @@ impl ExprNode {
operator
),
}
}
}
/// Evaluate an unary operator.
fn on_unary(
&self,
es: &mut InterpreterState,
operator: &Token,
right: &ExprNode,
) -> InterpreterResult {
/// Evaluate an unary operator.
fn on_unary(es: &mut InterpreterState, operator: &Token, right: &ExprNode) -> InterpreterResult {
let right_value = right.interpret(es)?.result();
match operator.token_type {
TokenType::Minus => {
@ -539,10 +495,10 @@ impl ExprNode {
operator
),
}
}
}
/// Evaluate a litteral.
fn on_litteral(&self, value: &Token) -> InterpreterResult {
/// Evaluate a litteral.
fn on_litteral(value: &Token) -> InterpreterResult {
let out_value = match &value.token_type {
TokenType::Nil => Value::Nil,
TokenType::True => Value::Boolean(true),
@ -552,16 +508,15 @@ impl ExprNode {
_ => panic!("Unsupported token type for litteral (token {:?})", value),
};
Ok(out_value.into())
}
}
/// Evaluate a function call.
fn on_call(
&self,
/// Evaluate a function call.
fn on_call(
es: &mut InterpreterState,
callee: &ExprNode,
right_paren: &Token,
arguments: &Vec<ExprNode>,
) -> InterpreterResult {
) -> InterpreterResult {
let callee = callee.interpret(es)?.result();
let arg_values = {
let mut v = Vec::with_capacity(arguments.len());
@ -588,27 +543,19 @@ impl ExprNode {
},
|| error(right_paren, "expression result is not callable"),
)
}
}
/// Evaluate a get expression.
fn on_get_expression(
&self,
itpr_state: &mut InterpreterState,
get_expr: &GetExpr,
) -> InterpreterResult {
/// Evaluate a get expression.
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()),
|| error(&get_expr.name, "this object doesn't have properties"),
)
}
}
/// Evaluate a set expression.
fn on_set_expression(
&self,
itpr_state: &mut InterpreterState,
set_expr: &SetExpr,
) -> InterpreterResult {
/// Evaluate a set expression.
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| {
@ -618,5 +565,27 @@ 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())
}