Creating a lexer for Python-like indentation and dedentation requires knowing when to emit these tokens. Python uses indentation levels to define block scope, and whenever the indentation level increases, an INDENT token should be emitted; conversely, when the indentation level decreases, a DEDENT token should be emitted. To keep things simple, this example lexer will only recognize indentation changes, new lines, and basic words.
Here is a simple lexer written in Rust to illustrate the concept:
#[derive(Debug, PartialEq)]
enum Token {
Indent,
Dedent,
Newline,
Word(String),
}
struct Lexer<'a> {
input: &'a str,
position: usize,
indent_stack: Vec<usize>,
}
impl<'a> Lexer<'a> {
fn new(input: &'a str) -> Self {
Lexer {
input,
position: 0,
indent_stack: vec![0],
}
}
fn next_token(&mut self) -> Option<Token> {
self.skip_whitespace_except_newline();
if let Some(ch) = self.input.chars().nth(self.position) {
match ch {
'\n' => {
self.position += 1;
// Push current newline to make sure next line is checked for indentation
Some(Token::Newline)
}
_ if ch.is_alphabetic() => {
let word_start = self.position;
while let Some(ch) = self.input.chars().nth(self.position) {
if !ch.is_alphabetic() {
break;
}
self.position += 1;
}
let word = &self.input[word_start..self.position];
Some(Token::Word(word.to_string()))
}
' ' => {
let start = self.position;
while let Some(ch) = self.input.chars().nth(self.position) {
if ch != ' ' {
break;
}
self.position += 1;
}
let spaces = self.position - start;
if spaces > *self.indent_stack.last().unwrap() {
self.indent_stack.push(spaces);
Some(Token::Indent)
} else {
while *self.indent_stack.last().unwrap() > spaces {
self.indent_stack.pop();
return Some(Token::Dedent)
}
None // No change in indentation, move to the next character
}
}
_ => None, // Skip any unknown characters
}
} else {
None // End of input
}
}
fn skip_whitespace_except_newline(&mut self) {
while let Some(ch) = self.input.chars().nth(self.position) {
if ch == ' ' && self.input.chars().nth(self.position + 1) != Some('\n') {
self.position += 1;
} else {
break;
}
}
}
}
fn main() {
let input = "\
def foo():
if bar:
baz
qux
";
let mut lexer = Lexer::new(input);
while let Some(token) = lexer.next_token() {
println!("{:?}", token);
}
}
This code defines a lexer that converts a Python-like input string into tokens; it identifies words, new lines, and adjusts indentation levels. The lexer uses an indent_stack to track indentation levels and compare them with the current line's indentation. When there's a change in indentation, it emits INDENT and DEDENT tokens accordingly. This is a simplified version and won't work for all Python code cases, but it demonstrates handling indentation in a basic lexer.
Please note that in a real-world scenario, you'd want to handle other aspects of Python syntax, like comments, strings, multiple character tokens (e.g., ==, !=), and more. Furthermore, a lexer should ideally work with a stream of input rather than a static string to be more efficient.