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.Set;
023
024import com.puppycrawl.tools.checkstyle.StatelessCheck;
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.TokenTypes;
028import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
029
030/**
031 * <div>
032 * Checks that switch statement has a {@code default} clause.
033 * </div>
034 *
035 * <p>
036 * Rationale: It's usually a good idea to introduce a
037 * default case in every switch statement. Even if the developer is sure that all currently possible
038 * cases are covered, this should be expressed in the
039 * default branch, e.g. by using an assertion. This way
040 * the code is protected against later changes, e.g.
041 * introduction of new types in an enumeration type.
042 * </p>
043 *
044 * <p>
045 * This check does not validate any switch expressions. Rationale:
046 * The compiler requires switch expressions to be exhaustive. This means
047 * that all possible inputs must be covered.
048 * </p>
049 *
050 * <p>
051 * This check does not validate switch statements that use pattern or null
052 * labels. Rationale: Switch statements that use pattern or null labels are
053 * checked by the compiler for exhaustiveness. This means that all possible inputs must be covered.
054 * </p>
055 *
056 * <p>
057 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.28">
058 *     Java Language Specification</a> for more information about switch statements and expressions.
059 * </p>
060 *
061 * <p>
062 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
063 *     Java Language Specification</a> for more information about patterns.
064 * </p>
065 *
066 * @since 3.1
067 */
068@StatelessCheck
069public class MissingSwitchDefaultCheck extends AbstractCheck {
070
071    /**
072     * A key is pointing to the warning message text in "messages.properties" file.
073     */
074    public static final String MSG_KEY = "missing.switch.default";
075
076    /**
077     * Represents the possible parent tokens of a switch statement.
078     */
079    private static final Set<Integer> SWITCH_STATEMENT_PARENTS = Set.of(
080            TokenTypes.SLIST,
081            TokenTypes.LITERAL_IF,
082            TokenTypes.LITERAL_ELSE,
083            TokenTypes.LITERAL_DO,
084            TokenTypes.LITERAL_WHILE,
085            TokenTypes.LITERAL_FOR,
086            TokenTypes.LABELED_STAT
087    );
088
089    /**
090     * Creates a new {@code MissingSwitchDefaultCheck} instance.
091     */
092    public MissingSwitchDefaultCheck() {
093        // no code by default
094    }
095
096    @Override
097    public int[] getDefaultTokens() {
098        return getRequiredTokens();
099    }
100
101    @Override
102    public int[] getAcceptableTokens() {
103        return getRequiredTokens();
104    }
105
106    @Override
107    public int[] getRequiredTokens() {
108        return new int[] {TokenTypes.LITERAL_SWITCH};
109    }
110
111    @Override
112    public void visitToken(DetailAST ast) {
113        if (!containsDefaultLabel(ast)
114                && !containsPatternCaseLabelElement(ast)
115                && !containsNullCaseLabelElement(ast)
116                && !isSwitchExpression(ast)) {
117            log(ast, MSG_KEY);
118        }
119    }
120
121    /**
122     * Checks if the case group or its sibling contain the 'default' switch.
123     *
124     * @param detailAst first case group to check.
125     * @return true if 'default' switch found.
126     */
127    private static boolean containsDefaultLabel(DetailAST detailAst) {
128        return TokenUtil.findFirstTokenByPredicate(detailAst,
129                ast -> ast.findFirstToken(TokenTypes.LITERAL_DEFAULT) != null
130        ).isPresent();
131    }
132
133    /**
134     * Checks if a switch block contains a case label with a pattern variable definition
135     * or record pattern definition.
136     * In this situation, the compiler enforces the given switch block to cover
137     * all possible inputs, and we do not need a default label.
138     *
139     * @param detailAst first case group to check.
140     * @return true if switch block contains a pattern case label element
141     */
142    private static boolean containsPatternCaseLabelElement(DetailAST detailAst) {
143        return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
144            return ast.getFirstChild() != null
145                    && (ast.getFirstChild().findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null
146                    || ast.getFirstChild().findFirstToken(TokenTypes.RECORD_PATTERN_DEF) != null);
147        }).isPresent();
148    }
149
150    /**
151     * Checks if a switch block contains a null case label.
152     *
153     * @param detailAst first case group to check.
154     * @return true if switch block contains null case label
155     */
156    private static boolean containsNullCaseLabelElement(DetailAST detailAst) {
157        return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
158            return ast.getFirstChild() != null
159                     && hasNullCaseLabel(ast.getFirstChild());
160        }).isPresent();
161    }
162
163    /**
164     * Checks if this LITERAL_SWITCH token is part of a switch expression.
165     *
166     * @param ast the switch statement we are checking
167     * @return true if part of a switch expression
168     */
169    private static boolean isSwitchExpression(DetailAST ast) {
170        return !TokenUtil.isOfType(ast.getParent().getType(), SWITCH_STATEMENT_PARENTS);
171    }
172
173    /**
174     * Checks if the case contains null label.
175     *
176     * @param detailAST the switch statement we are checking
177     * @return returnValue the ast of null label
178     */
179    private static boolean hasNullCaseLabel(DetailAST detailAST) {
180        return TokenUtil.findFirstTokenByPredicate(detailAST.getParent(), ast -> {
181            final DetailAST expr = ast.findFirstToken(TokenTypes.EXPR);
182            return expr != null && expr.findFirstToken(TokenTypes.LITERAL_NULL) != null;
183        }).isPresent();
184    }
185
186}