Creating a simple math interpreter is a great way to delve into fluent programming techniques and understand the basics of compilers and interpreters. Rust, with its strong type system and memory safety features, is a suitable candidate for this endeavor. In this guide, we'll explore how to build a basic math interpreter in Rust that can handle addition, subtraction, multiplication, and division.
Setting up the Project
To begin, ensure that you have Rust installed on your machine. You can check this by running:
rustc --versionIf Rust is not yet installed, you can visit the official Rust website for installation instructions.
Once ready, create a new Rust project:
cargo new math_interpreter --binThis command initializes a new Rust binary package in a directory named math_interpreter. Navigate into this directory to start coding:
cd math_interpreterTokenization
The first step in building our math interpreter is tokenizing the input. Tokenization is the process of breaking a string of text into manageable pieces. For our math interpreter, these pieces include numbers and operators.
enum Token {
Number(f64),
Plus,
Minus,
Star,
Slash,
}
fn tokenize(input: &str) -> Vec {
let mut tokens: Vec = Vec::new();
let mut chars = input.chars().peekable();
while let Some(&c) = chars.peek() {
match c {
'0'..='9' => {
let mut number = String::new();
while let Some(digit) = chars.peek() {
if digit.is_digit(10) || *digit == '.' {
number.push(*digit);
chars.next();
} else {
break;
}
}
let number = number.parse().unwrap();
tokens.push(Token::Number(number));
}
'+' => {
chars.next();
tokens.push(Token::Plus);
}
'-' => {
chars.next();
tokens.push(Token::Minus);
}
'*' => {
chars.next();
tokens.push(Token::Star);
}
'/' => {
chars.next();
tokens.push(Token::Slash);
}
_ => {
chars.next(); // Skip whitespace or unknown characters
}
}
}
tokens
}Parsing and Evaluation
After tokenization, the next step is parsing, where we understand the input’s grammatical structure, followed by evaluation, where we compute the result based on parsed results. For simplicity, we will use a basic parsing function that evaluates the expressions directly:
fn parse_expression(tokens: &mut Vec) -> f64 {
let mut total = 0.0;
let mut current_operator = Token::Plus;
while let Some(token) = tokens.pop() {
match token {
Token::Number(num) => {
match current_operator {
Token::Plus => total += num,
Token::Minus => total -= num,
Token::Star => total *= num,
Token::Slash => total /= num,
_ => (),
}
}
Token::Plus => current_operator = Token::Plus,
Token::Minus => current_operator = Token::Minus,
Token::Star => current_operator = Token::Star,
Token::Slash => current_operator = Token::Slash,
}
}
total
}Running the Interpreter
Finally, we will integrate the tokenize and parse_expression functions to create a simple REPL (Read-Eval-Print-Loop) to allow users to input expressions and get results:
use std::io::{self, Write};
fn main() {
loop {
print!("Enter expression: ");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let mut tokens = tokenize(&input);
tokens.reverse(); // Reverse for ease of pop()
let result = parse_expression(&mut tokens);
println!("Result: {}", result);
}
}This code will continuously prompt the user for input. Input expressions, such as 3 + 4 * 2, result in 11 based on our simplistic parsing function.
While our interpreter does not handle operator precedence and has rudimentary error-handling capabilities, this provides a good starting point for those looking to understand the core concepts of language parsing and evaluation in Rust.