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   
7   import java.util.List;
8   import java.util.Map;
9   
10  import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
11  import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
12  
13  /**
14   * This scope is the outer most scope of a Java file.
15   * A Source File can contain one ore more classes.
16   */
17  public class SourceFileScope extends AbstractJavaScope {
18  
19      private String packageImage;
20  
21      public SourceFileScope() {
22          this("");
23      }
24  
25      public SourceFileScope(String packageImage) {
26          this.packageImage = packageImage;
27      }
28  
29      public String getPackageName() {
30          return packageImage;
31      }
32  
33      /**
34       * {@inheritDoc}
35       * @throws IllegalArgumentException if declaration is not a {@link ClassNameDeclaration}
36       */
37      @Override
38      public void addDeclaration(NameDeclaration declaration) {
39          if (!(declaration instanceof ClassNameDeclaration)) {
40              throw new IllegalArgumentException("A SourceFileScope can only contain classes.");
41          }
42          super.addDeclaration(declaration);
43      }
44  
45      /**
46       * Convenience method that casts the declarations to {@link ClassNameDeclaration}s.
47       * @see #getDeclarations()
48       * @return all class name declarations
49       */
50      public Map<ClassNameDeclaration, List<NameOccurrence>> getClassDeclarations() {
51          return getDeclarations(ClassNameDeclaration.class);
52      }
53  
54      public String toString() {
55          return "SourceFileScope: " + glomNames(getClassDeclarations().keySet());
56      }
57  
58      protected NameDeclaration findVariableHere(JavaNameOccurrence occ) {
59          ImageFinderFunction finder = new ImageFinderFunction(occ.getImage());
60          Applier.apply(finder, getDeclarations().keySet().iterator());
61          return finder.getDecl();
62      }
63  }