Parser - Support for if statement
* Different from the book's implemenation as it doesn't use additional parens
This commit is contained in:
parent
2eda13de38
commit
8711fde112
1 changed files with 21 additions and 0 deletions
|
@ -86,6 +86,8 @@ impl Parser {
|
||||||
self.parse_declaration()
|
self.parse_declaration()
|
||||||
} else if self.expect(&[TokenType::LeftBrace]).is_some() {
|
} else if self.expect(&[TokenType::LeftBrace]).is_some() {
|
||||||
self.parse_block()
|
self.parse_block()
|
||||||
|
} else if self.expect(&[TokenType::If]).is_some() {
|
||||||
|
self.parse_if_statement()
|
||||||
} else if self.expect(&[TokenType::Print]).is_some() {
|
} else if self.expect(&[TokenType::Print]).is_some() {
|
||||||
let expression = self.parse_expression()?;
|
let expression = self.parse_expression()?;
|
||||||
self.consume(&TokenType::Semicolon, "expected ';' after value")?;
|
self.consume(&TokenType::Semicolon, "expected ';' after value")?;
|
||||||
|
@ -132,6 +134,25 @@ impl Parser {
|
||||||
Ok(ast::StmtNode::Block(stmts))
|
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:
|
/// Parse the following rule:
|
||||||
/// ```
|
/// ```
|
||||||
/// expression := assignment
|
/// expression := assignment
|
||||||
|
|
Loading…
Reference in a new issue