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.design;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
027
028/**
029 * <p>
030 * Checks that each top-level class, interface, enum
031 * or annotation resides in a source file of its own.
032 * Official description of a 'top-level' term:
033 * <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-7.html#jls-7.6">
034 * 7.6. Top Level Type Declarations</a>. If file doesn't contains
035 * public class, interface, enum or annotation, top-level type is the first type in file.
036 * </p>
037 * <p>
038 * To configure the check:
039 * </p>
040 * <pre>
041 * &lt;module name=&quot;OneTopLevelClass&quot;/&gt;
042 * </pre>
043 * <p>
044 * <b>ATTENTION:</b> This Check does not support customization of validated tokens,
045 * so do not use the "tokens" property.
046 * </p>
047 * <p>
048 * An example of code with violations:
049 * </p>
050 * <pre>
051 * public class Foo { // OK, first top-level class
052 *   // methods
053 * }
054 *
055 * class Foo2 { // violation, second top-level class
056 *   // methods
057 * }
058 * </pre>
059 * <p>
060 * An example of code without public top-level type:
061 * </p>
062 * <pre>
063 * class Foo { // OK, first top-level class
064 *   // methods
065 * }
066 *
067 * class Foo2 { // violation, second top-level class
068 *   // methods
069 * }
070 * </pre>
071 * <p>
072 * An example of code without violations:
073 * </p>
074 * <pre>
075 * public class Foo { // OK, only one top-level class
076 *   // methods
077 * }
078 * </pre>
079 *
080 * @since 5.8
081 */
082@StatelessCheck
083public class OneTopLevelClassCheck extends AbstractCheck {
084
085    /**
086     * A key is pointing to the warning message text in "messages.properties"
087     * file.
088     */
089    public static final String MSG_KEY = "one.top.level.class";
090
091    @Override
092    public int[] getDefaultTokens() {
093        return getRequiredTokens();
094    }
095
096    @Override
097    public int[] getAcceptableTokens() {
098        return getRequiredTokens();
099    }
100
101    // ZERO tokens as Check do Traverse of Tree himself, he does not need to subscribed to Tokens
102    @Override
103    public int[] getRequiredTokens() {
104        return CommonUtil.EMPTY_INT_ARRAY;
105    }
106
107    @Override
108    public void beginTree(DetailAST rootAST) {
109        DetailAST currentNode = rootAST;
110        boolean publicTypeFound = false;
111        DetailAST firstType = null;
112
113        while (currentNode != null) {
114            if (isTypeDef(currentNode)) {
115                if (isPublic(currentNode)) {
116                    // log the first type later
117                    publicTypeFound = true;
118                }
119                if (firstType == null) {
120                    // first type is set aside
121                    firstType = currentNode;
122                }
123                else if (!isPublic(currentNode)) {
124                    // extra non-public type, log immediately
125                    final String typeName = currentNode
126                        .findFirstToken(TokenTypes.IDENT).getText();
127                    log(currentNode, MSG_KEY, typeName);
128                }
129            }
130            currentNode = currentNode.getNextSibling();
131        }
132
133        // if there was a public type and first type is non-public, log it
134        if (publicTypeFound && !isPublic(firstType)) {
135            final String typeName = firstType
136                .findFirstToken(TokenTypes.IDENT).getText();
137            log(firstType, MSG_KEY, typeName);
138        }
139    }
140
141    /**
142     * Checks if an AST node is a type definition.
143     *
144     * @param node AST node to check.
145     * @return true if the node is a type (class, enum, interface, annotation) definition.
146     */
147    private static boolean isTypeDef(DetailAST node) {
148        return node.getType() == TokenTypes.CLASS_DEF
149                || node.getType() == TokenTypes.ENUM_DEF
150                || node.getType() == TokenTypes.INTERFACE_DEF
151                || node.getType() == TokenTypes.ANNOTATION_DEF;
152    }
153
154    /**
155     * Checks if a type is public.
156     *
157     * @param typeDef type definition node.
158     * @return true if a type has a public access level modifier.
159     */
160    private static boolean isPublic(DetailAST typeDef) {
161        final DetailAST modifiers =
162                typeDef.findFirstToken(TokenTypes.MODIFIERS);
163        return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null;
164    }
165
166}