Skip to content

Commit

Permalink
🎁 added return statements
Browse files Browse the repository at this point in the history
  • Loading branch information
aym-n committed Jan 7, 2024
1 parent 6aac37d commit 870ed04
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
6 changes: 3 additions & 3 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ pub enum Error {
ParseError { token: Token, message: String },
RuntimeError { token: Token, message: String },
SystemError { message: String },
ReturnValue { value: Object },
Return { value: Object },
}

impl Error {
pub fn return_value(value: Object) -> Error {
Error::ReturnValue { value }
Error::Return { value }
}

pub fn parse_error(token: &Token, message: &str) -> Error {
Expand Down Expand Up @@ -51,7 +51,7 @@ impl Error {
Error::SystemError { message } => {
eprintln!("System Error: {message}");
}
Error::ReturnValue { .. } => {}
Error::Return { .. } => {}
};
}
}
11 changes: 9 additions & 2 deletions src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,15 @@ impl CallableTrait for Function {
e.define(param.lexeme.clone(), arg.clone());
}

interpreter.execute_block(&self.body, e)?;
Ok(Object::Nil)
match interpreter.execute_block(&self.body, e) {
Ok(_) => Ok(Object::Nil),
Err(e) => {
match e {
Error::Return { value } => Ok(value),
_ => Err(e),
}
}
}
}

fn arity(&self) -> usize {
Expand Down
7 changes: 6 additions & 1 deletion src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ pub struct Interpreter {

impl StmtVisitor<()> for Interpreter {
fn visit_return_stmt(&self, stmt: &ReturnStmt) -> Result<(), Error> {
Ok(())
if let Some(value) = &stmt.value {
let value = self.evaluate(value)?;
Err(Error::return_value(value))
} else {
Err(Error::return_value(Object::Nil))
}
}
fn visit_function_stmt(&self, stmt: &FunctionStmt) -> Result<(), Error>{
let function = Function::new(&stmt);
Expand Down

0 comments on commit 870ed04

Please sign in to comment.