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