简体   繁体   English

有没有简单的方法来查看Elixir宏扩展到什么?

[英]Is there an easy way to see what an Elixir macro expands to?

Elixir has been my goto language for the past 18 months or so, however I sometimes find there is a tension between the "no magic" mantra (especially cited with reference to Phoenix vs Rails) and the use of macros. Elixir在过去的18个月左右一直是我的goto语言,但是我有时会发现“没有魔法”的口头禅(特别是引用凤凰与Rails的引用)和宏的使用之间存在紧张关系。

While I now miss macros when I'm using languages without them, I still wish it was easier to see what they are actually doing. 虽然当我使用没有它们的语言时我现在想念宏,但我仍然希望看到它们实际上在做什么更容易。 Some part of me always wants to pull back the DSL curtain and see the real code. 我的某些部分总是希望拉回DSL幕,看看真实的代码。

Is there a simple way to expand macros and see the code they generate, (perhaps via IEx) so that I don't have to dig through the layers of defmacro trying to piece it together in my head. 有没有一种简单的方法来扩展宏并查看它们生成的代码(可能通过IEx),这样我就不必深入研究defmacro层,试图将它拼凑在一起。

You can expand a macro with Macro.expand/2 您可以使用Macro.expand / 2扩展宏

iex> Macro.expand((quote do: (if true, do: 1)), __ENV__)
{:case, [optimize_boolean: true],
 [true,
  [do: [{:->, [],
     [[{:when, [],
        [{:x, [counter: 6], Kernel},
         {:in, [context: Kernel, import: Kernel],
          [{:x, [counter: 6], Kernel}, [false, nil]]}]}], nil]},
    {:->, [], [[{:_, [], Kernel}], 1]}]]]}

You can then use Macro.to_string/2 to get the output as a string instead of an AST: 然后,您可以使用Macro.to_string / 2将输出作为字符串而不是AST获取:

iex> Macro.expand((quote do: (if true, do: 1)), __ENV__) |> Macro.to_string()
"case(true) do\n  x when x in [false, nil] ->\n    nil\n  _ ->\n    1\nend"

You can then use IO.puts/2 to print the string to the terminal: 然后,您可以使用IO.puts / 2将字符串打印到终端:

iex> Macro.expand((quote do: (if true, do: 1)), __ENV__) |> Macro.to_string() |> IO.puts()
case(true) do
  x when x in [false, nil] ->
    nil
  _ ->
    1
end

尝试Chris McCord的这个技巧:

your_ast |> Macro.expand(__ENV__) |> Macro.to_string |> IO.puts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM