From f3a252b5100c2d11567ee1829327a193b5a7df5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vili=20Sinerv=C3=A4?= Date: Tue, 28 Jan 2025 18:57:51 +0200 Subject: [PATCH] Add tests for if-then-else before adding parsing --- src/compiler/ast.rs | 6 ++- src/compiler/parser.rs | 118 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 1 deletion(-) diff --git a/src/compiler/ast.rs b/src/compiler/ast.rs index ac76662..d28cdc5 100644 --- a/src/compiler/ast.rs +++ b/src/compiler/ast.rs @@ -1,4 +1,3 @@ -#[expect(dead_code)] #[derive(Debug, PartialEq)] pub enum Expression<'source> { IntLiteral(u32), @@ -9,4 +8,9 @@ pub enum Expression<'source> { &'source str, Box>, ), + Conditional( + Box>, + Box>, + Option>>, + ), } diff --git a/src/compiler/parser.rs b/src/compiler/parser.rs index 877416b..7de252e 100644 --- a/src/compiler/parser.rs +++ b/src/compiler/parser.rs @@ -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] #[should_panic] 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] #[should_panic] fn test_empty() {