CS453 Intro and PA1 1CS453 Lecture Visitor Design Pattern 1Plan for Today Complexity of algorithm from Wednesday Tree traversals– depth-first traversal– pre-order, post-order, and in-order Visitor Design Pattern– why?– what?– traver sing trees with a visitor design pattern SableCC’s Visitor Design Pattern– terminology– using itCS453 Lecture Visitor Design Pattern 2Example for Tree TraversalsCS453 Lecture Visitor Design Pattern 3Visitor Design Pattern Situation– Want to perform some processing on all items in a data structure– Will be adding many different ways to process items, different features– Will not be changing the classes of the data structure itself much Possibilities– For each functionality add a method to all of the classes– Example of this in PA5, outputDot– Each new functionality is spread over multiple files– Sometimes can’t do it– Use a large if-then-else statement in visit method– pro: keeps all the code for the feature in one place– con: can be costly and involve lots of casting– Visitor design patternCS453 Lecture Visitor Design Pattern 4Borrowed SableCC Visitor Design PatternBuildSymTable buildSTvisitor = new BuildSymTable(linesToNodes);ast.apply(buildSTvisitor);! SymTable globalST = buildSTvisitor.getSymTable();!... // in class VarDeclpublic void apply(Switch sw)! {! ((Analysis) sw).caseVarDecl(this);! }!...// in class DepthFirstAdapterpublic void inVarDecl(VarDecl node) {!defaultIn(node);! }!! public void outVarDecl(VarDecl node) {! defaultOut(node);! }!! public void caseAndExp(VarDecl node)!{! inVarDecl(node); if(node.getType() != null) { node.getType().apply(this); } if(node.getName() != null) { node.getName().apply(this); } outVarDecl(node);}CS453 Intro and PA1 2CS453 Lecture Visitor Design Pattern 5FAQ How do I associate data with a node in the AST if I can’t add fields to thenode classes? What if I want to do the same thing on each node? What if I only need to do something on certain nodes? Shouldn’t the visit/case methods have return
View Full Document