This is an implementation of Intermediate Challenge #125, “Halt! It’s simulation time!”

The crux of the problem comes down to a table of virtual machine instructions like this:

I came up with the virtual machine abstraction, a 5-tuple machine with values for code, instruction pointer, instruction count, register values and whether or not the machine is halted. Then I defined some functions like get_register/3, set_register/4, set_instruction_pointer/3 which take a machine and some other arguments (a register number, for instance) and then return a value or a new machine with the appropriate change having been made. This is defined in

Then I wrote a parser for the assembler input. It’s quite simple, looking essentially like:

The entry point to the parser handles the rest:

A sample program like this:

SET 1 15
AND 0 1
JZ  0 1

will thus be parsed into a “program” like so: [set(1,15), and(0,1), jump_if_zero(0,1)]. The assembler is defined in

The table of operations is encoded directly using a custom operator:

Our evaluator is designed to first try to evaluate the instruction by loading and trying to evaluate the specification:

So, if I were to try evaluate(M, and(0,1), V) it will expand to evaluate(M, m(0) := m(0) /\ m(1), V). The rest of the rules for evaluate/3 handle the expansion in various ways:

The evaluation of m(0) := m(0) /\ m(1) will trigger the evaluation of m(0) /\ m(1), which will trigger the evaluation of m(0), then m(1), then A /\ B as it breaks the expression down into parts and evaluates each subtree, before evaluating m(0) := V to update the register. Special cases such as halted := true and ip := X are handled by calling special procedures to update other aspects of the machine.

The gain here is hard to overstate. Prolog doesn’t have arrays, for instance, but our sublanguage does.It’s easy to verify that the formal specification embedded in Prolog does the right thing, and it’s easy to verify that the sublanguage evaluator does the right thing. I think this technique will probably generalize nicely to other scenarios with Prolog. The rest of the code is visible in

This module doesn’t export the evaluation function directly; instead, callers are expected to provide the code and allow this module to handle executing it via execute/1 and execute/2, which run the code on a new machine, either discarding the final machine or returning it. The execution is also quite simple:

The loop is also pretty simple:

The halt semantics there are as specified; either the machine just executed HALT or we’re at instruction 10,000. execute_one simply finds the next instruction and prepares to execute it. do_halt prints out whether the machine halted of its own accord or if it hit the 10,000 instruction barrier.

The main program is suitably simple: