Sub topic 6
Syntax Trees and DAGs
Assume you know basic parse trees, context-free grammars, and expression evaluation. This chapter focuses on how a compiler represents expressions after parsing and why it sometimes replaces a tree with a directed acyclic graph (DAG).
From parse tree to syntax tree
A parse tree records every grammar symbol used during parsing. It may contain many nodes that help prove the grammar was followed, such as parentheses and nonterminals. A syntax tree, often called an abstract syntax tree (AST), removes this grammatical detail and keeps the meaning of the program.
For the expression a + b * c, the operator precedence rule makes multiplication happen first. The syntax tree is therefore:
+
/ \
a *
/ \
b cThe root represents the final operation. Its children represent the operands. The tree structure captures precedence without requiring parentheses in the representation.
Building and using an AST
A compiler can use an AST for type checking, constant evaluation, and later translation into intermediate code. A postorder traversal visits operands before their operator:
- Visit
a. - Visit
b. - Visit
c. - Apply
*. - Apply
+.
A simple Python program can ask the standard library to build an AST:
import ast
source = "a + b * c"
tree = ast.parse(source, mode="eval")
print(ast.dump(tree, indent=2))The multiplication node appears below the addition node. This confirms that the tree preserves the language's precedence rules.
DAGs and shared subexpressions
A tree gives every occurrence its own node. A DAG is a directed graph with no directed cycle, so one node can have multiple parents. Compilers use a DAG for a basic block when the same expression occurs more than once.
Consider:
a = b * -c + b * -c
Both occurrences contain the subexpression b * -c. A DAG can create one node for -c and one node for b * -c, then let the addition node refer to the shared result.
| Representation | Repeated subexpression | Main benefit |
|---|---|---|
| Syntax tree | Stored separately | Simple traversal |
| DAG | Stored once and shared | Exposes common subexpressions |
DAG construction often uses a value-number table. The table maps an operator and its operand nodes to an existing node. If the same key appears again, the compiler reuses the node instead of creating another one.
This sharing can support common subexpression elimination, but it is usually local to a basic block unless additional data-flow facts prove that the expression remains available across branches.
Exercise
What is the root operation in the syntax tree for x * y + z, and why?
Show answer
The root is + because multiplication has higher precedence, so the tree represents (x * y) + z.