Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 6 — Metaprogramming & DSLs

Elixir macros operate on the language’s own AST at compile time. This is not a party trick — it is the infrastructure the ecosystem is built on. It explains why Phoenix routes, Ecto queries, and Nx kernels all feel like native language constructs.

From Erlang you know: you have already written the crude version of this — a parse_transform, or -compile(export_all) plus manual code generation. Three differences make macros a daily tool rather than a legend: they are hygienic (no variable capture surprises), they are scoped (expansion happens at a call site, not to a whole module), and they are ordinary functions you can unit-test. Same underlying idea — code that runs at compile time and emits code — with the sharp edges filed off.

6.1 What Compilers Actually Do With Your Code

Before macros, fix the compilation picture:

flowchart TD
    SRC["Elixir source (.ex)"] --> PARSE["Parse → AST"]
    PARSE --> EXP["Macro expansion<br/>← compile-time code generation"]
    EXP --> LOWER["Lowered to BEAM code"]
    LOWER --> BEAM["BEAM bytecode (.beam)"]
    BEAM --> VM["BEAM VM / OTP"]

Macros are functions that run during expansion: they receive quoted code, return transformed/generated code. Everything downstream never knew they existed. Ch 08 expands this picture; here you only need the stage where macros live.

6.2 A Minimal Macro

Two cells (paste in Livebook or IEx). Keep them separate — see the note after cell 2.

Cell 1 — define (evaluate on its own):

defmodule Greeting do
  defmacro __using__(_opts) do
    quote do
      import Greeting, only: [hi: 1]

      def hello(name) do
        "Your name is #{inspect(name)}"
      end
    end
  end

  defmacro hi(name) do
    quote do
      "Hi, " <> unquote(name)
    end
  end
end

Cell 2 — use it (a separate cell, after cell 1 has been evaluated):

defmodule Hello do
  use Greeting

  def my_fun, do: hi("BEAM")
end

IO.puts Hello.hello("Erlang")
IO.puts Hello.my_fun()

Do not paste definition and use into one cell, or into one .exs file. It fails with module Greeting is not loaded but was defined, because use expands to require Greeting; Greeting.__using__(opts) — a remote call that needs the module already compiled. Every require/use example in this chapter assumes this, as does every library you try first.

Reading guide:

  • quote do ... end returns the AST of its body instead of executing it.

  • unquote(...) splices runtime values into that AST.

  • defmacro hi/1 runs at compile time of callers: hi("BEAM") becomes "Hi, " <> "BEAM" before the BEAM ever sees it.

  • __using__/1 defines what use Greeting injects — imports, function definitions, behaviour declarations. This is the hook behind every use Phoenix.LiveView, use Ecto.Schema, use GenServer.

  • use is exactly two things: use Foo expands to require Foo; Foo.__using__(opts). Nothing more. The four callbacks a library can hook are:

    CallbackFiresUsed by
    __using__/1at use Fooinject imports/defs/@behaviour
    __before_compile__/1after the module body, before compileDSLs that collect clauses (§6.4)
    __after_compile__/2after compile, gets the bytecodeemit files, run codegen
    __on_definition__/6on every def in the using modulemacro tracing, DSL registries

    Erlang has no equivalent for any of these; the closest is a parse transform, the last section of this chapter, which is coarser and unhygienic.

Step by Step: What quote Returns

An AST node is a three-element tuple: {form, metadata, args} — Erlang’s abstract-format idea with friendlier metadata. Literals represent themselves; everything else is a tuple:

iex> quote do: 1 + 2
{:+, [context: Elixir, imports: [{1, Kernel}, {2, Kernel}]],
 [1, 2]}

iex> quote do: x
{:x, [], Elixir}
  • form — node kind: operator, call target, variable name
  • metadata — compile-time info: line/column, context, imports
  • args — child nodes; a variable’s third element names its hygiene context (Elixir at the shell, a unique tag inside macros)

Hygiene: Broken, Then Fixed

The classic first mistake is treating a macro argument as a value instead of splicing it:

Evaluate the defmodule and the require/calls as separate cells, as in §6.2 — one cell for the module, one for the use:

