1 package polyglot.visit; 2 3 import polyglot.ast.*; 4 import polyglot.util.*; 5 import java.util.*; 6 7 11 public class AlphaRenamer extends NodeVisitor { 12 13 protected NodeFactory nf; 14 15 protected Stack setStack; 18 19 protected Map renamingMap; 20 21 protected Set freshVars; 23 24 29 public AlphaRenamer(NodeFactory nf) { 30 this.nf = nf; 31 32 this.setStack = new Stack(); 33 this.setStack.push( new HashSet() ); 34 35 this.renamingMap = new HashMap(); 36 this.freshVars = new HashSet(); 37 } 38 39 public NodeVisitor enter( Node n ) { 40 if ( n instanceof Block ) { 41 setStack.push( new HashSet() ); 43 } 44 45 if ( n instanceof LocalDecl ) { 46 LocalDecl l = (LocalDecl)n; 47 String name = l.name(); 48 49 if ( !freshVars.contains(name) ) { 50 String name_ = UniqueID.newID(name); 52 53 freshVars.add(name_); 54 55 ((Set)setStack.peek()).add( name ); 56 renamingMap.put( name, name_ ); 57 } 58 } 59 60 return this; 61 } 62 63 public Node leave( Node old, Node n, NodeVisitor v ) { 64 if ( n instanceof Block ) { 65 Set s = (Set)setStack.pop(); 68 renamingMap.keySet().removeAll(s); 69 return n; 70 } 71 72 if ( n instanceof Local ) { 73 Local l = (Local)n; 75 String name = l.name(); 76 77 if ( !renamingMap.containsKey(name) ) { 78 return n; 79 } 80 81 return l.name( (String )renamingMap.get(name) ); 82 } 83 84 if ( n instanceof LocalDecl ) { 85 LocalDecl l = (LocalDecl)n; 87 String name = l.name(); 88 89 if ( freshVars.contains(name) ) { 90 return n; 91 } 92 93 if ( !renamingMap.containsKey(name) ) { 94 throw new InternalCompilerError( "Unexpected error encountered while " 95 + "alpha-renaming." ); 96 } 97 98 return l.name( (String )renamingMap.get(name) ); 99 } 100 101 return n; 102 } 103 } 104 | Popular Tags |