Macro: extract the method name, arguments and the body

There are two syntaxes that I know that defines a function:

julia> Meta.@dump function f(x)
       x
       end
Expr
  head: Symbol function
  args: Array{Any}((2,))
    1: Expr
      head: Symbol call
      args: Array{Any}((2,))
        1: Symbol f
        2: Symbol x
    2: Expr
      head: Symbol block
      args: Array{Any}((3,))
        1: LineNumberNode
          line: Int64 1
          file: Symbol REPL[42]
        2: LineNumberNode
          line: Int64 2
          file: Symbol REPL[42]
        3: Symbol x

julia> Meta.@dump f(x)=x
Expr
  head: Symbol =
  args: Array{Any}((2,))
    1: Expr
      head: Symbol call
      args: Array{Any}((2,))
        1: Symbol f
        2: Symbol x
    2: Expr
      head: Symbol block
      args: Array{Any}((2,))
        1: LineNumberNode
          line: Int64 1
          file: Symbol REPL[43]
        2: Symbol x

when there is a where statement things just get more complicated. It’s common for a macro to take a function and manipulate its name, arguments and body. Is there a built-in method that extracts those information?

Further, when I use a macro before a function definition, the macro gets a collection of expressions. How do I merge them like how Meta.@dump does?

My solution for the second problem is

macro mymacro(expr...)
    mymacro(Meta.@dump(expr...))
end

Probably not exactly the answer to your questions, but MacroTools.jl provide some useful, well, macro tools. You can convert (normalize) function definitions to short or long form, among other things.

3 Likes

Just found ExprTools.jl that does the job.