001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.coding;
021
022import java.io.File;
023
024import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.FullIdent;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029
030/**
031 * <div>
032 * Ensures that a class has a package declaration, and (optionally) whether
033 * the package name matches the directory name for the source file.
034 * </div>
035 *
036 * <p>
037 * Rationale: Classes that live in the null package cannot be imported.
038 * Many novice developers are not aware of this.
039 * </p>
040 *
041 * <p>
042 * Packages provide logical namespace to classes and should be stored in
043 * the form of directory levels to provide physical grouping to your classes.
044 * These directories are added to the classpath so that your classes
045 * are visible to JVM when it runs the code.
046 * </p>
047 *
048 * @since 3.2
049 */
050@FileStatefulCheck
051public final class PackageDeclarationCheck extends AbstractCheck {
052
053    /**
054     * A key is pointing to the warning message text in "messages.properties" file.
055     */
056    public static final String MSG_KEY_MISSING = "missing.package.declaration";
057
058    /**
059     * A key is pointing to the warning message text in "messages.properties" file.
060     */
061    public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
062
063    /** Is package defined. */
064    private boolean defined;
065
066    /**
067     * Whether the file is a JEP 512 compact source file, which lives in the
068     * unnamed package by definition and cannot declare a package.
069     */
070    private boolean isCompactSourceFile;
071
072    /**
073     * Whether the file is a modular compilation unit, which consists of a
074     * module declaration and cannot declare a package.
075     */
076    private boolean isModularCompilationUnit;
077
078    /** Control whether to check for directory and package name match. */
079    private boolean matchDirectoryStructure = true;
080
081    /**
082     * Creates a new {@code PackageDeclarationCheck} instance.
083     */
084    public PackageDeclarationCheck() {
085        // no code by default
086    }
087
088    /**
089     * Setter to control whether to check for directory and package name match.
090     *
091     * @param matchDirectoryStructure the new value.
092     * @since 7.6.1
093     */
094    public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
095        this.matchDirectoryStructure = matchDirectoryStructure;
096    }
097
098    @Override
099    public int[] getDefaultTokens() {
100        return getRequiredTokens();
101    }
102
103    @Override
104    public int[] getRequiredTokens() {
105        return new int[] {TokenTypes.PACKAGE_DEF};
106    }
107
108    @Override
109    public int[] getAcceptableTokens() {
110        return getRequiredTokens();
111    }
112
113    @Override
114    public void beginTree(DetailAST ast) {
115        defined = false;
116        isCompactSourceFile = ast != null
117                && ast.getType() == TokenTypes.COMPACT_COMPILATION_UNIT;
118        isModularCompilationUnit = ast != null
119                && ast.findFirstToken(TokenTypes.MODULE_DEF) != null;
120    }
121
122    @Override
123    public void finishTree(DetailAST ast) {
124        if (!defined && !isCompactSourceFile && !isModularCompilationUnit && ast != null) {
125            log(ast, MSG_KEY_MISSING);
126        }
127    }
128
129    @Override
130    public void visitToken(DetailAST ast) {
131        defined = true;
132
133        if (matchDirectoryStructure) {
134            final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
135            final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
136            final String packageName = fullIdent.getText().replace('.', File.separatorChar);
137
138            final String directoryName = getDirectoryName();
139
140            if (!directoryName.endsWith(packageName)) {
141                log(ast, MSG_KEY_MISMATCH, packageName);
142            }
143        }
144    }
145
146    /**
147     * Returns the directory name this file is in.
148     *
149     * @return Directory name.
150     */
151    private String getDirectoryName() {
152        final String fileName = getFilePath();
153        final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
154        return fileName.substring(0, lastSeparatorPos);
155    }
156
157}