001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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;
025
026import com.puppycrawl.tools.checkstyle.StatelessCheck;
027import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
028import com.puppycrawl.tools.checkstyle.api.DetailAST;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
031
032/**
033 * <div>
034 * Ensures that {@code when} is used instead of a single {@code if}
035 * statement inside a case block.
036 * </div>
037 *
038 * <p>
039 * Rationale: Java 21 has introduced enhancements for switch statements and expressions
040 * that allow the use of patterns in case labels. The {@code when} keyword is used to specify
041 * condition for a case label, also called as guarded case labels. This syntax is more readable
042 * and concise than the single {@code if} statement inside the pattern match block.
043 * </p>
044 *
045 * <p>
046 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-Guard">
047 * Java Language Specification</a> for more information about guarded case labels.
048 * </p>
049 *
050 * <p>
051 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
052 * Java Language Specification</a> for more information about patterns.
053 * </p>
054 *
055 * <p>
056 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
057 * </p>
058 *
059 * <p>
060 * Violation Message Keys:
061 * </p>
062 * <ul>
063 * <li>
064 * {@code when.should.be.used}
065 * </li>
066 * </ul>
067 *
068 * @since 10.18.0
069 */
070
071@StatelessCheck
072public class WhenShouldBeUsedCheck extends AbstractCheck {
073
074    /**
075     * A key is pointing to the warning message text in "messages.properties"
076     * file.
077     */
078    public static final String MSG_KEY = "when.should.be.used";
079
080    @Override
081    public int[] getDefaultTokens() {
082        return getRequiredTokens();
083    }
084
085    @Override
086    public int[] getAcceptableTokens() {
087        return getRequiredTokens();
088    }
089
090    @Override
091    public int[] getRequiredTokens() {
092        return new int[] {TokenTypes.LITERAL_CASE};
093    }
094
095    @Override
096    public void visitToken(DetailAST ast) {
097        final boolean hasPatternLabel = hasPatternLabel(ast);
098        final DetailAST statementList = getStatementList(ast);
099        // until https://github.com/checkstyle/checkstyle/issues/15270
100        final boolean isInSwitchRule = ast.getParent().getType() == TokenTypes.SWITCH_RULE;
101
102        if (hasPatternLabel && statementList != null && isInSwitchRule) {
103            final List<DetailAST> blockStatements = getBlockStatements(statementList);
104
105            final boolean hasAcceptableStatementsOnly = blockStatements.stream()
106                    .allMatch(WhenShouldBeUsedCheck::isAcceptableStatement);
107
108            final boolean hasSingleIfWithNoElse = blockStatements.stream()
109                    .filter(WhenShouldBeUsedCheck::isSingleIfWithNoElse)
110                    .count() == 1;
111
112            if (hasAcceptableStatementsOnly && hasSingleIfWithNoElse) {
113                log(ast, MSG_KEY);
114            }
115        }
116    }
117
118    /**
119     * Get the statement list token of the case block.
120     *
121     * @param caseAST the AST node representing {@code LITERAL_CASE}
122     * @return the AST node representing {@code SLIST} of the current case
123     */
124    private static DetailAST getStatementList(DetailAST caseAST) {
125        final DetailAST caseParent = caseAST.getParent();
126        return caseParent.findFirstToken(TokenTypes.SLIST);
127    }
128
129    /**
130     * Get all statements inside the case block.
131     *
132     * @param statementList the AST node representing {@code SLIST} of the current case
133     * @return statements inside the current case block
134     */
135    private static List<DetailAST> getBlockStatements(DetailAST statementList) {
136        final List<DetailAST> blockStatements = new ArrayList<>();
137        DetailAST ast = statementList.getFirstChild();
138        while (ast != null) {
139            blockStatements.add(ast);
140            ast = ast.getNextSibling();
141        }
142        return Collections.unmodifiableList(blockStatements);
143    }
144
145    /**
146     * Check if the statement is an acceptable statement inside the case block.
147     * If these statements are the only ones in the case block, this case
148     * can be considered a violation. If at least one of the statements
149     * is not acceptable, this case can not be a violation.
150     *
151     * @param ast the AST node representing the statement
152     * @return true if the statement is an acceptable statement, false otherwise
153     */
154    private static boolean isAcceptableStatement(DetailAST ast) {
155        final int[] acceptableChildrenOfSlist = {
156            TokenTypes.LITERAL_IF,
157            TokenTypes.LITERAL_BREAK,
158            TokenTypes.EMPTY_STAT,
159            TokenTypes.RCURLY,
160        };
161        return TokenUtil.isOfType(ast, acceptableChildrenOfSlist);
162    }
163
164    /**
165     * Check if the case block has a pattern variable definition
166     * or a record pattern definition.
167     *
168     * @param caseAST the AST node representing {@code LITERAL_CASE}
169     * @return true if the case block has a pattern label, false otherwise
170     */
171    private static boolean hasPatternLabel(DetailAST caseAST) {
172        return caseAST.findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null
173                || caseAST.findFirstToken(TokenTypes.RECORD_PATTERN_DEF) != null
174                || caseAST.findFirstToken(TokenTypes.PATTERN_DEF) != null;
175    }
176
177    /**
178     * Check if the case block statement is a single if statement with no else branch.
179     *
180     * @param statement statement to check inside the current case block
181     * @return true if the statement is a single if statement with no else branch, false otherwise
182     */
183    private static boolean isSingleIfWithNoElse(DetailAST statement) {
184        return statement.getType() == TokenTypes.LITERAL_IF
185                && statement.findFirstToken(TokenTypes.LITERAL_ELSE) == null;
186    }
187
188}