diff options
| author | Edvard Thörnros <edvard.thornros@gmail.com> | 2021-01-11 15:08:35 +0100 |
|---|---|---|
| committer | Edvard Thörnros <edvard.thornros@gmail.com> | 2021-01-11 15:08:35 +0100 |
| commit | b81e250fab7f54838a9b205e51a49bd5b932c618 (patch) | |
| tree | 60aa47663068e5b051fa291ea54ab02d21c791ac | |
| parent | cf9ad28eb0a62c2c89f2f679157a54eded97c1cf (diff) | |
| download | sylt-b81e250fab7f54838a9b205e51a49bd5b932c618.tar.gz | |
If-statements
| -rw-r--r-- | src/compiler.rs | 29 | ||||
| -rw-r--r-- | src/tokenizer.rs | 5 | ||||
| -rw-r--r-- | tests/simple.tdy | 21 |
3 files changed, 36 insertions, 19 deletions
diff --git a/src/compiler.rs b/src/compiler.rs index 8275618..4bd519d 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -347,6 +347,29 @@ impl Compiler { expect!(self, Token::RightBrace, "Expected '}' at end of block."); } + fn if_statment(&mut self, block: &mut Block) { + expect!(self, Token::If, "Expected 'if' at start of if-statement."); + self.expression(block); + let jump = block.add(Op::Illegal, self.line()); + self.scope(block); + + if Token::Else == self.peek() { + let else_jmp = block.add(Op::Illegal, self.line()); + block.patch(Op::JmpFalse(block.curr()), jump); + + self.eat(); + match self.peek() { + Token::If => self.if_statment(block), + Token::LeftBrace => self.scope(block), + _ => error!(self, "Epected 'if' or '{' after else."), + } + block.patch(Op::Jmp(block.curr()), else_jmp); + } else { + block.patch(Op::JmpFalse(block.curr()), jump); + } + + } + fn statement(&mut self, block: &mut Block) { self.clear_panic(); @@ -381,11 +404,7 @@ impl Compiler { } (Token::If, _, _, _) => { - self.eat(); - self.expression(block); - let jump = block.add(Op::Illegal, self.line()); - self.scope(block); - block.patch(Op::JmpFalse(block.curr()), jump); + self.if_statment(block); } (Token::LeftBrace, _, _, _) => { diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 18e1aa1..8778430 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -20,6 +20,8 @@ pub enum Token { #[token("if")] If, + #[token("else")] + Else, #[token("for")] For, #[token("in")] @@ -64,8 +66,11 @@ pub enum Token { EqualEqual, #[token("!=")] NotEqual, + #[token("<=>")] AssertEqual, + #[token("<!>")] + Unreachable, #[token("(")] LeftParen, diff --git a/tests/simple.tdy b/tests/simple.tdy index 9d05b40..59355d2 100644 --- a/tests/simple.tdy +++ b/tests/simple.tdy @@ -13,19 +13,12 @@ // print d // print c -a int := 0 -b int := 3 -{ - a int := a + 1 - print a - - { - b int := 2 - print b - } - print b +a int := 2 +if a == 0 { + print 0 +} else if a == 1 { + print 1 +} else { + print 2 } -a = 4 -print a - // 1, 2, 3, 4 |
