Assembler, Part 2
April 18, 2014
Here’s our very simple simulator:
(define (sim mem) (let loop ((pc 0) (acc 0)) (let ((addr (modulo (vector-ref mem pc) 1000)) (code (quotient (vector-ref mem pc) 1000))) (case code ((1) (loop (+ pc 1) (read))) ; get ((2) (display acc) (newline) (loop (+ pc 1) acc)) ; put ((3) (loop (+ pc 1) (vector-ref mem addr))) ; ld ((4) (vector-set! mem addr acc) (loop (+ pc 1) acc)) ; st ((5) (loop (+ pc 1) (+ acc (vector-ref mem addr)))) ; add ((6) (loop (+ pc 1) (- acc (vector-ref mem addr)))) ; sub ((7) (loop (if (positive? acc) addr (+ pc 1)) acc)) ; jpos ((8) (loop (if (zero? acc) addr (+ pc 1)) acc)) ; jz ((9) (loop addr acc)) ; j ((10) (if #f #f)) ; halt (else (error 'sim "unrecognized command"))))))
The two loop control variables are the program counter and accumulator. At each step, the current memory location is split into address and opcode, then the program dispatches on opcode, performs the indicated action, then either advances the program counter or resets it for a jump. The
(if #f #f) is the standard Scheme idiom for a no-op that does nothing and returns nothing; output is created by the
put opcode, not by returning a value from the function. Here’s what a run of the sample program looks like:
> (sim (asm2 (asm1 "program.asm"))) 17 35 102 0 154
There is no prompt in the program, so the program pauses, waiting for input. At the first pause the user enters 17, at the second pause the user enters 35, at the third pause the user enters 102, and at the fourth pause the user enters 0 to stop the program. Then the program reports the result, 154, and exits.
You can run the program at http://programmingpraxis.codepad.org/gDjSzX9P.
Pages: 1 2