Macro.escape
escape
, go back to Macro module for more information.
Specs
Recursively escapes a value so it can be inserted into a syntax tree.
Examples
iex> Macro.escape(:foo)
:foo
iex> Macro.escape({:a, :b, :c})
{:{}, [], [:a, :b, :c]}
iex> Macro.escape({:unquote, [], [1]}, unquote: true)
1
Options
:unquote
- when true, this function leavesunquote/1
andunquote_splicing/1
statements unescaped, effectively unquoting the contents on escape. This option is useful only when escaping ASTs which may have quoted fragments in them. Defaults to false.:prune_metadata
- when true, removes metadata from escaped AST nodes. Note this option changes the semantics of escaped code and it should only be used when escaping ASTs, never values. Defaults to false.As an example,
ExUnit
stores the AST of every assertion, so when an assertion fails we can show code snippets to users. Without this option, each time the test module is compiled, we get a different MD5 of the module bytecode, because the AST contains metadata, such as counters, specific to the compilation environment. By pruning the metadata, we ensure that the module is deterministic and reduce the amount of dataExUnit
needs to keep around.
Comparison to Kernel.SpecialForms.quote/2
The escape/2
function is sometimes confused with Kernel.SpecialForms.quote/2
,
because the above examples behave the same with both. The key difference is
best illustrated when the value to escape is stored in a variable.
iex> Macro.escape({:a, :b, :c})
{:{}, [], [:a, :b, :c]}
iex> quote do: {:a, :b, :c}
{:{}, [], [:a, :b, :c]}
iex> value = {:a, :b, :c}
iex> Macro.escape(value)
{:{}, [], [:a, :b, :c]}
iex> quote do: value
{:value, [], __MODULE__}
iex> value = {:a, :b, :c}
iex> quote do: unquote(value)
{:a, :b, :c}
escape/2
is used to escape values (either directly passed or variable
bound), while Kernel.SpecialForms.quote/2
produces syntax trees for
expressions.