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