如何检索 Julia 宏的方法?

How can I retrieve the methods of a Julia macro?

提问人:Harrison Grodin 提问时间:3/27/2017 更新时间:11/17/2023 访问量:307

问:

在 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

宏也可以有多种方法。

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"
""

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

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

我尝试使用 ession 来包含宏,但这不起作用。Expr

julia> methods(:@g)
# 0 methods for generic function "(::Expr)":

如何检索宏的方法?

方法 Julia

评论

1赞 Dan Getz 3/27/2017
methods(eval(Symbol("@g")))对我有用,但必须有更干净的方法
3赞 Dan Getz 3/27/2017
清洁剂(无):evalmethods(Main.(Symbol("@g")))
4赞 Harrison Grodin 3/28/2017
@DanGetz不错。但是,是的,应该有一种更清洁的方法......(顺便说一句,已弃用,应该改用。Main.(Symbol("@g"))getfield(Main, Symbol("@g")

答:

2赞 HarmonicaMuse 5/16/2017 #1

我会在我的模块 () 中放置一个通用宏 (),并附上以下行: .这样一来,你就可以在每个 Julia 会话中使用它,例如:@methodsMethodsMacro~/.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