On the first part of this series I’m going to guide you through the assemble I build.
In 2019 AdventOfCode had the participants build a VM, which could interpret a language that Eric Wastl made up for the event. If you haven’t tried AdventOfCode yet, you should definitely give it a go! I enjoyed every year so far, with 2019 giving me additional inspiration every so often :D (as you will see in this series).
Ok so Eric gave us the VM instructions bit by bit, I won’t bother going into all the details here. I will include them when necessary.
My assembler was a a bit of a layer above machine code, but not that much:
ADD 5 {5} [5]
OUT [10]
there_are_labels:
JNZ 1 there_are_labels
ADD [there_are_labels+0] 0 [5]
> 0 1 there_are_labels [there_are_labels+2]
[x]
means “positional”. Take the value at memory position x
.{x}
means “relative”. Take the value at memory position x + base_pointer
. base_pointer
is an extra register, and can be moved with it’s own instruction MPB 5
.ADD 1 2 [label+2]
, ADD 1 2 [label-label2]
>
denotes the start of a data line. It should be followed by data seperated by spaces. Each data entry can be immediate or positional. It will just be copied to the memory (after label resolution).Because we cannot add offset and label during runtime, a trick you will see later is self-modifying code!:
ADD {-3} {-2} [create_array_add_instruction+3] # <- we link to the `ADD` statement below, and modify it's third parameter
create_array_add_instruction:
ADD {-1} 0 [0] # <- Note that the `[]` are still needed to set the correct mode for the parameter!,
# we will only change the value, not the mode!
As with most assembly languages this one has 2 main goals:
But we can use this allready to do some coding!
MBP data # moving base pointer to the data label
fib: # label for loop
ADD {0} {1} {2} # adding offset 0 and offset 1 to offset 2
ADD {1} 0 {0} # moving {1} to {0}
ADD {2} 0 {1} # {2} to {1}
OUT {0} # printing
ADD {3} 1 {3} # adding one to {3}
CM= {3} 18 {4} # aboring after 3
JEZ {4} fib
HLT # Halt
data:
> 0 1 0 18