Type an arithmetic expression such as 2 * (3 + x) ^ 2. Watch a tiny compiler split it into tokens, parse it into a syntax tree that respects precedence, generate stack-machine instructions, and run them step by step.
How the model works
Lexer: scans characters into tokens: numbers, names, operators and parentheses. It rejects unknown characters.
Parser: a recursive-descent parser for the grammar expr β term (('+'|'β') term)*, term β unary (('*'|'/') unary)*, unary β 'β' unary | power, power β atom ('^' unary)?, atom β number | name | '(' expr ')'. The grammar encodes precedence (^ above unary minus above * / above + β), so β2^2 = β4, and ^ is right-associative.
Code generation: a post-order walk of the tree emits instructions for a stack machine (PUSH, LOAD, ADD, MUL, POW, NEGβ¦).
Execution: the virtual machine pops operands and pushes results. The final stack value is the answer.
Variables x and y take the values set in the controls.
Deliberately restricted language: numbers, x, y, + β * / ^ and parentheses only. No function calls and no assignment. Nothing is evaluated with the browser's own eval.
Guided experiments
Precedence. 2 + 3 * 4.
Prediction: the tree puts * below +, so the result is 14, not 20.
Syntax error. 3 * (4 + .
Prediction: the parser reports what it expected and where, and no code is generated.
Challenge
How many instructions does the stack machine run for (x + 1) * (x β 1)? What is the deepest the stack gets?
Reveal the explanation
LOAD x, PUSH 1, ADD, LOAD x, PUSH 1, SUB, MUL: 7 instructions. The stack peaks at 3 values (the first sum, then x and 1 for the second bracket). Step through it to watch the stack.