Macro.escape_once

53 views
Skip to first unread message

Andrea Leopardi

unread,
Apr 14, 2015, 10:05:20 AM4/14/15
to elixir-l...@googlegroups.com
Today, we have Macro.expand and Macro.expand_once, but we only have Macro.escape. I've recently found myself in need for something like Macro.escape_once.

Say you want to build a map to be pattern matched agains, so that the result of the macro is the following code:

%{foo: foo, bar: bar} = something

If I do something like this to build the map:

for var <- [:foo, :bar], into: %{} do
  {var, Macro.var(var, __MODULE__)
end
#=> %{foo: {:foo, [], Elixir}, bar: {:bar, [], Elixir}}

and then escape it in order to insert it into a quote, it becomes

{:%{}, [], [foo: {:{}, ...}, ...]}

since the variables {:foo, [], Elixir} and {:bar, [], Elixir} will be escaped (recursively). In order to solve this, I have to manually do:

kv = for var <- [:foo, :bar] do
  {var, Macro.var(var, __MODULE__)
end

{:%{}, [], kv}

It's very very possible that I'm missing something here, so I apologise in advance for that :). However, in the remote case I'm not missing anything, what do you think about adding a Macro.escape_once function?

José Valim

unread,
Apr 14, 2015, 10:11:26 AM4/14/15
to elixir-l...@googlegroups.com
I am not sure if we can escape things once since {:{}, ...} can appear any time in an AST and it would be impossible to know if it is a previously escaped result or something that we want to further escape.

FWIW, we had the same issue in Ecto and adopted the same solution.



José Valim
Skype: jv.ptec
Founder and Lead Developer

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/9230a616-7415-4fa2-90a8-c87a121e034d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Andrea Leopardi

unread,
Apr 14, 2015, 6:19:59 PM4/14/15
to elixir-l...@googlegroups.com, jose....@plataformatec.com.br
I had to face this today and after implementing with this solution (manually using {:%{}, ...}) I remembered I already saw this pattern used for Ecto queries.
I'm afraid that it's a very "mysterious" pattern though. It's also true that the use cases where you want to do this are probably not common at all.

I'm not sure I understood the reason why this would be hard to do, but I'll trust your judgement :).
Reply all
Reply to author
Forward
0 new messages