Skip to content

Commit

Permalink
feat: add identifier()
Browse files Browse the repository at this point in the history
  • Loading branch information
c-kirkeby committed Sep 22, 2023
1 parent f0bcd45 commit 1f9cd54
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions src/scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ impl Scanner {
b'\n' => self.line += 1,
b'"' => self.string()?,
b'0'..=b'9' => self.number()?,
c if c.is_ascii_alphabetic() => self.identifier(),
_ => bail!("Unexpected character on line {}", self.line),
}
Ok(())
Expand Down Expand Up @@ -161,19 +162,15 @@ impl Scanner {
Ok(())
}

fn is_digit(c: u8) -> bool {
c >= b'0' && c <= b'9'
}

fn number(&mut self) -> Result<()> {
while Self::is_digit(self.peek()) {
while self.peek().is_ascii_digit() {
self.advance();
}

if self.peek() == b'.' && Self::is_digit(self.peek_next()) {
if self.peek() == b'.' && self.peek_next().is_ascii_digit() {
self.advance();

while Self::is_digit(self.peek()) {
while self.peek().is_ascii_digit() {
self.advance();
}
}
Expand All @@ -186,6 +183,13 @@ impl Scanner {
);
Ok(())
}

fn identifier(&mut self) {
while self.peek().is_ascii_alphanumeric() {
self.advance();
}
self.add_token(TokenType::Identifier, None);
}
}

#[cfg(test)]
Expand Down Expand Up @@ -241,4 +245,19 @@ mod tests {
);
Ok(())
}

#[test]
fn test_scan_tokens_identifier() -> Result<()> {
let mut scanner = Scanner::new("hello world".to_string());
scanner.scan_tokens()?;
assert_eq!(
scanner.tokens,
vec![
Token::new(TokenType::Identifier, String::from("hello"), None, 1),
Token::new(TokenType::Identifier, String::from("world"), None, 1),
Token::new(TokenType::EOF, String::from(""), None, 1)
]
);
Ok(())
}
}

0 comments on commit 1f9cd54

Please sign in to comment.