# How to generate expression inside the returned expression of a Macro

**URL:** <https://discourse.julialang.org/t/how-to-generate-expression-inside-the-returned-expression-of-a-macro/6758>\
**Category:** General Usage\
**Tags:** macros\
**Created:** [October 29, 2017, 8:17pm UTC](https://discourse.julialang.org/t/how-to-generate-expression-inside-the-returned-expression-of-a-macro/6758 "2017-10-29T20:17:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![favba](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/favba/32/2735_2.png) [@favba](https://discourse.julialang.org/u/favba)\
**Post date:** [October 29, 2017, 8:17pm UTC](https://discourse.julialang.org/t/how-to-generate-expression-inside-the-returned-expression-of-a-macro/6758/1 "2017-10-29T20:17:59Z")

</div>

Consider this macro:

```julia
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
julia> @macroexpand @test2 a=10
:(:(a = 10))

```

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

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

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [October 29, 2017, 8:58pm UTC](https://discourse.julialang.org/t/how-to-generate-expression-inside-the-returned-expression-of-a-macro/6758/2 "2017-10-29T20:58:01Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [October 29, 2017, 9:02pm UTC](https://discourse.julialang.org/t/how-to-generate-expression-inside-the-returned-expression-of-a-macro/6758/3 "2017-10-29T21:02:25Z")

</div>

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