001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2023 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/se17/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 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
059 * </p>
060 * <p>
061 * Violation Message Keys:
062 * </p>
063 * <ul>
064 * <li>
065 * {@code missing.switch.default}
066 * </li>
067 * </ul>
068 *
069 * @since 3.1
070 */
071@StatelessCheck
072public class MissingSwitchDefaultCheck 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 = "missing.switch.default";
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_SWITCH};
093    }
094
095    @Override
096    public void visitToken(DetailAST ast) {
097        if (!containsDefaultLabel(ast)
098                && !containsPatternCaseLabelElement(ast)
099                && !containsDefaultCaseLabelElement(ast)
100                && !isSwitchExpression(ast)) {
101            log(ast, MSG_KEY);
102        }
103    }
104
105    /**
106     * Checks if the case group or its sibling contain the 'default' switch.
107     *
108     * @param detailAst first case group to check.
109     * @return true if 'default' switch found.
110     */
111    private static boolean containsDefaultLabel(DetailAST detailAst) {
112        return TokenUtil.findFirstTokenByPredicate(detailAst,
113                ast -> ast.findFirstToken(TokenTypes.LITERAL_DEFAULT) != null
114        ).isPresent();
115    }
116
117    /**
118     * Checks if a switch block contains a case label with a pattern variable definition.
119     * In this situation, the compiler enforces the given switch block to cover
120     * all possible inputs, and we do not need a default label.
121     *
122     * @param detailAst first case group to check.
123     * @return true if switch block contains a pattern case label element
124     */
125    private static boolean containsPatternCaseLabelElement(DetailAST detailAst) {
126        return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
127            return ast.getFirstChild() != null
128                    && ast.getFirstChild().findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null;
129        }).isPresent();
130    }
131
132    /**
133     * Checks if a switch block contains a default case label.
134     *
135     * @param detailAst first case group to check.
136     * @return true if switch block contains default case label
137     */
138    private static boolean containsDefaultCaseLabelElement(DetailAST detailAst) {
139        return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
140            return ast.getFirstChild() != null
141                    && ast.getFirstChild().findFirstToken(TokenTypes.LITERAL_DEFAULT) != null;
142        }).isPresent();
143    }
144
145    /**
146     * Checks if this LITERAL_SWITCH token is part of a switch expression.
147     *
148     * @param ast the switch statement we are checking
149     * @return true if part of a switch expression
150     */
151    private static boolean isSwitchExpression(DetailAST ast) {
152        return ast.getParent().getType() == TokenTypes.EXPR
153                || ast.getParent().getParent().getType() == TokenTypes.EXPR;
154    }
155}