Computer Science · Simulator 067
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.
CollegeCollege compilers
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.
How many instructions does the stack machine run for (x + 1) * (x − 1)? What is the deepest the stack gets?
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.
Expression: x * (y + 3) − 2 with x = 4 and y = 2.
Tokens: x, *, (, y, +, 3, ), −, 2: nine tokens.
Syntax tree: the root is −, because it has the lowest precedence outside brackets. Its left child is * with children x and (y + 3); its right child is 2.
Stack code (post-order walk of the tree): LOAD x, LOAD y, PUSH 3, ADD, MUL, PUSH 2, SUB. Seven instructions; the stack is deepest, 3 values (4, 2, 3), just before ADD.
Run it: ADD gives 5, MUL gives 20, SUB gives 18. Type the expression with x = 4 and y = 2 and step through the code.
Lexing splits the text into tokens, parsing builds a syntax tree from the grammar, semantic checks verify types and names, and code generation turns the tree into instructions, usually with optimisation in between.
The grammar has a level for each precedence, so * and / are grouped before + and −. A recursive-descent parser calls one function per level, which puts higher-precedence operators lower in the tree.
A machine whose instructions take their inputs from the top of a stack and push the result back. The Java virtual machine, .NET and WebAssembly work this way.