Interpreter finish

This commit is contained in:
Moritz Gmeiner 2023-01-28 21:11:01 +01:00
commit 647a095a05
5 changed files with 29 additions and 21 deletions

View file

@ -133,7 +133,7 @@ impl Eval for Expr {
.collect::<EvalResult<Vec<Value>>>()?;
match callee {
Value::Function(fun) => fun.call(args, env),
Value::Function(fun) => LoxFunction::call(fun, args, env),
Value::ExternFunction(ext_fun) => ext_fun.call(args, env),
Value::Class(class) => LoxClass::call(class, args, env),
_ => Err(RuntimeError::NotCallable { callee }),
@ -286,22 +286,26 @@ impl Eval for Stmt {
/*====================================================================================================================*/
impl LoxFunction {
pub fn call(&self, args: Vec<Value>, env: &mut Environment) -> EvalResult<Value> {
if args.len() != self.arity() {
pub fn call(fun: Rc<LoxFunction>, args: Vec<Value>, env: &mut Environment) -> EvalResult<Value> {
if args.len() != fun.arity() {
return Err(RuntimeError::WrongArity {
name: self.name().to_owned(),
arity: self.arity(),
name: fun.name().to_owned(),
arity: fun.arity(),
given: args.len(),
});
}
env.push_scope(self.closure().clone());
env.enter_scope();
for (name, value) in std::iter::zip(self.param_names(), args) {
env.define(fun.name(), Value::Function(fun.clone()));
env.insert_closure(fun.closure().clone());
for (name, value) in std::iter::zip(fun.param_names(), args) {
env.define(name, value);
}
let ret_val = match self.body().eval(env) {
let ret_val = match fun.body().eval(env) {
Ok(_) => Ok(Value::Nil),
Err(RuntimeError::Return { value }) => Ok(value),
Err(err) => Err(err),
@ -343,7 +347,7 @@ impl LoxClass {
// object.init(args, env)?;
if let Some(Value::Function(method)) = object.get("init") {
method.call(args, env)?;
LoxFunction::call(method, args, env)?;
}
Ok(Value::Object(object))