VUTPXHZOHNZE7EWKYSPMU4Q4U5F3OPPHVBFKZCLCBYCW2TUPUPEAC
def compile(parse_stream) do
parsed =
parse_stream
|> Stream.filter(fn {k, _v} -> k == :section_type or k == :section_body end)
|> Stream.chunk_every(2)
|> Enum.into(%{}, fn [section_type: type, section_body: body] -> {type, body} end)
forms =
List.flatten([
compile_module(parsed),
compile_export(parsed),
compile_functions(parsed),
{:eof, 5}
])
{:ok, module, bin} = :compile.forms(forms)
:code.load_binary(module, 'test', bin)
end
@doc """
Hello world.
defp compile_module(parsed) do
[
{:attribute, 1, :file, {'test.wasm', 1}},
{:attribute, 1, :module, :wasm_test}
]
end
defp compile_export(%{export: export, type: type}) do
exported_functions = Enum.filter(export, fn {export_name, {type, _idx}} -> type == :func end)
exported =
Enum.map(exported_functions, fn {name, {_, idx}} ->
{params, _out} = Enum.at(type, idx)
{
name |> :erlang.binary_to_atom(),
length(params)
}
end)
{:attribute, 2, :export, exported}
end
defp compile_functions(%{code: code, export: export}) do
exported_functions =
Stream.filter(export, fn {export_name, {type, _idx}} -> type == :func end)
|> Enum.into(%{}, fn {n, {_, idx}} -> {idx, :erlang.binary_to_atom(n)} end)
"""
def hello do
:world
defp compile_function(%{code: %{expr: []}}) do
nil
end
defp compile_function(%{code: %{expr: exprs, locals: []}}) do
function_body = compile_function_body(exprs)
function_desc = [{:clause, 4, [], [], function_body}]
{:function, 4, nil, 0, function_desc}
end
defp compile_function_body(exprs) do
compile_function_body(exprs, [])