Guide
Abstract Syntax Trees: How They Work and How to Use One
Source code as a tree of the constructs it is made of, with the punctuation and layout taken out. Here is what an AST holds, what it leaves behind, how to print one for your own code, and how review tools put it to work.
By Code Graph Review · Updated
An abstract syntax tree (AST) is a tree representation of the structure of source code. Each node is a construct of the language (a module, a function definition, a call, a binary operation, a name, a literal) and its children are the parts that construct is made of. It is called abstract because it keeps what the code means structurally and drops what only the text needed: parentheses, semicolons, commas, keywords that the node type already implies, and, in most ASTs, whitespace and comments.
Almost every tool that reads code as code rather than as text starts by building one. Compilers check and translate it, linters walk it looking for patterns, formatters reprint it, refactoring tools rewrite it, and richer code graphs such as the control flow graph and the code property graph are built on top of it.
A worked example: one Python function
Take this function:
def total(prices, tax):
return sum(prices) * (1 + tax)
Python's standard library parses it with ast.parse, and ast.dump(tree, indent=2) prints the tree. On Python 3.12 the output is:
Module(
body=[
FunctionDef(
name='total',
args=arguments(
posonlyargs=[],
args=[
arg(arg='prices'),
arg(arg='tax')],
kwonlyargs=[],
kw_defaults=[],
defaults=[]),
body=[
Return(
value=BinOp(
left=Call(
func=Name(id='sum', ctx=Load()),
args=[
Name(id='prices', ctx=Load())],
keywords=[]),
op=Mult(),
right=BinOp(
left=Constant(value=1),
op=Add(),
right=Name(id='tax', ctx=Load()))))],
decorator_list=[],
type_params=[])],
type_ignores=[])
Field names vary a little between Python versions (type_params arrived in 3.12, for instance), but the shape is the point. A few things to notice:
- The parentheses are gone.
(1 + tax)has no node of its own. The grouping survives as structure: the addition is aBinOpnested as the right-hand child of the multiplication, so the tree already says which operation happens first. - Keywords became node types. There is no
deforreturntoken in the tree; there is aFunctionDefnode and aReturnnode. - Names are just names.
Name(id='sum')records that the code mentions something calledsum. The tree does not know whether that is the built-in or a function defined elsewhere; working that out is a later step. - Positions are kept.
ast.dumphides them by default, but every expression and statement node carrieslinenoandcol_offset, which is how tools point back to the line they are complaining about.
AST versus parse tree (concrete syntax tree)
A parser first recognises code against a grammar. A tree that records every grammar rule and every token it matched, including the brackets and separators, is a parse tree or concrete syntax tree (CST). An AST is the slimmer tree you get by keeping only the nodes that carry meaning.
- Use an AST when you want to reason about what the code does: analysis, compilation, linting, finding patterns.
- Use a CST when you need to give the text back exactly as it was apart from your change: refactoring and codemod tools that must keep comments, blank lines and formatting. Python's LibCST and the tree-sitter parsing library both produce concrete trees for this reason.
The line between the two is not fixed. Clang's own introduction to its AST notes that it closely resembles the written code, keeping parenthesis expressions in unreduced form, which it says makes the AST a good fit for refactoring tools. Clang's tree is also built after semantic analysis, so its nodes carry types and resolved references that a purely syntactic AST such as Python's does not.
How to print the AST of your own code
Most languages ship a parser you can call, and most of them can print the tree. Output formats and option names change between releases, so check the documentation for the version you run.
Python. The ast module is in the standard library. From Python 3.9, ast.dump accepts indent, and python -m ast file.py prints a file's tree from the command line. ast.unparse turns a tree back into source, normalising the formatting as it goes.
python3 -c "import ast; print(ast.dump(ast.parse('total = (a+b)*c'), indent=2))"
python3 -m ast app.py
JavaScript and TypeScript. AST Explorer shows the tree for a snippet in the browser and lets you switch between parsers. Most JavaScript tools share the node shapes defined by the ESTree specification; parsers such as Acorn, Espree (ESLint's default) and @babel/parser produce ESTree trees or extensions of them. TypeScript's compiler API has its own node types.
C and C++. Clang dumps its AST with a frontend flag:
clang -Xclang -ast-dump -fsyntax-only test.c
Go. The standard library's go/ast and go/parser packages parse Go source, and ast.Print writes the resulting tree.
Many languages with one library. Tree-sitter is a parser generator and incremental parsing library with grammars for a long list of languages. Its documentation describes the result as a concrete syntax tree that can be updated efficiently as the file is edited, and it is designed to give useful results even when the code has syntax errors, which is why editors and code-graph tools use it to parse code that is half written.
Walking an AST: find calls, not text
The reason to build a tree is that you can ask it questions grep cannot answer. This script lists every call to Python's built-in eval in a file:
import ast
import sys
path = sys.argv[1]
tree = ast.parse(open(path).read(), filename=path)
for node in ast.walk(tree):
if (isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == "eval"):
print(f"{path}:{node.lineno}: call to eval()")
Run it on this file:
x = "eval(1)" # eval in a string
# eval() in a comment
y = eval(input())
z = obj.eval()
A text search for eval matches all four lines. The script reports only line 3: the string and the comment are not calls, and obj.eval() is a method call whose function is an Attribute node, not a Name. The same idea, a visitor that matches node types and their fields, is how most rule engines work; it just comes with a nicer way to write the pattern.
What ASTs are used for
- Compilers and interpreters. After parsing, the AST is what name resolution and type checking run over, and what is lowered into an intermediate representation for optimisation and code generation.
- Linters. An ESLint rule is a set of functions keyed by node type (or by selector) that ESLint calls as it traverses the tree. Python linters such as Pylint and Flake8 plugins work from the same kind of tree.
- Formatters. Prettier and Black parse code into a tree and print it again in their own style, which is why they can reformat code without changing what it does.
- Codemods and large refactors. Tools such as jscodeshift and LibCST find nodes and rewrite them across a codebase: rename an API, change a call's arguments, remove a deprecated option. Because the edit is made to the tree, it cannot accidentally change a string or a comment that happens to contain the same text.
- Structural search. Semgrep and ast-grep let you write a pattern that looks like code, with metavariables in place of the parts that can vary, and match it against syntax trees rather than lines.
- Code graphs and AI context. Call graphs, symbol indexes and the graphs that feed LLM code assistants are often extracted from ASTs: every function definition, call site and import becomes a node or an edge.
Using ASTs in code review
Line-based diffs and text search are what most review still runs on, and they are where an AST helps most:
- Structural diffs. Difftastic parses both versions of a file with tree-sitter and compares the syntax, so a formatter splitting a call over several lines, or a new wrapper around an unchanged expression, shows up as what it is. The GumTree algorithm, from the 2014 ASE paper Fine-grained and accurate source code differencing, computes edit scripts between two ASTs as moves, updates, insertions and deletions of nodes.
- Rules that run on every change. Project-specific checks written as AST patterns (never call this API without a timeout, never build a query from string concatenation) run in CI and comment on the diff, so a reviewer starts from a flagged construct rather than searching for it.
- Mechanical changes reviewed as a recipe. When a refactor touches hundreds of files, reviewing the codemod that made it, and spot-checking its output, is more reliable than reading every hunk.
- Telling form from substance. If the AST of a file is unchanged, the change was formatting only. That is a quick way to separate a reformat from a behaviour change in a noisy diff.
Limits to plan for
- Syntax only. A syntactic AST does not know what a name refers to, what type an expression has or which method a call will dispatch to. Answering that needs symbol tables and type information from a compiler or language server, or a pre-built index.
- No order of execution, no data flow. The tree says how code is nested, not which statement can run after which or where a value goes. That is the job of the control flow graph and of data dependence edges, which a code property graph combines with the AST.
- One tree per language, and per parser. Node names and shapes differ between languages and between parsers for the same language, so rules and scripts rarely carry over without changes.
- What the parser sees is not always what you wrote. C and C++ ASTs are built after the preprocessor has expanded macros and includes; code generated at build time is absent until it has been generated.
- Comments and layout are usually lost. Rewrite a file from a plain AST and its formatting and comments may not survive; use a concrete syntax tree tool when the output has to be committed.
Frequently asked questions
- What is an abstract syntax tree in simple terms?
- A tree that shows what a piece of code is made of: a function contains statements, a statement contains expressions, an expression contains names and values. Punctuation and layout are left out because the shape of the tree already carries them.
- What is the difference between an AST and a parse tree?
- A parse tree, or concrete syntax tree, records every grammar rule and token the parser matched, including brackets and separators, so the original text can be rebuilt exactly. An abstract syntax tree keeps only the nodes that carry meaning, which makes it smaller and easier to analyse but usually loses formatting and comments.
- How do I see the AST of my code?
- In Python, run python3 -m ast file.py or print ast.dump(ast.parse(source), indent=2). For JavaScript, paste a snippet into AST Explorer. For C and C++, run clang -Xclang -ast-dump -fsyntax-only file.c. In Go, parse the file with go/parser and print it with ast.Print.
- Is tree-sitter an AST?
- Tree-sitter's documentation describes the tree it builds as a concrete syntax tree. In practice tools use it much as they would an AST, matching named nodes and ignoring punctuation, while still having every token available when they need to edit the text.
- How is an AST different from a control flow graph?
- An AST shows how code is nested; a control flow graph shows the order in which it can run, with an edge for each possible jump between blocks of statements. Control flow graphs are usually built from the AST or from an intermediate representation lowered from it.
Sources
Read next on Code Graph Review
- Code Graphs as Context Windows for LLM Code Assistants
Graph-based retrieval beats flat file search on accuracy and token cost.
- Graph-Based Impact Analysis for Large-Scale API Changes
Dependency graphs map what API changes touch across millions of client applications.