Intcode assembler: add data labels

This commit is contained in:
Shadowfacts 2019-12-06 10:32:41 -05:00
parent 1964c576fc
commit 36ea4a177d
1 changed files with 17 additions and 13 deletions

View File

@ -1,9 +1,9 @@
defmodule Assembler do
@asm """
in #30
clt 30 #8 #31
in #res
clt res #8 #31
jnz 31 #lessThan
ceq 30 #8 #31
ceq res #8 #31
jnz 31 #equal
out #1001
hlt
@ -15,14 +15,16 @@ defmodule Assembler do
equal:
out #1000
hlt
res: 0
"""
def test do
@asm
|> IO.inspect()
|> assemble(32)
|> assemble()
end
def assemble(asm, pad_length \\ 0) do
def assemble(asm) do
{memory, labels} =
asm
|> String.split("\n")
@ -44,6 +46,15 @@ defmodule Assembler do
Map.put(labels, String.slice(line, 0..-2), length(memory))
}
Regex.match?(~r/^\w+: \d+$/, line) ->
[name, value] = String.split(line, ": ")
value = String.to_integer(value)
{
[value | memory],
Map.put(labels, name, length(memory))
}
true ->
IO.inspect("Ignoring line: #{line}")
end
@ -55,13 +66,6 @@ defmodule Assembler do
it -> it
end)
memory =
if pad_length > length(memory) do
repeat(0, pad_length - length(memory)) ++ memory
else
memory
end
IO.inspect(labels)
Enum.reverse(memory)
end
@ -84,7 +88,7 @@ defmodule Assembler do
String.to_integer(digits)
_ ->
[_, name] = Regex.run(~r/^#(\w+)$/, param)
[_, name] = Regex.run(~r/^#?(\w+)$/, param)
{:label, name}
end