我正在尝试编写生成模块的宏:
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
无法编译,因为在生成的NewModule中hello_world函数不可见。
所以我需要生成
import Test
在模块主体之前,以某种方式获取从中调用宏的模块的名称。我该怎么做呢?
谢谢鲍里斯
要获取调用宏的模块,可以使用特殊形式__CALLER__
。它包含大量信息,但是您可以像这样提取调用模块:
__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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句