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