EDDYMENS

Published a year ago

What Is An Abstract Syntax Tree?

Table of contents

Definition

An abstract syntax tree (AST) is a hierarchical tree-like structure that represents the syntax [→] of a computer language. This produced tree-like structure is used by compilers [→] and interpreters [→] to better convert code [→] into something the computer can further understand.

Use cases and Examples

Here is a mathematical example: 5+(10*2)

Now the AST of the above statement should look something like the figure below.

Figure 1

Note how we don’t care about the brackets, because what we’re saying here (reading from the root node ie: the top) is:

  • The first thing we’re doing is adding something together.
  • The left side of our addition is the number 5.
  • The right side of our addition is the result of multiplying something.
  • The left side of our multiplication is 10.
  • The right side of our multiplication is 2.

With this visual breakdown, a computer can execute meaningful microinstructions and by the time it's done would have achieved the overall instruction set.

Summary

Abstract syntax trees are used to represent the structure of a program’s source code [→] for the compiler [→] or interpreter [→] to use.

ASTs are also used in transpilers thus translating the syntax of one language to another. For example when transpiling TypeScript to Javascript.

Here is another article you might like 😊 What Is An Abstraction?