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 8 — The Compilation Model

An Erlang developer already knows the destination: BEAM bytecode. This chapter confirms there is no runtime surprise waiting — and shows exactly where Elixir adds steps.

From Erlang you know: rebar3’s compile pipeline, .app.src → .app, beam_lib:chunks/2, beam_disasm, and the hot-code-loading model all apply unchanged. What is new is where Elixir sits in that pipeline and the incremental-build graph Mix maintains for you. Nothing about the artifact differs; only the front end does.

8.1 From .ex to Execution

flowchart TD
    SRC["Elixir source (.ex)"] --> AST["Parse → AST"]
    AST --> EXP["Macro expansion<br/>← Ch 06 lives here"]
    EXP --> LOW["Lowered to Erlang/BEAM code"]
    LOW --> BC["BEAM bytecode (.beam)"]
    BC --> VM["BEAM VM / OTP"]
    VM --> P["Processes<br/>schedulers · GC<br/>distribution"]

Steps at a high level:

  1. Parse — source becomes the internal AST representation
  2. Macro expansion — macros execute at compile time, transform/generate code (types from Ch 07 are checked around here too)
  3. Compilation — resulting program compiled to BEAM-compatible modules
  4. .beam output — same file format Erlang produces
  5. Runtime — OTP executes them exactly as Erlang modules

You can prove identity to yourself. Compile the module, then ask the runtime from the other language:

mix compile
erl -pa _build/dev/lib/hello/ebin -noshell -eval '
  io:format("which: ~p~n", [code:which('"'"'Elixir.Hello'"'"')]),
  io:format("exports: ~p~n", ['"'"'Elixir.Hello'"'"':module_info(exports)]),
  halt().'
which: ".../_build/dev/lib/hello/ebin/Elixir.Hello.beam"
exports: [{'__info__',1},{add,2},{module_info,0},{module_info,1}]

(That export list is real output, not a sketch.) Note the quoted module name: in an Erlang shell, unquoted Hello parses as a variable — Elixir modules are always addressed as 'Elixir.Name' from Erlang.

Your Elixir module is callable from Erlang as any other module — because it is one. (Names are atoms like :"Elixir.Hello".)

What Mix Actually Writes

The build output is worth reading once, because it makes several later chapters concrete. After mix compile in a two-file app:

_build/dev/lib/hello/
├── .mix/compile.app_cache          ← build graph; delete it and everything rebuilds
├── .mix/compile.elixir             ← per-module manifests: mtimes, deps, digests
├── .mix/compile.elixir_scm
├── consolidated/                   ← protocol dispatch tables (Ch 05)
│   ├── Elixir.Collectable.beam
│   ├── Elixir.Enumerable.beam
│   ├── Elixir.IEx.Info.beam
│   ├── Elixir.Inspect.beam
│   ├── Elixir.List.Chars.beam
│   ├── Elixir.String.Chars.beam
│   └── Elixir.JSON.Encoder.beam
├── ebin/Elixir.Hello.beam          ← your code
└── ebin/hello.app                  ← generated, NOT hand-written

Three things an Erlang developer should notice:

There is no src/ directory and no .app.src. Mix generates the .app from mix.exs. Here is the real content of a minimal app:

{application,hello,[
  {modules,['Elixir.Hello']},
  {optional_applications,[]},
  {applications,[kernel,stdlib,elixir,logger]},
  {description,"hello"},
  {registered,[]},
  {vsn,"0.1.0"},
  {mod,{'Elixir.Hello.Application',[]}}
]}.

Compare that to the .app.src you used to write by hand: same keys, same semantics, {mod, ...} present only because you declared it. The one real difference is elixir sitting in applications — every Elixir app depends on the elixir OTP application, and the dependency list is computed from your extra_applications plus your deps, not typed out.

The consolidated/ directory is new to you. Erlang devs implement -callback dispatch; protocol dispatch (Ch 05 §5.2) is Elixir’s addition, and Mix builds its lookup tables here. Delete the directory and protocol calls get slower; nothing breaks.

