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.ASTName;
06: import net.sourceforge.pmd.ast.SimpleNode;
07: import net.sourceforge.pmd.util.Applier;
08:
09: import java.util.ArrayList;
10: import java.util.HashMap;
11: import java.util.List;
12: import java.util.Map;
13:
14: public class LocalScope extends AbstractScope {
15:
16: protected Map<VariableNameDeclaration, List<NameOccurrence>> variableNames = new HashMap<VariableNameDeclaration, List<NameOccurrence>>();
17:
18: public NameDeclaration addVariableNameOccurrence(
19: NameOccurrence occurrence) {
20: NameDeclaration decl = findVariableHere(occurrence);
21: if (decl != null && !occurrence.isThisOrSuper()) {
22: List<NameOccurrence> nameOccurrences = variableNames
23: .get(decl);
24: nameOccurrences.add(occurrence);
25: SimpleNode n = occurrence.getLocation();
26: if (n instanceof ASTName) {
27: ((ASTName) n).setNameDeclaration(decl);
28: } // TODO what to do with PrimarySuffix case?
29: }
30: return decl;
31: }
32:
33: public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
34: VariableUsageFinderFunction f = new VariableUsageFinderFunction(
35: variableNames);
36: Applier.apply(f, variableNames.keySet().iterator());
37: return f.getUsed();
38: }
39:
40: public void addDeclaration(VariableNameDeclaration nameDecl) {
41: if (variableNames.containsKey(nameDecl)) {
42: throw new RuntimeException("Variable " + nameDecl
43: + " is already in the symbol table");
44: }
45: variableNames.put(nameDecl, new ArrayList<NameOccurrence>());
46: }
47:
48: public NameDeclaration findVariableHere(NameOccurrence occurrence) {
49: if (occurrence.isThisOrSuper()
50: || occurrence.isMethodOrConstructorInvocation()) {
51: return null;
52: }
53: ImageFinderFunction finder = new ImageFinderFunction(occurrence
54: .getImage());
55: Applier.apply(finder, variableNames.keySet().iterator());
56: return finder.getDecl();
57: }
58:
59: public String toString() {
60: return "LocalScope:" + glomNames(variableNames.keySet());
61: }
62: }
|