Browse Source

Add conditional else if branch

github-actions
Garrit Franke 2 years ago
parent
commit
aaab0a4b28
  1. 13
      examples/playground.sb
  2. 5
      src/generator/js.rs
  3. 12
      src/parser/mod.rs
  4. 36
      src/parser/tests.rs

13
examples/playground.sb

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

5
src/generator/js.rs

@ -75,6 +75,11 @@ fn generate_conditional(
outcome += &generate_statement(statement);
}
outcome += "}";
if let Some(else_state) = else_state {
outcome += "else ";
outcome += &generate_statement(else_state);
}
outcome
}

12
src/parser/mod.rs

@ -316,7 +316,17 @@ impl Parser {
self.match_token(TokenKind::CurlyBracesClose)?;
Ok(Statement::If(condition, statements, None))
match self.peek() {
Some(tok) if tok.kind == TokenKind::Keyword(Keyword::Else) => {
self.next_token();
Ok(Statement::If(
condition,
statements,
Some(Box::new(self.parse_conditional_statement()?)),
))
}
_ => Ok(Statement::If(condition, statements, None)),
}
}
/// In some occurences a complex expression has been evaluated before a binary operation is encountered.

36
src/parser/tests.rs

@ -262,3 +262,39 @@ fn test_parse_basic_conditional_with_multiple_statements() {
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}
#[test]
fn test_parse_conditional_else_if_branch() {
let raw = "
fn main(n) {
if n > 10 {
let x = 2 * n
return x
} else if n <= 10 {
return n
}
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}
#[test]
fn test_parse_conditional_multiple_else_if_branch_branches() {
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
}
}
";
let tokens = tokenize(raw);
let tree = parse(tokens, Some(raw.to_string()));
assert!(tree.is_ok())
}

Loading…
Cancel
Save