Course contentsShow
← Computer Science
Lesson 1975 of 2,87244. Lexical Analysis and ParsingFree lesson

What is an Abstract Syntax Tree (AST)?

Define ASTs as tree representations of code structure, explaining how they differ from parse trees and concrete syntax.

What is an Abstract Syntax Tree (AST)?

You'll learn how ASTs represent the essential structure of parsed code in a tree form, stripped of unnecessary syntax details.

The Core Idea

After a parser successfully analyzes source code according to its grammar rules, it needs to represent the program's structure in a way that's useful for the compiler or interpreter. An Abstract Syntax Tree (AST) is that representation—a tree data structure where each node represents a meaningful construct in the source code.

Think of it like architectural blueprints versus construction photos. A parse tree (also called a concrete syntax tree) is like the photos—it shows every detail of how the building was assembled, including scaffolding and temporary supports. An AST is like the blueprints—it shows only the essential structure needed to understand and work with the building.

How ASTs Differ from Parse Trees

Parse trees capture every grammar rule used during parsing, including punctuation, parentheses, and intermediate non-terminals. They're a direct trace of the parsing process.

ASTs, in contrast, are abstract—they omit syntactic details that don't affect meaning:

  • Parentheses (the tree structure already shows precedence)
  • Semicolons and other delimiters
  • Unnecessary intermediate grammar nodes

For example, the expression (x + 2) * 3 would have a parse tree with nodes for every parenthesis and operator precedence rule. The AST simply shows: a multiplication node with two children—an addition node (with x and 2 as children) and a 3 leaf node.

Why ASTs Matter

ASTs are the input for later compiler phases: semantic analysis, optimization, and code generation. They're easier to traverse and transform because they contain only the meaningful structure.

Key Takeaway: An AST is a tree representation of code that captures its essential syntactic structure while omitting concrete syntax details like punctuation and redundant grammar rules—making it ideal for compiler processing.