AST
- Dart course
- Expert
- Lesson 8/47
- 5 min
Learn the Abstract Syntax Tree (AST) structure.
AST
AST (Abstract Syntax Tree) is the tree-shaped representation of source code. Each node represents an expression, statement, or declaration. For example, a + b is modeled as a BinaryOp('+', a, b) node.
Being abstract, the AST omits irrelevant details (whitespace, comments). The parser produces an AST from the token stream; type checking, optimization and Kernel conversion run on this tree. The AST is the first stage where the compiler represents code semantically.
AST node types
The AST contains different node types: Literal (constant values), Identifier (variable references), BinaryOp (two-operand operation), FunctionCall (a call). Each node may have child nodes.
For example, add(1, 2) is modeled as FunctionCall('add', [Literal(1), Literal(2)]). Type checking runs on the AST; each node gets a static type. This is the basis of compile-time errors.
Practice An AST Node class
Define a Node class with final String name; final List<Node> children; Node(this.name, this.children); field and constructor. Add an int count() => 1 + children.length; method. In main create final n = Node('BinaryOp', [Node('a', []), Node('b', [])]);; print with print(n.count());.
Starter code
void main() {
// define a Node class (name, children; count method)
// create a Node; print count()
}Sample solution
class Node {
final String name;
final List<Node> children;
Node(this.name, this.children);
int count() => 1 + children.length;
}
void main() {
final n = Node('BinaryOp', [Node('a', []), Node('b', [])]);
print(n.count());
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 An AST node
final node = Node('____', [Node('a', []), Node('b', [])]);
print(node.name);
final node = Node('BinaryOp', [Node('a', []), Node('b', [])]);
print(node.name);
Explanation: BinaryOp is an AST node type (e.g. a + b).
2 What is the purpose of the AST?
- To represent source semantically Correct answer
- To write code
- To collect garbage
- To download packages
Explanation: the AST is the semantic tree representation of source code.
3 Match the AST nodes
| Term | Meaning |
|---|---|
Literal |
Constant value |
Identifier |
Variable reference |
BinaryOp |
Two-operand operation |
FunctionCall |
Call |