about summary refs log tree commit diff
path: root/users/tazjin/rlox/src
diff options
context:
space:
mode:
Diffstat (limited to 'users/tazjin/rlox/src')
-rw-r--r--users/tazjin/rlox/src/errors.rs1
-rw-r--r--users/tazjin/rlox/src/parser.rs34
2 files changed, 19 insertions, 16 deletions
diff --git a/users/tazjin/rlox/src/errors.rs b/users/tazjin/rlox/src/errors.rs
index 484b06bdf6ab..4f173d016039 100644
--- a/users/tazjin/rlox/src/errors.rs
+++ b/users/tazjin/rlox/src/errors.rs
@@ -6,7 +6,6 @@ pub enum ErrorKind {
     ExpectedExpression(String),
     ExpectedSemicolon,
     ExpectedClosingBrace,
-    ExpectedVariableName,
     ExpectedToken(&'static str),
     TypeError(String),
     UndefinedVariable(String),
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) {