This video is available to students only

What is an AST?

Understand the basics of an AST and how it relates to real-world code

What is an Abstract Syntax Tree?#

This course is designed to provide a concrete understanding of the theory and practical uses of "abstract syntax trees" (ASTs).

Example abstract syntax tree

Before we explore the practical uses, we need to gain a conceptual understanding of ASTs. At a high level, an abstract syntax tree is an intermediate representation of source code as a tree structure. What does that mean? 🤔

Tree (data) structure#

A tree data structure starts with a root. The root can then point to other values, and those values to others, and so on. This begins to create an implicit hierarchy, and also happens to be a great way to represent source code in a way computers can easily interpret.

tree data structure example

Each one of these values (circles in the tree) are referred to as nodes. The relationships between nodes are often described with terms like child node, parent node, sibling node, and so on.

By convention, the root node is shown at the top, however if it's flipped, with the root node at the bottom and heading upwards, it starts to look like an actual tree with all its branches forking out.

tree data structure with root at the bottom

Tree data structures are common in computer science and have many practical applications, such as searching and sorting data. There are also many different types of trees with different constraints. For example, a binary tree is a tree with at most two child nodes.

For the purpose of working with ASTs, the important aspect is understanding how a tree can be used to represent data and the relationships between nodes.

ASTs and compilers#

Some of the most prominent uses of ASTs are in compilers. A compiler accepts source code as input, and then outputs another language. This is often from a high-level programming language to something low-level, like machine code.

compiler input and output

In the frontend web ecosystem, this includes tools like webpack or parcel. These tools compile many modules into a bundle, and perform other optimizations such as transpiling from modern JavaScript to an older version, or minifying the code by renaming variables and functions to shorter names. Although they are a little different to conventional compilers, they follow many of the same fundamental steps.


This page is a preview of Practical Abstract Syntax Trees

Start a new discussion. All notification go to the author.