如何检索Julia宏的方法?

Har*_*din 6 methods macros julia

在Julia中,该methods函数可用于检索函数的方法.

julia> f(::Int) = 0
f (generic function with 1 method)

julia> f(::String) = ""
f (generic function with 2 methods)

julia> methods(f)
# 2 methods for generic function "f":
f(::String) in Main at REPL[1]:1
f(::Int64) in Main at REPL[0]:1
Run Code Online (Sandbox Code Playgroud)

宏也可以有多种方法.

julia> macro g(::Int)
           0
       end
@g (macro with 1 method)

julia> macro g(::String)
           ""
       end
@g (macro with 2 methods)

julia> @g 123
0

julia> @g "abc"
""
Run Code Online (Sandbox Code Playgroud)

但是,该methods函数似乎不适用于宏,因为Julia首先调用宏,因为它们不需要括号.

julia> methods(@g)
ERROR: MethodError: no method matching @g()
Closest candidates are:
  @g(::String) at REPL[2]:2
  @g(::Int64) at REPL[1]:2
Run Code Online (Sandbox Code Playgroud)

我尝试使用Expression来包含宏,但这不起作用.

julia> methods(:@g)
# 0 methods for generic function "(::Expr)":
Run Code Online (Sandbox Code Playgroud)

如何检索宏的方法?

Sal*_*apa 2

我会在 my 的模块() 中放置一个通用宏@methods( )以及以下行:。这样,您就可以在每个 Julia 会话中使用它,例如:MethodsMacro~/.juliarc.jlusing MethodsMacro

julia> module MethodsMacro

       export @methods

       macro methods(arg::Expr)
           arg.head == :macrocall || error("expected macro name")
           name = arg.args[1]
           :(methods($name))
       end

       macro methods(arg::Symbol)
           :(methods($arg)) |> esc
       end

   end
MethodsMacro
julia> using MethodsMacro

julia> @methods @methods
# 2 methods for macro "@methods":
@methods(arg::Symbol) at REPL[48]:12
@methods(arg::Expr) at REPL[48]:6

julia> f() = :foo; f(x) = :bar
f (generic function with 2 methods)

julia> @methods f
# 2 methods for generic function "f":
f() at REPL[51]:1
f(x) at REPL[51]:1
Run Code Online (Sandbox Code Playgroud)