View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks;
21  
22  import java.io.File;
23  import java.util.regex.Pattern;
24  
25  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27  import com.puppycrawl.tools.checkstyle.api.DetailAST;
28  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
29  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
30  
31  /**
32   * <div>
33   * Checks that the outer type name and the file name match.
34   * For example, the class {@code Foo} must be in a file named {@code Foo.java}.
35   * </div>
36   *
37   * @since 5.3
38   */
39  @FileStatefulCheck
40  public class OuterTypeFilenameCheck extends AbstractCheck {
41  
42      /**
43       * A key is pointing to the warning message text in "messages.properties"
44       * file.
45       */
46      public static final String MSG_KEY = "type.file.mismatch";
47  
48      /** Pattern matching any file extension with dot included. */
49      private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("\\.[^.]*$");
50  
51      /** Indicates whether the first token has been seen in the file. */
52      private boolean seenFirstToken;
53  
54      /** Current file name. */
55      private String fileName;
56  
57      /** If file has public type. */
58      private boolean hasPublic;
59  
60      /** Outer type with mismatched file name. */
61      private DetailAST wrongType;
62  
63      /**
64       * Indicates whether the file is a compact source file. Its outer type is an
65       * implicit unnamed class that is not declared with a name in the source, so
66       * there is no type name to compare against the file name.
67       */
68      private boolean isCompactSourceFile;
69  
70      /**
71       * Creates a new {@code OuterTypeFilenameCheck} instance.
72       */
73      public OuterTypeFilenameCheck() {
74          // no code by default
75      }
76  
77      @Override
78      public int[] getDefaultTokens() {
79          return getRequiredTokens();
80      }
81  
82      @Override
83      public int[] getAcceptableTokens() {
84          return getRequiredTokens();
85      }
86  
87      @Override
88      public int[] getRequiredTokens() {
89          return new int[] {
90              TokenTypes.CLASS_DEF,
91              TokenTypes.INTERFACE_DEF,
92              TokenTypes.ENUM_DEF,
93              TokenTypes.ANNOTATION_DEF,
94              TokenTypes.RECORD_DEF,
95          };
96      }
97  
98      @Override
99      public void beginTree(DetailAST rootAST) {
100         fileName = getSourceFileName();
101         seenFirstToken = false;
102         hasPublic = false;
103         wrongType = null;
104         isCompactSourceFile = rootAST != null
105                 && rootAST.getType() == TokenTypes.COMPACT_COMPILATION_UNIT;
106     }
107 
108     @Override
109     public void visitToken(DetailAST ast) {
110         if (!isCompactSourceFile) {
111             if (seenFirstToken) {
112                 final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
113                 if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
114                         && TokenUtil.isRootNode(ast.getParent())) {
115                     hasPublic = true;
116                 }
117             }
118             else {
119                 final String outerTypeName = TokenUtil.getIdent(ast).getText();
120 
121                 if (!fileName.equals(outerTypeName)) {
122                     wrongType = ast;
123                 }
124             }
125             seenFirstToken = true;
126         }
127     }
128 
129     @Override
130     public void finishTree(DetailAST rootAST) {
131         if (!hasPublic && wrongType != null) {
132             log(wrongType, MSG_KEY);
133         }
134     }
135 
136     /**
137      * Get source file name.
138      *
139      * @return source file name.
140      */
141     private String getSourceFileName() {
142         String name = getFilePath();
143         name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
144         return FILE_EXTENSION_PATTERN.matcher(name).replaceAll("");
145     }
146 
147 }