Interpreter - Filter non-static methods during class creation

This commit is contained in:
Emmanuel BENOîT 2023-01-12 08:47:16 +01:00
parent fb588e07a2
commit d2b66db852

View file

@ -1,13 +1,16 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use std::{cell::RefCell, collections::HashMap, rc::Rc};
use crate::{ use crate::{
ast::{ClassDecl, ExprNode, FunDecl, GetExpr, ProgramNode, SetExpr, StmtNode, VariableExpr}, ast::{
ClassDecl, ClassMemberDecl, ExprNode, FunDecl, GetExpr, ProgramNode, SetExpr, StmtNode,
VariableExpr,
},
errors::{ErrorKind, SloxError, SloxResult}, errors::{ErrorKind, SloxError, SloxResult},
resolver::ResolvedVariables, resolver::ResolvedVariables,
tokens::{Token, TokenType}, tokens::{Token, TokenType},
}; };
use super::{classes::{Class, PropertyCarrier}, functions::Function, Environment, EnvironmentRef, Value}; use super::{classes::Class, functions::Function, Environment, EnvironmentRef, Value};
/// Evaluate an interpretable, returning its value. /// Evaluate an interpretable, returning its value.
pub fn evaluate(ast: &ProgramNode, vars: ResolvedVariables) -> SloxResult<Value> { pub fn evaluate(ast: &ProgramNode, vars: ResolvedVariables) -> SloxResult<Value> {
@ -198,10 +201,10 @@ impl StmtNode {
fn on_class_decl(&self, es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult { fn on_class_decl(&self, es: &mut InterpreterState, decl: &ClassDecl) -> InterpreterResult {
es.environment.borrow_mut().define(&decl.name, None)?; es.environment.borrow_mut().define(&decl.name, None)?;
let methods = decl let methods = decl
.methods .members
.iter() .iter()
.map(|method| { .filter_map(|member| match member {
( ClassMemberDecl::Method(method) => Some((
method.name.lexeme.clone(), method.name.lexeme.clone(),
Function::new( Function::new(
Some(&method.name), Some(&method.name),
@ -210,7 +213,8 @@ impl StmtNode {
es.environment.clone(), es.environment.clone(),
method.name.lexeme == "init", method.name.lexeme == "init",
), ),
) )),
_ => None,
}) })
.collect::<HashMap<String, Function>>(); .collect::<HashMap<String, Function>>();
let class = Class::new(decl.name.lexeme.clone(), methods); let class = Class::new(decl.name.lexeme.clone(), methods);