View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import java.io.File;
23  
24  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
25  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26  import com.puppycrawl.tools.checkstyle.api.DetailAST;
27  import com.puppycrawl.tools.checkstyle.api.FullIdent;
28  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
29  
30  /**
31   * <div>
32   * Ensures that a class has a package declaration, and (optionally) whether
33   * the package name matches the directory name for the source file.
34   * </div>
35   *
36   * <p>
37   * Rationale: Classes that live in the null package cannot be imported.
38   * Many novice developers are not aware of this.
39   * </p>
40   *
41   * <p>
42   * Packages provide logical namespace to classes and should be stored in
43   * the form of directory levels to provide physical grouping to your classes.
44   * These directories are added to the classpath so that your classes
45   * are visible to JVM when it runs the code.
46   * </p>
47   *
48   * @since 3.2
49   */
50  @FileStatefulCheck
51  public final class PackageDeclarationCheck extends AbstractCheck {
52  
53      /**
54       * A key is pointing to the warning message text in "messages.properties"
55       * file.
56       */
57      public static final String MSG_KEY_MISSING = "missing.package.declaration";
58  
59      /**
60       * A key is pointing to the warning message text in "messages.properties"
61       * file.
62       */
63      public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
64  
65      /** Is package defined. */
66      private boolean defined;
67  
68      /**
69       * Whether the file is a JEP 512 compact source file, which lives in the
70       * unnamed package by definition and cannot declare a package.
71       */
72      private boolean isCompactSourceFile;
73  
74      /**
75       * Whether the file is a modular compilation unit, which consists of a
76       * module declaration and cannot declare a package.
77       */
78      private boolean isModularCompilationUnit;
79  
80      /** Control whether to check for directory and package name match. */
81      private boolean matchDirectoryStructure = true;
82  
83      /**
84       * Creates a new {@code PackageDeclarationCheck} instance.
85       */
86      public PackageDeclarationCheck() {
87          // no code by default
88      }
89  
90      /**
91       * Setter to control whether to check for directory and package name match.
92       *
93       * @param matchDirectoryStructure the new value.
94       * @since 7.6.1
95       */
96      public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
97          this.matchDirectoryStructure = matchDirectoryStructure;
98      }
99  
100     @Override
101     public int[] getDefaultTokens() {
102         return getRequiredTokens();
103     }
104 
105     @Override
106     public int[] getRequiredTokens() {
107         return new int[] {TokenTypes.PACKAGE_DEF};
108     }
109 
110     @Override
111     public int[] getAcceptableTokens() {
112         return getRequiredTokens();
113     }
114 
115     @Override
116     public void beginTree(DetailAST ast) {
117         defined = false;
118         isCompactSourceFile = ast != null
119                 && ast.getType() == TokenTypes.COMPACT_COMPILATION_UNIT;
120         isModularCompilationUnit = ast != null
121                 && ast.findFirstToken(TokenTypes.MODULE_DEF) != null;
122     }
123 
124     @Override
125     public void finishTree(DetailAST ast) {
126         if (!defined && !isCompactSourceFile && !isModularCompilationUnit && ast != null) {
127             log(ast, MSG_KEY_MISSING);
128         }
129     }
130 
131     @Override
132     public void visitToken(DetailAST ast) {
133         defined = true;
134 
135         if (matchDirectoryStructure) {
136             final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
137             final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
138             final String packageName = fullIdent.getText().replace('.', File.separatorChar);
139 
140             final String directoryName = getDirectoryName();
141 
142             if (!directoryName.endsWith(packageName)) {
143                 log(ast, MSG_KEY_MISMATCH, packageName);
144             }
145         }
146     }
147 
148     /**
149      * Returns the directory name this file is in.
150      *
151      * @return Directory name.
152      */
153     private String getDirectoryName() {
154         final String fileName = getFilePath();
155         final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
156         return fileName.substring(0, lastSeparatorPos);
157     }
158 
159 }