diff --git a/src/callable/function.rs b/src/callable/function.rs new file mode 100644 index 0000000..73c1760 --- /dev/null +++ b/src/callable/function.rs @@ -0,0 +1,35 @@ +use crate::{ + ast::Stmt, + callable::Callable, + environment::Env, + interpreter::{Interpreter, RuntimeError}, + span::Spanned, + value::Value, +}; + +#[derive(Clone, Debug)] +pub struct LoxFunction { + params: Vec, + body: Vec>, +} + +impl LoxFunction { + pub fn new(params: Vec, body: Vec>) -> Self { + Self { params, body } + } +} + +impl Callable for LoxFunction { + fn params(&self) -> Vec { + self.params.clone() + } + + fn call(&self, interpreter: &mut Interpreter, env: &Env) -> Result { + for stmt in &self.body { + if let Some(return_value) = interpreter.execute_stmt(stmt, env)? { + return Ok(return_value); + } + } + Ok(Value::Nil) + } +} diff --git a/src/callable/mod.rs b/src/callable/mod.rs new file mode 100644 index 0000000..14a1de8 --- /dev/null +++ b/src/callable/mod.rs @@ -0,0 +1,16 @@ +mod function; +mod native; + +use std::fmt::Debug; + +use crate::{environment::Env, interpreter::Interpreter, interpreter::RuntimeError, value::Value}; + +pub use function::LoxFunction; +pub use native::NativeFunction; + +pub trait Callable: Debug { + fn params(&self) -> Vec { + Vec::new() + } + fn call(&self, interpreter: &mut Interpreter, env: &Env) -> Result; +} diff --git a/src/callable.rs b/src/callable/native.rs similarity index 52% rename from src/callable.rs rename to src/callable/native.rs index 51b6414..d4c2a56 100644 --- a/src/callable.rs +++ b/src/callable/native.rs @@ -3,51 +3,17 @@ use std::{ time::SystemTime, }; -use crate::ast::Stmt; -use crate::interpreter::Interpreter; -use crate::span::Spanned; -use crate::{environment::Env, interpreter::RuntimeError, value::Value}; - -type CallableOutput = Result; - -pub trait Callable: Debug { - fn params(&self) -> Vec { - Vec::new() - } - fn call(&self, interpreter: &mut Interpreter, env: &Env) -> CallableOutput; -} - -#[derive(Clone, Debug)] -pub struct LoxFunction { - params: Vec, - body: Vec>, -} - -impl LoxFunction { - pub fn new(params: Vec, body: Vec>) -> Self { - Self { params, body } - } -} - -impl Callable for LoxFunction { - fn params(&self) -> Vec { - self.params.clone() - } - - fn call(&self, interpreter: &mut Interpreter, env: &Env) -> CallableOutput { - for stmt in &self.body { - if let Some(return_value) = interpreter.execute_stmt(stmt, env)? { - return Ok(return_value); - } - } - Ok(Value::Nil) - } -} +use crate::{ + callable::Callable, + environment::Env, + interpreter::{Interpreter, RuntimeError}, + value::Value, +}; pub struct NativeFunction { arity: usize, #[allow(clippy::type_complexity)] - implementation: Box CallableOutput>, + implementation: Box Result>, } impl NativeFunction {