diff --git a/lib/orb/constants.ex b/lib/orb/constants.ex index 39d0570..c03fc14 100644 --- a/lib/orb/constants.ex +++ b/lib/orb/constants.ex @@ -105,6 +105,13 @@ defmodule Orb.Constants do defmodule NulTerminatedString do defstruct memory_offset: nil, string: nil, type: Orb.I32.String + def empty() do + %__MODULE__{ + memory_offset: 0x0, + string: "" + } + end + defimpl Orb.ToWat do def to_wat(%Orb.Constants.NulTerminatedString{memory_offset: memory_offset}, indent) do [ @@ -126,10 +133,12 @@ defmodule Orb.Constants do def expand_if_needed(value) when is_binary(value), do: expand_string!(value) def expand_if_needed(value) when is_list(value), do: :lists.map(&expand_if_needed/1, value) def expand_if_needed(value) when is_struct(value, Orb.IfElse), do: Orb.IfElse.expand(value) + def expand_if_needed(%_{body: _} = struct) do body = expand_if_needed(struct.body) %{struct | body: body} end + def expand_if_needed(value), do: value defp expand_string!(string) when is_binary(string) do diff --git a/lib/orb/global.ex b/lib/orb/global.ex index 1178e58..8ae3604 100644 --- a/lib/orb/global.ex +++ b/lib/orb/global.ex @@ -75,13 +75,23 @@ defmodule Orb.Global do end end + def expand!(%Orb.Global{type: Orb.I32.String, initial_value: ""} = global) do + %Orb.Global{global | type: Orb.I32.String, initial_value: Orb.Constants.NulTerminatedString.empty()} + end + def expand!(%Orb.Global{type: Orb.I32.String, initial_value: string} = global) do - %Orb.Global{global | type: :i32, initial_value: Orb.Constants.expand_if_needed(string)} + %Orb.Global{ + global + | type: Orb.I32.String, + initial_value: Orb.Constants.expand_if_needed(string) + } end def expand!(%Orb.Global{} = global), do: global defimpl Orb.ToWat do + import Orb.ToWat.Helpers + def to_wat( %Orb.Global{ name: name, @@ -101,8 +111,8 @@ defmodule Orb.Global do end, " ", case mutability do - :readonly -> to_string(type) - :mutable -> ["(mut ", to_string(type), ?)] + :readonly -> do_type(type) + :mutable -> ["(mut ", do_type(type), ?)] end, " ", Orb.ToWat.to_wat(initial_value, ""), diff --git a/test/orb_test.exs b/test/orb_test.exs index 968771b..04c435a 100644 --- a/test/orb_test.exs +++ b/test/orb_test.exs @@ -85,6 +85,7 @@ defmodule OrbTest do global :mutable do @language "en" @mime_type "text/html" + @empty "" end defw mime_type_constant, I32.String do @@ -109,6 +110,7 @@ defmodule OrbTest do (global $five_quarters f32 (f32.const 1.25)) (global $language (mut i32) (i32.const 255)) (global $mime_type (mut i32) (i32.const 258)) + (global $empty (mut i32) (i32.const 0)) (data (i32.const 258) \"text/html\") (data (i32.const 255) \"en\") (func $mime_type_constant (export \"mime_type_constant\") (result i32)