View Source Circe (circe v0.2.1)

Documentation for Circe.

Link to this section Summary

Functions

Handles the sigil ~m to match on code's ast.

Link to this section Functions

Link to this macro

sigil_m(arg, modifiers)

View Source (macro)

Handles the sigil ~m to match on code's ast.

This is meant as a symmetric tool to quote/2.

The sigil should be used within a matching context:

You can directly match code:

iex> import Circe
iex> ast = quote do {:banana} end
{:{}, [], [:banana]}
iex> match?(~m/{:banana}/, ast)
true

You can ignore parts of the code by combining interpolation and an underscore:

iex> import Circe
iex> ast = quote do {:test_atom_pls_ignore} end
{:{}, [], [:test_atom_pls_ignore]}
iex> match?(~m/{#{_}}/, ast)
true

Instead of ignoring parts of the code, you can bind it to a variable:

iex> import Circe
iex> ~m/{#{banana}}/ = quote do {:split} end
{:{}, [], [:split]}
iex> banana
:split

Sometime the ast that would correspond to the code you wrote is wrapped in a list, (typically concerning the -> operator), you can unwrap it with the modifier w:

iex> import Circe
iex> ast = quote do case 4 do 1 -> :one ; 2 -> :two ; 3 -> :three ; _ -> :too_big end end
iex> ~m/case #{_} do #{clauses} end/ = ast
iex> Enum.any?(clauses, fn ~m/(#{_} -> :too_big)/ -> true ; _ -> false end)
false
iex> Enum.any?(clauses, fn ~m/(#{_} -> :too_big)/w -> true ; _ -> false end)
true

The equivalent to unquote_splicing/3 is #{..._}:

iex> import Circe
iex> ~m/{#{...desserts}}/ = quote do {:banana, :split, :peach, :melba} end
{:{}, [], [:banana, :split, :peach, :melba]}
iex> desserts
[:banana, :split, :peach, :melba]

... is parsed by Elixir as an identifier, so ...[whatever] will be parsed as key-based access to a data structure, to avoid problems, insert a space between ... and the opening bracket [, for example ~m/def #{... [head, [do: body]]}/