# cell 1
defmodule Hygiene do
  defmacro double_broken(x), do: quote(do: x * 2)   # fresh hygienic var
  defmacro double_fixed(x),  do: quote(do: unquote(x) * 2)
end

# cell 2
require Hygiene

Hygiene.double_broken(21)
#=> ** (CompileError) undefined variable x

Hygiene.double_fixed(21)
#=> 42

Hygiene renamed x inside quote, so the broken version references a variable nobody bound; splicing the argument’s AST fixes it.

The actual compiler output for the broken version is worth reading once, because it names the variable’s context — which is the mechanism made visible:

warning: variable "x" is unused (if the variable is not meant to be used,
prefix it with an underscore)
  │
2 │   defmacro double_broken(x), do: quote(do: x * 2)
  │                         ~

error: undefined variable "x" (context Hygiene)
  │
2 │ Hygiene.double_broken(21)
  │ ^^^^^^^^^^^^^^^^^^^^^

(context Hygiene) is the whole of hygiene in three words: the x inside your quote is not the x bound as the macro’s parameter — it is a fresh variable in the macro’s own context. unquote(x) is what splices the caller’s actual AST in place of it.

When a macro must assign one of the caller’s variables, var!/1 deliberately breaks hygiene:

defmodule Ctx do
  defmacro put(_key, val) do
    quote do: var!(assigned) = unquote(val)
  end
end

defmodule CallerMod do
  require Ctx
  def go do
    Ctx.put(:k, 41 + 1)
    assigned               # ← visible here only because of var!
  end
end

CallerMod.go()             #=> 42

bind_quoted & unquote_splicing: The Injection Toolkit

Two mechanics appear in every serious macro (including the Validator DSL in §6.3) and deserve their own pass before you meet them in the wild.

bind_quoted: solves double evaluation. Splicing the same argument AST twice evaluates it twice at the call site:

defmodule Twice do
  # BAD: x's AST spliced twice → caller's expression runs twice
  defmacro twice_bad(x),  do: quote(do: unquote(x) + unquote(x))

  # GOOD: bind_quoted evaluates x ONCE, binds the result under x,
  #       and disables bare unquote inside this quote block
  defmacro twice_good(x), do: quote(bind_quoted: [x: x], do: x + x)
end

require Twice
side_effect = fn -> IO.puts("evaluated!"); 21 end

Twice.twice_bad(side_effect.())    # prints "evaluated!" twice → 42
Twice.twice_good(side_effect.())   # prints "evaluated!" once  → 42

The bind_quoted: [x: x] form means “evaluate the outer x once at macro-expansion time, inject the result as a hygienic variable named x.” That disabling of stray unquote is deliberate — mixing both mechanisms in one quote is how subtle expansion bugs happen; if you truly need both, opt back in with quote unquote: true, bind_quoted: [...].

unquote_splicing: splats a list of AST nodes into an argument list — the difference between inserting one node and many:

defmodule MyDef do
  defmacro deflogged(name, args, do: body) do
    quote do
      def unquote(name)(unquote_splicing(args)) do   # ← args become the
        IO.puts("-> #{unquote(name)}")               #   parameter list
        unquote(body)
      end
    end
  end
end

defmodule Demo do
  require MyDef
  MyDef.deflogged :double, [x], do: x * 2
end

Demo.double(21)          #=> prints "-> double", returns 42

Without the splice, def f([x]) would define a one-argument function whose parameter is a literal list. With it, [x] becomes the parameter list (x).

Re-reading §6.3’s Validator with these eyes: field/2 records through bind_quoted, and __before_compile__ builds its clause list then splices it with unquote_splicing(clauses) ahead of the fallback clause. There is no third mechanism to learn for reading most library macros.

Debugging Your Expansions

Three moves cover 95% of macro debugging:

iex> ast = quote do: if List.first([1]), do: :yes
iex> ast |> Macro.expand_once(__ENV__) |> Macro.to_string() |> IO.puts()
case(List.first([1])) do
  x when :erlang.orelse(:erlang."=:="(x, false), :erlang."=:="(x, nil)) ->
    nil
  _ -> :yes
end

