sicp.io
5.2.5 · Generating execution procedures

Assembly can move instruction dispatch out of the run loop.

Turn each controller instruction into a closure that captures its operands and control rule, then reuse the assembled procedure vector across machines.

Guiding question

Which work can the assembler perform once so the machine loop only fetches and invokes an execution procedure?

  • Generate one execution closure for every assembled instruction
  • Capture register names, source expressions, and branch targets during assembly
  • Keep fetched-instruction counting in the machine loop
  • Execute controllers without rechecking instruction tags on every cycle
  • Reuse one execution-procedure sequence with fresh machine states

make-execution-procedure performs the instruction-tag dispatch during assembly. Each branch returns a closure that remembers the destination register, source expression, label, or stack operation it needs. The run loop no longer contains an assign/test/branch/goto cond; it selects the closure at pc and invokes it.

The first program shows that even the assignment skipped by a true branch receives an execution procedure, because assembly covers controller structure rather than one run path. The factorial program assembles six closures once and uses the same sequence with two fresh machine instances. The closures still receive the current machine, so registers, stack, flag, pc, and operation package remain instance-specific.

SICP code9,477 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 assembly log returns ((assign test branch assign assign goto save assign restore perform halt) 11 #t complete 10 (10) 10). The reusable factorial sequence returns (6 (complete 120 28) (complete 6 18)).

    Trace focus

    Separate the one-time map over instruction data from the later fetch-and-call loop. The skipped -1 assignment still appears in generation-log, while the run path never invokes its closure. In the factorial example, verify that both machine instances share the procedure list but not their mutable registers or counters.

    Try it yourself

    Change the program and compare the result.

    Add save and restore to the factorial controller or instrument each generated closure with its instruction tag. Predict which work happens during assembly and which work repeats for every machine run.

    Show hint

    Anything derived only from controller syntax belongs in the generated closure. Register values and pc-dependent control remain runtime inputs.

    Complete this lesson

    0 of 23 lessons complete in this chapter0%