@generated inside macro: who's interpolating?

Well, I think in the end I must bow to Cedric cstjean’s hard earned wisdom.

As I see it the main issue is that with a @generated -in-a-macro, where some of the interpolation is intended to occur at macro time, some at generation time, the code I was trying to write is not explicit enough on this decision: even if we got the code to work (and I still struggle with this :a vs. :(:a) business in spite of Tom’s good remark), it’s not readable. At least I get a headache reading my own code. So I got it all to work with the readable, is somewhat verbose, code:

Base.replace(ex::Symbol,a::Symbol,b) = ex==a ? deepcopy(b) : ex
Base.replace(ex::Expr  ,a::Symbol,b) = Expr(ex.head,replace.(ex.args,a,Ref(b))...)
Base.replace(ex        ,a::Symbol,b) = ex
macro mac(A)
    ex = quote
        @generated jenny(a,b) = :(a+b*øa)
        foo(a,b) = a+b*øb
    end
    ex = replace(ex,:øa,A)
    ex = replace(ex,:øb,A)
    return esc(ex)
end

@mac(a)
jenny(2.,3.)
foo(1.,2.)

Here I explicitely prescribe the interpolations that are to occur at macro time - and I could have done the same within the @generate function. Flexible, explicit, and so far, works.

A bit of syntax sweetening on the replace function and the job is done.

Neat thing with a Scandinavian keyboard: øReplaceMe :wink:

1 Like