View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2017 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.Objects;
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  
29  /**
30   * <p>
31   * Check that the {@code default} is after all the {@code case}s
32   * in a {@code switch} statement.
33   * </p>
34   * <p>
35   * Rationale: Java allows {@code default} anywhere within the
36   * {@code switch} statement. But if it comes after the last
37   * {@code case} then it is more readable.
38   * </p>
39   * <p>
40   * An example of how to configure the check is:
41   * </p>
42   * <pre>
43   * &lt;module name="DefaultComesLast"/&gt;
44   * </pre>
45   * @author o_sukhodolsky
46   */
47  @StatelessCheck
48  public class DefaultComesLastCheck extends AbstractCheck {
49  
50      /**
51       * A key is pointing to the warning message text in "messages.properties"
52       * file.
53       */
54      public static final String MSG_KEY = "default.comes.last";
55  
56      /**
57       * A key is pointing to the warning message text in "messages.properties"
58       * file.
59       */
60      public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE =
61              "default.comes.last.in.casegroup";
62  
63      /** Whether to process skipIfLastAndSharedWithCaseInSwitch() invocations. */
64      private boolean skipIfLastAndSharedWithCase;
65  
66      @Override
67      public int[] getAcceptableTokens() {
68          return getRequiredTokens();
69      }
70  
71      @Override
72      public int[] getDefaultTokens() {
73          return getRequiredTokens();
74      }
75  
76      @Override
77      public int[] getRequiredTokens() {
78          return new int[] {
79              TokenTypes.LITERAL_DEFAULT,
80          };
81      }
82  
83      /**
84       * Whether to allow default keyword not in last but surrounded with case.
85       * @param newValue whether to ignore checking.
86       */
87      public void setSkipIfLastAndSharedWithCase(boolean newValue) {
88          skipIfLastAndSharedWithCase = newValue;
89      }
90  
91      @Override
92      public void visitToken(DetailAST ast) {
93          final DetailAST defaultGroupAST = ast.getParent();
94          //default keywords used in annotations too - not what we're
95          //interested in
96          if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF
97                  && defaultGroupAST.getType() != TokenTypes.MODIFIERS) {
98  
99              if (skipIfLastAndSharedWithCase) {
100                 if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) {
101                     log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE);
102                 }
103                 else if (ast.getPreviousSibling() == null
104                     && Objects.nonNull(findNextSibling(defaultGroupAST,
105                                                        TokenTypes.CASE_GROUP))) {
106                     log(ast, MSG_KEY);
107                 }
108             }
109             else if (Objects.nonNull(findNextSibling(defaultGroupAST,
110                                                      TokenTypes.CASE_GROUP))) {
111                 log(ast, MSG_KEY);
112             }
113         }
114     }
115 
116     /**
117      * Return token type only if passed tokenType in argument is found or returns -1.
118      *
119      * @param ast root node.
120      * @param tokenType tokentype to be processed.
121      * @return token if desired token is found or else null.
122      */
123     private static DetailAST findNextSibling(DetailAST ast, int tokenType) {
124         DetailAST token = null;
125         DetailAST node = ast.getNextSibling();
126         while (node != null) {
127             if (node.getType() == tokenType) {
128                 token = node;
129                 break;
130             }
131             node = node.getNextSibling();
132         }
133         return token;
134     }
135 }