From 1ba0e61e0143e66e49c21c20f572bea58df277f0 Mon Sep 17 00:00:00 2001 From: coletonodonnell Date: Tue, 8 Feb 2022 20:38:41 -0500 Subject: [PATCH] Rewrite parser to include statements --- src/parser.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/parser.rs b/src/parser.rs index fb213f0..5189bb4 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,5 +1,6 @@ use crate::token::{Token, TokenType, Literal}; use crate::expression::{Expr}; +use crate::stmt::Stmt; pub struct Parser { pub tokens: Vec, @@ -177,6 +178,26 @@ impl Parser { return Self::equality(self); } + fn expression_statement(&mut self) -> Stmt { + let value: Expr = self.expression(); + let _a: Result = self.consume(TokenType::Semicolon, "Expect ';' after value.".to_string()); + return Stmt::Expression{ expression: value }; + } + + fn print_statement(&mut self) -> Stmt { + let value: Expr = self.expression(); + let _a: Result = self.consume(TokenType::Semicolon, "Expect ';' after value.".to_string()); + return Stmt::Print{ expression: value }; + } + + fn statement(&mut self) -> Stmt { + if self.match_type(vec![TokenType::Print]) { + return self.print_statement(); + } + + return self.expression_statement(); + } + pub fn parser_builder(tokens: Vec, instance: crate::Lox) -> Parser { return Parser { tokens: tokens, @@ -185,12 +206,17 @@ impl Parser { } } - pub fn parse(&mut self) -> Option{ - let a: Expr = Self::expression(self); + pub fn parse(&mut self) -> Option>{ + let mut statements: Vec = Vec::new(); + + while !self.is_end() { + statements.push(self.statement()); + } + if !self.instance.had_error { - return Some(a); + return Some(statements) } else { - return None; + return None } } } \ No newline at end of file