From db372a8c9a3c9d28728b875b7ba8945ba2924d5b Mon Sep 17 00:00:00 2001 From: Patrick Smith Date: Tue, 30 Jan 2024 10:25:05 +1100 Subject: [PATCH] Wasm building blocks --- lib/orb/module_definition.ex | 44 ++++++++++++++++++++++++++++++++---- test/wasm_output_test.exs | 8 ------- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/lib/orb/module_definition.ex b/lib/orb/module_definition.ex index b8d0942..8322c47 100644 --- a/lib/orb/module_definition.ex +++ b/lib/orb/module_definition.ex @@ -190,13 +190,45 @@ defmodule Orb.ModuleDefinition do ) do [ <<"\0asm", 0x01000000::32>>, - section(:type, <<0x01, 0x60, 0x00, 0x01, 0x7F>>), - section(:function, <<0x01, 0x00>>), - section(:export, <<0x01, 0x06, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72, 0x00, 0x00>>), + section(:type, vec([func_type({}, {:i32})])), + section(:function, vec([0x00])), + section(:export, vec([export_func("answer", 0x00)])), section(:code, <<0x01, 0x04, 0x00, 0x41, 0x2A, 0x0B>>) ] end + defp vec(items) when is_list(items) do + [ + length(items), + items + ] + |> IO.iodata_to_binary() + end + + defp func_type(params, results) do + [ + 0x60, + for types <- [params, results] do + vec( + for type <- Tuple.to_list(types) do + case type do + :i32 -> 0x7F + end + end + ) + end + ] + end + + defp export_func(name, func_index) do + [ + byte_size(name), + name, + 0x00, + func_index + ] + end + defp section(:custom, bytes), do: section(0x00, bytes) defp section(:type, bytes), do: section(0x01, bytes) defp section(:import, bytes), do: section(0x02, bytes) @@ -212,7 +244,11 @@ defmodule Orb.ModuleDefinition do defp section(:data_count, bytes), do: section(0x0C, bytes) defp section(id, bytes) do - <> <> bytes + [ + id, + byte_size(bytes), + bytes + ] end end end diff --git a/test/wasm_output_test.exs b/test/wasm_output_test.exs index 66c45ad..fa0b76a 100644 --- a/test/wasm_output_test.exs +++ b/test/wasm_output_test.exs @@ -14,14 +14,6 @@ defmodule WasmOutputTest do end end - wasm_source = """ - (module $Basic - (func $answer (export "answer") (result i32) - (i32.const 42) - ) - ) - """ - assert <<"\0asm", 0x01000000::32>> <> <<0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7F>> <> <<0x03, 0x02, 0x01, 0x00>> <>