From 78fe5968e34a6365a098065470b5ba39ef6c808b Mon Sep 17 00:00:00 2001 From: KPMGE Date: Fri, 26 Apr 2024 20:49:12 -0300 Subject: [PATCH] :recycle: refactor ast with a box to BlockStatement --- src/ast.rs | 2 +- src/parser.rs | 15 +++++---------- tests/parser.rs | 4 ++-- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/ast.rs b/src/ast.rs index a0348a2..309137a 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -19,7 +19,7 @@ pub enum Expression { IfExpression { condition: Box, consequence: Box, - alternative: Option, + alternative: Option>, }, FunctionExpression { parameters: Vec, diff --git a/src/parser.rs b/src/parser.rs index 56684a4..86fc6e7 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -100,10 +100,7 @@ impl Parser { return None; } - Some(AstNode::Statement(Box::new(Statement::LetStatement { - name, - value, - }))) + Some(AstNode::Statement(Box::new(Statement::LetStatement { name, value }))) } fn parse_expression_statement(&mut self) -> Option { @@ -129,9 +126,7 @@ impl Parser { let expression = Box::new(self.parse_expression(Precedence::Lowest)?); - Some(AstNode::Statement(Box::new(Statement::ReturnStatement( - expression, - )))) + Some(AstNode::Statement(Box::new(Statement::ReturnStatement(expression)))) } fn parse_expression(&mut self, precedence: Precedence) -> Option { @@ -300,9 +295,9 @@ impl Parser { let alternative = match self.current_token { Token::Else => { self.advance_tokens(); - self.parse_block_statement() - } - _ => None, + Some(Box::new(self.parse_block_statement()?)) + }, + _ => None }; Some(Expression::IfExpression { diff --git a/tests/parser.rs b/tests/parser.rs index 0420e92..20d1c4d 100644 --- a/tests/parser.rs +++ b/tests/parser.rs @@ -333,11 +333,11 @@ fn given_an_if_else_expression_it_should_parse_correctly() { "x".to_string(), )))], }), - alternative: Some(BlockStatement { + alternative: Some(Box::new(BlockStatement { statements: vec![AstNode::Expression(Box::new(Expression::Identifier( "y".to_string(), )))], - }), + })), }; let parsed_program = parser.parse_program();