Skip to content
C++ project #19Advanced

Expression Interpreter

A small programming language: lexer, recursive-descent parser, AST of unique_ptr nodes, variables, recursive user functions and errors that point at the exact column.

Estimated time
~10 hours to build
Files
11 files · 750 lines
Technologies
C++17, <memory>, <map>, <functional>, <cmath>, Multi-file project

Introduction

Every compiler and calculator follows the same pipeline: characters become tokens, tokens become a tree, and the tree is evaluated. This project builds that pipeline by hand for an expression language with precedence, right-associative powers, variables, built-in functions and user-defined (even recursive) functions — the best possible exercise in recursion, polymorphism and ownership.

Problem statement

Write an interactive interpreter. It must evaluate arithmetic with correct precedence and associativity (2 ^ 3 ^ 2 is 512, -2 ^ 2 is −4), support assignment (x = 3), the ans variable, constants pi and e, built-ins (sqrt abs floor ln sin cos min max if), and user functions (def hyp(a, b) = sqrt(a*a + b*b)), including recursion with a lazy if. It must report syntax and run-time errors with the line, column and a caret, guard against runaway recursion, and offer :ast to show how an expression was parsed and :vars to list definitions.

Objectives

  • Write a lexer that tracks token positions
  • Implement a recursive-descent parser from a written grammar
  • Represent an AST with polymorphic nodes owned by std::unique_ptr
  • Evaluate with an environment of variables and call frames

Features

  • Operator precedence and right-associative ^
  • Variables, constants and ans
  • Built-in and user-defined functions with arity checks
  • Lazy if enabling recursion; recursion depth limit
  • Precise error positions with a caret

Concepts demonstrated

  • Lexing
  • Recursive-descent parsing
  • Abstract syntax trees
  • Virtual dispatch
  • RAII guards
  • Environments and call frames

System architecture

lexer.cpp produces a vector of Tokens (kind, text, value, column). parser.cpp implements one function per grammar rule (expr → term → unary → power → primary); each returns a NodePtr (std::unique_ptr<Node>). Node types (NumberNode, VarNode, UnaryNode, BinaryNode, CallNode) override eval and show. interpreter.cpp holds Env: globals, user functions (bodies kept in shared_ptr so redefinition during a call is safe), a stack of parameter frames popped by an RAII guard, and a table of built-ins. Errors are ScriptErrors carrying a column; errors inside a function body are re-reported at the call site.

TextArchitecture diagram
"hyp(3, 4)" --lexer--> [Ident hyp][(][Number 3][,][Number 4][)]
--parser--> CallNode(hyp)
/ \
NumberNode 3 NumberNode 4
--eval--> Env: push frame {a=3, b=4} -> body -> 5

Folder structure

TextProject tree
expression-interpreter/
├── README.md
├── Makefile
├── src/ast.h
├── src/interpreter.cpp
├── src/interpreter.h
├── src/lexer.cpp
├── src/lexer.h
├── src/main.cpp
├── src/parser.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/lexer.h
Token kinds, the Token struct and the position-aware ScriptError exception.
src/lexer.cpp
The tokenizer: numbers with exponents, identifiers, operators and comments.
src/ast.h
The grammar, the AST node hierarchy and the Statement produced for each line.
src/parser.cpp
The recursive-descent Parser and the show (pretty-print) functions.
src/interpreter.h
The evaluation environment: globals, functions, call frames and built-ins.
src/interpreter.cpp
Built-in table, variable lookup, function calls with arity and depth checks, and node evaluation.
src/main.cpp
The read–eval–print loop, :ast and :vars commands and error display.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
calc> 7
calc> 9
calc> (2 ^ (3 ^ 2))
calc> 512
calc> -4
calc> -1
calc> x = 10
calc> y = 3
calc> defined sq/1
calc> defined hyp/2
calc> 5
calc>
def fact(n) = if(n <= 1, 1, n * fact(n - 1))
^
error (line 12, col 20): unexpected character '<'
calc> defined fact/1
calc> 3628800
calc> defined fib/1
calc> 610
calc> defined loop/1
calc>
loop(0)
^
error (line 18, col 1): recursion deeper than 200 calls
calc> 10
calc>
sqrt(-1)
^
error (line 20, col 1): sqrt() is undefined for that input
calc>
1 / (x - 10)
^
error (line 21, col 3): division by zero
calc>
3 + * 4
^
error (line 22, col 5): expected a number, name or '(' but found '*'
calc>
z + 1
^
error (line 23, col 1): unknown variable 'z'
calc>
sq(1, 2)
^
error (line 24, col 1): sq() takes 1 argument(s), got 2
calc>
(1 + 2
^
error (line 25, col 7): expected ')' but found 'end of input'
calc>
error (line 26): 'pi' is a constant
calc> ans = 10
e = 2.71828182846
pi = 3.14159265359
x = 10
y = 3
fact(n) = if((n - 1), (n * fact((n - 1))), 1)
fib(n) = if(floor((n / 2)), (fib((n - 1)) + fib((n - 2))), n)
hyp(a, b) = sqrt((sq(a) + sq(b)))
loop(n) = loop((n + 1))
sq(n) = (n * n)
calc> calc>
Input
1 + 2 * 3
(1 + 2) * 3
:ast 2 ^ 3 ^ 2
2 ^ 3 ^ 2
-2 ^ 2
ans / 4
x = 10
y = x * 1.5e1 % 7
def sq(n) = n * n
def hyp(a, b) = sqrt(sq(a) + sq(b))
hyp(3, 4)
def fact(n) = if(n <= 1, 1, n * fact(n - 1))
def fact(n) = if(n - 1, n * fact(n - 1), 1)
fact(10)
def fib(n) = if(floor(n / 2), fib(n - 1) + fib(n - 2), n)
fib(15)
def loop(n) = loop(n + 1)
loop(0)
max(sq(3), 2 ^ 3) + min(1, 2)
sqrt(-1)
1 / (x - 10)
3 + * 4
z + 1
sq(1, 2)
(1 + 2
pi = 3
:vars
# a comment line

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • :ast 2 ^ 3 ^ 2 prints (2 ^ (3 ^ 2)), proving right associativity.
  • fact(10) = 3628800 and fib(15) = 610 via recursive definitions.
  • loop(0) stops with 'recursion deeper than 200 calls' instead of crashing.
  • The < in the first fact definition is reported at column 20 with a caret.

Common errors

Recursive functions never terminate

An ordinary function evaluates all its arguments first. if must evaluate only the chosen branch — see the special case in CallNode::eval.

1 - 2 - 3 gives 2

Left-associative operators need a loop (while in expr/term), not right recursion.

Possible improvements

  • Add comparison and logical operators (<, ==, and, or)
  • Compile the AST to bytecode for the Stack VM project
  • Support multi-line function bodies with local variables

Additional challenges

  1. 1Add constant folding: simplify 2 * 3 + x to 6 + x before evaluating.
  2. 2Implement closures (functions that capture variables).
  3. 3Add a :time command that reports how many nodes were evaluated.

Built and tested it yourself? Mark it to update your dashboard.