How to view module source after code generation?

Hi @dimitarvp

why aren’t the module attributes visible in the generated source?

The modulus attribute is only available at compile time and is replaced by the assigned value. Here is an example with an additional function and decompile by beam_file:

iex(1)> {:module, _name, binary, _bindings} =
...(1)>   defmodule Xyz do
...(1)>     @names [:a, :b, :c]
...(1)>
...(1)>     def names, do: @names
...(1)>
...(1)>     for name <- @names do
...(1)>       def hello(unquote(name)), do: "hello #{unquote(name)}"
...(1)>     end
...(1)>   end
{:module, Xyz,
 <<70, 79, 82, 49, 0, 0, 6, 252, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 216,
   0, 0, 0, 24, 10, 69, 108, 105, 120, 105, 114, 46, 88, 121, 122, 8, 95, 95,
   105, 110, 102, 111, 95, 95, 10, 97, 116, ...>>,
 [hello: 1, hello: 1, hello: 1]}
iex(2)> binary |> BeamFile.elixir_code!() |> IO.puts()
defmodule Elixir.Xyz do
  def names do
    [:a, :b, :c]
  end

  def hello(:a) do
    <<"hello ", String.Chars.to_string(:a)::binary()>>
  end

  def hello(:b) do
    <<"hello ", String.Chars.to_string(:b)::binary()>>
  end

  def hello(:c) do
    <<"hello ", String.Chars.to_string(:c)::binary()>>
  end
end
:ok
2 Likes