# Calling a macro within a macro

**URL:** <https://discourse.julialang.org/t/calling-a-macro-within-a-macro/57766>\
**Category:** General Usage\
**Tags:** macros\
**Created:** [March 23, 2021, 4:24am UTC](https://discourse.julialang.org/t/calling-a-macro-within-a-macro/57766 "2021-03-23T04:24:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![turquoise](https://avatars.discourse-cdn.com/v4/letter/t/71e660/32.png) [@turquoise](https://discourse.julialang.org/u/turquoise)\
**Post date:** [March 23, 2021, 4:24am UTC](https://discourse.julialang.org/t/calling-a-macro-within-a-macro/57766/1 "2021-03-23T04:24:24Z")

</div>

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):

```julia
macro identity(x)
    x
end

```

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

```julia
@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:

```julia
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)))`.

```julia
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

```

---

<div class="post-metadata">

**Author:** ![johnmyleswhite](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/johnmyleswhite/32/31_2.png) [@johnmyleswhite](https://discourse.julialang.org/u/johnmyleswhite)\
**Post date:** [March 24, 2021, 1:36am UTC](https://discourse.julialang.org/t/calling-a-macro-within-a-macro/57766/2 "2021-03-24T01:36:27Z")

</div>

One previous discussion of some issues involved here: [Nested macros and esc](https://discourse.julialang.org/t/nested-macros-and-esc/47857)

---

<div class="post-metadata">

**Author:** ![turquoise](https://avatars.discourse-cdn.com/v4/letter/t/71e660/32.png) [@turquoise](https://discourse.julialang.org/u/turquoise)\
**Post date:** [March 25, 2021, 6:40pm UTC](https://discourse.julialang.org/t/calling-a-macro-within-a-macro/57766/3 "2021-03-25T18:40:40Z")

</div>

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 ?
