KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > visit > AlphaRenamer


1 package polyglot.visit;
2
3 import polyglot.ast.*;
4 import polyglot.util.*;
5 import java.util.*;
6
7 /**
8  * The <code>AlphaRenamer</code> runs over the AST and alpha-renames any local
9  * variable declarations that it encounters.
10  **/

11 public class AlphaRenamer extends NodeVisitor {
12
13   protected NodeFactory nf;
14
15   // Each set in this stack tracks the set of local decls in a block that
16
// we're traversing.
17
protected Stack setStack;
18
19   protected Map renamingMap;
20
21   // Tracks the set of variables known to be fresh.
22
protected Set freshVars;
23
24   /**
25    * Creates a visitor for alpha-renaming locals.
26    *
27    * @param nf The node factory to be used when generating new nodes.
28    **/

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       // Push a new, empty set onto the stack.
42
setStack.push( new HashSet() );
43     }
44
45     if ( n instanceof LocalDecl ) {
46       LocalDecl l = (LocalDecl)n;
47       String JavaDoc name = l.name();
48
49       if ( !freshVars.contains(name) ) {
50     // Add a new entry to the current renaming map.
51
String JavaDoc 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       // Pop the current name set off the stack and remove the corresponding
66
// entries from the renaming map.
67
Set s = (Set)setStack.pop();
68       renamingMap.keySet().removeAll(s);
69       return n;
70     }
71
72     if ( n instanceof Local ) {
73       // Rename the local if its name is in the renaming map.
74
Local l = (Local)n;
75       String JavaDoc name = l.name();
76
77       if ( !renamingMap.containsKey(name) ) {
78     return n;
79       }
80
81       return l.name( (String JavaDoc)renamingMap.get(name) );
82     }
83
84     if ( n instanceof LocalDecl ) {
85       // Rename the local decl.
86
LocalDecl l = (LocalDecl)n;
87       String JavaDoc 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 JavaDoc)renamingMap.get(name) );
99     }
100
101     return n;
102   }
103 }
104
Popular Tags