sicp.io
5.5.8 · From tree to instructions

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.

Guiding question

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.

SICP code1,088 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns the five emitted instructions and the executed value 17.

    Trace focus

    Separate the recursive compile calls from the later execute calls. During execution, each instruction consumes code while changing the stack.

    Try it yourself

    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.

    Complete this lesson

    0 of 23 lessons complete in this chapter0%