Skip to content

Commit

Permalink
Wasm building blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
RoyalIcing committed Jan 29, 2024
1 parent a338ca2 commit db372a8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
44 changes: 40 additions & 4 deletions lib/orb/module_definition.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -212,7 +244,11 @@ defmodule Orb.ModuleDefinition do
defp section(:data_count, bytes), do: section(0x0C, bytes)

defp section(id, bytes) do
<<id, byte_size(bytes)>> <> bytes
[
id,
byte_size(bytes),
bytes
]
end
end
end
8 changes: 0 additions & 8 deletions test/wasm_output_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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>> <>
Expand Down

0 comments on commit db372a8

Please sign in to comment.