001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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;
029
030/**
031 * <p>
032 * Checks that the outer type name and the file name match.
033 * For example, the class {@code Foo} must be in a file named {@code Foo.java}.
034 * </p>
035 * <p>
036 * To configure the check:
037 * </p>
038 * <pre>
039 * &lt;module name=&quot;OuterTypeFilename&quot;/&gt;
040 * </pre>
041 *
042 * @since 5.3
043 */
044@FileStatefulCheck
045public class OuterTypeFilenameCheck extends AbstractCheck {
046
047    /**
048     * A key is pointing to the warning message text in "messages.properties"
049     * file.
050     */
051    public static final String MSG_KEY = "type.file.mismatch";
052
053    /** Pattern matching any file extension with dot included. */
054    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("\\.[^.]*$");
055
056    /** Indicates whether the first token has been seen in the file. */
057    private boolean seenFirstToken;
058
059    /** Current file name. */
060    private String fileName;
061
062    /** If file has public type. */
063    private boolean hasPublic;
064
065    /** Outer type with mismatched file name. */
066    private DetailAST wrongType;
067
068    @Override
069    public int[] getDefaultTokens() {
070        return getRequiredTokens();
071    }
072
073    @Override
074    public int[] getAcceptableTokens() {
075        return getRequiredTokens();
076    }
077
078    @Override
079    public int[] getRequiredTokens() {
080        return new int[] {
081            TokenTypes.CLASS_DEF,
082            TokenTypes.INTERFACE_DEF,
083            TokenTypes.ENUM_DEF,
084            TokenTypes.ANNOTATION_DEF,
085        };
086    }
087
088    @Override
089    public void beginTree(DetailAST rootAST) {
090        fileName = getFileName();
091        seenFirstToken = false;
092        hasPublic = false;
093        wrongType = null;
094    }
095
096    @Override
097    public void visitToken(DetailAST ast) {
098        if (seenFirstToken) {
099            final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
100            if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
101                    && ast.getParent() == null) {
102                hasPublic = true;
103            }
104        }
105        else {
106            final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText();
107
108            if (!fileName.equals(outerTypeName)) {
109                wrongType = ast;
110            }
111        }
112        seenFirstToken = true;
113    }
114
115    @Override
116    public void finishTree(DetailAST rootAST) {
117        if (!hasPublic && wrongType != null) {
118            log(wrongType.getLineNo(), MSG_KEY);
119        }
120    }
121
122    /**
123     * Get source file name.
124     * @return source file name.
125     */
126    private String getFileName() {
127        String name = getFileContents().getFileName();
128        name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
129        name = FILE_EXTENSION_PATTERN.matcher(name).replaceAll("");
130        return name;
131    }
132
133}