Search⌘ K
AI Features

Tying AST and Macros Together

Explore how macros and abstract syntax trees (ASTs) work together in Elixir metaprogramming. Understand the representation of code as ASTs, write macros to transform and generate code, and learn essential rules to use macros responsibly and effectively for clearer programs.

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 few expressions. Let’s try out a ...