Implement elif

This commit is contained in:
imaqtkatt 2024-05-27 08:15:36 -03:00
parent ddb964fb85
commit 24b3219016
5 changed files with 69 additions and 0 deletions

View File

@ -532,6 +532,21 @@ impl<'a> PyParser<'a> {
if nxt_indent != *indent {
return self.expected_indent(*indent, nxt_indent);
}
let mut elifs = Vec::new();
while self.try_parse_keyword("elif") {
let cond = self.parse_expr(true)?;
self.skip_trivia_inline();
self.consume_exactly(":")?;
indent.enter_level();
self.consume_indent_exactly(*indent)?;
let (then, nxt_indent) = self.parse_statement(indent)?;
indent.exit_level();
if nxt_indent != *indent {
return self.expected_indent(*indent, nxt_indent);
}
elifs.push((cond, then));
}
self.parse_keyword("else")?;
self.skip_trivia_inline();
self.consume_exactly(":")?;
@ -539,6 +554,13 @@ impl<'a> PyParser<'a> {
self.consume_indent_exactly(*indent)?;
let (otherwise, nxt_indent) = self.parse_statement(indent)?;
let otherwise = elifs.into_iter().fold(otherwise, |acc, (cond, then)| Stmt::If {
cond: Box::new(cond),
then: Box::new(then),
otherwise: Box::new(acc),
nxt: None,
});
indent.exit_level();
if nxt_indent == *indent {
let (nxt, nxt_indent) = self.parse_statement(indent)?;

View File

@ -0,0 +1,16 @@
def main:
cond1 = 1 == 2
cond2 = 2 < 1
cond3 = 3 > 2
cond4 = 2 == 2
if cond1:
res = 1
elif cond2:
res = 2
elif cond3:
res = 3
elif cond4:
res = 4
else:
res = 0
return res

View File

@ -0,0 +1,5 @@
def main:
if 1 == 1:
return 0
elif 2 == 2:
return 1

View File

@ -0,0 +1,18 @@
---
source: tests/golden_tests.rs
input_file: tests/golden_tests/compile_file/elif.bend
---
@main = d
& @main__C3 ~ (a (b (c d)))
& $(1 a) ~ [<2]
& $(2 b) ~ [>3]
& $(2 c) ~ [=2]
@main__C0 = (?((0 (* 2)) a) a)
@main__C1 = (a (?((@main__C0 (* (* 3))) (a b)) b))
@main__C2 = (a (b (?((@main__C1 (* (* (* 4)))) (a (b c))) c)))
@main__C3 = a
& $(2 ?((@main__C2 (* (* (* (* 1))))) a)) ~ [=1]

View File

@ -0,0 +1,8 @@
---
source: tests/golden_tests.rs
input_file: tests/golden_tests/compile_file/elif_no_else.bend
---
Errors:
In tests/golden_tests/compile_file/elif_no_else.bend :
Indentation error. Expected 2 spaces, got end-of-input.
 6 |