From 8711fde112e10a2c43146ad60bd5cc824883bf0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sun, 1 Jan 2023 11:04:32 +0100 Subject: [PATCH] Parser - Support for if statement * Different from the book's implemenation as it doesn't use additional parens --- src/parser.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/parser.rs b/src/parser.rs index 8bd81b9..38f516a 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -86,6 +86,8 @@ impl Parser { self.parse_declaration() } else if self.expect(&[TokenType::LeftBrace]).is_some() { self.parse_block() + } else if self.expect(&[TokenType::If]).is_some() { + self.parse_if_statement() } else if self.expect(&[TokenType::Print]).is_some() { let expression = self.parse_expression()?; self.consume(&TokenType::Semicolon, "expected ';' after value")?; @@ -132,6 +134,25 @@ impl Parser { Ok(ast::StmtNode::Block(stmts)) } + /// Parse the following rule: + /// ``` + /// if := "if" condition statement + /// if := "if" condition statement "else" statement + /// ``` + fn parse_if_statement(&mut self) -> ParserResult { + let expression = self.parse_expression()?; + let then_branch = Box::new(self.parse_statement()?); + let else_branch = match self.expect(&[TokenType::Else]) { + Some(_) => Some(Box::new(self.parse_statement()?)), + None => None, + }; + Ok(ast::StmtNode::IfStmt { + condition: expression, + then_branch, + else_branch, + }) + } + /// Parse the following rule: /// ``` /// expression := assignment