From 692531ca652f36496e07b1da846d750dd7382833 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sat, 7 Jan 2023 14:21:10 +0100 Subject: [PATCH] Interpreter - Class declarations --- src/interpreter/interpretable.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/interpreter/interpretable.rs b/src/interpreter/interpretable.rs index 7639379..7144a6b 100644 --- a/src/interpreter/interpretable.rs +++ b/src/interpreter/interpretable.rs @@ -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 { 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(