001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.coding;
021
022import java.util.ArrayList;
023import java.util.Collections;
024import java.util.List;
025import java.util.Optional;
026
027import com.puppycrawl.tools.checkstyle.StatelessCheck;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.TokenTypes;
031import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
032
033/**
034 * <div>
035 * Ensures that {@code when} is used instead of a single {@code if}
036 * statement inside a case block.
037 * </div>
038 *
039 * <p>
040 * Rationale: Java 21 has introduced enhancements for switch statements and expressions
041 * that allow the use of patterns in case labels. The {@code when} keyword is used to specify
042 * condition for a case label, also called as guarded case labels. This syntax is more readable
043 * and concise than the single {@code if} statement inside the pattern match block.
044 * </p>
045 *
046 * <p>
047 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-Guard">
048 * Java Language Specification</a> for more information about guarded case labels.
049 * </p>
050 *
051 * <p>
052 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
053 * Java Language Specification</a> for more information about patterns.
054 * </p>
055 *
056 * @since 10.18.0
057 */
058
059@StatelessCheck
060public class WhenShouldBeUsedCheck extends AbstractCheck {
061
062    /**
063     * A key is pointing to the warning message text in "messages.properties" file.
064     */
065    public static final String MSG_KEY = "when.should.be.used";
066
067    /**
068     * Creates a new {@code WhenShouldBeUsedCheck} instance.
069     */
070    public WhenShouldBeUsedCheck() {
071        // no code by default
072    }
073
074    @Override
075    public int[] getDefaultTokens() {
076        return getRequiredTokens();
077    }
078
079    @Override
080    public int[] getAcceptableTokens() {
081        return getRequiredTokens();
082    }
083
084    @Override
085    public int[] getRequiredTokens() {
086        return new int[] {TokenTypes.LITERAL_CASE};
087    }
088
089    @Override
090    public void visitToken(DetailAST ast) {
091        final boolean hasPatternLabel = hasPatternLabel(ast);
092        // until https://github.com/checkstyle/checkstyle/issues/15270
093        final boolean isInSwitchRule = ast.getParent().getType() == TokenTypes.SWITCH_RULE;
094
095        final Optional<DetailAST> statementList = getStatementList(ast);
096
097        if (hasPatternLabel && isInSwitchRule && statementList.isPresent()) {
098            final List<DetailAST> blockStatements = getBlockStatements(statementList.get());
099
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 Optional containing the AST node representing {@code SLIST} of the current case
118     */
119    private static Optional<DetailAST> getStatementList(DetailAST caseAST) {
120        final DetailAST caseParent = caseAST.getParent();
121        return Optional.ofNullable(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 or a record pattern definition.
161     *
162     * @param caseAST the AST node representing {@code LITERAL_CASE}
163     * @return true if the case block has a pattern label, false otherwise
164     */
165    private static boolean hasPatternLabel(DetailAST caseAST) {
166        return caseAST.findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null
167                || caseAST.findFirstToken(TokenTypes.RECORD_PATTERN_DEF) != null
168                || caseAST.findFirstToken(TokenTypes.PATTERN_DEF) != null;
169    }
170
171    /**
172     * Check if the case block statement is a single if statement with no else branch.
173     *
174     * @param statement statement to check inside the current case block
175     * @return true if the statement is a single if statement with no else branch, false otherwise
176     */
177    private static boolean isSingleIfWithNoElse(DetailAST statement) {
178        return statement.getType() == TokenTypes.LITERAL_IF
179                && statement.findFirstToken(TokenTypes.LITERAL_ELSE) == null;
180    }
181
182}