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
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
ifenabling 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.
Folder structure
Complete source code
Makefile
What each file does
- src/lexer.h
- Token kinds, the
Tokenstruct and the position-awareScriptErrorexception. - src/lexer.cpp
- The tokenizer: numbers with exponents, identifiers, operators and comments.
- src/ast.h
- The grammar, the AST node hierarchy and the
Statementproduced for each line. - src/parser.cpp
- The recursive-descent
Parserand theshow(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,
:astand:varscommands and error display. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
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.txtwithtests/expected-output.txt. :ast 2 ^ 3 ^ 2prints(2 ^ (3 ^ 2)), proving right associativity.fact(10)= 3628800 andfib(15)= 610 via recursive definitions.loop(0)stops with 'recursion deeper than 200 calls' instead of crashing.- The
<in the firstfactdefinition 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
- 1Add constant folding: simplify
2 * 3 + xto6 + xbefore evaluating. - 2Implement closures (functions that capture variables).
- 3Add a
:timecommand that reports how many nodes were evaluated.
Built and tested it yourself? Mark it to update your dashboard.