Skip to main content

Building a Math Expressions Interpreter

2025-10-26

For the weekend project, I wanted to explore building a toy math expressions interpreter. I missed working on parsers and interpreters, so I thought this would be a fun way to get back into it. I also decided that instead of just shipping a binary that I would build a web-based playground for playing with the language.

Here’s an interactive demo of my project:

Goals

  • Support basic arithmetic operations: addition, subtraction, multiplication, and division.
  • Handle parentheses for grouping expressions.
  • Implement operator precedence and associativity.
  • Provide meaningful error messages for invalid expressions.
  • Support a print statement to inspect values.
  • Support variable assignments and usage.
  • Support assertions to validate expressions.
  • Support scientific notation in the form of 1.23x10^4.
  • Create a web-based interface for users to input expressions and see results.

Implementation

I started by defining the grammar for the math expressions. The grammar needed to account for numbers, operators, and parentheses. After a few rounds of iteration, I settled on the following grammar:

Using ANTLR, I generated the parser and lexer code. I then implemented the visitor pattern to traverse the parse tree and evaluate expressions. The visitor handled each type of expression according to the defined grammar. I also implemented error handling to provide meaningful messages when users input invalid expressions. This involved catching exceptions during parsing and evaluation and returning user-friendly feedback.

When I started thinking about the web interface, I thought I would implement a streaming interpreter that could send results back to the client as they were computed. I also wanted to implement syntax highlighting for the input expressions.

Overall, it was a fun weekend project that allowed me to revisit some concepts in parsing and interpreting while also exploring web development. The final product is a simple yet effective math expressions interpreter that users can interact with through a web interface. I also had fun looking at different deployment options for web applications.

You can check out the project on GitHub. And you can try the web-based playground here.

The code needs a lot of cleaning up, but I am happy with the progress I made over the weekend!

Happy coding!