Tying AST and Macros Together
Learn how the Abstract Syntax Tree (AST) and macros interact to extend Elixir language and build custom features with the help of an example.
We’ve seen how Elixir itself is built with macros and how to use quote
to return the AST representation of any expression in the previous section. Now, let’s fit the pieces together. The most important takeaway is that macros receive ASTs as arguments and provide ASTs as return values. By writing macros, we build ASTs using Elixir’s high-level syntax.
For example, when calculating a result, we will write a macro that can print the spoken form of an Elixir mathematical expression, such as 5 + 2
. Before moving to the example, let’s see the ASTs of some simple expressions.
ASTs of simple expressions
In most languages, we would have to parse a string expression into something digestible by our program. With Elixir, we can access the representation of expressions directly with macros.
Our first step is to examine the AST structure of some example expressions that our macro will accept. Let’s head back to iex
and quote a ...