Conceptcore
Abstract syntax tree
Also called AST, syntax tree, abstract syntax.
An abstract syntax tree holds the structure of a program as a tree of operators, operands and statements. It drops the tokens that only guide the parser, such as parentheses.
- Applies to
- core-languages
Idea
A program is a string of characters. A compiler or an interpreter cannot work on the string directly. It needs to know which operator applies to which operands, which statements are inside a loop, and which name a declaration binds. An abstract syntax tree (AST) holds this structure. Each node is one construct of the language: a number, a name, a binary operation, a call, an assignment. The children of a node are its parts.
The tree is abstract because it keeps the structure and drops the notation. The source 1 + 2 * (3 - x) has parentheses. They tell the parser to group 3 - x, but after the parser has built the tree, the grouping is in the shape of the tree. A parse tree keeps every rule of the grammar as a node. An AST leaves out the productions that later phases do not need.1 Python's ast module shows the tree that the CPython compiler works on.
import ast
tree = ast.parse("1 + 2 * (3 - x)", mode="eval")
print(ast.dump(tree, indent=2))
Expression(
body=BinOp(
left=Constant(value=1),
op=Add(),
right=BinOp(
left=Constant(value=2),
op=Mult(),
right=BinOp(
left=Constant(value=3),
op=Sub(),
right=Name(id='x', ctx=Load())))))
The tree has no node for the parentheses. The multiplication is below the addition because * binds tighter than +. The subtraction is below the multiplication because the parentheses said so. The precedence rules and the parentheses have done their work, and the shape of the tree is the result.
McCarthy gave the idea its name. His abstract syntax is "analytic rather than synthetic". It asks of a term whether it is a sum and what its addend and augend are. It does not care whether the source wrote the sum as a + b, as +ab or as (PLUS A B).23
How it works
From characters to tokens to a tree
A front end works in two steps. The lexer turns characters into tokens: numbers, names, operators and punctuation. The parser reads the tokens and builds the tree. Each rule of the parser returns the node for the text that it matched. A rule for a parenthesized expression reads (, calls the rule for an expression, reads ) and returns the inner node unchanged. That is where the parentheses disappear. The page Recursive descent parsing builds such a parser.
The token stream of the same source still has everything that the programmer typed, including the parentheses.
import io
import tokenize
source = "1 + 2 * (3 - x)"
for tok in tokenize.generate_tokens(io.StringIO(source).readline):
if tok.type in (tokenize.NEWLINE, tokenize.ENDMARKER):
continue
print(tokenize.tok_name[tok.type], repr(tok.string))
NUMBER '1'
OP '+'
NUMBER '2'
OP '*'
OP '('
NUMBER '3'
OP '-'
NAME 'x'
OP ')'
Nine tokens become seven nodes: four leaves and three operations. The tree is smaller than the text, and each node has a known kind and known children.
The node kinds form a sum type
The kinds of node are fixed by the language. An expression is a constant, or a name, or a binary operation with two child expressions, and so on. This is a sum type that is recursive. Python's documentation gives the whole set as an abstract grammar in ASDL. For example, it has the line BinOp(expr left, operator op, expr right).7 In a language with sum types, each kind is one variant. In an object-oriented language, each kind is a class that implements a common interface, which is the Composite pattern. The example files show both forms.
A user-defined AST in Python fits in a few dataclasses. A match statement selects the case for each kind of node (see The match statement).
from dataclasses import dataclass
@dataclass
class Num:
value: int
@dataclass
class Var:
name: str
@dataclass
class Bin:
op: str
left: "Num | Var | Bin"
right: "Num | Var | Bin"
def show(node, depth=0):
pad = " " * depth
match node:
case Num(value):
print(f"{pad}Num {value}")
case Var(name):
print(f"{pad}Var {name}")
case Bin(op, left, right):
print(f"{pad}Bin {op}")
show(left, depth + 1)
show(right, depth + 1)
show(Bin("+", Num(1), Bin("*", Num(2), Bin("-", Num(3), Var("x")))))
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
Positions
A tree that has lost the source text must still report errors at the right place. So each node keeps its position. In Python, expression and statement nodes have the attributes lineno, col_offset, end_lineno and end_col_offset.7 A type checker or a linter uses them to point at the source.
Walking the tree
Every later phase is a walk over the tree: a type checker, an optimizer, a code generator or an interpreter. A walk is a recursive function with one case for each kind of node. When the set of operations grows and the set of node kinds stays fixed, the walk is often written as a visitor. Python's ast.NodeVisitor calls a method visit_<ClassName> for each node that it visits, and generic_visit visits the children.8 ast.walk yields all nodes of a tree, but "in no specified order".9
import ast
class Names(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_Name(self, node):
self.names.append((node.id, node.col_offset))
tree = ast.parse("total = price * count + tax")
finder = Names()
finder.visit(tree)
print(finder.names)
print(sum(1 for _ in ast.walk(tree)), "nodes")
[('total', 0), ('price', 8), ('count', 16), ('tax', 24)]
14 nodes
An interpreter is a walk that computes a value for each node. The page Tree-walking interpreter builds one. A compiler is a walk that emits instructions for each node; the page Bytecode shows it.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Standard library | |
| Rust | Idiom | |
| Kotlin | Idiom | |
| SQL | Does not apply | A query language has no access to the syntax tree of a query or of a program. |
| Bash | Does not apply | The shell parses its scripts but exposes no syntax tree to them. |
| PowerShell | Standard library | A script block has an Ast property that holds the syntax tree of PowerShell code; no example file because PowerShell is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup describes a document; the DOM is a tree of the document, not of a program. |
| CSS | Does not apply | Style rules have no way to build or walk a syntax tree. |
| Regular expressions | Does not apply | A pattern language matches text; it cannot build or hold a tree. Alternative: A parser written in a general language. |
Some standard libraries expose the language's own parser and its AST. In the other languages, a program that needs an AST defines one. The examples parse 1 + 2 * (3 - x), print the tree, walk it to count the nodes and collect the names, and evaluate it for x = 1.
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | the ast module: ast.parse, ast.dump, ast.NodeVisitor, ast.NodeTransformer |
| Go | stdlib | go/parser builds go/ast nodes; ast.Inspect walks them |
| C# | stdlib | expression trees in System.Linq.Expressions; the compiler builds one from a lambda |
| Java | idiom | a sealed interface and records; the JDK parser in com.sun.source.tree is a module of the JDK |
| Kotlin | idiom | a sealed interface and data classes, matched with when |
| TypeScript | idiom | a discriminated union; the compiler API exposes the TypeScript AST |
| JavaScript | idiom | plain objects with a kind field |
| Rust | idiom | an enum with Box children; the syn crate parses Rust itself |
| C++ | idiom | std::variant with std::unique_ptr children |
| C | idiom | a tagged struct with a union and pointers to children |
| SQL | n/a | queries have no access to a syntax tree |
| Bash | n/a | the shell exposes no syntax tree |
| PowerShell | stdlib | the Ast property of a script block22 |
| Regex | n/a | a pattern language, not a host for trees |
| HTML/CSS | n/a | the DOM is a tree of the document, not of a program |
Python's ast.parse takes a mode. "exec" parses a module, "eval" a single expression, and "single" one interactive statement.5 ast.dump prints a tree, and its indent argument puts each node on its own line.6 The documentation warns that the abstract syntax "might change with each Python release".4
Go's go/parser produces the AST of a file or of a single expression. parser.ParseExpr is a convenience function for one expression, and with a syntax error it returns a partial tree with ast.Bad* nodes.11 Unlike Python's tree, Go's tree keeps parentheses: ast.ParenExpr "represents a parenthesized expression".12 ast.Inspect walks the tree in depth-first order and calls a function for each node.13
The TypeScript compiler API exposes the trees that tsc builds. ts.createSourceFile parses a file, ts.forEachChild visits the children of a node, and node.kind holds a value of ts.SyntaxKind. The wiki warns that a later major version of TypeScript will have a different API.14 The examples do not use the API, because typescript is a package and not part of a standard library.
Java's compiler exposes its tree in the package com.sun.source.tree of the module jdk.compiler. The package "provides interfaces to represent source code as abstract syntax trees". It has BinaryTree for a binary expression, ParenthesizedTree for a parenthesized one, and TreeVisitor, "a visitor of trees, in the style of the visitor design pattern".15 Like Go, it keeps the parentheses.
Rust's standard library has no parser for Rust. The syn crate parses a stream of Rust tokens into a syntax tree and is "geared toward use in Rust procedural macros". syn::Expr is its expression type, and its visit module walks the tree.16
C# builds expression trees in the compiler. When a lambda is assigned to an Expression<TDelegate>, the compiler emits code that builds the tree instead of a delegate.17 The tree can be walked with an ExpressionVisitor18 and turned into code with Compile.19 Only expression lambdas can be converted. Statement lambdas and await cannot.17
import ast
import operator
tree = ast.parse("1 + 2 * (3 - x)", mode="eval")
def show(node, depth=0):
label = type(node).__name__
if isinstance(node, ast.Constant):
label += f" {node.value}"
elif isinstance(node, ast.Name):
label += f" {node.id}"
elif isinstance(node, ast.BinOp):
label += f" {type(node.op).__name__}"
print(" " * depth + label)
for child in (node.left, node.right) if isinstance(node, ast.BinOp) else ():
show(child, depth + 1)
class Names(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_Name(self, node):
self.names.append(node.id)
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul}
def evaluate(node, env):
match node:
case ast.Constant(value=value):
return value
case ast.Name(id=name):
return env[name]
case ast.BinOp(left=left, op=op, right=right):
return OPS[type(op)](evaluate(left, env), evaluate(right, env))
raise ValueError(f"unsupported node {type(node).__name__}")
show(tree.body)
print("nodes:", sum(isinstance(n, ast.expr) for n in ast.walk(tree)))
finder = Names()
finder.visit(tree)
print("names:", finder.names)
print("value at x = 1:", evaluate(tree.body, {"x": 1}))
print("compiled:", eval(compile(tree, "<expr>", "eval"), {"x": 1}))
BinOp Add
Constant 1
BinOp Mult
Constant 2
BinOp Sub
Constant 3
Name x
nodes: 7
names: ['x']
value at x = 1: 5
compiled: 5
- Verdict: stdlib.
ast.parsereturns the tree that the CPython compiler uses, andast.NodeVisitorwalks it. - The tree has no node for the parentheses. The operator of a
BinOpis itself a node, such asAdd(), so the example counts only expression nodes. compileaccepts the tree in place of source text. A program can build or change a tree and then run it.- The abstract grammar can change between Python versions, so code that matches on node fields may need updates.
#include <cctype>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <variant>
#include <vector>
struct Expr;
using Ptr = std::unique_ptr<Expr>;
struct Num { int value; };
struct Var { std::string name; };
struct Bin { char op; Ptr left, right; };
struct Expr {
std::variant<Num, Var, Bin> node;
};
template <class... F> struct overloaded : F... { using F::operator()...; };
class Parser {
public:
explicit Parser(std::string src) : src_(std::move(src)) {}
Ptr expr() {
Ptr left = term();
while (peek() == '+' || peek() == '-') {
char op = src_[pos_++];
left = std::make_unique<Expr>(Expr{Bin{op, std::move(left), term()}});
}
return left;
}
private:
char peek() {
while (pos_ < src_.size() && src_[pos_] == ' ') ++pos_;
return pos_ < src_.size() ? src_[pos_] : '\0';
}
Ptr term() {
Ptr left = factor();
while (peek() == '*') {
++pos_;
left = std::make_unique<Expr>(Expr{Bin{'*', std::move(left), factor()}});
}
return left;
}
Ptr factor() {
char c = peek();
if (c == '(') {
++pos_;
Ptr inner = expr();
if (peek() != ')') throw std::runtime_error("expected ) at " + std::to_string(pos_));
++pos_;
return inner;
}
std::size_t start = pos_;
if (std::isdigit(static_cast<unsigned char>(c))) {
while (pos_ < src_.size() && std::isdigit(static_cast<unsigned char>(src_[pos_]))) ++pos_;
return std::make_unique<Expr>(Expr{Num{std::stoi(src_.substr(start, pos_ - start))}});
}
if (std::isalpha(static_cast<unsigned char>(c))) {
while (pos_ < src_.size() && std::isalpha(static_cast<unsigned char>(src_[pos_]))) ++pos_;
return std::make_unique<Expr>(Expr{Var{src_.substr(start, pos_ - start)}});
}
throw std::runtime_error(std::string("unexpected '") + c + "' at " + std::to_string(pos_));
}
std::string src_;
std::size_t pos_ = 0;
};
void show(const Expr& e, int depth = 0) {
std::string pad(2 * depth, ' ');
std::visit(overloaded{
[&](const Num& n) { std::cout << pad << "Num " << n.value << '\n'; },
[&](const Var& v) { std::cout << pad << "Var " << v.name << '\n'; },
[&](const Bin& b) {
std::cout << pad << "Bin " << b.op << '\n';
show(*b.left, depth + 1);
show(*b.right, depth + 1);
},
}, e.node);
}
int count(const Expr& e) {
if (auto* b = std::get_if<Bin>(&e.node)) return 1 + count(*b->left) + count(*b->right);
return 1;
}
void names(const Expr& e, std::vector<std::string>& out) {
if (auto* v = std::get_if<Var>(&e.node)) out.push_back(v->name);
if (auto* b = std::get_if<Bin>(&e.node)) {
names(*b->left, out);
names(*b->right, out);
}
}
int eval(const Expr& e, const std::map<std::string, int>& env) {
return std::visit(overloaded{
[](const Num& n) { return n.value; },
[&](const Var& v) { return env.at(v.name); },
[&](const Bin& b) {
int l = eval(*b.left, env), r = eval(*b.right, env);
return b.op == '+' ? l + r : b.op == '-' ? l - r : l * r;
},
}, e.node);
}
int main() {
Ptr tree = Parser("1 + 2 * (3 - x)").expr();
show(*tree);
std::cout << "nodes: " << count(*tree) << '\n';
std::vector<std::string> found;
names(*tree, found);
std::cout << "names:";
for (const auto& n : found) std::cout << ' ' << n;
std::cout << '\n';
std::cout << "value at x = 1: " << eval(*tree, {{"x", 1}}) << '\n';
}
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: x
value at x = 1: 5
- Verdict: idiom.
std::variantholds one of the node kinds, andstd::visitwith a set of lambdas selects the case. The compiler rejects a visit that misses a kind. Binholds its children instd::unique_ptr. The typeExpris incomplete insideBin, so it cannot hold anExprby value. The tree owns its nodes, and destroying the root frees the whole tree.- A class hierarchy with a virtual
acceptmethod is the other common form in C++.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Main {
sealed interface Expr permits Num, Var, Bin {}
record Num(int value) implements Expr {}
record Var(String name) implements Expr {}
record Bin(char op, Expr left, Expr right) implements Expr {}
static final class Parser {
private final String src;
private int pos;
Parser(String src) { this.src = src; }
private char peek() {
while (pos < src.length() && src.charAt(pos) == ' ') pos++;
return pos < src.length() ? src.charAt(pos) : '\0';
}
Expr expr() {
Expr left = term();
while (peek() == '+' || peek() == '-') {
char op = src.charAt(pos++);
left = new Bin(op, left, term());
}
return left;
}
Expr term() {
Expr left = factor();
while (peek() == '*') {
pos++;
left = new Bin('*', left, factor());
}
return left;
}
Expr factor() {
char c = peek();
if (c == '(') {
pos++;
Expr inner = expr();
if (peek() != ')') throw new IllegalStateException("expected ) at " + pos);
pos++;
return inner;
}
int start = pos;
if (Character.isDigit(c)) {
while (pos < src.length() && Character.isDigit(src.charAt(pos))) pos++;
return new Num(Integer.parseInt(src.substring(start, pos)));
}
if (Character.isLetter(c)) {
while (pos < src.length() && Character.isLetter(src.charAt(pos))) pos++;
return new Var(src.substring(start, pos));
}
throw new IllegalStateException("unexpected '" + c + "' at " + pos);
}
}
static void show(Expr e, int depth) {
String pad = " ".repeat(depth);
switch (e) {
case Num n -> System.out.println(pad + "Num " + n.value());
case Var v -> System.out.println(pad + "Var " + v.name());
case Bin b -> {
System.out.println(pad + "Bin " + b.op());
show(b.left(), depth + 1);
show(b.right(), depth + 1);
}
}
}
static int count(Expr e) {
return switch (e) {
case Num n -> 1;
case Var v -> 1;
case Bin b -> 1 + count(b.left()) + count(b.right());
};
}
static void names(Expr e, List<String> out) {
switch (e) {
case Num n -> { }
case Var v -> out.add(v.name());
case Bin b -> {
names(b.left(), out);
names(b.right(), out);
}
}
}
static int eval(Expr e, Map<String, Integer> env) {
return switch (e) {
case Num n -> n.value();
case Var v -> env.get(v.name());
case Bin b -> switch (b.op()) {
case '+' -> eval(b.left(), env) + eval(b.right(), env);
case '-' -> eval(b.left(), env) - eval(b.right(), env);
default -> eval(b.left(), env) * eval(b.right(), env);
};
};
}
public static void main(String[] args) {
Expr tree = new Parser("1 + 2 * (3 - x)").expr();
show(tree, 0);
System.out.println("nodes: " + count(tree));
List<String> found = new ArrayList<>();
names(tree, found);
System.out.println("names: " + found);
System.out.println("value at x = 1: " + eval(tree, Map.of("x", 1)));
}
}
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: [x]
value at x = 1: 5
- Verdict: idiom. A sealed interface lists the kinds of node, and records give each kind its fields. A
switchover the sealed interface needs nodefault, because the compiler knows every case. - The parser has one method per precedence level. Each method returns the node for the text that it read, and
factorreturns the inner node of a parenthesized expression, so the tree has no node for the parentheses.
The JDK also exposes its own parser. JavacTask.parse returns trees from com.sun.source.tree, and a TreeScanner walks them. Unlike the hand-written tree, javac keeps a PARENTHESIZED node.
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreeScanner;
import java.net.URI;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Main {
static class Source extends SimpleJavaFileObject {
final String code;
Source(String code) {
super(URI.create("string:///F.java"), Kind.SOURCE);
this.code = code;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
public static void main(String[] args) throws Exception {
String code = "class F { int f(int x) { return 1 + 2 * (3 - x); } }";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new Source(code)));
for (CompilationUnitTree unit : task.parse()) {
unit.accept(new TreeScanner<Void, Integer>() {
@Override
public Void visitBinary(BinaryTree node, Integer depth) {
System.out.println(" ".repeat(depth) + node.getKind());
scan(node.getLeftOperand(), depth + 1);
return scan(node.getRightOperand(), depth + 1);
}
@Override
public Void visitParenthesized(ParenthesizedTree node, Integer depth) {
System.out.println(" ".repeat(depth) + node.getKind());
return scan(node.getExpression(), depth + 1);
}
@Override
public Void visitLiteral(LiteralTree node, Integer depth) {
System.out.println(" ".repeat(depth) + node.getKind() + " " + node.getValue());
return null;
}
@Override
public Void visitIdentifier(IdentifierTree node, Integer depth) {
System.out.println(" ".repeat(depth) + node.getKind() + " " + node.getName());
return null;
}
}, 0);
}
}
}
PLUS
INT_LITERAL 1
MULTIPLY
INT_LITERAL 2
PARENTHESIZED
MINUS
INT_LITERAL 3
IDENTIFIER x
com.sun.source.treeis in the modulejdk.compiler. It ships with the JDK but not with every Java runtime, and it is not part of the Java SE API.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum kind { NUM, VAR, BIN };
struct expr {
enum kind kind;
union {
int value;
char name[16];
struct {
char op;
struct expr *left, *right;
} bin;
} u;
};
static const char *src;
static size_t pos;
static struct expr *node(enum kind kind) {
struct expr *e = calloc(1, sizeof *e);
if (!e) abort();
e->kind = kind;
return e;
}
static struct expr *bin(char op, struct expr *l, struct expr *r) {
struct expr *e = node(BIN);
e->u.bin.op = op;
e->u.bin.left = l;
e->u.bin.right = r;
return e;
}
static char peek(void) {
while (src[pos] == ' ') pos++;
return src[pos];
}
static struct expr *expr(void);
static struct expr *factor(void) {
char c = peek();
if (c == '(') {
pos++;
struct expr *inner = expr();
if (peek() != ')') {
fprintf(stderr, "expected ) at %zu\n", pos);
exit(1);
}
pos++;
return inner;
}
if (isdigit((unsigned char)c)) {
struct expr *e = node(NUM);
while (isdigit((unsigned char)src[pos])) e->u.value = e->u.value * 10 + (src[pos++] - '0');
return e;
}
if (isalpha((unsigned char)c)) {
struct expr *e = node(VAR);
size_t n = 0;
while (isalpha((unsigned char)src[pos]) && n < sizeof e->u.name - 1) e->u.name[n++] = src[pos++];
return e;
}
fprintf(stderr, "unexpected '%c' at %zu\n", c, pos);
exit(1);
}
static struct expr *term(void) {
struct expr *left = factor();
while (peek() == '*') {
pos++;
left = bin('*', left, factor());
}
return left;
}
static struct expr *expr(void) {
struct expr *left = term();
while (peek() == '+' || peek() == '-') {
char op = src[pos++];
left = bin(op, left, term());
}
return left;
}
static void show(const struct expr *e, int depth) {
printf("%*s", 2 * depth, "");
switch (e->kind) {
case NUM: printf("Num %d\n", e->u.value); break;
case VAR: printf("Var %s\n", e->u.name); break;
case BIN:
printf("Bin %c\n", e->u.bin.op);
show(e->u.bin.left, depth + 1);
show(e->u.bin.right, depth + 1);
break;
}
}
static int count(const struct expr *e) {
return e->kind == BIN ? 1 + count(e->u.bin.left) + count(e->u.bin.right) : 1;
}
static void names(const struct expr *e) {
if (e->kind == VAR) printf(" %s", e->u.name);
if (e->kind == BIN) {
names(e->u.bin.left);
names(e->u.bin.right);
}
}
static int eval(const struct expr *e, int x) {
switch (e->kind) {
case NUM: return e->u.value;
case VAR: return x;
case BIN: {
int l = eval(e->u.bin.left, x), r = eval(e->u.bin.right, x);
return e->u.bin.op == '+' ? l + r : e->u.bin.op == '-' ? l - r : l * r;
}
}
return 0;
}
static void free_tree(struct expr *e) {
if (e->kind == BIN) {
free_tree(e->u.bin.left);
free_tree(e->u.bin.right);
}
free(e);
}
int main(void) {
src = "1 + 2 * (3 - x)";
struct expr *tree = expr();
show(tree, 0);
printf("nodes: %d\n", count(tree));
printf("names:");
names(tree);
printf("\nvalue at x = 1: %d\n", eval(tree, 1));
free_tree(tree);
return 0;
}
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: x
value at x = 1: 5
- Verdict: idiom. A tagged struct is the C form of a sum type: an
enumfield says which member of theunionis valid. The compiler does not check that the code reads the right member. - Each node is a separate
callocallocation, and the program frees the tree with a post-order walk. Forgettingfree_treeleaks every node. - The evaluator has one variable,
x, to keep the example short. A real interpreter looks names up in an environment, as the tree-walking interpreter page shows.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
Expression<Func<int, int>> lambda = x => 1 + 2 * (3 - x);
Console.WriteLine(lambda.Body);
var printer = new Printer();
printer.Visit(lambda.Body);
Console.WriteLine($"nodes: {printer.Count}");
Console.WriteLine($"names: {string.Join(", ", printer.Names)}");
Func<int, int> f = lambda.Compile();
Console.WriteLine($"value at x = 1: {f(1)}");
class Printer : ExpressionVisitor
{
int depth;
public int Count;
public List<string> Names = new();
public override Expression? Visit(Expression? node)
{
if (node is null) return null;
Count++;
string label = node switch
{
ConstantExpression c => $"Constant {c.Value}",
ParameterExpression p => $"Parameter {p.Name}",
_ => node.NodeType.ToString(),
};
Console.WriteLine(new string(' ', 2 * depth) + label);
if (node is ParameterExpression pe) Names.Add(pe.Name!);
depth++;
var result = base.Visit(node);
depth--;
return result;
}
}
(1 + (2 * (3 - x)))
Add
Constant 1
Multiply
Constant 2
Subtract
Constant 3
Parameter x
nodes: 7
names: x
value at x = 1: 5
- Verdict: stdlib. The C# compiler builds an expression tree when a lambda is assigned to
Expression<TDelegate>. The program parses nothing at run time; the parser is the compiler. ExpressionVisitorcallsVisitfor each node. The override prints the node and then lets the base class visit the children.ToStringprints the body with full parentheses, andCompileturns the tree into a delegate that runs.- Expression trees cover expressions only. A statement lambda cannot be converted, so a full language needs its own AST, as in the Java example.
function parse(src) {
let pos = 0;
const peek = () => {
while (src[pos] === " ") pos++;
return src[pos];
};
function expr() {
let left = term();
while (peek() === "+" || peek() === "-") {
const op = src[pos++];
left = { kind: "bin", op, left, right: term() };
}
return left;
}
function term() {
let left = factor();
while (peek() === "*") {
pos++;
left = { kind: "bin", op: "*", left, right: factor() };
}
return left;
}
function factor() {
const c = peek();
if (c === "(") {
pos++;
const inner = expr();
if (peek() !== ")") throw new SyntaxError(`expected ) at ${pos}`);
pos++;
return inner;
}
const m = /^(\d+)|^([a-z]+)/.exec(src.slice(pos));
if (!m) throw new SyntaxError(`unexpected ${c} at ${pos}`);
pos += m[0].length;
return m[1] ? { kind: "num", value: Number(m[1]) } : { kind: "var", name: m[2] };
}
return expr();
}
function show(node, depth = 0) {
const pad = " ".repeat(depth);
switch (node.kind) {
case "num":
console.log(`${pad}Num ${node.value}`);
break;
case "var":
console.log(`${pad}Var ${node.name}`);
break;
case "bin":
console.log(`${pad}Bin ${node.op}`);
show(node.left, depth + 1);
show(node.right, depth + 1);
}
}
function* nodes(node) {
yield node;
if (node.kind === "bin") {
yield* nodes(node.left);
yield* nodes(node.right);
}
}
function evaluate(node, env) {
switch (node.kind) {
case "num":
return node.value;
case "var":
return env[node.name];
case "bin": {
const l = evaluate(node.left, env);
const r = evaluate(node.right, env);
return node.op === "+" ? l + r : node.op === "-" ? l - r : l * r;
}
}
}
const tree = parse("1 + 2 * (3 - x)");
show(tree);
const all = [...nodes(tree)];
console.log("nodes:", all.length);
console.log("names:", all.filter((n) => n.kind === "var").map((n) => n.name));
console.log("value at x = 1:", evaluate(tree, { x: 1 }));
console.log(JSON.stringify(tree));
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: [ 'x' ]
value at x = 1: 5
{"kind":"bin","op":"+","left":{"kind":"num","value":1},"right":{"kind":"bin","op":"*","left":{"kind":"num","value":2},"right":{"kind":"bin","op":"-","left":{"kind":"num","value":3},"right":{"kind":"var","name":"x"}}}}
- Verdict: idiom. Each node is a plain object with a
kindfield, and aswitchonkindselects the case. Nothing stops a node from having the wrong fields; the TypeScript example adds the check. - A generator function walks the tree.
yield*hands over to the walk of each child, so the caller gets a flat sequence of nodes in depth-first order. - A tree of plain objects is also valid JSON.
JSON.stringifyprints it with the nesting of the tree. - Node.js and the browsers expose no parser for JavaScript itself. A program that needs the AST of JavaScript source uses a parser package from npm.
type Expr =
| { kind: "num"; value: number }
| { kind: "var"; name: string }
| { kind: "bin"; op: "+" | "-" | "*"; left: Expr; right: Expr };
function parse(src: string): Expr {
let pos = 0;
const peek = (): string => {
while (src[pos] === " ") pos++;
return src[pos] ?? "";
};
function expr(): Expr {
let left = term();
while (peek() === "+" || peek() === "-") {
const op = src[pos++] as "+" | "-";
left = { kind: "bin", op, left, right: term() };
}
return left;
}
function term(): Expr {
let left = factor();
while (peek() === "*") {
pos++;
left = { kind: "bin", op: "*", left, right: factor() };
}
return left;
}
function factor(): Expr {
const c = peek();
if (c === "(") {
pos++;
const inner = expr();
if (peek() !== ")") throw new SyntaxError(`expected ) at ${pos}`);
pos++;
return inner;
}
const m = /^(\d+)|^([a-z]+)/.exec(src.slice(pos));
if (!m) throw new SyntaxError(`unexpected ${c} at ${pos}`);
pos += m[0].length;
return m[1] ? { kind: "num", value: Number(m[1]) } : { kind: "var", name: m[2] };
}
return expr();
}
function show(node: Expr, depth = 0): void {
const pad = " ".repeat(depth);
switch (node.kind) {
case "num":
console.log(`${pad}Num ${node.value}`);
break;
case "var":
console.log(`${pad}Var ${node.name}`);
break;
case "bin":
console.log(`${pad}Bin ${node.op}`);
show(node.left, depth + 1);
show(node.right, depth + 1);
}
}
function count(node: Expr): number {
return node.kind === "bin" ? 1 + count(node.left) + count(node.right) : 1;
}
function names(node: Expr): string[] {
switch (node.kind) {
case "num":
return [];
case "var":
return [node.name];
case "bin":
return [...names(node.left), ...names(node.right)];
}
}
function evaluate(node: Expr, env: Record<string, number>): number {
switch (node.kind) {
case "num":
return node.value;
case "var":
return env[node.name];
case "bin": {
const l = evaluate(node.left, env);
const r = evaluate(node.right, env);
switch (node.op) {
case "+":
return l + r;
case "-":
return l - r;
case "*":
return l * r;
}
}
}
}
const tree = parse("1 + 2 * (3 - x)");
show(tree);
console.log("nodes:", count(tree));
console.log("names:", names(tree));
console.log("value at x = 1:", evaluate(tree, { x: 1 }));
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: [ 'x' ]
value at x = 1: 5
- Verdict: idiom. A discriminated union lists the kinds of node. Inside
case "bin", the type checker narrowsnodeto the variant that hasleftandright. - The TypeScript compiler API (
ts.createSourceFile,ts.forEachChild) parses TypeScript itself. It lives in thetypescriptpackage, not in a standard library.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"strconv"
"strings"
)
func eval(e ast.Expr, env map[string]int) int {
switch e := e.(type) {
case *ast.BasicLit:
v, _ := strconv.Atoi(e.Value)
return v
case *ast.Ident:
return env[e.Name]
case *ast.ParenExpr:
return eval(e.X, env)
case *ast.BinaryExpr:
l, r := eval(e.X, env), eval(e.Y, env)
switch e.Op {
case token.ADD:
return l + r
case token.SUB:
return l - r
case token.MUL:
return l * r
}
}
panic(fmt.Sprintf("unsupported node %T", e))
}
func main() {
expr, err := parser.ParseExpr("1 + 2*(3 - x)")
if err != nil {
panic(err)
}
depth, count := 0, 0
var names []string
ast.Inspect(expr, func(n ast.Node) bool {
if n == nil {
depth--
return false
}
count++
pad := strings.Repeat(" ", depth)
switch n := n.(type) {
case *ast.BinaryExpr:
fmt.Printf("%sBinaryExpr %s\n", pad, n.Op)
case *ast.ParenExpr:
fmt.Printf("%sParenExpr\n", pad)
case *ast.BasicLit:
fmt.Printf("%sBasicLit %s\n", pad, n.Value)
case *ast.Ident:
fmt.Printf("%sIdent %s\n", pad, n.Name)
names = append(names, n.Name)
}
depth++
return true
})
fmt.Println("nodes:", count)
fmt.Println("names:", names)
fmt.Println("value at x = 1:", eval(expr, map[string]int{"x": 1}))
}
BinaryExpr +
BasicLit 1
BinaryExpr *
BasicLit 2
ParenExpr
BinaryExpr -
BasicLit 3
Ident x
nodes: 8
names: [x]
value at x = 1: 5
- Verdict: stdlib.
go/parserparses Go source into the node types ofgo/ast. - The tree keeps the parentheses as an
*ast.ParenExprnode, so it has eight nodes where Python's tree has seven. The evaluator must handleParenExprand step into itsXfield. ast.Inspectcalls the function for each node in depth-first order, and calls it withnilafter the children of a node. The example uses that call to track the depth.- The same packages back
gofmtandgo vet. A tool that inspects Go code needs no third-party parser.
use std::collections::HashMap;
#[derive(Debug)]
enum Expr {
Num(i64),
Var(String),
Bin(char, Box<Expr>, Box<Expr>),
}
struct Parser<'a> {
src: &'a [u8],
pos: usize,
}
impl<'a> Parser<'a> {
fn peek(&mut self) -> u8 {
while self.pos < self.src.len() && self.src[self.pos] == b' ' {
self.pos += 1;
}
if self.pos < self.src.len() { self.src[self.pos] } else { 0 }
}
fn expr(&mut self) -> Result<Expr, String> {
let mut left = self.term()?;
while matches!(self.peek(), b'+' | b'-') {
let op = self.src[self.pos] as char;
self.pos += 1;
left = Expr::Bin(op, Box::new(left), Box::new(self.term()?));
}
Ok(left)
}
fn term(&mut self) -> Result<Expr, String> {
let mut left = self.factor()?;
while self.peek() == b'*' {
self.pos += 1;
left = Expr::Bin('*', Box::new(left), Box::new(self.factor()?));
}
Ok(left)
}
fn factor(&mut self) -> Result<Expr, String> {
let c = self.peek();
if c == b'(' {
self.pos += 1;
let inner = self.expr()?;
if self.peek() != b')' {
return Err(format!("expected ) at {}", self.pos));
}
self.pos += 1;
return Ok(inner);
}
let start = self.pos;
let text = |p: &Parser| std::str::from_utf8(&p.src[start..p.pos]).unwrap().to_string();
if c.is_ascii_digit() {
while self.pos < self.src.len() && self.src[self.pos].is_ascii_digit() {
self.pos += 1;
}
return Ok(Expr::Num(text(self).parse().unwrap()));
}
if c.is_ascii_alphabetic() {
while self.pos < self.src.len() && self.src[self.pos].is_ascii_alphabetic() {
self.pos += 1;
}
return Ok(Expr::Var(text(self)));
}
Err(format!("unexpected {:?} at {}", c as char, self.pos))
}
}
fn show(e: &Expr, depth: usize) {
let pad = " ".repeat(depth);
match e {
Expr::Num(v) => println!("{pad}Num {v}"),
Expr::Var(name) => println!("{pad}Var {name}"),
Expr::Bin(op, l, r) => {
println!("{pad}Bin {op}");
show(l, depth + 1);
show(r, depth + 1);
}
}
}
fn count(e: &Expr) -> usize {
match e {
Expr::Bin(_, l, r) => 1 + count(l) + count(r),
_ => 1,
}
}
fn names<'a>(e: &'a Expr, out: &mut Vec<&'a str>) {
match e {
Expr::Num(_) => {}
Expr::Var(name) => out.push(name),
Expr::Bin(_, l, r) => {
names(l, out);
names(r, out);
}
}
}
fn eval(e: &Expr, env: &HashMap<&str, i64>) -> i64 {
match e {
Expr::Num(v) => *v,
Expr::Var(name) => env[name.as_str()],
Expr::Bin(op, l, r) => {
let (l, r) = (eval(l, env), eval(r, env));
match op {
'+' => l + r,
'-' => l - r,
_ => l * r,
}
}
}
}
fn main() {
let tree = Parser { src: b"1 + 2 * (3 - x)", pos: 0 }.expr().unwrap();
show(&tree, 0);
println!("nodes: {}", count(&tree));
let mut found = Vec::new();
names(&tree, &mut found);
println!("names: {found:?}");
println!("value at x = 1: {}", eval(&tree, &HashMap::from([("x", 1)])));
println!("{tree:?}");
}
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: ["x"]
value at x = 1: 5
Bin('+', Num(1), Bin('*', Num(2), Bin('-', Num(3), Var("x"))))
- Verdict: idiom. An
enumlists the kinds of node, andmatchmust cover all of them. A recursive variant holds its children inBox, because anExprthat contained anExprdirectly would have no finite size. - The parser returns
Result, and?passes a syntax error up through the recursive calls. #[derive(Debug)]prints the whole tree. Thesyncrate parses Rust source into its own tree types, and procedural macros use it. It is a crate, not part of the standard library.
sealed interface Expr
data class Num(val value: Int) : Expr
data class Var(val name: String) : Expr
data class Bin(val op: Char, val left: Expr, val right: Expr) : Expr
class Parser(private val src: String) {
private var pos = 0
private fun peek(): Char {
while (pos < src.length && src[pos] == ' ') pos++
return if (pos < src.length) src[pos] else '\u0000'
}
fun expr(): Expr {
var left = term()
while (peek() == '+' || peek() == '-') {
val op = src[pos++]
left = Bin(op, left, term())
}
return left
}
private fun term(): Expr {
var left = factor()
while (peek() == '*') {
pos++
left = Bin('*', left, factor())
}
return left
}
private fun factor(): Expr {
val c = peek()
if (c == '(') {
pos++
val inner = expr()
check(peek() == ')') { "expected ) at $pos" }
pos++
return inner
}
val start = pos
return when {
c.isDigit() -> {
while (pos < src.length && src[pos].isDigit()) pos++
Num(src.substring(start, pos).toInt())
}
c.isLetter() -> {
while (pos < src.length && src[pos].isLetter()) pos++
Var(src.substring(start, pos))
}
else -> error("unexpected '$c' at $pos")
}
}
}
fun show(e: Expr, depth: Int = 0) {
val pad = " ".repeat(depth)
when (e) {
is Num -> println("${pad}Num ${e.value}")
is Var -> println("${pad}Var ${e.name}")
is Bin -> {
println("${pad}Bin ${e.op}")
show(e.left, depth + 1)
show(e.right, depth + 1)
}
}
}
fun nodes(e: Expr): Sequence<Expr> = sequence {
yield(e)
if (e is Bin) {
yieldAll(nodes(e.left))
yieldAll(nodes(e.right))
}
}
fun eval(e: Expr, env: Map<String, Int>): Int = when (e) {
is Num -> e.value
is Var -> env.getValue(e.name)
is Bin -> {
val l = eval(e.left, env)
val r = eval(e.right, env)
when (e.op) {
'+' -> l + r
'-' -> l - r
else -> l * r
}
}
}
fun main() {
val tree = Parser("1 + 2 * (3 - x)").expr()
show(tree)
println("nodes: ${nodes(tree).count()}")
println("names: ${nodes(tree).filterIsInstance<Var>().map { it.name }.toList()}")
println("value at x = 1: ${eval(tree, mapOf("x" to 1))}")
println(tree)
}
Bin +
Num 1
Bin *
Num 2
Bin -
Num 3
Var x
nodes: 7
names: [x]
value at x = 1: 5
Bin(op=+, left=Num(value=1), right=Bin(op=*, left=Num(value=2), right=Bin(op=-, left=Num(value=3), right=Var(name=x))))
- Verdict: idiom. A sealed interface and data classes describe the nodes, and
whenwithischecks selects the case. Awhenused as an expression must cover every subclass. - Data classes give structural
toStringandequals, so the last line prints the whole tree, and two trees with the same shape compare equal. - On the JVM, Kotlin programs can also call the JDK parser in
com.sun.source.tree, as the Java example does. It parses Java, not Kotlin.
Variations and related ideas
- Parse trees and concrete syntax trees. A parse tree has one node for each grammar rule that matched, and it keeps every token.1 A tool that rewrites source code and must keep the comments and the layout needs such a tree. An AST is the wrong input for it (see Pitfalls).
- Code as data. In LISP, a program is an S-expression, the same list structure that the program works on. McCarthy defined the translation of each form of a function into an S-expression, so that a function can take a program as its argument.21 The AST and the surface syntax are almost the same thing.
- Transforms. An optimizer or a macro system rewrites one tree into another. Python's
ast.NodeTransformerreplaces each node with the value that its visit method returns.20 Rust procedural macros work on token streams and usesynto see them as trees.16 - Intermediate representations. After the AST, many compilers lower the program to a flatter form: three-address code, a control-flow graph, or Bytecode. A flat form is easier to optimize and to run, but it loses the nesting of the source.
- Interpreters. An AST can be run directly by a recursive evaluator. This is the Interpreter pattern at the scale of a whole language, and the Tree-walking interpreter page builds one.
Pitfalls
Walking in the wrong order
ast.walk visits the nodes in no specified order.9 In this run, the names of a * b + c come out level by level and not in source order.
This code runs but gives a wrong answer on purpose.
import ast
tree = ast.parse("a * b + c", mode="eval")
print([n.id for n in ast.walk(tree) if isinstance(n, ast.Name)])
['c', 'a', 'b']
c is closer to the root than a and b, so it comes first. A code generator or a pretty printer needs a depth-first walk in the order of the fields. A NodeVisitor gives that order.
import ast
class Names(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_Name(self, node):
self.names.append(node.id)
finder = Names()
finder.visit(ast.parse("a * b + c", mode="eval"))
print(finder.names)
['a', 'b', 'c']
A deep tree overflows a recursive walk
A sum of many terms is a deep tree. + is left-associative, so 1 + 1 + 1 + ... with 3,000 terms nests 3,000 BinOp nodes on the left. A walk that calls itself for each child needs one frame per level (see Recursion).
This code raises RecursionError, on purpose.
import ast
tree = ast.parse("1" + " + 1" * 3000, mode="eval")
def height(node):
return 1 + max((height(c) for c in ast.iter_child_nodes(node)), default=0)
print(height(tree))
The fix is a walk with an explicit stack of nodes that are still to visit. The stack lives on the heap, so its size is limited only by memory. ast.walk also counts the nodes of the same tree without an error.
import ast
tree = ast.parse("1" + " + 1" * 3000, mode="eval")
deepest = 0
stack = [(tree, 1)]
while stack:
node, depth = stack.pop()
deepest = max(deepest, depth)
for child in ast.iter_child_nodes(node):
stack.append((child, depth + 1))
print(deepest)
print(sum(1 for _ in ast.walk(tree)))
3002
9002
Expecting the tree to keep the source
An AST does not keep comments, and Python's does not keep redundant parentheses. A tool that reads a file into an AST and writes it back with ast.unparse loses both.10
This code runs but gives a wrong answer on purpose.
import ast
source = "x = (1 + 2) # three\n"
print(ast.unparse(ast.parse(source)))
x = 1 + 2
The output is valid code with the same meaning, but the comment is gone. A formatter or a refactoring tool needs a concrete syntax tree, or it must edit the original text at the positions that the AST records.
Cost
- Memory. Each node is a separate object with pointers to its children and four position fields. The deep example above has 9,002 nodes for 12,001 characters of source. In Python, each operator such as
Add()is a node too. - Time. A parser builds each node once, so building the tree is proportional to the number of tokens for the grammars on these pages. Each later phase walks the tree again.
- Stack. A recursive walk needs stack space in proportion to the height of the tree. Long chains of left-associative operators and deeply nested blocks make tall trees.
- Locality. A walk follows pointers from node to node. The nodes may be far apart in memory. A flat encoding such as Bytecode avoids this, which is one reason that interpreters compile the AST before they run it.
History
- 1960. John McCarthy defined LISP. He gave a rule that translates each form of a LISP function into an S-expression, so that programs and data share one tree structure.21
- 1962. McCarthy presented "Towards a Mathematical Science of Computation" at IFIP Congress 62.3 Its section on abstract syntax describes a term by predicates such as
issumand functions such asaddendandaugend, and it ignores the notation of the source.2
References
- Robert Nystrom, Crafting Interpreters, chapter 5, Representing Code, 5.2 Implementing Syntax Trees (parse tree and AST)
- John McCarthy, Towards a Mathematical Science of Computation, Proceedings of IFIP Congress 62 (retyped copy, 1996), section 12, Abstract Syntax of Programming Languages
- John McCarthy's papers, Towards a Mathematical Science of Computation, the description of the paper (given at the congress IFIP-62)
- The Python Standard Library, ast, Python 3.14, introduction of the module ast
- The Python Standard Library, ast, Python 3.14, ast.parse
- The Python Standard Library, ast, Python 3.14, ast.dump
- The Python Standard Library, ast, Python 3.14, Abstract Grammar (attributes lineno, col_offset, end_lineno, end_col_offset)
- The Python Standard Library, ast, Python 3.14, ast.NodeVisitor
- The Python Standard Library, ast, Python 3.14, ast.walk
- The Python Standard Library, ast, Python 3.14, ast.unparse
- Go standard library, package go/parser, Overview and func ParseExpr
- Go standard library, package go/ast, type ParenExpr
- Go standard library, package go/ast, func Inspect
- TypeScript wiki, Using the Compiler API, the caution at the top, and Traversing the AST with a little linter
- Java SE 25 API, module jdk.compiler, package com.sun.source.tree, package description, BinaryTree, ParenthesizedTree, TreeVisitor
- syn crate documentation, crate overview, syn::Expr, the visit module
- C# documentation, Expression Trees, the introduction and Limitations
- .NET API reference, ExpressionVisitor Class, class summary
- .NET API reference, Expression<TDelegate>.Compile Method, Compile()
- The Python Standard Library, ast, Python 3.14, ast.NodeTransformer
- John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, pages 184 to 195, section 3e, Representation of S-Functions by S-Expressions
- PowerShell SDK reference, ScriptBlock.Ast Property, Definition
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag NFVR71 Edit this page History Report an error Markdown