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