A compiler changes the representation of the work.
A lesson compiler can turn an expression tree into stack instructions that a separate machine executes later.
How does an expression tree become a linear instruction sequence?
- Emit constant and arithmetic instructions from syntax data
- Preserve operand order in stack code
- Separate compilation from machine execution
compile emits the left operand code, then the right operand code, and finally one arithmetic instruction. Recursion flattens the nested expression into a linear list.
execute pushes constants. An arithmetic instruction pops the right and left values, combines them, and pushes the result. When no code remains, the stack top is the program value.
- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns the five emitted instructions and the executed value 17.
Separate the recursive compile calls from the later execute calls. During execution, each instruction consumes code while changing the stack.
Change the program and compare the result.
Compile (+ 1 (* 2 (+ 3 4))). Write the instruction list before you execute it.
Show hint
Each number emits const. Each compound expression emits its operator after both operands.