1
2
3
4 package net.sourceforge.pmd.lang.java.symboltable;
5
6 import java.util.List;
7 import java.util.Map;
8
9 import net.sourceforge.pmd.lang.ast.Node;
10 import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
11 import net.sourceforge.pmd.lang.java.ast.ASTName;
12 import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
13 import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
14
15
16
17
18 public class MethodScope extends AbstractJavaScope {
19
20 private Node node;
21
22 public MethodScope(Node node) {
23 this.node = node;
24 }
25
26 public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
27 return getDeclarations(VariableNameDeclaration.class);
28 }
29
30 public NameDeclaration addNameOccurrence(NameOccurrence occurrence) {
31 JavaNameOccurrence javaOccurrence = (JavaNameOccurrence)occurrence;
32 NameDeclaration decl = findVariableHere(javaOccurrence);
33 if (decl != null && !javaOccurrence.isThisOrSuper()) {
34 getVariableDeclarations().get(decl).add(javaOccurrence);
35 Node n = javaOccurrence.getLocation();
36 if (n instanceof ASTName) {
37 ((ASTName) n).setNameDeclaration(decl);
38 }
39 }
40 return decl;
41 }
42
43 public void addDeclaration(NameDeclaration variableDecl) {
44 if (!(variableDecl instanceof VariableNameDeclaration || variableDecl instanceof ClassNameDeclaration)) {
45 throw new IllegalArgumentException("A MethodScope can contain only VariableNameDeclarations or ClassNameDeclarations");
46 }
47 super.addDeclaration(variableDecl);
48 }
49
50 public NameDeclaration findVariableHere(JavaNameOccurrence occurrence) {
51 if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
52 return null;
53 }
54 ImageFinderFunction finder = new ImageFinderFunction(occurrence.getImage());
55 Applier.apply(finder, getVariableDeclarations().keySet().iterator());
56 return finder.getDecl();
57 }
58
59 public String getName() {
60 if (node instanceof ASTConstructorDeclaration) {
61 return this.getEnclosingScope(ClassScope.class).getClassName();
62 }
63 return node.jjtGetChild(1).getImage();
64 }
65
66 public String toString() {
67 return "MethodScope:" + glomNames(getVariableDeclarations().keySet());
68 }
69 }