Is there a trick to input an `Expr` into a macro?

Given a macro @something you can get the actual macro object by writing var"@something" and from that you can inspect it’s methods and call it. For example:

julia> macro do_nothing(ex)
           ex
       end
@do_nothing (macro with 1 method)

julia> methods(var"@do_nothing")
# 1 method for macro "@do_nothing":
[1] var"@do_nothing"(__source__::LineNumberNode, __module__::Module, ex) in Main at REPL[13]:1

This says that var"@do_nothing" has a method that takes in LineNumberNode and Module telling you where the macro was invoked, and an expression that it operates on. If you provide this stuff, you can run the macro on a runtime Expr and get out an Expr. For example,

julia> var"@do_nothing"(LineNumberNode(@__LINE__(), @__FILE__()), @__MODULE__(), :(x + 1))
:(x + 1)
4 Likes