Below is a minimal implementation of a lexer and parser in Rust that handles simple arithmetic expressions. The language supports:
- Numbers (integers only, e.g.,
42).
- Operators:
+, -, *, /.
- Parentheses for grouping:
( and ).
- Whitespace is ignored.
The lexer tokenizes the input string into a stream of tokens. The parser uses recursive descent to build an Abstract Syntax Tree (AST) from the tokens. It follows a basic grammar for expressions with operator precedence (multiplication/division before addition/subtraction):
- Expression: Term ((
+ | -) Term)*
- Term: Factor ((
* | /) Factor)*
- Factor: Number |
( Expression )
This is kept minimal: no floating-point support, no error recovery (just basic error handling via Result), and no advanced features. The code uses only the Rust standard library.
Code
use std::iter::Peekable;
use std::str::Chars;
// --- Token Definition ---
#[derive(Debug, Clone, PartialEq)]
enum Token {
Number(i64),
Plus,
Minus,
Multiply,
Divide,
LParen,
RParen,
Eof,
}
// --- Lexer ---
struct Lexer<'a> {
chars: Peekable<Chars<'a>>,
}
impl<'a> Lexer<'a> {
fn new(input: &'a str) -> Self {
Lexer {
chars: input.chars().peekable(),
}
}
fn next_token(&mut self) -> Result<Token, String> {
while let Some(&ch) = self.chars.peek() {
if ch.is_whitespace() {
self.chars.next();
continue;
}
break;
}
match self.chars.next() {
Some('+') => Ok(Token::Plus),
Some('-') => Ok(Token::Minus),
Some('*') => Ok(Token::Multiply),
Some('/') => Ok(Token::Divide),
Some('(') => Ok(Token::LParen),
Some(')') => Ok(Token::RParen),
Some(ch) if ch.is_digit(10) => {
let mut num = ch.to_digit(10).unwrap() as i64;
while let Some(&next) = self.chars.peek() {
if next.is_digit(10) {
num = num * 10 + next.to_digit(10).unwrap() as i64;
self.chars.next();
} else {
break;
}
}
Ok(Token::Number(num))
}
Some(ch) => Err(format!("Unexpected character: {}", ch)),
None => Ok(Token::Eof),
}
}
}
// --- AST Definition ---
#[derive(Debug)]
enum AstNode {
Number(i64),
BinaryOp {
left: Box<AstNode>,
op: Token, // Plus, Minus, Multiply, Divide
right: Box<AstNode>,
},
}
// --- Parser ---
struct Parser<'a> {
lexer: Lexer<'a>,
current_token: Token,
}
impl<'a> Parser<'a> {
fn new(input: &'a str) -> Result<Self, String> {
let mut lexer = Lexer::new(input);
let current_token = lexer.next_token()?;
Ok(Parser {
lexer,
current_token,
})
}
fn advance(&mut self) -> Result<(), String> {
self.current_token = self.lexer.next_token()?;
Ok(())
}
fn parse(&mut self) -> Result<AstNode, String> {
self.parse_expression()
}
// Expression: Term ((+|-) Term)*
fn parse_expression(&mut self) -> Result<AstNode, String> {
let mut node = self.parse_term()?;
loop {
match self.current_token {
Token::Plus | Token::Minus => {
let op = self.current_token.clone();
self.advance()?;
let right = self.parse_term()?;
node = AstNode::BinaryOp {
left: Box::new(node),
op,
right: Box::new(right),
};
}
_ => break,
}
}
Ok(node)
}
// Term: Factor ((*|/) Factor)*
fn parse_term(&mut self) -> Result<AstNode, String> {
let mut node = self.parse_factor()?;
loop {
match self.current_token {
Token::Multiply | Token::Divide => {
let op = self.current_token.clone();
self.advance()?;
let right = self.parse_factor()?;
node = AstNode::BinaryOp {
left: Box::new(node),
op,
right: Box::new(right),
};
}
_ => break,
}
}
Ok(node)
}
// Factor: Number | ( Expression )
fn parse_factor(&mut self) -> Result<AstNode, String> {
match self.current_token {
Token::Number(num) => {
self.advance()?;
Ok(AstNode::Number(num))
}
Token::LParen => {
self.advance()?;
let node = self.parse_expression()?;
if self.current_token != Token::RParen {
return Err("Expected ')'".to_string());
}
self.advance()?;
Ok(node)
}
_ => Err(format!("Unexpected token: {:?}", self.current_token)),
}
}
}
// --- Main Function (Demo) ---
fn main() {
let input = "2 + 3 * (4 - 1)";
let mut parser = Parser::new(input).expect("Failed to create parser");
match parser.parse() {
Ok(ast) => println!("AST: {:#?}", ast),
Err(err) => eprintln!("Error: {}", err),
}
}
Explanation
-
Lexer:
- Takes a string input and produces tokens one by one via
next_token().
- Skips whitespace.
- Recognizes numbers by accumulating digits.
- Returns an error for unexpected characters.
-
Parser:
- Uses recursive descent to handle the grammar.
- Starts with
parse_expression() and drills down to terms and factors.
- Builds an AST using the
AstNode enum, which represents either a number or a binary operation.
- Advances tokens as it parses and checks for expected tokens (e.g., matching parentheses).
-
AST:
- A simple enum:
Number for literals, BinaryOp for operations with left/right subtrees.
-
Demo:
- The
main function parses "2 + 3 * (4 - 1)" and prints the AST.
- Expected output (pretty-printed):
AST: BinaryOp {
left: Number(2),
op: Plus,
right: BinaryOp {
left: Number(3),
op: Multiply,
right: BinaryOp {
left: Number(4),
op: Minus,
right: Number(1),
},
},
}
Limitations and Extensions
- Minimal Error Handling: It returns
Result with string errors but doesn't recover (e.g., it panics on unwrap in main for simplicity).
- No Evaluation: This only builds the AST. You could add a method to evaluate it (e.g., recursively traverse the tree).
- Extensions: Add more operators, variables, or error recovery. For real-world use, consider crates like
nom or pest for more power.
- Testing: Try inputs like
"42", "1+2*3", or invalid ones like "1+" to see errors.
This should serve as a starting point! If you need modifications (e.g., different grammar or features), let me know.