001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2025 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"
055     * file.
056     */
057    public static final String MSG_KEY_MISSING = "missing.package.declaration";
058
059    /**
060     * A key is pointing to the warning message text in "messages.properties"
061     * file.
062     */
063    public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
064
065    /** Is package defined. */
066    private boolean defined;
067
068    /** Control whether to check for directory and package name match. */
069    private boolean matchDirectoryStructure = true;
070
071    /**
072     * Setter to control whether to check for directory and package name match.
073     *
074     * @param matchDirectoryStructure the new value.
075     * @since 7.6.1
076     */
077    public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
078        this.matchDirectoryStructure = matchDirectoryStructure;
079    }
080
081    @Override
082    public int[] getDefaultTokens() {
083        return getRequiredTokens();
084    }
085
086    @Override
087    public int[] getRequiredTokens() {
088        return new int[] {TokenTypes.PACKAGE_DEF};
089    }
090
091    @Override
092    public int[] getAcceptableTokens() {
093        return getRequiredTokens();
094    }
095
096    @Override
097    public void beginTree(DetailAST ast) {
098        defined = false;
099    }
100
101    @Override
102    public void finishTree(DetailAST ast) {
103        if (!defined && ast != null) {
104            log(ast, MSG_KEY_MISSING);
105        }
106    }
107
108    @Override
109    public void visitToken(DetailAST ast) {
110        defined = true;
111
112        if (matchDirectoryStructure) {
113            final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
114            final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
115            final String packageName = fullIdent.getText().replace('.', File.separatorChar);
116
117            final String directoryName = getDirectoryName();
118
119            if (!directoryName.endsWith(packageName)) {
120                log(ast, MSG_KEY_MISMATCH, packageName);
121            }
122        }
123    }
124
125    /**
126     * Returns the directory name this file is in.
127     *
128     * @return Directory name.
129     */
130    private String getDirectoryName() {
131        final String fileName = getFilePath();
132        final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
133        return fileName.substring(0, lastSeparatorPos);
134    }
135
136}