View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.symboltable;
5   
6   import java.util.ArrayList;
7   import java.util.HashMap;
8   import java.util.List;
9   import java.util.Map;
10  
11  import net.sourceforge.pmd.lang.ast.Node;
12  import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
13  import net.sourceforge.pmd.lang.java.ast.ASTName;
14  
15  public class MethodScope extends AbstractScope {
16  
17      protected Map<VariableNameDeclaration, List<NameOccurrence>> variableNames = new HashMap<VariableNameDeclaration, List<NameOccurrence>>();
18      private Node node;
19  
20      public MethodScope(Node node) {
21          this.node = node;
22      }
23  
24      public MethodScope getEnclosingMethodScope() {
25          return this;
26      }
27  
28      public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
29          VariableUsageFinderFunction f = new VariableUsageFinderFunction(variableNames);
30          Applier.apply(f, variableNames.keySet().iterator());
31          return f.getUsed();
32      }
33  
34      public NameDeclaration addVariableNameOccurrence(NameOccurrence occurrence) {
35          NameDeclaration decl = findVariableHere(occurrence);
36          if (decl != null && !occurrence.isThisOrSuper()) {
37              variableNames.get(decl).add(occurrence);
38              Node n = occurrence.getLocation();
39              if (n instanceof ASTName) {
40                  ((ASTName) n).setNameDeclaration(decl);
41              } // TODO what to do with PrimarySuffix case?
42          }
43          return decl;
44      }
45  
46      public void addDeclaration(VariableNameDeclaration variableDecl) {
47          if (variableNames.containsKey(variableDecl)) {
48              throw new RuntimeException("Variable " + variableDecl + " is already in the symbol table");
49          }
50          variableNames.put(variableDecl, new ArrayList<NameOccurrence>());
51      }
52  
53      public NameDeclaration findVariableHere(NameOccurrence occurrence) {
54          if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
55              return null;
56          }
57          ImageFinderFunction finder = new ImageFinderFunction(occurrence.getImage());
58          Applier.apply(finder, variableNames.keySet().iterator());
59          return finder.getDecl();
60      }
61  
62      public String getName() {
63          if (node instanceof ASTConstructorDeclaration) {
64              return this.getEnclosingClassScope().getClassName();
65          }
66          return node.jjtGetChild(1).getImage();
67      }
68  
69      public String toString() {
70          return "MethodScope:" + glomNames(variableNames.keySet());
71      }
72  }