2017-01-01 75 views
0

我發現similar question,但沒有關於某些宏調用的擴展的解釋。例如,我怎麼看這個調用擴展到什麼地方?展開某些宏調用

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

回答

2

你幾乎可以遵循你鏈接的問題的辦法:

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 

如果用mix test現在運行測試,你會看到test宏的擴展版本:

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 
) 
) 

您可以取消註釋IO.puts inspect(_, pretty: true)行以查看原始和擴展版本在Abstract Syntax Tree表示。

+0

我在鏈接問題的方法中錯過了'if/2'也是宏:) – raacer