Interpolate inside a Quote inside a Macro inside a Quote?

Is it possible to do this? I need this for my package Reduce.jl

Let’s say I have a bunch of functions, call them fun and I need a macro for each

macro fun(expr)
    :(fun($expr))
end

But I need to automate this using code generation. So I want to do something like

for fun in [:name_of_func, :name_of_another_func]
    quote
        macro $fun(expr)
            ## what to put here ?
        end
    end
end

Now, so the line of code needs to look like this, but it needs to appear inside the quote:

julia> :($fun($(Symbol("\$expr"))))
:(func_name($expr))

But how can I nest an expression like that inside of a quote?

So the expr needs to be interpolated into the output quote of the macro, and all of this needs to happen within a quote block.

Please let me know if it is possible, how to do it. Hopefully, question makes sense to everyone.

If you do q = Expr(:quote, :($fun($(Expr(:$, :expr))))) and then interpolate $q into your macro, that should work, I think?

for fun in [:name_of_func, :name_of_another_func]
    @eval begin
        macro $fun(expr)
            :($$(QuoteNode(fun))($(esc(expr))))
        end
    end
end
julia> @macroexpand @name_of_another_func(bla)
:((Main.name_of_another_func)(bla))

julia> @macroexpand @name_of_func(bla)
:((Main.name_of_func)(bla))

maybe

Thanks, both worked!

1 Like