In order to gain a good understanding of the design of register machines, we must test the machines we design to see if they perform as expected. One way to test a design is to hand-simulate the operation of the controller, as in exercise 5.5. But this is extremely tedious for all but the simplest machines. In this section we construct a simulator for machines described in the register-machine language. The simulator is a Scheme JavaScript program with four interface procedures. functions. The first uses a description of a register machine to construct a model of the machine (a data structure whose parts correspond to the parts of the machine to be simulated), and the other three allow us to simulate the machine by manipulating the model:
As an example of how these procedures functions are used, we can define gcd-machine gcd_machine to be a model of the GCD machine of section 5.1.1 as follows:
Original | JavaScript |
(define gcd-machine (make-machine '(a b t) (list (list 'rem remainder) (list '= =)) '(test-b (test (op =) (reg b) (const 0)) (branch (label gcd-done)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) (goto (label test-b)) gcd-done))) | const gcd_machine = make_machine( list("a", "b", "t"), list(list("rem", (a, b) => a % b), list("=", (a, b) => a === b)), list( "test_b", test(list(op("="), reg("b"), constant(0))), branch(label("gcd_done")), assign("t", list(op("rem"), reg("a"), reg("b"))), assign("a", reg("b")), assign("b", reg("t")), go_to(label("test_b")), "gcd_done")); |
To compute GCDs with this machine, we set the input registers, start the machine, and examine the result when the simulation terminates:
Original | JavaScript |
(set-register-contents! gcd-machine 'a 206) done | set_register_contents(gcd_machine, "a", 206); "done" |
Original | JavaScript |
(set-register-contents! gcd-machine 'b 40) done | set_register_contents(gcd_machine, "b", 40); "done" |
Original | JavaScript |
(start gcd-machine) done | start(gcd_machine); "done" |
Original | JavaScript |
(get-register-contents gcd-machine 'a) 2 | get_register_contents(gcd_machine, "a"); 2 |