Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

+ while break continue syntax #11

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 24 additions & 22 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ pub enum Expr {
consequence: BlockStmt,
alternative: Option<BlockStmt>,
},
While {
cond: Box<Expr>,
consequence: BlockStmt,
},
Func {
params: Vec<Ident>,
body: BlockStmt,
Expand All @@ -85,6 +89,8 @@ pub enum Literal {
#[derive(PartialEq, Clone, Debug)]
pub enum Stmt {
Blank,
Break,
Continue,
Let(Ident, Expr),
Return(Expr),
Expr(Expr),
Expand Down
80 changes: 80 additions & 0 deletions src/evaluator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,26 @@ impl Evaluator {
result
}

fn eval_block_stmt_with_continue_and_break_statement(&mut self, stmts: BlockStmt) -> Option<Object> {
let mut result = None;

for stmt in stmts {
if stmt == Stmt::Blank {
continue;
}

match self.eval_stmt(stmt) {
Some(Object::ReturnValue(value)) => return Some(Object::ReturnValue(value)),
Some(Object::BreakStatement) => return Some(Object::BreakStatement),
Some(Object::ContinueStatement) => return Some(Object::ContinueStatement),
Some(Object::Error(msg)) => return Some(Object::Error(msg)),
obj => result = obj,
}
}

result
}

fn eval_stmt(&mut self, stmt: Stmt) -> Option<Object> {
match stmt {
Stmt::Let(ident, expr) => {
Expand All @@ -88,6 +108,8 @@ impl Evaluator {
None
}
}
Stmt::Break => Some(Object::BreakStatement),
Stmt::Continue => Some(Object::ContinueStatement),
Stmt::Expr(expr) => self.eval_expr(expr),
Stmt::Return(expr) => {
let value = match self.eval_expr(expr) {
Expand Down Expand Up @@ -136,6 +158,7 @@ impl Evaluator {
consequence,
alternative,
} => self.eval_if_expr(*cond, consequence, alternative),
Expr::While { cond, consequence } => self.eval_while_expr(&*cond, consequence),
Expr::Func { params, body } => Some(Object::Func(params, body, Rc::clone(&self.env))),
Expr::Call { func, args } => Some(self.eval_call_expr(func, args)),
}
Expand Down Expand Up @@ -313,6 +336,37 @@ impl Evaluator {
}
}


fn eval_while_expr(&mut self, cond: &Expr, consequence: BlockStmt) -> Option<Object> {
let mut result: Option<Object> = None;

loop {
let cond_result = match self.eval_expr(cond.clone()) {
Some(cond) => cond,
None => break,
};
if !Self::is_truthy(cond_result.clone()) {
break;
}

result = self.eval_block_stmt_with_continue_and_break_statement(consequence.clone());
match result {
Some(Object::BreakStatement) => {
result = Some(Object::Null);
break;
},
Some(Object::ContinueStatement) => {
result = Some(Object::Null);
continue;
},
Some(Object::ReturnValue(value)) => return Some(Object::ReturnValue(value)),
_ => {}
}
}

result
}

fn eval_call_expr(&mut self, func: Box<Expr>, args: Vec<Expr>) -> Object {
let args = args
.iter()
Expand Down Expand Up @@ -690,6 +744,32 @@ identity(100);
}
}

#[test]
fn test_while_application() {
let tests = vec![
(
"let a = 0; while (a < 5) { let a = a + 1; }; a;",
Some(Object::Int(5)),
),
(
"let a = 0; while (a < 5) { let a = a + 1; if (a == 2) { return 2; } }; a;",
Some(Object::Int(2)),
),
(
"let a = 0; let b = 0; while (a < 5) { let a = a + 1; if (a == 2) { break; } let b = b + 1; }; b;",
Some(Object::Int(1)),
),
(
"let a = 0; let b = 0; while (a < 5) { let a = a + 1; if (a == 2) { continue; } let b = b + 1; }; b;",
Some(Object::Int(4)),
),
];

for (input, expect) in tests {
assert_eq!(expect, eval(input));
}
}

#[test]
fn test_closures() {
let input = r#"
Expand Down
4 changes: 4 additions & 0 deletions src/evaluator/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub enum Object {
Func(Vec<Ident>, BlockStmt, Rc<RefCell<Env>>),
Builtin(i32, BuiltinFunc),
Null,
BreakStatement,
ContinueStatement,
ReturnValue(Box<Object>),
Error(String),
}
Expand Down Expand Up @@ -63,6 +65,8 @@ impl fmt::Display for Object {
}
Object::Builtin(_, _) => write!(f, "[builtin function]"),
Object::Null => write!(f, "null"),
Object::BreakStatement => write!(f, "break statement"),
Object::ContinueStatement => write!(f, "continue statement"),
Object::ReturnValue(ref value) => write!(f, "{}", value),
Object::Error(ref value) => write!(f, "{}", value),
}
Expand Down
42 changes: 42 additions & 0 deletions src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ impl Formatter {
alternative: _,
}
| &Expr::Func { params: _, body: _ } => true,
| &Expr::While { cond: _, consequence: _ } => true,
_ => false,
}
}
Expand Down Expand Up @@ -101,6 +102,8 @@ impl Formatter {
match stmt {
Stmt::Let(ident, expr) => self.format_let_stmt(ident, expr),
Stmt::Return(expr) => self.format_return_stmt(expr),
Stmt::Break => String::from("break;"),
Stmt::Continue => String::from("continue;"),
Stmt::Expr(expr) => {
if Self::ignore_semicolon_expr(&expr) {
self.format_expr(expr, Precedence::Lowest)
Expand Down Expand Up @@ -147,6 +150,7 @@ impl Formatter {
} => self.format_if_expr(cond, consequence, alternative),
Expr::Func { params, body } => self.format_func_expr(params, body),
Expr::Call { func, args } => self.format_call_expr(func, args),
Expr::While { cond, consequence } => self.format_while_expr(cond, consequence),
}
}

Expand Down Expand Up @@ -385,6 +389,20 @@ impl Formatter {

format!("{}({})", func_str, args_str)
}

fn format_while_expr(&mut self, cond: Box<Expr>, consequence: BlockStmt) -> String {
let cond_str = self.format_expr(*cond, Precedence::Lowest);
self.indent += 1;

let consequence_str = self.format_block_stmt(consequence);
self.indent -= 1;

let result = format!(
"while ({}) {{\n{}\n{}}}",
cond_str, consequence_str, self.indent_str(0)
);
result
}
}

#[cfg(test)]
Expand Down Expand Up @@ -696,6 +714,30 @@ fn (y) {y;}
}
}

#[test]
fn test_while_expr() {
let tests = vec![
(
"while ( x ){ break}",
r#"while (x) {
break;
}"#,
),
(
r#"while (x) {
continue
}"#,
r#"while (x) {
continue;
}"#,
),
];

for (input, expect) in tests {
assert_eq!(String::from(expect), format(input));
}
}

#[test]
fn test_call_expr() {
let tests = vec![
Expand Down
3 changes: 3 additions & 0 deletions src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ impl<'a> Lexer<'a> {
"if" => Token::If,
"else" => Token::Else,
"return" => Token::Return,
"while" => Token::While,
"break" => Token::Break,
"continue" => Token::Continue,
_ => Token::Ident(String::from(literal)),
}
}
Expand Down
Loading