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