Sling Academy
Home/Rust/Building a Simple Math Interpreter in Rust

Building a Simple Math Interpreter in Rust

Last updated: January 03, 2025

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 --version

If 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 --bin

This command initializes a new Rust binary package in a directory named math_interpreter. Navigate into this directory to start coding:

cd math_interpreter

Tokenization

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.

Next Article: Working with Interval Arithmetic for Bounds Checking in Rust

Previous Article: Implementing Quadratic Equations and Polynomial Evaluations in Rust

Series: Math and Numbers in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior