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.modifier;
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.Scope;
26  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
27  import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
28  
29  /**
30   * <div>
31   * Checks for implicit modifiers on nested types in classes and records.
32   * </div>
33   *
34   * <p>
35   * This check is effectively the opposite of
36   * <a href="https://checkstyle.org/checks/modifier/redundantmodifier.html">
37   * RedundantModifier</a>.
38   * It checks the modifiers on nested types in classes and records, ensuring that certain modifiers
39   * are explicitly specified even though they are actually redundant.
40   * </p>
41   *
42   * <p>
43   * Nested enums, interfaces, and records within a class are always {@code static} and as such the
44   * compiler does not require the {@code static} modifier. This check provides the ability to enforce
45   * that the {@code static} modifier is explicitly coded and not implicitly added by the compiler.
46   * </p>
47   * <div class="wrapper"><pre class="prettyprint"><code class="language-java">
48   * public final class Person {
49   *   enum Age {  // violation
50   *     CHILD, ADULT
51   *   }
52   * }
53   * </code></pre></div>
54   *
55   * <p>
56   * Rationale for this check: Nested enums, interfaces, and records are treated differently from
57   * nested classes as they are only allowed to be {@code static}. Developers should not need to
58   * remember this rule, and this check provides the means to enforce that the modifier is coded
59   * explicitly.
60   * </p>
61   *
62   * @since 8.16
63   */
64  @StatelessCheck
65  public class ClassMemberImpliedModifierCheck
66      extends AbstractCheck {
67  
68      /**
69       * A key is pointing to the warning message text in "messages.properties" file.
70       */
71      public static final String MSG_KEY = "class.implied.modifier";
72  
73      /** Name for 'static' keyword. */
74      private static final String STATIC_KEYWORD = "static";
75  
76      /**
77       * Control whether to enforce that {@code static} is explicitly coded
78       * on nested enums in classes and records.
79       */
80      private boolean violateImpliedStaticOnNestedEnum = true;
81  
82      /**
83       * Control whether to enforce that {@code static} is explicitly coded
84       * on nested interfaces in classes and records.
85       */
86      private boolean violateImpliedStaticOnNestedInterface = true;
87  
88      /**
89       * Control whether to enforce that {@code static} is explicitly coded
90       * on nested records in classes and records.
91       */
92      private boolean violateImpliedStaticOnNestedRecord = true;
93  
94      /**
95       * Creates a new {@code ClassMemberImpliedModifierCheck} instance.
96       */
97      public ClassMemberImpliedModifierCheck() {
98          // no code by default
99      }
100 
101     /**
102      * Setter to control whether to enforce that {@code static} is explicitly coded
103      * on nested enums in classes and records.
104      *
105      * @param violateImplied
106      *        True to perform the check, false to turn the check off.
107      * @since 8.16
108      */
109     public void setViolateImpliedStaticOnNestedEnum(boolean violateImplied) {
110         violateImpliedStaticOnNestedEnum = violateImplied;
111     }
112 
113     /**
114      * Setter to control whether to enforce that {@code static} is explicitly coded
115      * on nested interfaces in classes and records.
116      *
117      * @param violateImplied
118      *        True to perform the check, false to turn the check off.
119      * @since 8.16
120      */
121     public void setViolateImpliedStaticOnNestedInterface(boolean violateImplied) {
122         violateImpliedStaticOnNestedInterface = violateImplied;
123     }
124 
125     /**
126      * Setter to control whether to enforce that {@code static} is explicitly coded
127      * on nested records in classes and records.
128      *
129      * @param violateImplied
130      *        True to perform the check, false to turn the check off.
131      * @since 8.36
132      */
133     public void setViolateImpliedStaticOnNestedRecord(boolean violateImplied) {
134         violateImpliedStaticOnNestedRecord = violateImplied;
135     }
136 
137     @Override
138     public int[] getDefaultTokens() {
139         return getAcceptableTokens();
140     }
141 
142     @Override
143     public int[] getRequiredTokens() {
144         return getAcceptableTokens();
145     }
146 
147     @Override
148     public int[] getAcceptableTokens() {
149         return new int[] {
150             TokenTypes.INTERFACE_DEF,
151             TokenTypes.ENUM_DEF,
152             TokenTypes.RECORD_DEF,
153         };
154     }
155 
156     @Override
157     public void visitToken(DetailAST ast) {
158         if (isInTypeBlock(ast)) {
159             final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
160             switch (ast.getType()) {
161                 case TokenTypes.ENUM_DEF -> {
162                     if (violateImpliedStaticOnNestedEnum
163                             && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) {
164                         log(ast, MSG_KEY, STATIC_KEYWORD);
165                     }
166                 }
167 
168                 case TokenTypes.INTERFACE_DEF -> {
169                     if (violateImpliedStaticOnNestedInterface
170                             && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) {
171                         log(ast, MSG_KEY, STATIC_KEYWORD);
172                     }
173                 }
174 
175                 case TokenTypes.RECORD_DEF -> {
176                     if (violateImpliedStaticOnNestedRecord
177                             && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) {
178                         log(ast, MSG_KEY, STATIC_KEYWORD);
179                     }
180                 }
181 
182                 default -> throw new IllegalStateException(ast.toString());
183             }
184         }
185     }
186 
187     /**
188      * Checks if ast is in a class, enum, anon class or record block.
189      *
190      * @param ast the current ast
191      * @return true if ast is in a class, enum, anon class or record
192      */
193     private static boolean isInTypeBlock(DetailAST ast) {
194         return ScopeUtil.isInScope(ast, Scope.ANONINNER)
195                 || ScopeUtil.isInClassBlock(ast)
196                 || ScopeUtil.isInEnumBlock(ast)
197                 || ScopeUtil.isInRecordBlock(ast);
198     }
199 
200 }