How to generate expression inside the returned expression of a Macro

Consider this macro:

julia> macro test(ex)
       return ex
       end
@test (macro with 1 method)

julia> @macroexpand @test a=10
:(a = 10)

Now, I want to make a macro that return that encapsulated in a expression, that is, a want a macro test2 that when used with @macroexpand returns:

julia> @macroexpand @test2 a=10
:(:(a = 10))

I tried the following (ignoring the escaping for simplicity) but it didn’t work:

julia> macro test2(ex)
       return :(:($ex))
       end
@test2 (macro with 1 method)

julia> @macroexpand @test2 a=10
:ex 

Of course this is not the macro that I really want, just a reduction of the problem. I came across the problem when trying to make a macro to help with repeated code for the body of @generated functions, but wasn’t able to interpolate the input expression to a expression inside the expression returned by the macro.

julia> macro test2(ex)
       return QuoteNode(ex)
       end
@test2 (macro with 1 method)

julia> @test2 a=1
:(a = 1)

Following my maxim: when in doubt use Meta.quot QuoteNode.

Edited according to @yuyichao’s suggestions.

3 Likes

:($...) is always identity. QuoteNode instead of Meta.quot can also be slightly better.

1 Like