implement chapter 12 in rust

This commit is contained in:
Sebastian Hugentobler 2025-05-25 16:04:00 +02:00
parent 283155c38b
commit 621c97102a
Signed by: shu
SSH key fingerprint: SHA256:ppcx6MlixdNZd5EUM1nkHOKoyQYoJwzuQKXM6J/t66M
10 changed files with 366 additions and 17 deletions

View file

@ -1,6 +1,7 @@
use crate::{
callable::{Callable, CallingError},
environment::Environment,
instance::Instance,
interpreter::Interpreter,
statement::Statement,
token::Token,
@ -13,6 +14,7 @@ use std::{cell::RefCell, fmt::Display, rc::Rc};
#[derive(Debug, Clone)]
pub struct Function {
pub name: Token,
pub is_initializer: bool,
pub params: Vec<Token>,
pub body: Vec<Statement>,
pub closure: Rc<RefCell<Environment>>,
@ -52,10 +54,24 @@ impl Callable for Function {
env.define(param.lexeme.clone(), arg);
}
let result = interpreter
Ok(interpreter
.block(&self.body, env)
.map_err(|e| CallingError::CallInterpretationFailed(e.to_string()))?
.unwrap_or(Value::Nil);
Ok(result)
.unwrap_or(Value::Nil))
}
}
impl Function {
pub fn bind(&self, instance: Rc<RefCell<Instance>>) -> Self {
let mut env = Environment::with_enclosing(self.closure.clone());
env.define("this".to_string(), Value::Instance(instance));
Self {
name: self.name.clone(),
is_initializer: self.is_initializer,
params: self.params.clone(),
body: self.body.clone(),
closure: Rc::new(RefCell::new(env)),
}
}
}