View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 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 com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
27  
28  /**
29   * <p>
30   * Checks that switch statement has a {@code default} clause.
31   * </p>
32   * <p>
33   * Rationale: It's usually a good idea to introduce a
34   * default case in every switch statement. Even if
35   * the developer is sure that all currently possible
36   * cases are covered, this should be expressed in the
37   * default branch, e.g. by using an assertion. This way
38   * the code is protected against later changes, e.g.
39   * introduction of new types in an enumeration type.
40   * </p>
41   * <p>
42   * This check does not validate any switch expressions. Rationale:
43   * The compiler requires switch expressions to be exhaustive. This means
44   * that all possible inputs must be covered.
45   * </p>
46   * <p>
47   * This check does not validate switch statements that use pattern or null
48   * labels. Rationale: Switch statements that use pattern or null labels are
49   * checked by the compiler for exhaustiveness. This means that all possible
50   * inputs must be covered.
51   * </p>
52   * <p>
53   * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.28">
54   *     Java Language Specification</a> for more information about switch statements
55   *     and expressions.
56   * </p>
57   * <p>
58   * See the <a href="https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.30">
59   *     Java Language Specification</a> for more information about patterns.
60   * </p>
61   * <p>
62   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
63   * </p>
64   * <p>
65   * Violation Message Keys:
66   * </p>
67   * <ul>
68   * <li>
69   * {@code missing.switch.default}
70   * </li>
71   * </ul>
72   *
73   * @since 3.1
74   */
75  @StatelessCheck
76  public class MissingSwitchDefaultCheck extends AbstractCheck {
77  
78      /**
79       * A key is pointing to the warning message text in "messages.properties"
80       * file.
81       */
82      public static final String MSG_KEY = "missing.switch.default";
83  
84      @Override
85      public int[] getDefaultTokens() {
86          return getRequiredTokens();
87      }
88  
89      @Override
90      public int[] getAcceptableTokens() {
91          return getRequiredTokens();
92      }
93  
94      @Override
95      public int[] getRequiredTokens() {
96          return new int[] {TokenTypes.LITERAL_SWITCH};
97      }
98  
99      @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 }