From 447e0fe623c51a9de90f3b9d73a675668469d90a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sat, 31 Dec 2022 15:39:52 +0100 Subject: [PATCH] Parser - Handle variable declarations --- src/parser.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/parser.rs b/src/parser.rs index f461752..76e5cca 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -71,9 +71,12 @@ impl Parser { /// ``` /// statement := expression ";" /// statement := "print" expression ";" + /// statement := declaration ";" /// ``` fn parse_statement(&mut self) -> Result { - 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 { + let name = match self.peek().token_type { + TokenType::Identifier(_) => self.advance().clone(), + _ => return Err(ParserError::new(self.peek(), "expected variable name")), + }; + let initializer: Option = 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