Parser - Handle variable declarations
This commit is contained in:
parent
8e5a26bcc3
commit
447e0fe623
1 changed files with 25 additions and 1 deletions
|
@ -71,9 +71,12 @@ impl Parser {
|
|||
/// ```
|
||||
/// statement := expression ";"
|
||||
/// statement := "print" expression ";"
|
||||
/// statement := declaration ";"
|
||||
/// ```
|
||||
fn parse_statement(&mut self) -> Result<ast::StmtNode, ParserError> {
|
||||
if self.expect(&[TokenType::Print]).is_some() {
|
||||
if self.expect(&[TokenType::Var]).is_some() {
|
||||
self.parse_declaration()
|
||||
} else if self.expect(&[TokenType::Print]).is_some() {
|
||||
let expression = self.parse_expression()?;
|
||||
self.consume(&TokenType::Semicolon, "expected ';' after value")?;
|
||||
Ok(ast::StmtNode::Print(expression))
|
||||
|
@ -84,6 +87,27 @@ impl Parser {
|
|||
}
|
||||
}
|
||||
|
||||
/// Parse the following rule:
|
||||
/// ```
|
||||
/// declaration := "var" IDENTIFIER ";"
|
||||
/// declaration := "var" IDENTIFIER "=" expression ";"
|
||||
/// ```
|
||||
fn parse_declaration(&mut self) -> Result<ast::StmtNode, ParserError> {
|
||||
let name = match self.peek().token_type {
|
||||
TokenType::Identifier(_) => self.advance().clone(),
|
||||
_ => return Err(ParserError::new(self.peek(), "expected variable name")),
|
||||
};
|
||||
let initializer: Option<ast::ExprNode> = match self.expect(&[TokenType::Equal]) {
|
||||
Some(_) => Some(self.parse_expression()?),
|
||||
None => None,
|
||||
};
|
||||
self.consume(
|
||||
&TokenType::Semicolon,
|
||||
"expected ';' after variable declaration",
|
||||
)?;
|
||||
Ok(ast::StmtNode::VarDecl(name.lexeme, initializer))
|
||||
}
|
||||
|
||||
/// Parse the following rule:
|
||||
/// ```
|
||||
/// expression := equality
|
||||
|
|
Loading…
Reference in a new issue