ASTs and tree traversals
Lecture 8
Table of Contents
(Abstract) syntax trees
Tree walking
Review tree traversals, differences between pre and post order, recursion
The visitor pattern
Illustrate the visitor pattern on the tree example
notes
tree: left is either a node, leaf, or null right is either a node, leaf, or null data
walk_and_print_each_nodes_data_postorder(tree): // base if tree == null: return
// recursive step walk_and_print_each_nodes_data_postorder(tree.left) walk_and_print_each_nodes_data_postorder(tree.right) print(tree.data)
Live coding: calculator example
- Start with the LabeledExpr grammar
- Download ANTLR examples
- Start with code/tour/LabeledExpr.g4 and code/tour/Calc.java
- We will hand-write the EvalVisitor.java evaluator together
Live coding: SimpleC language analysis
- Language processing example: collect variables and functions
- SimpleC semantics
- SimpleC grammar
- SimpleC driver
- SimpleC symbol visitor skeleton