# Peek INSIDE a macro while it expands — plain IO.puts at compile time:
defmacro loud(x) do
  IO.puts("expanding with: #{Macro.to_string(x)}")
  quote(do: unquote(x))
end

Macro.expand_once/2 performs one expansion step against your environment; Macro.to_string/1 renders any AST back into readable code. Expand, print, read — no debugger required.

6.3 Why the Ecosystem Looks Like It Does

Metaprogramming pipeline feeding major libraries:

flowchart TD
    AST["Elixir AST"] --> MC["Macro / Compiler"]
    MC --> PHX["Phoenix<br/>routes · plugs"]
    MC --> ECTO["Ecto<br/>schema · queries"]
    MC --> ASH["Ash<br/>resources · policies"]
    PHX --> OUT["plain Elixir code<br/>(no runtime magic)"]
    ECTO --> OUT
    ASH --> OUT

Phoenix — declarative routing

scope "/", MyAppWeb do
  pipe_through(:browser)

  live "/dashboard", DashboardLive
  live "/users", UserLive.Index, :index
end

pipeline :authenticated do
  plug(MyAppWeb.Plugs.EnsureAuthenticated)
end

live, plug, pipe_through, scope are macros building a route table at compile time. No reflection at request time — it compiles down to plain pattern matches.

Ecto — schemas and composable queries

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do                    # ← macro defining fields as struct keys
    field :name, :string
    field :email, :string
    has_many :posts, MyApp.Blog.Post
    timestamps()
  end

  def changeset(user, attrs) do
    user
    |> cast(attrs, [:name, :email])
    |> validate_required([:name, :email])
    |> unique_constraint(:email)
  end
end

import Ecto.Query

query =
  from u in User,                      # ← macro producing a query AST...
  where: u.email == ^email,            #   ...checked & compiled to SQL
  preload: [:posts],
  limit: 1

The query DSL is parsed at compile time and translated to SQL — invalid queries fail early, not at runtime.

Ash — declarative domain resources

Verified against ash ~> 3.0; the DSL shifts between minor versions, so check the installed version’s docs before copying.

defmodule MyApp.Accounts.User2 do
  use Ash.Resource,
    domain: MyApp.Accounts,
    data_layer: Ash.DataLayer.Ets

  attributes do
    uuid_primary_key :id
    attribute :name, :string, allow_nil?: false
    attribute :email, :ci_string, allow_nil?: false
    timestamps()
  end

  actions do
    defaults [:read, :destroy]

    create :register do
      accept [:name, :email]
    end
  end

  code_interface do
    # `define :register` generates a function named after the action; pass
    # `action: :register` explicitly when they differ.
    define :register, args: [:name, :email]
  end
end

# Usage (the code_interface puts it on the resource, not the domain):
# MyApp.Accounts.User2.register!("Alice", "alice@example.com")

Nx — numerical definitions (preview of Part IV)

defmodule MyModel do
  import Nx.Defn

  defn forward(x, params) do
    x
    |> linear_layer(params.w1, params.b1)
    |> relu()
    |> linear_layer(params.w2, params.b2)
  end
end

defn restricts Elixir to a tensor-safe subset, then hands the AST to a compiler backend (XLA/MLX). Same macro machinery, targeting accelerators instead of SQL.

Roll Your Own: A Tiny Compile-Time Validation DSL

Everything above scales down to a weekend-sized example: accumulate fields as module attributes during the body, generate validator clauses in __before_compile__ — exactly the trick behind schema do ... end:

defmodule Validator do
  defmacro __using__(_) do
    quote do
      import Validator, only: [field: 2]
      Module.register_attribute(__MODULE__, :fields, accumulate: true)
      @before_compile Validator
    end
  end

  # Runs at the *caller's* compile time: records, generates nothing yet.
  defmacro field(name, opts) do
    quote bind_quoted: [name: name, opts: opts] do
      @fields {name, Keyword.get(opts, :presence, false)}
    end
  end

  # Runs after the caller's body finished accumulating @fields.
  defmacro __before_compile__(env) do
    fields = Module.get_attribute(env.module, :fields) |> Enum.reverse()

    clauses =
      for {name, true} <- fields do     # presence flag filters here
        quote do
          def validate(unquote(name), data) do
            case Map.fetch(data, unquote(name)) do
              {:ok, v} when v in [nil, ""] ->
                {:error, "#{unquote(name)} is required"}
              {:ok, _} -> :ok
              :error -> {:error, "#{unquote(name)} is missing"}
            end
          end
        end
      end

    quote do
      unquote_splicing(clauses)
      def validate(_field, _data), do: :ok
    end
  end
