001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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 * <p>
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 * </p>
036 * <p>
037 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
038 * </p>
039 * <p>
040 * Violation Message Keys:
041 * </p>
042 * <ul>
043 * <li>
044 * {@code type.file.mismatch}
045 * </li>
046 * </ul>
047 *
048 * @since 5.3
049 */
050@FileStatefulCheck
051public class OuterTypeFilenameCheck 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 = "type.file.mismatch";
058
059    /** Pattern matching any file extension with dot included. */
060    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("\\.[^.]*$");
061
062    /** Indicates whether the first token has been seen in the file. */
063    private boolean seenFirstToken;
064
065    /** Current file name. */
066    private String fileName;
067
068    /** If file has public type. */
069    private boolean hasPublic;
070
071    /** Outer type with mismatched file name. */
072    private DetailAST wrongType;
073
074    @Override
075    public int[] getDefaultTokens() {
076        return getRequiredTokens();
077    }
078
079    @Override
080    public int[] getAcceptableTokens() {
081        return getRequiredTokens();
082    }
083
084    @Override
085    public int[] getRequiredTokens() {
086        return new int[] {
087            TokenTypes.CLASS_DEF,
088            TokenTypes.INTERFACE_DEF,
089            TokenTypes.ENUM_DEF,
090            TokenTypes.ANNOTATION_DEF,
091            TokenTypes.RECORD_DEF,
092        };
093    }
094
095    @Override
096    public void beginTree(DetailAST rootAST) {
097        fileName = getSourceFileName();
098        seenFirstToken = false;
099        hasPublic = false;
100        wrongType = null;
101    }
102
103    @Override
104    public void visitToken(DetailAST ast) {
105        if (seenFirstToken) {
106            final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
107            if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
108                    && TokenUtil.isRootNode(ast.getParent())) {
109                hasPublic = true;
110            }
111        }
112        else {
113            final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText();
114
115            if (!fileName.equals(outerTypeName)) {
116                wrongType = ast;
117            }
118        }
119        seenFirstToken = true;
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}