# Macro to generate do block

I use a lot of code that looks like this

``````foo(arg1, arg2) do bar
bar.this = 5
bar.that = 6
end
``````

What I initially wanted to do is replace the repetitive "bar"s by defining macros for “this” and “that”, which seems easy enough. This, however, relies on the argument actually being called “bar”. So I wanted to write a macro to generate the complete do-block as well.
Now, I do realize this might not actually be a good idea as there is an obvious upside to explicitly defining the argument name. However, as I thought about it and I couldn’t get it to work, I got curious if it is actually possible.

So my question is, is there a way to make a macro like this (or similar) generate the code from above:

``````@foo arg1 arg2 begin
bar.this = 5
bar.that = 6
end
``````

Something like

``````using MacroTools

macro foo(a1, a2, block)
@capture(block, begin body__ end)
quote foo(\$(esc(a1)), \$(esc(a2))) do \$(esc(:bar))
\$(map(esc, body))
end
end
end
``````

but I am 99% certain I got the hygiene/escaping wrong somewhere (because I always do); fix accordingly.

1 Like

Actually, it even worked without the capture magic like this:

``````macro foo(a1, a2, block)
quote
_foo(\$(esc(a1)), \$(esc(a2))) do \$(esc(:bar))
\$(esc(block))
end
end
end
``````

…which I am fairly certain I tried yesterday as well, but it was late, I guess.
Anyway, thanks for pointing me in the right direction