💧 Elixir Advanced

What is the Elixir macro system and how does metaprogramming work?

Answer

Elixir's macro system is a first-class feature — the compiler itself is written in Elixir macros. Macros operate on the AST (Abstract Syntax Tree) at compile time, transforming code before it is compiled to BEAM bytecode. Define a macro: defmacro my_if(condition, do: body) do; quote do; case unquote(condition) do; true -> unquote(body); false -> nil; end; end; end. quote creates an AST. unquote injects values into the AST. Unlike C macros (text substitution), Elixir macros are hygenic and work with the full language. Use macros sparingly: they are powerful but increase complexity. Most Elixir code that looks like magic (use GenServer, defmodule, Ecto schema DSL, Phoenix router) is implemented as macros. The use macro: use ModuleName calls ModuleName.__using__/1 which typically injects code via quote/defmacro. Metaprogramming enables creating DSLs (domain-specific languages) embedded within Elixir.