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;
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    @Override
064    public int[] getDefaultTokens() {
065        return getRequiredTokens();
066    }
067
068    @Override
069    public int[] getAcceptableTokens() {
070        return getRequiredTokens();
071    }
072
073    @Override
074    public int[] getRequiredTokens() {
075        return new int[] {
076            TokenTypes.CLASS_DEF,
077            TokenTypes.INTERFACE_DEF,
078            TokenTypes.ENUM_DEF,
079            TokenTypes.ANNOTATION_DEF,
080            TokenTypes.RECORD_DEF,
081        };
082    }
083
084    @Override
085    public void beginTree(DetailAST rootAST) {
086        fileName = getSourceFileName();
087        seenFirstToken = false;
088        hasPublic = false;
089        wrongType = null;
090    }
091
092    @Override
093    public void visitToken(DetailAST ast) {
094        if (seenFirstToken) {
095            final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
096            if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
097                    && TokenUtil.isRootNode(ast.getParent())) {
098                hasPublic = true;
099            }
100        }
101        else {
102            final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText();
103
104            if (!fileName.equals(outerTypeName)) {
105                wrongType = ast;
106            }
107        }
108        seenFirstToken = true;
109    }
110
111    @Override
112    public void finishTree(DetailAST rootAST) {
113        if (!hasPublic && wrongType != null) {
114            log(wrongType, MSG_KEY);
115        }
116    }
117
118    /**
119     * Get source file name.
120     *
121     * @return source file name.
122     */
123    private String getSourceFileName() {
124        String name = getFilePath();
125        name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
126        return FILE_EXTENSION_PATTERN.matcher(name).replaceAll("");
127    }
128
129}