diff options
Diffstat (limited to 'users/tazjin/rlox/src/parser.rs')
-rw-r--r-- | users/tazjin/rlox/src/parser.rs | 34 |
1 files changed, 19 insertions, 15 deletions
diff --git a/users/tazjin/rlox/src/parser.rs b/users/tazjin/rlox/src/parser.rs index ba258a637f8b..74c2f448ede9 100644 --- a/users/tazjin/rlox/src/parser.rs +++ b/users/tazjin/rlox/src/parser.rs @@ -169,24 +169,17 @@ impl<'a> Parser<'a> { fn var_declaration(&mut self) -> StmtResult<'a> { // Since `TokenKind::Identifier` carries data, we can't use // `consume`. - if let TokenKind::Identifier(_) = self.peek().kind { - let mut var = Var { - name: self.advance(), - initialiser: None, - }; - - if self.match_token(&TokenKind::Equal) { - var.initialiser = Some(self.expression()?); - } + let mut var = Var { + name: self.identifier("Expected variable name.")?, + initialiser: None, + }; - self.consume(&TokenKind::Semicolon, ErrorKind::ExpectedSemicolon)?; - return Ok(Statement::Var(var)); + if self.match_token(&TokenKind::Equal) { + var.initialiser = Some(self.expression()?); } - return Err(Error { - line: self.peek().line, - kind: ErrorKind::ExpectedVariableName, - }); + self.consume(&TokenKind::Semicolon, ErrorKind::ExpectedSemicolon)?; + Ok(Statement::Var(var)) } fn statement(&mut self) -> StmtResult<'a> { @@ -492,6 +485,17 @@ impl<'a> Parser<'a> { // internal helpers + fn identifier(&mut self, err: &'static str) -> Result<Token<'a>, Error> { + if let TokenKind::Identifier(_) = self.peek().kind { + Ok(self.advance()) + } else { + Err(Error { + line: self.peek().line, + kind: ErrorKind::ExpectedToken(err), + }) + } + } + /// Check if the next token is in `oneof`, and advance if it is. fn match_token(&mut self, token: &TokenKind) -> bool { if self.check_token(token) { |