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