...

/

The Abstract Syntax Tree

The Abstract Syntax Tree

Learn about the Abstract Syntax Tree (AST) in detail.

Understanding the AST is essential as you get into advanced metaprogramming. Once we uncover the nuances, we’ll find that Elixir code is much closer to the AST than we might have imagined.

Understanding ASTs will change the way we think about solving problems and drive our macro design decisions in the future. After reviewing the finer details of the AST, we’ll be ready to begin the metaprogramming exercises.

%0 node_1 + node_2 * node_1->node_2 node_3 * node_1->node_3 node_1626433959104 a node_2->node_1626433959104 node_1626433905717 b node_2->node_1626433905717 node_1626433894386 * node_3->node_1626433894386 node_1626433906280 c node_3->node_1626433906280 node_1626433923111 d node_1626433894386->node_1626433923111 node_1626433901090 a node_1626433894386->node_1626433901090
The Structure of the Abstract Syntax Tree

The structure of the AST

Every expression we write in Elixir breaks down to a three-element tuple in the AST. We often rely on this uniform breakdown when pattern matching arguments in macros.

Since we know that an expression like 5 + 2 turns into the tuple {:+, [...], [5, 2]}, we pattern matched directly against the AST to determine the meaning of each calculation.

Let’s quote a couple more complex expressions to see how entire Elixir programs are structured in the AST.

Try the command quote do: (5 * 2) - 1 + 7 in ...