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