jonnifyelixir
F3 · The Elixir Language / Under the hood

F3 · before the lessons · reading 3

Under the hood

Elixir is a compiled language. Source files become bytecode for the BEAM, the same virtual machine Erlang runs on. Knowing the few steps in between makes the rest of the chapter — especially macros — far less mysterious.

From source to bytecode

Compilation is a short pipeline. Text is split into tokens, the tokens are parsed into a tree, macros rewrite that tree, and the result is compiled to BEAM bytecode that the virtual machine runs. Step through it with the expression 1 + 2.

The compilation pipeline · select a stage

source tokens AST expanded bytecode BEAM VM

      

Only one of these steps is unusual: macros run during compilation and can rewrite the tree before it becomes bytecode. That is the feature the next idea explains.

Code is data

The tree in the middle of that pipeline — the AST, or quoted form — is an ordinary Elixir data structure. Almost every expression quotes to a three-element tuple: {form, metadata, arguments}. Because code is data, a macro is a function that takes that tuple and returns a new one. Select an expression to see its quoted form.

quote · select an expression

FORM METADATA ARGUMENTS :+ [] [1, 2]

      

Homoiconicity

Code is represented as ordinary data — the same tuples you build by hand.

Macros

quote turns code into its AST; a macro transforms that AST and returns new code.

A compiled .ex file becomes a .beam module on disk; an .exs script is evaluated without writing one. Everything is an expression, and everything ultimately runs as lightweight processes on the BEAM. Next: F3.01 — Values, types & IEx, where the lessons begin.