View Javadoc

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