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.coding;
21  
22  import java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.List;
25  import java.util.Optional;
26  
27  import com.puppycrawl.tools.checkstyle.StatelessCheck;
28  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
29  import com.puppycrawl.tools.checkstyle.api.DetailAST;
30  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
31  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
32  
33  /**
34   * <div>
35   * Ensures that {@code when} is used instead of a single {@code if}
36   * statement inside a case block.
37   * </div>
38   *
39   * <p>
40   * Rationale: Java 21 has introduced enhancements for switch statements and expressions
41   * that allow the use of patterns in case labels. The {@code when} keyword is used to specify
42   * condition for a case label, also called as guarded case labels. This syntax is more readable
43   * and concise than the single {@code if} statement inside the pattern match block.
44   * </p>
45   *
46   * <p>
47   * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-Guard">
48   * Java Language Specification</a> for more information about guarded case labels.
49   * </p>
50   *
51   * <p>
52   * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
53   * Java Language Specification</a> for more information about patterns.
54   * </p>
55   *
56   * @since 10.18.0
57   */
58  
59  @StatelessCheck
60  public class WhenShouldBeUsedCheck extends AbstractCheck {
61  
62      /**
63       * A key is pointing to the warning message text in "messages.properties"
64       * file.
65       */
66      public static final String MSG_KEY = "when.should.be.used";
67  
68      /**
69       * Creates a new {@code WhenShouldBeUsedCheck} instance.
70       */
71      public WhenShouldBeUsedCheck() {
72          // no code by default
73      }
74  
75      @Override
76      public int[] getDefaultTokens() {
77          return getRequiredTokens();
78      }
79  
80      @Override
81      public int[] getAcceptableTokens() {
82          return getRequiredTokens();
83      }
84  
85      @Override
86      public int[] getRequiredTokens() {
87          return new int[] {TokenTypes.LITERAL_CASE};
88      }
89  
90      @Override
91      public void visitToken(DetailAST ast) {
92          final boolean hasPatternLabel = hasPatternLabel(ast);
93          // until https://github.com/checkstyle/checkstyle/issues/15270
94          final boolean isInSwitchRule = ast.getParent().getType() == TokenTypes.SWITCH_RULE;
95  
96          final Optional<DetailAST> statementList = getStatementList(ast);
97  
98          if (hasPatternLabel && isInSwitchRule && statementList.isPresent()) {
99              final List<DetailAST> blockStatements = getBlockStatements(statementList.get());
100 
101             final boolean hasAcceptableStatementsOnly = blockStatements.stream()
102                     .allMatch(WhenShouldBeUsedCheck::isAcceptableStatement);
103 
104             final boolean hasSingleIfWithNoElse = blockStatements.stream()
105                     .filter(WhenShouldBeUsedCheck::isSingleIfWithNoElse)
106                     .count() == 1;
107 
108             if (hasAcceptableStatementsOnly && hasSingleIfWithNoElse) {
109                 log(ast, MSG_KEY);
110             }
111         }
112     }
113 
114     /**
115      * Get the statement list token of the case block.
116      *
117      * @param caseAST the AST node representing {@code LITERAL_CASE}
118      * @return Optional containing the AST node representing {@code SLIST} of the current case
119      */
120     private static Optional<DetailAST> getStatementList(DetailAST caseAST) {
121         final DetailAST caseParent = caseAST.getParent();
122         return Optional.ofNullable(caseParent.findFirstToken(TokenTypes.SLIST));
123     }
124 
125     /**
126      * Get all statements inside the case block.
127      *
128      * @param statementList the AST node representing {@code SLIST} of the current case
129      * @return statements inside the current case block
130      */
131     private static List<DetailAST> getBlockStatements(DetailAST statementList) {
132         final List<DetailAST> blockStatements = new ArrayList<>();
133         DetailAST ast = statementList.getFirstChild();
134         while (ast != null) {
135             blockStatements.add(ast);
136             ast = ast.getNextSibling();
137         }
138         return Collections.unmodifiableList(blockStatements);
139     }
140 
141     /**
142      * Check if the statement is an acceptable statement inside the case block.
143      * If these statements are the only ones in the case block, this case
144      * can be considered a violation. If at least one of the statements
145      * is not acceptable, this case can not be a violation.
146      *
147      * @param ast the AST node representing the statement
148      * @return true if the statement is an acceptable statement, false otherwise
149      */
150     private static boolean isAcceptableStatement(DetailAST ast) {
151         final int[] acceptableChildrenOfSlist = {
152             TokenTypes.LITERAL_IF,
153             TokenTypes.LITERAL_BREAK,
154             TokenTypes.EMPTY_STAT,
155             TokenTypes.RCURLY,
156         };
157         return TokenUtil.isOfType(ast, acceptableChildrenOfSlist);
158     }
159 
160     /**
161      * Check if the case block has a pattern variable definition
162      * or a record pattern definition.
163      *
164      * @param caseAST the AST node representing {@code LITERAL_CASE}
165      * @return true if the case block has a pattern label, false otherwise
166      */
167     private static boolean hasPatternLabel(DetailAST caseAST) {
168         return caseAST.findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null
169                 || caseAST.findFirstToken(TokenTypes.RECORD_PATTERN_DEF) != null
170                 || caseAST.findFirstToken(TokenTypes.PATTERN_DEF) != null;
171     }
172 
173     /**
174      * Check if the case block statement is a single if statement with no else branch.
175      *
176      * @param statement statement to check inside the current case block
177      * @return true if the statement is a single if statement with no else branch, false otherwise
178      */
179     private static boolean isSingleIfWithNoElse(DetailAST statement) {
180         return statement.getType() == TokenTypes.LITERAL_IF
181                 && statement.findFirstToken(TokenTypes.LITERAL_ELSE) == null;
182     }
183 
184 }