Interpreter - Initialize methods when creating classes
This commit is contained in:
parent
392aaa630d
commit
e371217df0
2 changed files with 21 additions and 5 deletions
|
@ -5,12 +5,13 @@ use crate::{
|
|||
tokens::Token,
|
||||
};
|
||||
|
||||
use super::{Callable, InterpreterState, Value};
|
||||
use super::{functions::Function, Callable, InterpreterState, Value};
|
||||
|
||||
/// A Lox class.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Class {
|
||||
name: String,
|
||||
methods: HashMap<String, Function>,
|
||||
}
|
||||
|
||||
/// Classes are mostly used through references.
|
||||
|
@ -29,8 +30,8 @@ pub struct Instance {
|
|||
|
||||
impl Class {
|
||||
/// Create a new class, specifying its name.
|
||||
pub fn new(name: String) -> Self {
|
||||
Self { name }
|
||||
pub fn new(name: String, methods: HashMap<String, Function>) -> Self {
|
||||
Self { name, methods }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use std::{cell::RefCell, rc::Rc};
|
||||
use std::{cell::RefCell, collections::HashMap, rc::Rc};
|
||||
|
||||
use crate::{
|
||||
ast::{ClassDecl, ExprNode, FunDecl, GetExpr, ProgramNode, SetExpr, StmtNode},
|
||||
|
@ -197,7 +197,22 @@ impl StmtNode {
|
|||
/// 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());
|
||||
let methods = decl
|
||||
.methods
|
||||
.iter()
|
||||
.map(|method| {
|
||||
(
|
||||
method.name.lexeme.clone(),
|
||||
Function::new(
|
||||
Some(&method.name),
|
||||
&method.params,
|
||||
&method.body,
|
||||
es.environment.clone(),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<String, Function>>();
|
||||
let class = Class::new(decl.name.lexeme.clone(), methods);
|
||||
es.environment
|
||||
.borrow_mut()
|
||||
.assign(&decl.name, class.into())?;
|
||||
|
|
Loading…
Reference in a new issue