Macros Elixir:生成具有正确导入的模块
我正在尝试编写生成模块的宏:Macros Elixir:生成具有正确导入的模块,macros,elixir,Macros,Elixir,我正在尝试编写生成模块的宏: defmodule GenModules do defmacro module(name, do: body) do quote do defmodule unquote(String.to_atom(name)) do unquote(body) end end
defmodule GenModules do
defmacro module(name, do: body) do
quote do
defmodule unquote(String.to_atom(name)) do
unquote(body)
end
end
end
end
我缺少的是如何注入“import”语句,该语句将引用从中调用宏的模块
即,以下代码:
defmodule Test do
import GenModules
module "NewModule" do
def test_call do
hello_world
end
end
def hello_world do
IO.puts "Hello"
end
end
不会编译,因为hello_world函数在生成的NewModule中不可见
所以我需要生成
import Test
在模块主体之前,以某种方式获取调用宏的模块的名称。我该怎么做
谢谢,,
Boris要获取从中调用宏的模块,可以使用特殊形式
\uuuuu调用者\uuuuu
。它包含一组信息,但您可以像这样提取调用模块:
__CALLER__.context_modules |> hd
但更一般地说,我不认为您想要什么是可能的——您不能在完成定义模块之前导入它。例如:
defmodule A do
defmodule B do
import A
end
end
导致错误:
** (CompileError) test.exs:3: module A is not loaded but was defined.
This happens because you are trying to use a module in the same context it is defined.
Try defining the module outside the context that requires it.
谢谢你。是的,我意识到我不能按我计划的方式导入。但我仍然认为,一旦使用您建议的方法获得Mod值,我可以使用模块名来替换诸如hello\u world到Mod.hello\u world的调用。