How can I get Julia macro methods?

In Julia, the methods function can be used to retrieve the methods of a function.

 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 

Macros can also have several methods.

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

However, the methods function does not seem to work with macros because Julia first calls the macro because they do not need parentheses.

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

I tried using Expr ession to contain a macro, but that didn't work.

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

How can I get macro methods?

+5
source share
1 answer

I would put a common macro ( @methods ) inside the module ( MethodsMacro ) in my ~/.juliarc.jl along with the line: using MethodsMacro . So you can use it in every session of Julia, for example:

 julia> module MethodsMacro export @methods macro methods(arg::Expr) arg.head == :macrocall || error("expected macro name") name = arg.args[] |> Meta.quot :(methods(eval($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 
+1
source

Source: https://habr.com/ru/post/1265938/


All Articles