Calling a macro within a macro

I have defined a macro called @m.trial which simply escapes its argument and feeds into the @identity macro. The @identity macro is defined as (not escaped at the moment intentionally):

macro identity(x)
    x
end

@m.trial a doesn’t work as expected. Lets define a=0 in the Main module.

@m.trial @identity a

gives the error that a is not defined. An inspection with @macroexpand shows that it looks a in the module m. I would assume that since @identity doesn’t escape its argument, one would get Main.a.

If I define the unhygienic_identity macro:

macro unhygienic_identity(x)
    esc(x)
end

Now modified trial macro @m.unhygienic_trial works.
Now @m.foreach @unhygienic_identity a works. How exactly macro expansion happens ? I think this question is also related to the fact that escape expressions are not resolved before all macros are expanded. That is, @identity sees :($(Expr(:escape, :a))).

module m 

macro trial(x)
  quote 
    @Main.identity $(esc(x))
  end
end

macro unhygienic_trial(x)
  quote 
    @Main.unhygienic_identity $(esc(x))
  end 
end

end

One previous discussion of some issues involved here: Nested macros and esc

1 Like

Your hypothesis for the order of macro expansion

expand @outer
expand @inner
apply hygiene for @inner
apply hygiene for @outer

agrees with my experiments. Have you noticed any inconsistencies with this hypothesis ?