View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package net.sourceforge.pmd.symboltable;
5   
6   import net.sourceforge.pmd.util.Applier;
7   
8   import java.util.ArrayList;
9   import java.util.HashMap;
10  import java.util.Iterator;
11  import java.util.List;
12  import java.util.Map;
13  
14  /***
15   * Provides behavior common to all Scopes
16   */
17  public abstract class AbstractScope implements Scope {
18  
19      private Scope parent;
20      protected Map variableNames = new HashMap();
21      protected Map methodNames = new HashMap();
22  
23      public ClassScope getEnclosingClassScope() {
24          return parent.getEnclosingClassScope();
25      }
26  
27      public void setParent(Scope parent) {
28          this.parent = parent;
29      }
30  
31      public Scope getParent() {
32          return parent;
33      }
34  
35      public void addDeclaration(VariableNameDeclaration variableDecl) {
36          if (variableNames.containsKey(variableDecl)) {
37              throw new RuntimeException("Variable " + variableDecl + " is already in the symbol table");
38          }
39          variableNames.put(variableDecl, new ArrayList());
40      }
41  
42      public void addDeclaration(MethodNameDeclaration methodDecl) {
43          parent.addDeclaration(methodDecl);
44      }
45  
46      public boolean contains(NameOccurrence occurrence) {
47          return findVariableHere(occurrence) != null;
48      }
49  
50      public Map getVariableDeclarations(boolean lookingForUsed) {
51          VariableUsageFinderFunction f = new VariableUsageFinderFunction(variableNames, lookingForUsed);
52          Applier.apply(f, variableNames.keySet().iterator());
53          return f.getUsed();
54      }
55  
56      public NameDeclaration addVariableNameOccurrence(NameOccurrence occurrence) {
57          NameDeclaration decl = findVariableHere(occurrence);
58          if (decl != null && !occurrence.isThisOrSuper()) {
59              List nameOccurrences = (List) variableNames.get(decl);
60              nameOccurrences.add(occurrence);
61          }
62          return decl;
63      }
64  
65      protected abstract NameDeclaration findVariableHere(NameOccurrence occurrence);
66  
67      protected String glomNames() {
68          String result = "";
69          for (Iterator i = variableNames.keySet().iterator(); i.hasNext();) {
70              result += i.next().toString() + ",";
71          }
72          return result;
73      }
74  
75  }