SimuVeda

Computer Science Β· Simulator 067

Compiler Pipeline

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

  1. Lexer: scans characters into tokens: numbers, names, operators and parentheses. It rejects unknown characters.
  2. 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.
  3. Code generation: a post-order walk of the tree emits instructions for a stack machine (PUSH, LOAD, ADD, MUL, POW, NEG…).
  4. 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

  1. Precedence. 2 + 3 * 4. Prediction: the tree puts * below +, so the result is 14, not 20.
  2. Right-associative power. 2 ^ 3 ^ 2. Prediction: parsed as 2 ^ (3 ^ 2) = 512, not (2 ^ 3) ^ 2 = 64.
  3. 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.

References

  • Aho, Lam, Sethi & Ullman, Compilers: Principles, Techniques, and Tools, ch. 2.
  • Nystrom, Crafting Interpreters (free online), ch. 4–6 and 14–17.