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.HashSet;
7   import java.util.List;
8   import java.util.Map;
9   import java.util.Set;
10  
11  import net.sourceforge.pmd.lang.ast.Node;
12  import net.sourceforge.pmd.lang.java.ast.ASTName;
13  import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
14  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
15  
16  /**
17   * A LocalScope can have variable declarations and class declarations within it.
18   */
19  public class LocalScope extends AbstractJavaScope {
20  
21      public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
22          return getDeclarations(VariableNameDeclaration.class);
23      }
24  
25      public Set<NameDeclaration> addNameOccurrence(NameOccurrence occurrence) {
26          JavaNameOccurrence javaOccurrence = (JavaNameOccurrence) occurrence;
27          Set<NameDeclaration> declarations = findVariableHere(javaOccurrence);
28          if (!declarations.isEmpty() && !javaOccurrence.isThisOrSuper()) {
29              for (NameDeclaration decl : declarations) {
30                  List<NameOccurrence> nameOccurrences = getVariableDeclarations().get(decl);
31                  nameOccurrences.add(javaOccurrence);
32                  Node n = javaOccurrence.getLocation();
33                  if (n instanceof ASTName) {
34                      ((ASTName) n).setNameDeclaration(decl);
35                  } // TODO what to do with PrimarySuffix case?
36              }
37          }
38          return declarations;
39      }
40  
41      public void addDeclaration(NameDeclaration nameDecl) {
42          if (!(nameDecl instanceof VariableNameDeclaration || nameDecl instanceof ClassNameDeclaration)) {
43              throw new IllegalArgumentException(
44                      "A LocalScope can contain only VariableNameDeclarations or ClassNameDeclarations. "
45                              + "Tried to add " + nameDecl.getClass() + "(" + nameDecl + ")");
46          }
47          super.addDeclaration(nameDecl);
48      }
49  
50      public Set<NameDeclaration> findVariableHere(JavaNameOccurrence occurrence) {
51          Set<NameDeclaration> result = new HashSet<>();
52          if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
53              return result;
54          }
55          DeclarationFinderFunction finder = new DeclarationFinderFunction(occurrence);
56          Applier.apply(finder, getVariableDeclarations().keySet().iterator());
57          if (finder.getDecl() != null) {
58              result.add(finder.getDecl());
59          }
60          return result;
61      }
62  
63      public String toString() {
64          return "LocalScope:" + glomNames(getVariableDeclarations().keySet());
65      }
66  }