Abstract Syntax Tree
Table of Contents
A tree data structure representing the syntactic structure of source code after parsing. Each node is a language construct — an expression, statement, operator, or literal. The "abstract" means semantically irrelevant syntax (parentheses, commas, semicolons) is stripped — only the structure and meaning remains.
ASTs are the primary intermediate representation between raw source text and executable code. Compilers, linters, formatters, transpilers, and macro systems all operate on the AST.
Related: Metaprogramming Algorithms
Parse Tree vs AST
Source: 1 + 2 * 3
Parse tree (concrete): AST (abstract):
expr +
/ | \ / \
expr + expr 1 *
| / | \ / \
1 expr * expr 2 3
| |
2 3
The parse tree mirrors the grammar rules exactly. The AST discards the grammar machinery and keeps only what matters semantically.
Structure
# A minimal AST node in Python class BinOp: def __init__(self, left, op, right): self.left = left # AST node self.op = op # operator string self.right = right # AST node class Num: def __init__(self, value): self.value = value # AST for: 1 + 2 * 3 tree = BinOp( left=Num(1), op="+", right=BinOp( left=Num(2), op="*", right=Num(3) ) )
Python's Built-in AST Module
import ast source = "x = 1 + 2 * 3" tree = ast.parse(source) # Pretty-print the AST print(ast.dump(tree, indent=2)) # Walk all nodes for node in ast.walk(tree): if isinstance(node, ast.BinOp): print(f"BinOp: {type(node.op).__name__}") # Compile and execute code = compile(tree, "<string>", "exec") exec(code)
# Practical: find all function calls in source code import ast def find_calls(source): tree = ast.parse(source) return [ node.func.id for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) ] find_calls("print(len(x))") # ['print', 'len']
Applications
Compilers and Interpreters
Source text
→ Lexer (tokenise)
→ Parser (build AST)
→ Semantic analysis (type checking, scope resolution)
→ Optimisation passes (transform the AST)
→ Code generation (emit bytecode or machine code)
Linters and Static Analysis
Tools like Pylint, ESLint, and Clippy traverse the AST and flag patterns without executing the code:
# Detect use of eval() — a linter might do this for node in ast.walk(tree): if isinstance(node, ast.Call): if isinstance(node.func, ast.Name) and node.func.id == "eval": print(f"eval() found at line {node.lineno}")
Macros
Lisp and Elixir macros transform the AST at compile time — code that generates code as a first-class language feature. See Metaprogramming.
# Elixir macro — receives and returns AST
defmacro unless(condition, do: body) do
quote do
if !unquote(condition), do: unquote(body)
end
end
Transpilers
Babel converts modern JavaScript to older versions by parsing to an AST, transforming nodes (rewriting arrow functions, destructuring, etc.), and generating new source from the modified tree.
Tips
- Python's
astmodule is one of the most accessible ways to explore ASTs practically — parse any snippet andast.dumpit to see exactly what the language constructs map to - Understanding ASTs explains why macros in Lisp and Elixir are more powerful than text-based macros (C preprocessor) — they operate on structured code, not raw strings
- Static analysis tools (linters) are more reliable than regex for code patterns because they understand structure — a regex for "find all function calls named eval" fails on aliased or multi-line calls; an AST walk does not