Interpreter - Create superclass scope when defining subclasses

This commit is contained in:
Emmanuel BENOîT 2023-01-16 07:43:57 +01:00
parent cf909eef23
commit 60f86f28bc

View file

@ -225,22 +225,27 @@ impl StmtNode {
/// Handle a class declaration /// Handle a class declaration
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 superclass = match &decl.superclass { let class = match &decl.superclass {
None => None, None => Class::new(decl.name.lexeme.clone(), None, extract_members(es, decl)),
Some(superclass) => { Some(superclass) => {
let sc_value = superclass.interpret(es)?.result(); let sc_value = superclass.interpret(es)?.result();
if let Some(sc_ref) = sc_value.as_class_ref() { let sc_ref = if let Some(sc_ref) = sc_value.as_class_ref() {
Some(sc_ref) Some(sc_ref)
} else { } else {
return error(&superclass.token, "superclass must be a class"); return error(&superclass.token, "superclass must be a class");
} };
let mut sub_env = InterpreterState::create_child(es);
sub_env
.environment
.borrow_mut()
.set("super", sc_value.clone());
Class::new(
decl.name.lexeme.clone(),
sc_ref,
extract_members(&mut sub_env, decl),
)
} }
}; };
let class = Class::new(
decl.name.lexeme.clone(),
superclass,
extract_members(es, decl),
);
es.environment es.environment
.borrow_mut() .borrow_mut()
.assign(&decl.name, class.into())?; .assign(&decl.name, class.into())?;