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.Set;
8   
9   import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
10  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
11  import net.sourceforge.pmd.lang.symboltable.Scope;
12  
13  public class Search {
14      private static final boolean TRACE = false;
15  
16      private NameOccurrence occ;
17      private Set<NameDeclaration> declarations = new HashSet<>();
18  
19      public Search(JavaNameOccurrence occ) {
20          if (TRACE) {
21              System.out.println("new search for " + (occ.isMethodOrConstructorInvocation() ? "method" : "variable") + " " + occ);
22          }
23          this.occ = occ;
24      }
25  
26      public void execute() {
27          Set<NameDeclaration> found = searchUpward(occ, occ.getLocation().getScope());
28          if (TRACE) {
29              System.out.println("found " + found);
30          }
31          declarations.addAll(found);
32      }
33  
34      public void execute(Scope startingScope) {
35          Set<NameDeclaration> found = searchUpward(occ, startingScope);
36          if (TRACE) {
37              System.out.println("found " + found);
38          }
39          declarations.addAll(found);
40      }
41  
42      public Set<NameDeclaration> getResult() {
43          return declarations;
44      }
45  
46      private Set<NameDeclaration> searchUpward(NameOccurrence nameOccurrence, Scope scope) {
47          if (TRACE) {
48              System.out.println(" checking scope " + scope + " for name occurrence " + nameOccurrence);
49          }
50          if (!scope.contains(nameOccurrence) && scope.getParent() != null) {
51              if (TRACE) {
52                  System.out.println(" moving up from " + scope + " to " + scope.getParent());
53              }
54              return searchUpward(nameOccurrence, scope.getParent());
55          }
56          if (scope.contains(nameOccurrence)) {
57              if (TRACE) {
58                  System.out.println(" found it!");
59              }
60              return scope.addNameOccurrence(nameOccurrence);
61          }
62          return new HashSet<>();
63      }
64  }