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).
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.
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 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.