01: /**
02: * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03: */package net.sourceforge.pmd.symboltable;
04:
05: import net.sourceforge.pmd.ast.ASTConstructorDeclaration;
06: import net.sourceforge.pmd.ast.ASTName;
07: import net.sourceforge.pmd.ast.SimpleNode;
08: import net.sourceforge.pmd.util.Applier;
09:
10: import java.util.ArrayList;
11: import java.util.HashMap;
12: import java.util.List;
13: import java.util.Map;
14:
15: public class MethodScope extends AbstractScope {
16:
17: protected Map<VariableNameDeclaration, List<NameOccurrence>> variableNames = new HashMap<VariableNameDeclaration, List<NameOccurrence>>();
18: private SimpleNode node;
19:
20: public MethodScope(SimpleNode node) {
21: this .node = node;
22: }
23:
24: public MethodScope getEnclosingMethodScope() {
25: return this ;
26: }
27:
28: public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
29: VariableUsageFinderFunction f = new VariableUsageFinderFunction(
30: variableNames);
31: Applier.apply(f, variableNames.keySet().iterator());
32: return f.getUsed();
33: }
34:
35: public NameDeclaration addVariableNameOccurrence(
36: NameOccurrence occurrence) {
37: NameDeclaration decl = findVariableHere(occurrence);
38: if (decl != null && !occurrence.isThisOrSuper()) {
39: variableNames.get(decl).add(occurrence);
40: SimpleNode n = occurrence.getLocation();
41: if (n instanceof ASTName) {
42: ((ASTName) n).setNameDeclaration(decl);
43: } // TODO what to do with PrimarySuffix case?
44: }
45: return decl;
46: }
47:
48: public void addDeclaration(VariableNameDeclaration variableDecl) {
49: if (variableNames.containsKey(variableDecl)) {
50: throw new RuntimeException("Variable " + variableDecl
51: + " is already in the symbol table");
52: }
53: variableNames
54: .put(variableDecl, new ArrayList<NameOccurrence>());
55: }
56:
57: public NameDeclaration findVariableHere(NameOccurrence occurrence) {
58: if (occurrence.isThisOrSuper()
59: || occurrence.isMethodOrConstructorInvocation()) {
60: return null;
61: }
62: ImageFinderFunction finder = new ImageFinderFunction(occurrence
63: .getImage());
64: Applier.apply(finder, variableNames.keySet().iterator());
65: return finder.getDecl();
66: }
67:
68: public String getName() {
69: if (node instanceof ASTConstructorDeclaration) {
70: return this .getEnclosingClassScope().getClassName();
71: }
72: return ((SimpleNode) node.jjtGetChild(1)).getImage();
73: }
74:
75: public String toString() {
76: return "MethodScope:" + glomNames(variableNames.keySet());
77: }
78: }
|