.mix/compile.elixir is the incremental-build state. §8.5 is about what that file records.

Inside the .beam: Chunks

A .beam file is a container of named chunks — and beam_lib opens it from either language. From an Erlang shell:

1> beam_lib:chunks("Elixir.Hello.beam", [attributes, compile_info, exports]).
{ok,{'Elixir.Hello',
     [{attributes,[{vsn,[...]}]},
      {compile_info,[{version,"10.0.3"},
                     {options,...},
                     {source,"…/lib/hello.ex"}]},
      {exports,[{'__info__',1},{add,2},{module_info,0},{module_info,1}]}]}}

Note '__info__',1 in the exports list: that is Elixir’s reflection entry point. Hello.__info__(:functions), (:attributes), (:macros), (:compile) are what Elixir tooling (docs, compilers, mix xref) calls; the Erlang-side equivalent is Hello:module_info/0,1. No Erlang module has __info__/1.

(beam_lib:chunks/2 takes chunk aliases — pass atoms (abstract_code, attributes, compile_info, exports, imports, …), not the raw chunk ids as strings.)

Chunks worth knowing by name:

ChunkContent
Dbgi (debug_info)debug info — the source of abstract_code reconstruction
CInf (compile_info)compiler version, options, source path, timestamp
ExpT (exports)the interface Erlang tooling dispatches on

Ask for abstract_code and you get the expanded program: macros from Ch 06 are gone by now, and types were checked around Ch 07’s stage. The forms come back as Erlang erl_parse trees, because at that point the code is Erlang-shaped. One caveat: Elixir stores debug info in its own format, so abstract_code needs the Elixir compiler backend on the code path — run the query from iex/mix, or add Elixir’s elib to an erl session, or you’ll get {error, {missing_backend, _, elixir_erl}}.

Prove It: Disassemble Both Sides

beam_disasm opens Elixir-produced .beam files exactly like any other, because there is no “other”. Compile defmodule Hello do def add(a, b), do: a + b end, then from an Erlang shell:

1> {beam_file, M, _Exports, _Attrs, _Compile, Funs} =
    beam_disasm:file("Elixir.Hello.beam").
2> {function, add, 2, _Label, Asm} = lists:keyfind(add, 2, Funs).
3> io:format("~p~n", [Asm]).
[{label,10},
 {line,[{location,"hello.ex",2}]},
 {func_info,{atom,'Elixir.Hello'},{atom,add},2},
 {label,11},
 {gc_bif,'+',{f,0},2,[{x,0},{x,1}],{x,0}},
 return]

The hot path is two instructions: put both arguments through the same GC-safe + BIF your Erlang code compiles to (the func_info preamble is standard export trampoline boilerplate, present in every module). Hand-write the twin in pure Erlang (add(A, B) -> A + B.), disassemble it, and the opcode sequence matches modulo label numbers and line info. The only meaningful difference anywhere in either file: the module atom reads 'Elixir.Hello'.

8.2 .ex vs .exs

ExtensionPurposeExecution
.exApplication codeCompiled to .beam by mix compile
.exsScripts, tests, configCompiled in memory and executed; no .beam written to disk

That second row is the one worth getting right: .exs is not interpreted. The same pipeline runs — parse, expand, compile to BEAM bytecode — the only difference is that the bytecode is loaded and executed immediately instead of being persisted. The mental model is erl -eval or escript, not a scripting engine. Tests (test/**/*_test.exs) and config files stay .exs; everything shipped stays .ex.

There is a third case worth knowing, because it catches people migrating: a .exs file sitting inside lib/ is silently ignored by mix compile. Only .ex files there are compiled; the .exs is not even a warning. If you are porting a module and nothing appears in ebin/, check the extension before you check anything else.

