1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2025 the original author or authors.
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ///////////////////////////////////////////////////////////////////////////////////////////////
19
20 package com.puppycrawl.tools.checkstyle.checks.coding;
21
22 import java.util.Set;
23
24 import com.puppycrawl.tools.checkstyle.StatelessCheck;
25 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26 import com.puppycrawl.tools.checkstyle.api.DetailAST;
27 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
28 import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
29
30 /**
31 * <div>
32 * Checks that switch statement has a {@code default} clause.
33 * </div>
34 *
35 * <p>
36 * Rationale: It's usually a good idea to introduce a
37 * default case in every switch statement. Even if
38 * the developer is sure that all currently possible
39 * cases are covered, this should be expressed in the
40 * default branch, e.g. by using an assertion. This way
41 * the code is protected against later changes, e.g.
42 * introduction of new types in an enumeration type.
43 * </p>
44 *
45 * <p>
46 * This check does not validate any switch expressions. Rationale:
47 * The compiler requires switch expressions to be exhaustive. This means
48 * that all possible inputs must be covered.
49 * </p>
50 *
51 * <p>
52 * This check does not validate switch statements that use pattern or null
53 * labels. Rationale: Switch statements that use pattern or null labels are
54 * checked by the compiler for exhaustiveness. This means that all possible
55 * inputs must be covered.
56 * </p>
57 *
58 * <p>
59 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.28">
60 * Java Language Specification</a> for more information about switch statements
61 * and expressions.
62 * </p>
63 *
64 * <p>
65 * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
66 * Java Language Specification</a> for more information about patterns.
67 * </p>
68 *
69 * @since 3.1
70 */
71 @StatelessCheck
72 public class MissingSwitchDefaultCheck extends AbstractCheck {
73
74 /**
75 * A key is pointing to the warning message text in "messages.properties"
76 * file.
77 */
78 public static final String MSG_KEY = "missing.switch.default";
79
80 /**
81 * Represents the possible parent tokens of a switch statement.
82 */
83 private static final Set<Integer> SWITCH_STATEMENT_PARENTS = Set.of(
84 TokenTypes.SLIST,
85 TokenTypes.LITERAL_IF,
86 TokenTypes.LITERAL_ELSE,
87 TokenTypes.LITERAL_DO,
88 TokenTypes.LITERAL_WHILE,
89 TokenTypes.LITERAL_FOR,
90 TokenTypes.LABELED_STAT
91 );
92
93 @Override
94 public int[] getDefaultTokens() {
95 return getRequiredTokens();
96 }
97
98 @Override
99 public int[] getAcceptableTokens() {
100 return getRequiredTokens();
101 }
102
103 @Override
104 public int[] getRequiredTokens() {
105 return new int[] {TokenTypes.LITERAL_SWITCH};
106 }
107
108 @Override
109 public void visitToken(DetailAST ast) {
110 if (!containsDefaultLabel(ast)
111 && !containsPatternCaseLabelElement(ast)
112 && !containsNullCaseLabelElement(ast)
113 && !isSwitchExpression(ast)) {
114 log(ast, MSG_KEY);
115 }
116 }
117
118 /**
119 * Checks if the case group or its sibling contain the 'default' switch.
120 *
121 * @param detailAst first case group to check.
122 * @return true if 'default' switch found.
123 */
124 private static boolean containsDefaultLabel(DetailAST detailAst) {
125 return TokenUtil.findFirstTokenByPredicate(detailAst,
126 ast -> ast.findFirstToken(TokenTypes.LITERAL_DEFAULT) != null
127 ).isPresent();
128 }
129
130 /**
131 * Checks if a switch block contains a case label with a pattern variable definition
132 * or record pattern definition.
133 * In this situation, the compiler enforces the given switch block to cover
134 * all possible inputs, and we do not need a default label.
135 *
136 * @param detailAst first case group to check.
137 * @return true if switch block contains a pattern case label element
138 */
139 private static boolean containsPatternCaseLabelElement(DetailAST detailAst) {
140 return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
141 return ast.getFirstChild() != null
142 && (ast.getFirstChild().findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null
143 || ast.getFirstChild().findFirstToken(TokenTypes.RECORD_PATTERN_DEF) != null);
144 }).isPresent();
145 }
146
147 /**
148 * Checks if a switch block contains a null case label.
149 *
150 * @param detailAst first case group to check.
151 * @return true if switch block contains null case label
152 */
153 private static boolean containsNullCaseLabelElement(DetailAST detailAst) {
154 return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
155 return ast.getFirstChild() != null
156 && hasNullCaseLabel(ast.getFirstChild());
157 }).isPresent();
158 }
159
160 /**
161 * Checks if this LITERAL_SWITCH token is part of a switch expression.
162 *
163 * @param ast the switch statement we are checking
164 * @return true if part of a switch expression
165 */
166 private static boolean isSwitchExpression(DetailAST ast) {
167 return !TokenUtil.isOfType(ast.getParent().getType(), SWITCH_STATEMENT_PARENTS);
168 }
169
170 /**
171 * Checks if the case contains null label.
172 *
173 * @param detailAST the switch statement we are checking
174 * @return returnValue the ast of null label
175 */
176 private static boolean hasNullCaseLabel(DetailAST detailAST) {
177 return TokenUtil.findFirstTokenByPredicate(detailAST.getParent(), ast -> {
178 final DetailAST expr = ast.findFirstToken(TokenTypes.EXPR);
179 return expr != null && expr.findFirstToken(TokenTypes.LITERAL_NULL) != null;
180 }).isPresent();
181 }
182 }