end

defmodule Signup do
  use Validator

  field :email, presence: true
  field :bio,   presence: false
end

Signup.validate(:email, %{email: ""})   #=> {:error, "email is required"}
Signup.validate(:email, %{})            #=> {:error, "email is missing"}
Signup.validate(:bio, %{})              #=> :ok (fallback clause)

Two details carry the design: accumulate: true makes @fields grow into a list instead of being overwritten per call, and generated code is plain pattern-matched clauses — zero runtime reflection.

6.4 Practical Guidance for Erlang Developers

SituationReach for
Plain abstractionFunctions / higher-order functions
Module contractsBehaviours (Ch 05)
Delegate an API to another moduledefdelegate (no macro needed)
Compile-time injection of boilerplate across modules__using__ macro
New syntax for a domainFull DSL macro
Reading libraries’ sourceStart with their __using__ — it lists everything injected

Two more Kernel building blocks worth knowing by name:

# defdelegate — expose another module's function (plain code, not magic):
defmodule MyRepo do
  defdelegate all(query), to: BaseRepo
  defdelegate insert(changeset), to: BaseRepo
end

# defoverridable — let callers replace injected defaults:
defmodule Base do
  defmacro __using__(_) do
    quote do
      def name, do: "default"
      defoverridable name: 0
    end
  end
end

defmodule Child do
  use Base
  def name, do: "custom"     # overrides the injected default
end

Macro hygiene in one paragraph: variables inside quote are renamed per call site so macros don’t leak bindings. When a macro must touch the caller’s variables, it uses var!(name); when it must resolve an alias at the call site, alias!(Alias). You’ll read these far more often than write them.

Rules of thumb:

  1. Write macros last. Most needs are solved by functions + behaviours.
  2. Read macros first. When a library “feels magical,” find its defmacro __using__ — magic is always a finite list of injections.
  3. Macros expand at compile time, so stack traces point at the generated code unless the generator preserves locations. Keeping locations is a one-flag decision inside your quote:
quote location: :keep do
  def unquote(name)(unquote_splicing(args)) do
    unquote(body)
  end
end

Verified on 1.20.4. A __using__/1 generating boom/0 that raises, with a caller in a third module:

no keep:      {Loc2.Plain, :boom, 0, [file: ~c"lib/m.ex", line: 24]}
location: :keep:  {Loc2.Keep, :boom, 0, [file: ~c"lib/m.ex", line: 8]}

Line 24 is the use Loc2.M call; line 8 is raise("kaboom") inside the macro’s quote. So the precise statement is: without :keep, every generated definition is attributed to the use line that instantiated it — one line for all of them, which is useless when the macro emits ten functions. With :keep, each generated definition keeps the line inside your quote where its body was written.

Note it does not point at the caller of boom/0 — no quoting flag does that. What :keep buys is a stack trace that points into your macro’s source rather than collapsing onto one use line.

Inspect any expansion live:

iex> Macro.expand_once(quote(do: if(true, do: 1)), __ENV__)
{:case, [optimize_boolean: true, type_check: {:case, :if}],
 [
   true,
   [
     do: [
       # clause 1: {:->, _, [[{:when, _, [x, :erlang.orelse(
       #              :erlang."=:="(x, false), :erlang."=:="(x, nil))]}], nil]}
       # clause 2: {:->, _, [[{:_, _, Kernel}], 1]}
     ]
   ]
 ]}   # shape shown abbreviated — print it with Macro.to_string/1 to read

# dbg/1 is itself a great example of a small, useful macro:
iex> quote do: dbg(x)
{:dbg, [context: Elixir, imports: [...]], [{:x, [], Elixir}]}
     # dbg receives CODE, can print + re-inject it

