raacer
raacer

Reputation: 5462

Expand certain macro invocation

I've found similar question, but there is no explanation about expansion of certain macro invocations. For example, how do I see what this invocation expands to?

defmodule Test do
  use ExUnit.Case
  test "always pass", do: assert true
end

Upvotes: 0

Views: 161

Answers (1)

nietaki
nietaki

Reputation: 9010

You can pretty much follow the approach from the question you linked:

defmodule Test do
  use ExUnit.Case

  # (other tests here)  

  ast = quote do
    test "always pass", do: assert true
  end
  expanded = Macro.expand(ast, __ENV__)

  IO.puts "Original:"
  # IO.puts inspect(ast, pretty: true)
  IO.puts ast |> Macro.to_string
  IO.puts ""
  IO.puts "Expanded:"
  # IO.puts inspect(expanded, pretty: true)
  IO.puts expanded |> Macro.to_string
end

If you run the tests now with mix test, you'll see the expanded version of the test macro:

Original:
test("always pass") do
  assert(true)
end

Expanded:
(
  var = {:_, [], ExUnit.Case}
  contents = {:__block__, [], [{:assert, [context: CrawlieTest, import: ExUnit.Assertions], [true]}, :ok]}
  message = "always pass"
  (
    name = ExUnit.Case.register_test(__ENV__, :test, message, [])
    def(unquote(name)(unquote(var))) do
      unquote(contents)
    end
  )
)

You can uncomment the IO.puts inspect(_, pretty: true) lines to see how the original and the expanded version look in the Abstract Syntax Tree representation.

Upvotes: 2

Related Questions