From bf11a2b63a500ab6c29e3d2bd8fd633db8d02ca0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sat, 31 Dec 2022 14:45:55 +0100 Subject: [PATCH] Parser - Parse program as a list of statements --- src/parser.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index 5fdb0a6..db19aec 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -19,8 +19,8 @@ impl Parser { /// Parse the tokens into an AST and return it, or return nothing if a /// parser error occurs. - pub fn parse(mut self, err_hdl: &mut ErrorHandler) -> Option { - match self.parse_expression() { + pub fn parse(mut self, err_hdl: &mut ErrorHandler) -> Option { + match self.parse_program() { Ok(expr) => Some(expr), Err(e) => { e.report(err_hdl); @@ -54,6 +54,34 @@ impl Parser { * RECURSIVE DESCENT PARSER * * ------------------------ */ + /// Parse the following rule: + /// ``` + /// program := statement* + /// ``` + fn parse_program(&mut self) -> Result { + let mut stmts: Vec = Vec::new(); + while !self.is_at_end() { + let stmt = self.parse_statement()?; + stmts.push(stmt); + } + Ok(ast::ProgramNode(stmts)) + } + + /// Parse the following rule: + /// ``` + /// statement := expression ";" + /// statement := "print" expression ";" + /// ``` + fn parse_statement(&mut self) -> Result { + if self.expect(&[TokenType::Print]).is_some() { + let expression = self.parse_expression()?; + Ok(ast::StmtNode::Print(expression)) + } else { + let expression = self.parse_expression()?; + Ok(ast::StmtNode::Expression(expression)) + } + } + /// Parse the following rule: /// ``` /// expression := equality