有没有简单的方法可以查看Elixir宏的扩展范围? [英] Is there an easy way to see what an Elixir macro expands to?

查看:53
本文介绍了有没有简单的方法可以查看Elixir宏的扩展范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的18个月左右的时间里,Elixir一直是我使用的语言,但是我有时会发现没有魔术"的口头禅(特别是在Phoenix vs Rails的引用中)和宏的使用之间存在着紧张关系.

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.

虽然我现在在使用没有宏的语言时会错过宏,但我仍然希望能够更轻松地了解它们的实际作用.我的某些部分总是想拉回DSL的帷幕,看看真正的代码.

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.

是否有一种简单的方法可以扩展宏并查看它们生成的代码(也许通过IEx),这样我就不必深入研究defmacro的各个层,而将它们拼凑在一起.

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.

推荐答案

您可以使用然后您可以使用 Macro.to_string/2 来获取输出为字符串而不是AST:

You can then use Macro.to_string/2 to get the output as a string instead of an 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"

然后您可以使用 IO.puts/2 进行打印终端的字符串:

You can then use IO.puts/2 to print the string to the terminal:

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

这篇关于有没有简单的方法可以查看Elixir宏的扩展范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