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;
021
022import java.io.File;
023import java.util.regex.Pattern;
024
025import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
030
031/**
032 * <div>
033 * Checks that the outer type name and the file name match.
034 * For example, the class {@code Foo} must be in a file named {@code Foo.java}.
035 * </div>
036 *
037 * @since 5.3
038 */
039@FileStatefulCheck
040public class OuterTypeFilenameCheck extends AbstractCheck {
041
042    /**
043     * A key is pointing to the warning message text in "messages.properties"
044     * file.
045     */
046    public static final String MSG_KEY = "type.file.mismatch";
047
048    /** Pattern matching any file extension with dot included. */
049    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("\\.[^.]*$");
050
051    /** Indicates whether the first token has been seen in the file. */
052    private boolean seenFirstToken;
053
054    /** Current file name. */
055    private String fileName;
056
057    /** If file has public type. */
058    private boolean hasPublic;
059
060    /** Outer type with mismatched file name. */
061    private DetailAST wrongType;
062
063    /**
064     * Indicates whether the file is a compact source file. Its outer type is an
065     * implicit unnamed class that is not declared with a name in the source, so
066     * there is no type name to compare against the file name.
067     */
068    private boolean isCompactSourceFile;
069
070    @Override
071    public int[] getDefaultTokens() {
072        return getRequiredTokens();
073    }
074
075    @Override
076    public int[] getAcceptableTokens() {
077        return getRequiredTokens();
078    }
079
080    @Override
081    public int[] getRequiredTokens() {
082        return new int[] {
083            TokenTypes.CLASS_DEF,
084            TokenTypes.INTERFACE_DEF,
085            TokenTypes.ENUM_DEF,
086            TokenTypes.ANNOTATION_DEF,
087            TokenTypes.RECORD_DEF,
088        };
089    }
090
091    @Override
092    public void beginTree(DetailAST rootAST) {
093        fileName = getSourceFileName();
094        seenFirstToken = false;
095        hasPublic = false;
096        wrongType = null;
097        isCompactSourceFile = rootAST != null
098                && rootAST.getType() == TokenTypes.COMPACT_COMPILATION_UNIT;
099    }
100
101    @Override
102    public void visitToken(DetailAST ast) {
103        if (!isCompactSourceFile) {
104            if (seenFirstToken) {
105                final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
106                if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
107                        && TokenUtil.isRootNode(ast.getParent())) {
108                    hasPublic = true;
109                }
110            }
111            else {
112                final String outerTypeName = TokenUtil.getIdent(ast).getText();
113
114                if (!fileName.equals(outerTypeName)) {
115                    wrongType = ast;
116                }
117            }
118            seenFirstToken = true;
119        }
120    }
121
122    @Override
123    public void finishTree(DetailAST rootAST) {
124        if (!hasPublic && wrongType != null) {
125            log(wrongType, MSG_KEY);
126        }
127    }
128
129    /**
130     * Get source file name.
131     *
132     * @return source file name.
133     */
134    private String getSourceFileName() {
135        String name = getFilePath();
136        name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
137        return FILE_EXTENSION_PATTERN.matcher(name).replaceAll("");
138    }
139
140}