Browse Source

Add else branch

github-actions
Garrit Franke 2 years ago
parent
commit
f0f20b950a
  1. 6
      examples/playground.sb
  2. 14
      src/parser/mod.rs
  3. 38
      src/parser/tests.rs

6
examples/playground.sb

@ -1,8 +1,10 @@
fn main() {
let num = 10
let num = 5
if num > 5 {
return num
} else if num <= 5 {
} else if num < 5 {
return 1
} else {
return num + 1
}
}

14
src/parser/mod.rs

@ -318,10 +318,22 @@ impl Parser {
match self.peek() {
Some(tok) if tok.kind == TokenKind::Keyword(Keyword::Else) => {
self.next_token();
let peeked = self.peek().ok_or_else(|| "Token expected")?;
let has_else = match &peeked.kind {
TokenKind::CurlyBracesOpen => Some(self.parse_block()?),
_ => None,
};
let else_branch = match has_else {
Some(branch) => branch,
None => self.parse_conditional_statement()?,
};
Ok(Statement::If(
condition,
Box::new(body),
Some(Box::new(self.parse_conditional_statement()?)),
Some(Box::new(else_branch)),
))
}
_ => Ok(Statement::If(condition, Box::new(body), None)),

38
src/parser/tests.rs

@ -298,3 +298,41 @@ fn test_parse_conditional_multiple_else_if_branch_branches() {
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}
#[test]
fn test_parse_conditional_else_branch() {
let raw = "
fn main(n) {
if n > 10 {
let x = 2 * n
return x
} else {
return n
}
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}
#[test]
fn test_parse_conditional_elseif_else_branch() {
let raw = "
fn main(n) {
if n > 10 {
let x = 2 * n
return x
} else if n < 10 {
return n
} else if n == 10 {
return n + 1
} else {
return n
}
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}

Loading…
Cancel
Save