liveBook · Manning

Macro

As explained in Elixir in Action, Third Edition

A macro system is a language facility that transforms code during compilation or another pre-execution phase.

A macro is Elixir code that runs at compile time, receives parsed source code, and returns an alternative version. This transforms program structure before execution rather than operating on runtime values. section 2.6

Elixir macros operate on an abstract syntax tree rather than C-style textual substitution. That structure supports transformations over arbitrarily complex, nested expressions and enables language extensions that resemble built-in constructs. section 1.2.1 section 2.6

Use macros to:

  • Reduce repetitive code and boilerplate by generating alternative code during compilation. section 2.6
  • Build expressive mini-DSLs and language constructs on top of a small core. section 2.6
  • Extend existing abstractions without hiding the runtime mechanisms that matter for production behavior. section 1.2.1

Transforming unless

The unless construct can be expressed as a macro that transforms `unless some_expression do block_1 else block_2 end` into an equivalent `if` expression with the branches reversed. The syntax looks built in, but the transformation occurs during compilation. section 2.6

Injecting GenServer callbacks

Writing `use GenServer` invokes a macro during compilation. The macro injects default callback functions into the calling module; defining a callback with the same name and arity overrides that default. section 6.2.2

unless some_expression do
 block_1
else
 block_2
end

Compare the macro-shaped `unless` form with its equivalent `if` expansion. section 2.6

How Elixir in Action, Third Edition covers it

How deep it goes
Defines AST-based transformation and demonstrates expansions, but deliberately stops short of detailed macro implementation.
Examples
Uses unless-to-if expansion, use GenServer callback injection, and ExActor-based server simplification as concrete examples.
What it assumes
Assumes familiarity with Elixir functions and modules while explaining compile-time execution and parsed source transformation.
What you can do after
Apply the use macro with GenServer to obtain default callbacks and override only the behaviour required by a module.
How it connects
Connects macros to abstract syntax trees, functions, special forms, mini-DSLs, and GenServer behaviours.

Also explained in

Compare how 9 books explain macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.