Pattern Matching on Elixir's AST
Using Elixir's homoiconic AST as a query language, from exploration in IEx to structural fingerprinting
Elixir is homoiconic, which is to say that the syntax tree representing a program is made of ordinary Elixir data structures. The AST is therefore not a private artefact of the compiler. It is accessible at runtime, can be pattern-matched, walked with Enum and hashed like any other term, and so serves as a query language for code itself. The techniques behind static analysis tools such as Credo apply just as well to verifying generated code as to detecting structural duplication or enforcing a project’s own conventions.
Exploring in IEx
The quickest way to understand the AST is to interrogate it directly. Code.string_to_quoted!/1 parses any string into its AST representation:
iex> Code.string_to_quoted!("1 + 2")
{:+, [line: 1], [1, 2]}
Every node is a tuple of the shape {form, metadata, args}. The form is an atom naming the operation, metadata is a keyword list (line, column, compiler hints) and args is the list of child nodes. Literals such as integers, strings, atoms and booleans appear as themselves.1
Remote calls nest one level further. The form is itself a {:., meta, [module, function]} tuple, in which the module is an __aliases__ node:
iex> Code.string_to_quoted!("IO.puts(\"hello\")")
{{:., [line: 1], [{:__aliases__, [line: 1], [:IO]}, :puts]}, [line: 1], ["hello"]}
Module aliases always take this form, with the alias given as a list of atoms, so that Foo.Bar.Baz becomes {:__aliases__, meta, [:Foo, :Bar, :Baz]}. It is the node to match against when checking which modules a piece of code calls.
The pipe operator is left-associative, so a |> b |> c parses as (a |> b) |> c. The last pipe sits at the root, and the first is nested deepest, as its left operand:
iex> Code.string_to_quoted!("a |> b |> c")
{:|>, [line: 1],
[{:|>, [line: 1], [{:a, [line: 1], nil}, {:b, [line: 1], nil}]},
{:c, [line: 1], nil}]}
Anonymous functions expose their clause structure explicitly:
iex> Code.string_to_quoted!("fn a, b -> a + b end")
{:fn, [line: 1],
[{:->, [line: 1],
[[{:a, [line: 1], nil}, {:b, [line: 1], nil}],
{:+, [line: 1], [{:a, [line: 1], nil}, {:b, [line: 1], nil}]}]}]}
The -> node separates the argument list from the body. The variable a appears twice, with the same atom each time, and this is what allows a pattern to capture a variable across a clause and its body. Once the shapes can be read, the rest is pattern matching.
Walking the tree
Macro.prewalk/3 traverses the AST depth-first, threading an accumulator through each node, and it is the primitive on which structural analysis of every kind is built:2
def remote_calls(ast) do
{_ast, calls} =
Macro.prewalk(ast, [], fn
{{:., _, [{:__aliases__, _, parts}, fun]}, _, args} = node, acc ->
{node, [{Module.concat(parts), fun, length(args)} | acc]}
node, acc ->
{node, acc}
end)
calls
end
This collects every remote call as a {Module, function, arity} tuple. Any structural query of the sort uses the same skeleton, in which the pattern changes and the accumulator logic stays.
Four techniques
Structural pattern matching
The most direct approach is to write a pattern describing exactly the AST shape to be detected. To catch Enum.reduce(list, 0, fn n, acc -> n + acc end):
defp explicit_sum?({
{:., _, [{:__aliases__, _, [:Enum]}, :reduce]},
_,
[_enum, 0, fun]
}) do
sum_fn?(fun)
end
defp explicit_sum?(_), do: false
The inner check uses variable capture to verify that the fn adds its own two arguments, in either order:
# fn a, b -> a + b end OR fn a, b -> b + a end
defp sum_fn?({:fn, _, [{:->, _, [[{a, _, _}, {b, _, _}], {:+, _, [{a, _, _}, {b, _, _}]}]}]}), do: true
defp sum_fn?({:fn, _, [{:->, _, [[{a, _, _}, {b, _, _}], {:+, _, [{b, _, _}, {a, _, _}]}]}]}), do: true
defp sum_fn?(_), do: false
Pattern matching enforces that the variable named in the head of the fn is the same atom used in the body. No explicit equality check is required, since the compiler does the work.
Stripping metadata
Stripping metadata replaces every meta keyword list with [], after which two structurally equivalent nodes compare equal with ==. The standard library has no public function for this, but it is a one-liner with Macro.prewalk:
defp strip_meta(ast) do
Macro.prewalk(ast, fn
{form, _meta, args} -> {form, [], args}
leaf -> leaf
end)
end
# Catches: case result do {:ok, v} -> {:ok, v}; {:error, e} -> {:error, e} end
defp identity_clause?({:->, _meta, [[pattern], body]}) do
strip_meta(pattern) == strip_meta(body)
end
That this can be written as a plain Macro.prewalk is the point: the AST is data, and it is transformed with the same tools that query it.
Pipeline decomposition
A pipe {:|>, meta, [left, right]} is just another node. Matching a two-step pipeline takes a single pattern, and patterns for several variants can be generated at compile time:
# Decompose any pipeline into a flat list of steps
def steps({:|>, _, [left, right]}), do: steps(left) ++ [right]
def steps(ast), do: [ast]
# Catch Repo.all(...) |> Enum.filter/reject/find(...)
for filter_fun <- [:filter, :reject, :find] do
defp repo_then_filter?({:|>, _,
[
{{:., _, [{:__aliases__, _, _repo}, :all]}, _, _},
{{:., _, [{:__aliases__, _, [:Enum]}, unquote(filter_fun)]}, _, _}
]
}), do: true
end
defp repo_then_filter?(_), do: false
The for comprehension expands at compile time into three pattern-matching clauses, so that Elixir’s metaprogramming is itself writing the static analysis rules.
Normalising and hashing
Structural duplication across files is found by normalising the AST, so as to remove everything that makes equivalent code look different, and then hashing it. Any two subtrees with the same hash are structural clones. The normalisation pass walks each subtree and:
- strips metadata, so that formatting and line numbers are irrelevant;
- renames variables to positional placeholders in order of first occurrence (
a,x,nall become$0,$1, etc.); - canonicalises boolean operators (
&&→and,||→or); - expands sigils to their underlying representation.
After normalisation, fn(a, b) -> a + b end and fn(x, y) -> x + y end are identical. Since the normalised AST is a plain Elixir term, fingerprinting can use :erlang.term_to_binary/1:
def fingerprint(ast) do
ast
|> normalise()
|> :erlang.term_to_binary()
|> then(&:crypto.hash(:blake2b, &1))
end
Detection then reduces to grouping fragments by fingerprint. Wherever a hash appears more than once, the fragments that share it are structural clones of one another, and grouping requires no pairwise comparison. The pass is linear in the number of AST nodes only if the hashes are computed bottom-up, each node’s from its children’s; hashing every subtree from scratch, as fingerprint/1 would, costs time proportional to the sum of the subtree sizes, which is quadratic for deep trees.
Verification as a pipeline stage
These techniques compose into a verification pipeline for generated code. Before code returned by a template, a macro or a language model is handed to Code.eval_quoted/3, its structural invariants can be asserted before any of it runs. The check is a traversal of the AST, cheap but not free, and costs nothing at runtime only when it is done at compile time, inside a macro:
defmodule CodeVerifier do
@forbidden [IO, System, File, Port, :os, :file]
def verify(code_string, expected_fun) do
with {:ok, ast} <- Code.string_to_quoted(code_string),
:ok <- assert_single_def(ast, expected_fun),
:ok <- assert_no_forbidden_calls(ast) do
{:ok, ast}
end
end
defp assert_no_forbidden_calls(ast) do
case Enum.filter(remote_calls(ast), fn {mod, _, _} -> mod in @forbidden end) do
[] -> :ok
found -> {:error, {:forbidden_calls, found}}
end
end
# ...
end
def generate_and_run(prompt, expected_fun) do
with {:ok, code} <- LLM.generate(prompt),
{:ok, ast} <- CodeVerifier.verify(code, expected_fun),
{:ok, result, _bindings} <- Code.eval_quoted(ast) do
{:ok, result}
end
end
Validating the text would be brittle here, since whitespace, comments and equivalent variations of syntax all produce false negatives; verifying the AST normalises them away. The two forms def f(x), do: x * 2 and def f(x) do\n x * 2\nend parse to the same tree, and a structural assertion accepts both without modification.
Further reading
The patterns above are the foundation of tools such as Credo, whose style checks are built on Macro.prewalk, and they underpin the more specialised static analysis libraries that build on Credo’s infrastructure. Two of these are worth reading as worked examples. ex_dna implements the normalise-then-hash approach to structural clone detection, catching renamed copies and near-miss clones across an entire codebase in a single O(n) pass. ex_slop takes the pattern-matching approach to known anti-patterns (blanket rescues, obvious comments, unidiomatic uses of Enum), expressing each as a single walk/2 clause. Both integrate as Credo checks.
Sourceror provides cursor-based traversal with richer position tracking, for tooling that needs to rewrite source rather than merely report on it. For integration with the compiler, Mix.Task.Compiler.Diagnostic lets custom checks emit warnings and errors as first-class build artefacts. The quote and unquote guide in the official documentation covers the quoting mechanics that produce these trees in the first place.
Footnotes
-
The Elixir syntax reference specifies this three-element convention in full. ↩
-
The
Macromodule also providespostwalk/3andtraverse/4for post-order and combined traversal. ↩