View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 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.design;
21  
22  import com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
27  
28  /**
29   * <div>
30   * Checks that each top-level class, interface, enum
31   * or annotation resides in a source file of its own.
32   * Official description of a 'top-level' term:
33   * <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-7.html#jls-7.6">
34   * 7.6. Top Level Type Declarations</a>. If file doesn't contain
35   * public class, interface, enum or annotation, top-level type is the first type in file.
36   * </div>
37   *
38   * <p>
39   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
40   * </p>
41   *
42   * <p>
43   * Violation Message Keys:
44   * </p>
45   * <ul>
46   * <li>
47   * {@code one.top.level.class}
48   * </li>
49   * </ul>
50   *
51   * @since 5.8
52   */
53  @StatelessCheck
54  public class OneTopLevelClassCheck extends AbstractCheck {
55  
56      /**
57       * A key is pointing to the warning message text in "messages.properties"
58       * file.
59       */
60      public static final String MSG_KEY = "one.top.level.class";
61  
62      @Override
63      public int[] getDefaultTokens() {
64          return getRequiredTokens();
65      }
66  
67      @Override
68      public int[] getAcceptableTokens() {
69          return getRequiredTokens();
70      }
71  
72      @Override
73      public int[] getRequiredTokens() {
74          return new int[] {
75              TokenTypes.COMPILATION_UNIT,
76          };
77      }
78  
79      @Override
80      public void visitToken(DetailAST compilationUnit) {
81          DetailAST currentNode = compilationUnit.getFirstChild();
82  
83          boolean publicTypeFound = false;
84          DetailAST firstType = null;
85  
86          while (currentNode != null) {
87              if (isTypeDef(currentNode)) {
88                  if (isPublic(currentNode)) {
89                      // log the first type later
90                      publicTypeFound = true;
91                  }
92                  if (firstType == null) {
93                      // first type is set aside
94                      firstType = currentNode;
95                  }
96                  else if (!isPublic(currentNode)) {
97                      // extra non-public type, log immediately
98                      final String typeName = currentNode
99                          .findFirstToken(TokenTypes.IDENT).getText();
100                     log(currentNode, MSG_KEY, typeName);
101                 }
102             }
103             currentNode = currentNode.getNextSibling();
104         }
105 
106         // if there was a public type and first type is non-public, log it
107         if (publicTypeFound && !isPublic(firstType)) {
108             final String typeName = firstType
109                 .findFirstToken(TokenTypes.IDENT).getText();
110             log(firstType, MSG_KEY, typeName);
111         }
112     }
113 
114     /**
115      * Checks if an AST node is a type definition.
116      *
117      * @param node AST node to check.
118      * @return true if the node is a type (class, enum, interface, annotation) definition.
119      */
120     private static boolean isTypeDef(DetailAST node) {
121         return TokenUtil.isTypeDeclaration(node.getType());
122     }
123 
124     /**
125      * Checks if a type is public.
126      *
127      * @param typeDef type definition node.
128      * @return true if a type has a public access level modifier.
129      */
130     private static boolean isPublic(DetailAST typeDef) {
131         final DetailAST modifiers =
132                 typeDef.findFirstToken(TokenTypes.MODIFIERS);
133         return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null;
134     }
135 
136 }