Reflection Elixir中的运行时代码反射
在Elixir中,如何在运行时提取模块或函数的抽象语法树(AST)Reflection Elixir中的运行时代码反射,reflection,elixir,abstract-syntax-tree,Reflection,Elixir,Abstract Syntax Tree,在Elixir中,如何在运行时提取模块或函数的抽象语法树(AST) defmodule Car do def beep do :beep end end iex > Car."way to get the ast of the 'beep' function" {:def, [context: Elixir, import: Kernel], [{:beep, [context: ...], ...}, [do: :beep]]} 用长生不老药有没有办法做到这一点
defmodule Car do
def beep do
:beep
end
end
iex > Car."way to get the ast of the 'beep' function"
{:def, [context: Elixir, import: Kernel],
[{:beep, [context: ...], ...}, [do: :beep]]}
用长生不老药有没有办法做到这一点
defmodule Car do
def beep do
:beep
end
end
iex > Car."way to get the ast of the 'beep' function"
{:def, [context: Elixir, import: Kernel],
[{:beep, [context: ...], ...}, [do: :beep]]}
根据:
许多语言将这种表示称为抽象语法树(AST)。Elixir称之为引用的表达:
因此,使用quote宏可以获得Elixir Quoted表达式(AST),如下所示:
iex(7)> quote do Car.beep() end
{{:., [], [{:__aliases__, [alias: false], [:Car]}, :beep]}, [], []}
我想您正在寻找Macro.expand/2,但老实说,宏并不是我在Elixir中最深入的知识领域。我认为编译模块后,AST就会丢失。据我所知,只有在编译时,当宏被计算时,你才能得到AST。看看这个资源,它们显示了一个例子:{:ok,AST}=Code.string_to_quoted(File.read!(“lib/hello.ex”)@PatrickOscity这是一个很好的观点。我有点错过了关于“长生不老药中的运行时”的要点@GavinBrelstaff,谢谢。这是一种方式。我希望能够对应用程序加载的现有模块(其中包含宏的需求和用法)进行反射。我以前使用过此功能,如果您想构建可以使用unquote安全执行的代码,这非常有用。