To normalize the above lexer code, we should aim to reduce potential code overhead, prevent panics on unexpected input, and ensure our lexer is more maintainable and clear. We can accomplish this by improving the error handling and making the control flow more efficient.
Here's the normalized version of the lexer:
#[derive(Debug, PartialEq)]
enum Token<'a> {
Integer(&'a str),
Plus,
Space,
}
#[derive(Debug)]
struct Lexer<'a> {
input: &'a str,
current_pos: usize,
}
impl<'a> Lexer<'a> {
fn new(input: &'a str) -> Self {
Lexer { input, current_pos: 0 }
}
// Peek at the current character without consuming it.
fn peek_char(&self) -> Option<char> {
self.input[self.current_pos..].chars().next()
}
// Consume the current character and move to the next position.
fn advance(&mut self) {
if let Some(next_char) = self.peek_char() {
self.current_pos += next_char.len_utf8();
}
}
// A method that tokenizes the input string, now returning a Result to avoid panics.
fn tokenize(&mut self) -> Result<Vec<Token<'a>>, String> {
let mut tokens = Vec::new();
while let Some(next_char) = self.peek_char() {
match next_char {
'0'..='9' => {
let start_pos = self.current_pos;
while let Some(next_digit) = self.peek_char() {
if !next_digit.is_digit(10) {
break;
}
self.advance();
}
// Slice a reference to this integer part of the input string.
let int_token = &self.input[start_pos..self.current_pos];
tokens.push(Token::Integer(int_token));
}
'+' => {
tokens.push(Token::Plus);
self.advance();
}
' ' => {
tokens.push(Token::Space);
self.advance();
}
_ => {
// Instead of panicking, we now return an error.
return Err(format!("Unexpected character: {}", next_char));
}
}
}
Ok(tokens)
}
}
fn main() {
let input = "12 + 23 + 34";
let mut lexer = Lexer::new(input);
match lexer.tokenize() {
Ok(tokens) => println!("{:?}", tokens),
Err(e) => println!("Lexer error: {}", e),
}
}
Here is what's been improved or normalized in the code:
- The
Lexer struct now includes current_pos as a field to track the current position in the input slice. This avoids passing and updating current_pos manually through each loop iteration.
- Introduced
peek_char and advance helper functions to encapsulate common operations on the current character. This helps to make the code easier to read and maintain.
- Changed the
tokenize method to return a Result<Vec<Token<'a>>, String>. By using a Result, we avoid panicking when encountering an unexpected character and instead return a descriptive error.
- Updated the
main function to handle the Result returned by tokenize and print any lexer errors.
This is a fairly simple example of a lexer; a more complete implementation might involve more sophisticated error handling, additional token types, support for multi-character operators, and methods to skip whitespace or comments.