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