Parser - Support for if statement

* Different from the book's implemenation as it doesn't use additional parens
This commit is contained in:
Emmanuel BENOîT 2023-01-01 11:04:32 +01:00
parent 2eda13de38
commit 8711fde112

View file

@ -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<ast::StmtNode> {
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