The Abstract Syntax Tree
Learn about the Abstract Syntax Tree (AST) in detail.
We'll cover the following...
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.
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 ...