Introspect functions with guard clauses

244 Views Asked by At

Given a module having two functions with the same arity, but different guard clauses, how do I (ideally) see what those clauses are, or at least that there are two functions?

defmodule Test do
  def greet(name) when name == "foo" do
    IO.puts("Hello, bar")
  end

  def greet(name), do: IO.puts("Hello, #{name}")
end

Test.__info__(:functions) doesn't work as it only returns [greet: 1]

2

There are 2 best solutions below

0
On BEST ANSWER

You can decompile the code of a module into "abstract code" and dig into that to get this info. Here's how you can get the clauses of each function in a module:

module = Test

{:ok, {^module, [abstract_code: {:raw_abstract_v1, abstract_code}]}} = :beam_lib.chunks(module, [:abstract_code])

for {:function, _, name, arity, clauses} <- abstract_code do
  # Uncomment the next line to print the AST of the clauses.
  # IO.inspect(clauses)
  IO.inspect {name, arity, length(clauses)}
end

Output:

{:__info__, 1, 7}
{:greet, 1, 2}

Note: This is likely private API and might change in the future versions of Erlang/OTP. The output above is on Erlang/OTP 20.

0
On

If the module is 3rd-party and/or is already compiled, please refer to the answer provided by @Dogbert.

If the module is owned, the requested information might be collected on compilation stage using @on_definition hook:

defmodule TestInfo do
  def on_definition(_env, kind, name, args, guards, body) do
    with {:ok, table} <- :dets.open_file(:test_info, type: :set) do
      clauses =
        case :dets.lookup(table, name) do
          {:error, _reason} -> []
          [] -> []
          list when is_list(list) -> list[name]
        end

      :dets.insert(table, {name, [{kind, args, guards} | clauses]})
      :dets.close(table)
    end
  end
end

defmodule Test do
  @on_definition {TestInfo, :on_definition} # ⇐ THIS

  def greet(name) when name == "foo" do
    IO.puts("Hello, bar")
  end

  def greet(name), do: IO.puts("Hello, #{name}")
end

Now you have all the definitions stored in DETS:

{:ok, table} = :dets.open_file(:test_info, type: :set) 
:dets.lookup(table, :greet)
#⇒ [
#    greet: [
#      {:def, [{:name, [line: 10], nil}], []},
#      {:def, [{:name, [line: 6], nil}],
#       [{:==, [line: 6], [{:name, [line: 6], nil}, "foo"]}]}]
#  ]

:dets.close(table)

I used DETS to store the info because it’s being stored on compilation stage and the typical usage would be in runtime.