about summary refs log tree commit diff
path: root/users/tazjin/rlox/src/parser.rs
diff options
context:
space:
mode:
authorVincent Ambo <mail@tazj.in>2021-01-14T01·50+0300
committertazjin <mail@tazj.in>2021-01-14T02·05+0000
commit8bcbb041606b0fd15459415a3e5531a753c8bfd8 (patch)
tree7defc4d53cf2fc172ad0d8889cd03d46c73fdd0d /users/tazjin/rlox/src/parser.rs
parentfcd9801b017685eb11ef2578fe1b84a0f6a55460 (diff)
refactor(tazjin/rlox): Add helper method for parsing identifiers r/2102
Change-Id: I9a45f823f16919319d6135225d5bd53ed54c2530
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2388
Reviewed-by: tazjin <mail@tazj.in>
Tested-by: BuildkiteCI
Diffstat (limited to 'users/tazjin/rlox/src/parser.rs')
-rw-r--r--users/tazjin/rlox/src/parser.rs34
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) {