Skip to content

Commit

Permalink
♻️ refactor ast with a box to BlockStatement
Browse files Browse the repository at this point in the history
  • Loading branch information
KPMGE committed Apr 26, 2024
1 parent b543a6f commit 78fe596
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub enum Expression {
IfExpression {
condition: Box<Expression>,
consequence: Box<BlockStatement>,
alternative: Option<BlockStatement>,
alternative: Option<Box<BlockStatement>>,
},
FunctionExpression {
parameters: Vec<Token>,
Expand Down
15 changes: 5 additions & 10 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AstNode> {
Expand All @@ -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<Expression> {
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions tests/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 78fe596

Please sign in to comment.