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