Interpreter - Class declarations

This commit is contained in:
Emmanuel BENOîT 2023-01-07 14:21:10 +01:00
parent f834d84365
commit 692531ca65

View file

@ -1,13 +1,14 @@
use std::{cell::RefCell, rc::Rc};
use crate::{
ast::{ExprNode, FunDecl, ProgramNode, StmtNode},
ast::{ClassDecl, ExprNode, FunDecl, ProgramNode, StmtNode},
errors::{ErrorKind, SloxError, SloxResult},
interpreter::{functions::Function, Environment, EnvironmentRef, Value},
resolver::ResolvedVariables,
tokens::{Token, TokenType},
};
use super::{class::Class, functions::Function, Environment, EnvironmentRef, Value};
/// Evaluate an interpretable, returning its value.
pub fn evaluate(ast: &ProgramNode, vars: ResolvedVariables) -> SloxResult<Value> {
let mut state = InterpreterState::new(&vars);
@ -145,6 +146,7 @@ impl Interpretable for StmtNode {
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::Expression(expr) => expr.interpret(es),
StmtNode::Print(expr) => self.on_print(es, expr),
StmtNode::Block(statements) => self.on_block(es, statements),
@ -192,6 +194,16 @@ impl StmtNode {
Ok(InterpreterFlowControl::default())
}
/// Handle a class declaration
fn on_class_decl(&self, es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult {
es.environment.borrow_mut().define(&decl.name, None)?;
let class = Class::new(decl.name.lexeme.clone());
es.environment
.borrow_mut()
.assign(&decl.name, Value::Class(class))?;
Ok(InterpreterFlowControl::default())
}
/// Handle a function declaration.
fn on_fun_decl(&self, es: &mut InterpreterState, decl: &FunDecl) -> InterpreterResult {
let fun = Function::new(