When Not to Write a Macro

Reach for a macro only when functions genuinely cannot do the job — the common trap is wrapping trivial computation because it feels framework-y. defmacro square(x) buys nothing over def square(x): no new syntax, no deferred evaluation, no injected definitions. Functions compose with & captures and appear intact in stack traces:

defmodule Math do
  def square(x), do: x * x
end

Enum.map([1, 2, 3], &Math.square/1)   #=> [1, 4, 9]

Justified macro uses: new surface syntax (where: in Ecto), controlling when arguments evaluate (if/unless defer them), injecting definitions across modules (child_spec). If none apply, write a function.

Macros vs Erlang Parse Transforms

Erlang’s escape hatch for metaprogramming is the parse transform: a compiler plugin receiving a module’s entire abstract format after parsing, returning rewritten erl_parse trees. Enabled per module, no hygiene:

%% pt_version.erl — injects module_version/0 wherever enabled via -compile
-module(pt_version).
-export([parse_transform/2]).

parse_transform(Forms, _Opts) ->
    Fun = {function, 0, module_version, 0,
           [{clause, 0, [], [], [{integer, 0, 20260825}]}]},
    Forms ++ [Fun].
ConcernParse transformElixir macros
Scopewhole module, all-at-onceper call site
Inputraw abstract formatquoted Elixir AST
Activation-compile({...}) attributerequire / use
Hygienenoneautomatic (var! opts out)

Elixir source never routes through parse transforms — its own front end expands macros before Erlang compilation begins; you meet transforms only inside Erlang dependencies. Where Erlang rewrites modules wholesale, Elixir libraries grow syntax callers opt into line by line.

Elixir’s metaprogramming is not a party trick. It is infrastructure for the ecosystem.

Explore More

  • Quote and unquote guide — the AST construction mechanics behind §6.2
  • Domain-Specific Languages guide — building your own DSL the way Ash/Ecto do
  • Macro module — expand_once, to_string, traversal helpers; your debugging toolkit
  • Erlang Efficiency Guide: the compiler — the parse-transform and compile-time story from the Erlang side, useful for reading a macro-heavy Erlang dependency you inherited
  • Metaprogramming Elixir (Chris McCord) — short, classic, still relevant
  • Exercise: run Macro.expand_once(quote(do: x = 1 && 2), __ENV__) and read the generated case tree — demystify one “magic” construct today
  • Exercise: reproduce the location: :keep experiment in §6.4 — a __using__/1 that emits boom/0 raising an error, with and without :keep, and compare the file:line in each stacktrace

Checkpoint

  1. At which stage of compilation do macros run?
  2. What does use Something typically inject?
  3. How does Ecto validate queries early?
  4. What is the shape of an AST node for 1 + 2?
  5. Which two Kernel macros let you opt out of hygiene?
  6. Why does bind_quoted exist, and what does it disable inside its quote?
  7. What does location: :keep actually change in a stacktrace — and what does it not fix?
Answers
  1. Between parsing and lowering to BEAM code — during macro expansion.
  2. Imports, aliases, injected function/clause definitions, behaviour declarations, compile-time configuration — whatever its __using__/1 quotes.
  3. The query DSL builds a typed AST at compile time; it is translated to SQL against the adapter, so structural errors surface before execution.
  4. A 3-tuple {:+, metadata, [1, 2]} — operator, metadata, arguments.
  5. var!/1 (escape a variable binding) and alias!/1 (resolve an alias at the expansion site). Both are ordinary Kernel macros — they are not in Kernel.SpecialForms, which holds only the irreducible language core (defmodule, def, case, =, <<>>, quote, …).
  6. It evaluates the argument once at expansion time and injects the result — avoiding double evaluation when the same AST is spliced more than once. Inside a bind_quoted block, bare unquote is disabled (opt back in with unquote: true).
  7. Without it, every definition your macro generates is attributed to the use line that instantiated it — one line for all of them. With it, each generated definition keeps its own line inside your quote, so a macro emitting ten functions gives ten distinct stacktrace lines instead of ten identical ones. What it does not do is point at the caller of the generated function; no quoting flag does that.

Next: Chapter 7 — Gradual Typing