implement chapter 12 in rust
This commit is contained in:
parent
283155c38b
commit
621c97102a
10 changed files with 366 additions and 17 deletions
|
@ -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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue