include MARSLab m = make_test_machine("marsprog.txt") m.step m.dump m.status m m.run
ADD a, b | add the value at a to the value at b, storing the result at b |
ADD #a, b | add the number a to the value at b, storing the result at b |
SUB a, b | subtract a from b, storing the result in b |
DAT #b | halt the currently running
MARS program; the operand b can be used to store a number as data (hence, DAT for "data") |
MOV a, b | copy the instruction at a to the location b |
MOV #a, b | copy the number a to operand b of the instruction at b |
JMP a | change the pc so the next instruction executed is the one at a |
JMZ a, b | change the pc so the next instruction executed is the one at a if the value at b is 0 |
JMN a, b | change the pc so the next instruction executed is the one at a if the value at b is not 0 |
CMP a, b | compare a with b, skip the next instruction if the two are equal |
SLT a, b | skip over the next instruction if a is less than b |
Note: In the memory of the MARS virtual machine, all instruction have exactly two operands. When you dump an instruction that was originally written "DAT #b", you will see "DAT #0, #b", and when you dump an instruction that was originally written "JMP a", you will see "JMP a, #0".
x DAT #4 y DAT #7 simple ADD x, y DAT #0 end simplesimple.txt
x DAT #5 y DAT #9 acc DAT #0 mult ADD x, acc SUB #1, y JMN mult, y end multmult.txt
Consider the following MARS program:
in DAT #6 out DAT #0 l1 SLT #0, in JMP l2 ADD #1, out SUB #2, in JMP l1 l2 DAT #0 end l1
Save this program as mystery.txt, load it, and step through its execution. For each step in its execution, record the values of PC, in, and out in a table in mystery_trace.txt as shown below. The first few steps are done for you.
PC in out *2 6 0 *4 6 0 *5 6 1
If in is changed to be any non-negative integer, how will the value of out when the program halts be related to the value of in when the program starts? Write your answer at the bottom of mystery_trace.txt
In mystery.rb, write a Ruby function mystery(x) that implements the same algorithm as this MARS program (gets the same result in the same way).