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/se17/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   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
59   * </p>
60   * <p>
61   * Violation Message Keys:
62   * </p>
63   * <ul>
64   * <li>
65   * {@code missing.switch.default}
66   * </li>
67   * </ul>
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      @Override
81      public int[] getDefaultTokens() {
82          return getRequiredTokens();
83      }
84  
85      @Override
86      public int[] getAcceptableTokens() {
87          return getRequiredTokens();
88      }
89  
90      @Override
91      public int[] getRequiredTokens() {
92          return new int[] {TokenTypes.LITERAL_SWITCH};
93      }
94  
95      @Override
96      public void visitToken(DetailAST ast) {
97          if (!containsDefaultLabel(ast)
98                  && !containsPatternCaseLabelElement(ast)
99                  && !containsDefaultCaseLabelElement(ast)
100                 && !containsNullCaseLabelElement(ast)
101                 && !isSwitchExpression(ast)) {
102             log(ast, MSG_KEY);
103         }
104     }
105 
106     /**
107      * Checks if the case group or its sibling contain the 'default' switch.
108      *
109      * @param detailAst first case group to check.
110      * @return true if 'default' switch found.
111      */
112     private static boolean containsDefaultLabel(DetailAST detailAst) {
113         return TokenUtil.findFirstTokenByPredicate(detailAst,
114                 ast -> ast.findFirstToken(TokenTypes.LITERAL_DEFAULT) != null
115         ).isPresent();
116     }
117 
118     /**
119      * Checks if a switch block contains a case label with a pattern variable definition.
120      * In this situation, the compiler enforces the given switch block to cover
121      * all possible inputs, and we do not need a default label.
122      *
123      * @param detailAst first case group to check.
124      * @return true if switch block contains a pattern case label element
125      */
126     private static boolean containsPatternCaseLabelElement(DetailAST detailAst) {
127         return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
128             return ast.getFirstChild() != null
129                     && ast.getFirstChild().findFirstToken(TokenTypes.PATTERN_VARIABLE_DEF) != null;
130         }).isPresent();
131     }
132 
133     /**
134      * Checks if a switch block contains a default case label.
135      *
136      * @param detailAst first case group to check.
137      * @return true if switch block contains default case label
138      */
139     private static boolean containsDefaultCaseLabelElement(DetailAST detailAst) {
140         return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
141             return ast.getFirstChild() != null
142                     && ast.getFirstChild().findFirstToken(TokenTypes.LITERAL_DEFAULT) != null;
143         }).isPresent();
144     }
145 
146     /**
147      * Checks if a switch block contains a null case label.
148      *
149      * @param detailAst first case group to check.
150      * @return true if switch block contains null case label
151      */
152     private static boolean containsNullCaseLabelElement(DetailAST detailAst) {
153         return TokenUtil.findFirstTokenByPredicate(detailAst, ast -> {
154             return ast.getFirstChild() != null
155                      && hasNullCaseLabel(ast.getFirstChild());
156         }).isPresent();
157     }
158 
159     /**
160      * Checks if this LITERAL_SWITCH token is part of a switch expression.
161      *
162      * @param ast the switch statement we are checking
163      * @return true if part of a switch expression
164      */
165     private static boolean isSwitchExpression(DetailAST ast) {
166         return ast.getParent().getType() == TokenTypes.EXPR
167                 || ast.getParent().getParent().getType() == TokenTypes.EXPR;
168     }
169 
170     /**
171      * Checks if the case contains null label.
172      *
173      * @param ast the switch statement we are checking
174      * @return returnValue the ast of null label
175      */
176     private static boolean hasNullCaseLabel(DetailAST ast) {
177         final DetailAST firstChild = ast.getFirstChild();
178         return firstChild != null
179                 && TokenUtil.isOfType(firstChild.getFirstChild(), TokenTypes.LITERAL_NULL);
180 
181     }
182 }