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 * <p>Example of class Test in a file named Test.java</p>
042 * <pre>
043 * public class Test { // OK
044 *
045 * }
046 * </pre>
047 * <p>Example of class Foo in a file named Test.java</p>
048 * <pre>
049 * class Foo { // violation
050 *
051 * }
052 * </pre>
053 * <p>Example of interface Foo in a file named Test.java</p>
054 * <pre>
055 * interface Foo { // violation
056 *
057 * }
058 * </pre>
059 * <p>Example of enum Foo in a file named Test.java</p>
060 * <pre>
061 * enum Foo { // violation
062 *
063 * }
064 * </pre>
065 * <p>Example of record Foo in a file named Test.java</p>
066 * <pre>
067 * record Foo { // violation
068 *
069 * }
070 * </pre>
071 * <p>
072 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
073 * </p>
074 * <p>
075 * Violation Message Keys:
076 * </p>
077 * <ul>
078 * <li>
079 * {@code type.file.mismatch}
080 * </li>
081 * </ul>
082 *
083 * @since 5.3
084 */
085@FileStatefulCheck
086public class OuterTypeFilenameCheck extends AbstractCheck {
087
088    /**
089     * A key is pointing to the warning message text in "messages.properties"
090     * file.
091     */
092    public static final String MSG_KEY = "type.file.mismatch";
093
094    /** Pattern matching any file extension with dot included. */
095    private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("\\.[^.]*$");
096
097    /** Indicates whether the first token has been seen in the file. */
098    private boolean seenFirstToken;
099
100    /** Current file name. */
101    private String fileName;
102
103    /** If file has public type. */
104    private boolean hasPublic;
105
106    /** Outer type with mismatched file name. */
107    private DetailAST wrongType;
108
109    @Override
110    public int[] getDefaultTokens() {
111        return getRequiredTokens();
112    }
113
114    @Override
115    public int[] getAcceptableTokens() {
116        return getRequiredTokens();
117    }
118
119    @Override
120    public int[] getRequiredTokens() {
121        return new int[] {
122            TokenTypes.CLASS_DEF,
123            TokenTypes.INTERFACE_DEF,
124            TokenTypes.ENUM_DEF,
125            TokenTypes.ANNOTATION_DEF,
126            TokenTypes.RECORD_DEF,
127        };
128    }
129
130    @Override
131    public void beginTree(DetailAST rootAST) {
132        fileName = getFileName();
133        seenFirstToken = false;
134        hasPublic = false;
135        wrongType = null;
136    }
137
138    @Override
139    public void visitToken(DetailAST ast) {
140        if (seenFirstToken) {
141            final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
142            if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
143                    && ast.getParent() == null) {
144                hasPublic = true;
145            }
146        }
147        else {
148            final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText();
149
150            if (!fileName.equals(outerTypeName)) {
151                wrongType = ast;
152            }
153        }
154        seenFirstToken = true;
155    }
156
157    @Override
158    public void finishTree(DetailAST rootAST) {
159        if (!hasPublic && wrongType != null) {
160            log(wrongType, MSG_KEY);
161        }
162    }
163
164    /**
165     * Get source file name.
166     *
167     * @return source file name.
168     */
169    private String getFileName() {
170        String name = getFileContents().getFileName();
171        name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
172        name = FILE_EXTENSION_PATTERN.matcher(name).replaceAll("");
173        return name;
174    }
175
176}