The rule in one line: .exs is a load-and-run format for things Mix should not own — tests, scripts, config/*.exs, mix.exs. Anything Mix should own, including a Mix task, belongs in lib/mix/tasks/*.ex.

When you bypass Mix, elixirc takes the same options the compiler exposes through mix compile:

$ elixirc --warnings-as-errors --no-docs -o ebin lib/hello.ex
$ ls ebin
Elixir.Hello.beam

elixirc exposes only the negative forms: there is no --docs or --debug-info flag, because both chunks are on by default and you use --no-docs/--no-debug-info to strip them. The compiler switches are --warnings-as-errors, --no-docs, --no-debug-info, --ignore-module-conflict, --verbose, and --profile time. Everything else is configured through mix.exs (:docs, :debug_info).

8.3 What Is Identical at Runtime

Nothing below the language layer changed:

  • Preemptive scheduling — reductions-based, per process
  • Per-process heaps & GC — no stop-the-world pauses
  • Distribution — same EPMD/Dist protocol; nodes cluster identically
  • OTP behaviours — GenServer/supervisor semantics byte-for-byte
  • Hot code loading — two-version module model intact

Mental model:

flowchart TD
    EX["Elixir"] --> CM["compiled modules"]
    CM --> BEAM["BEAM"]
    BEAM --> OTP["OTP runtime"]
    OTP --> R["processes · schedulers ·<br/>supervision · distribution"]

Code Loading: Two Versions, Same Rules

Modules load interactively (on demand from the code path — your dev shell) or embedded (everything up front at boot — what releases use; Ch 09’s RELEASE_MODE flips it). Either way the two-version model holds: each module has at most a current and an old incarnation. Redefine a module and the new code becomes current immediately, while any process still executing the old incarnation keeps running it until :code.purge/1 retires that copy:

iex> defmodule Hello, do: (def v, do: :first)
iex> Code.compiler_options(ignore_module_conflict: true)
iex> defmodule Hello, do: (def v, do: :second)
iex> Hello.v()
:second

Same machinery an Erlang hot upgrade lives inside — the redefine-and-purge dance your shell’s l(Module) performs (l/1 in erl comes from the c module: c:l(Hello); in IEx the equivalent is recompile()). Here it is reached through defmodule re-evaluation. Ch 09 §9.8 shows processes being walked across versions deliberately, code_change and all.

8.4 Where Kernel Meets :erlang (BIF Inlining)

Many Kernel functions are inlined by the compiler into their Erlang counterparts in the :erlang module — the BIFs you already know. Capture a guard and you can see it directly:

iex> &Kernel.is_atom/1
&:erlang.is_atom/1

iex> &Kernel.byte_size/1
&:erlang.byte_size/1

This is why guards are cheap, why they’re allowed in match contexts, and why Kernel’s docs mark functions “inlined by the compiler.” The same applies to operators: +, <, == compile to :erlang arithmetic and comparison.

One asymmetry to respect: special forms (defmodule, def, quote, case, =, <<>>, …) live in Kernel.SpecialForms — they’re always imported and cannot be excluded or overridden. They aren’t functions at all; they’re the language’s irreducible core, handled directly by the compiler.

8.5 Compile-Time Dependencies & Incremental Recompiles

Edit one module, watch Mix recompile ten — this is Mix’s dependency graph at work, and it has no Erlang-make analogue worth missing. While compiling each file, the compiler records what that file depends on to compile:

Dependency kindCreated byConsequence
compile-timeimport, require, macro calls, defstruct expansion, behaviourschanging the source forces recompiling dependents
runtimeplain remote calls (OtherMod.fun(...))no recompilation of callers

The struct case surprises everyone once: %User{} patterns compile the struct’s field layout into the using module (§5.4), so editing User’s defstruct correctly triggers recompilation of every module that pattern-matches it. The graph is derived by the compiler — not hand-maintained in a makefile.

Measured, because “correctly triggers” deserves evidence. Two files, U (defining a struct) and V:

# V with a direct struct pattern
defmodule V do
  def name_of(%U{name: n}), do: n
end

Add one field to U’s defstruct and Mix recompiles both files:

$ mix compile
Compiling 1 file (.ex)      ← lib/u.ex
Compiling 1 file (.ex)      ← lib/v.ex, because its pattern no longer matches

Change V to a remote call instead, then extend the struct again:

defmodule V do
  def name_of(u), do: U.name(u)     # no struct pattern in V
end
$ mix compile
Compiling 1 file (.ex)      ← only lib/u.ex

One line of difference, and the cascade disappears. That asymmetry is the whole design: a struct pattern embeds the layout (so it must be recompiled when the layout moves), while a call resolves at runtime and does not. In Erlang the equivalent question never arises because records carry no compile-time shape at all.

Inspect and manage it:

mix xref graph --label compile-connected      # files whose compilation cascades
mix xref graph --sink lib/my_app/user.ex      # who recompiles when user.ex changes
mix xref unreachable                          # remote calls to undefined modules

Practical rule: keep macros, imports, and structs out of low-stability modules; put them behind small facade modules so the cascade stops there. A shrinking compile-connected set is the health metric for large codebases’ build times.

8.6 Key Takeaway

Elixir changes the programming experience more than it changes the runtime model.

That is why migration cost stays low: your operational knowledge — observer, crash dumps, :sys.get_state, distribution debugging — applies unchanged. And when you later attach native runtimes (Part IV: XLA, MLX, llama.cpp), they slot in beside the BEAM through Ports/NIFs, exactly as they would from Erlang.

Explore More

  • Compilation model notes — the abstract format your code becomes after parsing
  • Code module — compile_string, quoted_to_algebra; program the compiler yourself for a day
  • mix xref — the full graph command reference behind §8.5’s recompilation management
  • BEAM module docs (:code, :compile) — the Erlang-side view of the same pipeline
  • Erlang Efficiency Guide: modules and functions — where the Erlang compiler makes the same compile-time vs runtime calls, from the other direction
  • Exercise idea: compile a tiny .ex by hand with elixirc, then inspect the .beam with beam_lib:chunks("Elixir.Hello.beam", [abstract_code]) from an Erlang shell
  • Exercise idea: reproduce §8.5’s struct cascade yourself — write U with a struct and V with a %U{} pattern, add a field to U, and watch how many files recompile. Then delete the pattern and repeat.

Checkpoint

  1. Where do macros sit relative to type checking?
  2. Which extension would you give a one-off ops script? A library module?
  3. How can an Erlang shell call your Elixir module?
  4. Why does editing a struct’s defstruct force recompilation of modules that merely pattern-match it?
  5. Is .exs interpreted? If not, what actually differs from .ex?
  6. Which directory does Mix generate rather than expect you to write, and what does consolidated/ hold?
Answers
  1. Macros expand after parsing; type checking operates on expanded forms (Ch 07 diagnostics reference expanded call sites).
  2. Script: .exs. Library module: .ex.
  3. Add its _build/<env>/lib/*/ebin to the path and call 'Elixir.MyModule':fun(Args). from the Erlang shell (or :"Elixir.MyModule".fun(args) from Elixir). Quoting matters: bare Hello in an Erlang shell is a variable.
  4. %Struct{} patterns embed the field layout at each using module’s compile time (a compile-time dependency), so dependents must recompile to see the new layout. §8.5 measures it: adding a field recompiles both files; replacing the pattern with a plain remote call recompiles one.
  5. No — it compiles to bytecode and runs it, just without writing the .beam. A .exs inside lib/ is silently ignored by mix compile, which is the confusing symptom when a ported module never shows up in ebin/.
  6. ebin/hello.app, generated from mix.exs — there is no .app.src and no src/ directory. consolidated/ holds protocol dispatch tables built by mix compile (Ch 05), which is what turns protocol calls from dynamic lookups into static dispatch.

Next: Chapter 9 — Mix, Releases & Running OTP Apps