From 0290fbc2261d0585d2b394ff3448e4a19f065b1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Mon, 2 Jan 2023 20:20:47 +0100 Subject: [PATCH] Parser - Return statement --- src/parser.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/parser.rs b/src/parser.rs index e00a740..9ec561b 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -111,6 +111,7 @@ impl Parser { /// statement := while_statement /// statement := for_statement /// statement := loop_control_statement + /// statement := return_statement /// ``` fn parse_statement(&mut self) -> ParserResult { if self.expect(&[TokenType::Var]).is_some() { @@ -129,6 +130,8 @@ impl Parser { self.parse_for_statement(None) } else if let Some(lcs) = self.expect(&[TokenType::Break, TokenType::Continue]) { self.parse_loop_control_statement(&lcs) + } else if let Some(ret) = self.expect(&[TokenType::Return]) { + self.parse_return_statement(&ret) } else if self.expect(&[TokenType::Print]).is_some() { let expression = self.parse_expression()?; self.consume(&TokenType::Semicolon, "expected ';' after value")?; @@ -426,6 +429,22 @@ impl Parser { }) } + /// Parse the following rule: + /// ``` + /// return_statement := "return" expression? ";" + /// ``` + fn parse_return_statement(&mut self, ret_token: &Token) -> ParserResult { + let value = if self.check(&TokenType::Semicolon) { + None + } else { + Some(self.parse_expression()?) + }; + Ok(ast::StmtNode::Return { + token: ret_token.clone(), + value, + }) + } + /// Parse the following rule: /// ``` /// expression := assignment