Original JavaScript
(define (make-new-machine) (let ((pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) (the-instruction-sequence '())) (let ((the-ops (list (list 'initialize-stack (lambda () (stack 'initialize))))) (register-table (list (list 'pc pc) (list 'flag flag)))) (define (allocate-register name) (if (assoc name register-table) (error "Multiply defined register: " name) (set! register-table (cons (list name (make-register name)) register-table))) 'register-allocated) (define (lookup-register name) (let ((val (assoc name register-table))) (if val (cadr val) (error "Unknown register:" name)))) (define (execute) (let ((insts (get-contents pc))) (if (null? insts) 'done (begin ((instruction-execution-proc (car insts))) (execute))))) (define (dispatch message) (cond ((eq? message 'start) (set-contents! pc the-instruction-sequence) (execute)) ((eq? message 'install-instruction-sequence) (lambda (seq) (set! the-instruction-sequence seq))) ((eq? message 'allocate-register) allocate-register) ((eq? message 'get-register) lookup-register) ((eq? message 'install-operations) (lambda (ops) (set! the-ops (append the-ops ops)))) ((eq? message 'stack) stack) ((eq? message 'operations) the-ops) (else (error "Unknown request - - MACHINE" message)))) dispatch)))
function make_new_machine() { const pc = make_register("pc"); const flag = make_register("flag"); const stack = make_stack(); let the_instruction_sequence = null; let the_ops = list(list("initialize_stack", () => stack("initialize"))); let register_table = list(list("pc", pc), list("flag", flag)); function allocate_register(name) { if (is_undefined(assoc(name, register_table))) { register_table = pair(list(name, make_register(name)), register_table); } else { error(name, "multiply defined register"); } return "register allocated"; } function lookup_register(name) { const val = assoc(name, register_table); return is_undefined(val) ? error(name, "unknown register") : head(tail(val)); } function execute() { const insts = get_contents(pc); if (is_null(insts)) { return "done"; } else { inst_execution_fun(head(insts))(); return execute(); } } function dispatch(message) { function start() { set_contents(pc, the_instruction_sequence); return execute(); } return message === "start" ? start() : message === "install_instruction_sequence" ? seq => { the_instruction_sequence = seq; } : message === "allocate_register" ? allocate_register : message === "get_register" ? lookup_register : message === "install_operations" ? ops => { the_ops = append(the_ops, ops); } : message === "stack" ? stack : message === "operations" ? the_ops : error(message, "unknown request -- machine"); } return dispatch; }
Figure 5.14 The make_new_machine function implements the basic machine model.
5.2.1   The Machine Model