Intcode assembler: add _self label

This commit is contained in:
Shadowfacts 2019-12-06 11:48:28 -05:00
parent cbbd6d8692
commit fe5bc1de7c
2 changed files with 37 additions and 7 deletions

View File

@ -61,14 +61,36 @@ defmodule Assembler do
end
end)
memory =
Enum.map(memory, fn
{:label, name} -> Map.fetch!(labels, name)
it -> it
end)
# IO.inspect(labels)
Enum.reverse(memory)
memory
|> Enum.reverse()
|> Enum.with_index()
|> Enum.map(fn
{{:label, name}, index} -> get_label(name, index, labels)
{it, _} -> it
end)
end
@doc """
Get the address of a label.
`_self` is a special label that resolves to the address of where it's being inserted into the program.
## Examples
iex> Assembler.get_label("test", 1, %{"test" => 14})
14
iex> Assembler.get_label("_self", 1, %{})
1
"""
def get_label(name, index, labels)
def get_label("_self", index, _) do
index
end
def get_label(name, _, labels) do
Map.fetch!(labels, name)
end
@doc """

View File

@ -68,4 +68,12 @@ defmodule AssemblerTest do
0
]
end
test "assembles a program with a _self label" do
program = """
add 1 2 _self
"""
assert Assembler.assemble(program) == [1101, 1, 2, 3]
end
end