1
0
Fork 0

Add tests for if-then-else before adding parsing

This commit is contained in:
Vili Sinervä 2025-01-28 18:57:51 +02:00
parent e4ffd1ab55
commit f3a252b510
No known key found for this signature in database
GPG key ID: DF8FEAF54EFAC996
2 changed files with 123 additions and 1 deletions

View file

@ -1,4 +1,3 @@
#[expect(dead_code)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum Expression<'source> { pub enum Expression<'source> {
IntLiteral(u32), IntLiteral(u32),
@ -9,4 +8,9 @@ pub enum Expression<'source> {
&'source str, &'source str,
Box<Expression<'source>>, Box<Expression<'source>>,
), ),
Conditional(
Box<Expression<'source>>,
Box<Expression<'source>>,
Option<Box<Expression<'source>>>,
),
} }

View file

@ -324,6 +324,118 @@ mod tests {
); );
} }
#[test]
fn test_if_then() {
let result = parse(&vec![
new_id("if"),
new_int("1"),
new_id("+"),
new_int("2"),
new_id("then"),
new_int("3"),
]);
assert_eq!(
result,
Conditional(
Box::new(BinaryOp(
Box::new(IntLiteral(1)),
"+",
Box::new(IntLiteral(2))
)),
Box::new(IntLiteral(3)),
None,
)
);
}
#[test]
fn test_if_then_else() {
let result = parse(&vec![
new_id("if"),
new_id("a"),
new_id("then"),
new_id("b"),
new_id("+"),
new_id("c"),
new_id("else"),
new_int("1"),
new_id("*"),
new_int("2"),
]);
assert_eq!(
result,
Conditional(
Box::new(Identifier("a")),
Box::new(BinaryOp(
Box::new(Identifier("b")),
"+",
Box::new(Identifier("c")),
)),
Some(Box::new(BinaryOp(
Box::new(IntLiteral(1)),
"*",
Box::new(IntLiteral(2)),
)))
)
);
}
#[test]
fn test_embedded_if_then_else() {
let result = parse(&vec![
new_int("1"),
new_id("+"),
new_id("if"),
new_id("true"),
new_id("then"),
new_int("2"),
new_id("else"),
new_int("3"),
]);
assert_eq!(
result,
BinaryOp(
Box::new(IntLiteral(1)),
"+",
Box::new(Conditional(
Box::new(BoolLiteral(true)),
Box::new(IntLiteral(2)),
Some(Box::new(IntLiteral(3)))
))
)
);
}
#[test]
fn test_nested_if_then_else() {
// if true then if false then 1 else 2 else 3
let result = parse(&vec![
new_id("if"),
new_id("true"),
new_id("then"),
new_id("if"),
new_id("false"),
new_id("then"),
new_int("1"),
new_id("else"),
new_int("2"),
new_id("else"),
new_int("3"),
]);
assert_eq!(
result,
Conditional(
Box::new(BoolLiteral(true)),
Box::new(Conditional(
Box::new(BoolLiteral(false)),
Box::new(IntLiteral(1)),
Some(Box::new(IntLiteral(2)))
)),
Some(Box::new(IntLiteral(3)))
)
);
}
#[test] #[test]
#[should_panic] #[should_panic]
fn test_parenthesized_mismatched() { fn test_parenthesized_mismatched() {
@ -337,6 +449,12 @@ mod tests {
]); ]);
} }
#[test]
#[should_panic]
fn test_if_no_then() {
parse(&vec![new_id("if"), new_id("true")]);
}
#[test] #[test]
#[should_panic] #[should_panic]
fn test_empty() { fn test_empty() {