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