A label table turns names into instruction positions.
An assembler can scan controller text, count only executable instructions, and replace symbolic branch targets with positions in the assembled sequence.
How can a controller use readable labels before the machine needs numeric positions?
- Distinguish label symbols from instruction lists
- Count instruction positions without counting labels
- Build a table from each label to its next instruction
- Resolve branch and goto targets while removing labels
extract-labels carries the position of the next instruction. Encountering a symbol records that position without incrementing it; encountering an instruction increments the position. start therefore names 0, loop names 1, and done names 5.
assemble skips label symbols and asks resolve to replace only branch and goto targets. Ordinary instructions remain unchanged. The returned sequence is assembled controller data with numeric targets; this lesson does not execute that sequence or prove a complete machine assembler.
(begin
(define (extract-labels controller position)
(cond ((null? controller) '())
((symbol? (car controller))
(cons (cons (car controller) position)
(extract-labels (cdr controller) position)))
(else
(extract-labels (cdr controller) (+ position 1)))))
(define controller
'(start
(assign n 3)
loop
(test zero?)
(branch done)
(assign n sub1)
(goto loop)
done
(halt)))
(extract-labels controller 0))- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns ((start . 0) (loop . 1) (done . 5)). The second returns ((assign n 3) (test zero?) (branch 5) (assign n sub1) (goto 1) (halt)).
Watch position advance only for instruction lists, then locate assoc lookups for done and loop before branch and goto receive 5 and 1. The resulting list is assembled data, not an executed machine run.
Change the program before you read the hint.
Insert a label named check immediately before (test zero?). Predict its table entry and whether any existing instruction position changes.
Show one hint
A label names the next instruction but does not occupy an instruction position.