Understand Macro.escape

As in the documentation (Macro.escape/2), it does return the AST of the passed in value in contrast do quote which does return the AST of the passed in code.

As contrived example from an iex session should make the difference more clear:

iex(1)> defmodule Foo, do: def(bar, do: [1,2,3])
{:module, Foo, <<...>>, {:bar, 0}}
iex(2)> Foo.bar
[1, 2, 3]
iex(3)> quote do: Foo.bar 
{{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []}
iex(4)> Macro.escape(Foo.bar)
[1, 2, 3]
iex(5)> quote do: [1,2,3] 
[1, 2, 3]

So as you can see, the return value of quote, does give you an AST for some code that can generate the value [1,2,3], while for Macro.escape/1 the argument is evaluated to get its value and then this value is returned as AST. (for lists, atoms, and integers the AST is actually identically to the value).

9 Likes