View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.plsql.symboltable;
5   
6   import java.util.HashSet;
7   import java.util.List;
8   import java.util.Map;
9   import java.util.Set;
10  
11  import net.sourceforge.pmd.lang.ast.Node;
12  import net.sourceforge.pmd.lang.plsql.ast.ASTName;
13  import net.sourceforge.pmd.lang.symboltable.AbstractScope;
14  import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
15  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
16  
17  public class LocalScope extends AbstractScope {
18  
19      @Override
20      public Set<NameDeclaration> addNameOccurrence(NameOccurrence occ) {
21          PLSQLNameOccurrence occurrence = (PLSQLNameOccurrence)occ;
22          Set<NameDeclaration> declarations = findVariableHere(occurrence);
23          if (!declarations.isEmpty() && !occurrence.isThisOrSuper()) {
24              for (NameDeclaration decl : declarations) {
25                  List<NameOccurrence> nameOccurrences = getVariableDeclarations().get(decl);
26                  nameOccurrences.add(occurrence);
27                  Node n = occurrence.getLocation();
28                  if (n instanceof ASTName) {
29                      ((ASTName) n).setNameDeclaration(decl);
30                  } // TODO what to do with PrimarySuffix case?
31              }
32          }
33          return declarations;
34      }
35  
36      public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
37          return getDeclarations(VariableNameDeclaration.class);
38      }
39  
40      @Override
41      public void addDeclaration(NameDeclaration declaration) {
42          if (declaration instanceof VariableNameDeclaration && getDeclarations().keySet().contains(declaration)) {
43              throw new RuntimeException(declaration + " is already in the symbol table");
44          }
45          super.addDeclaration(declaration);
46      }
47  
48      public Set<NameDeclaration> findVariableHere(PLSQLNameOccurrence occurrence) {
49          Set<NameDeclaration> result = new HashSet<>();
50          if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
51              return result;
52          }
53          ImageFinderFunction finder = new ImageFinderFunction(occurrence.getImage());
54          Applier.apply(finder, getVariableDeclarations().keySet().iterator());
55          if (finder.getDecl() != null) {
56              result.add(finder.getDecl());
57          }
58          return result;
59      }
60  
61      public String toString() {
62          return "LocalScope:" + getVariableDeclarations().keySet();
63      }
64  }