001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2015 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 java.util.regex.Matcher; 023import java.util.regex.Pattern; 024 025import com.puppycrawl.tools.checkstyle.api.Check; 026import com.puppycrawl.tools.checkstyle.api.DetailAST; 027import com.puppycrawl.tools.checkstyle.api.TokenTypes; 028 029/** 030 * Checks for fall through in switch statements 031 * Finds locations where a case <b>contains</b> Java code - 032 * but lacks a break, return, throw or continue statement. 033 * 034 * <p> 035 * The check honors special comments to suppress warnings about 036 * the fall through. By default the comments "fallthru", 037 * "fall through", "falls through" and "fallthrough" are recognized. 038 * </p> 039 * <p> 040 * The following fragment of code will NOT trigger the check, 041 * because of the comment "fallthru" and absence of any Java code 042 * in case 5. 043 * </p> 044 * <pre> 045 * case 3: 046 * x = 2; 047 * // fallthru 048 * case 4: 049 * case 5: 050 * case 6: 051 * break; 052 * </pre> 053 * <p> 054 * The recognized relief comment can be configured with the property 055 * {@code reliefPattern}. Default value of this regular expression 056 * is "fallthru|fall through|fallthrough|falls through". 057 * </p> 058 * <p> 059 * An example of how to configure the check is: 060 * </p> 061 * <pre> 062 * <module name="FallThrough"> 063 * <property name="reliefPattern" 064 * value="Fall Through"/> 065 * </module> 066 * </pre> 067 * 068 * @author o_sukhodolsky 069 */ 070public class FallThroughCheck extends Check { 071 072 /** 073 * A key is pointing to the warning message text in "messages.properties" 074 * file. 075 */ 076 public static final String MSG_FALL_THROUGH = "fall.through"; 077 078 /** 079 * A key is pointing to the warning message text in "messages.properties" 080 * file. 081 */ 082 public static final String MSG_FALL_THROUGH_LAST = "fall.through.last"; 083 084 /** Do we need to check last case group. */ 085 private boolean checkLastCaseGroup; 086 087 /** Relief pattern to allow fall through to the next case branch. */ 088 private String reliefPattern = "fallthru|falls? ?through"; 089 090 /** Relief regexp. */ 091 private Pattern regExp; 092 093 @Override 094 public int[] getDefaultTokens() { 095 return new int[]{TokenTypes.CASE_GROUP}; 096 } 097 098 @Override 099 public int[] getRequiredTokens() { 100 return getDefaultTokens(); 101 } 102 103 @Override 104 public int[] getAcceptableTokens() { 105 return new int[]{TokenTypes.CASE_GROUP}; 106 } 107 108 /** 109 * Set the relief pattern. 110 * 111 * @param pattern 112 * The regular expression pattern. 113 */ 114 public void setReliefPattern(String pattern) { 115 reliefPattern = pattern; 116 } 117 118 /** 119 * Configures whether we need to check last case group or not. 120 * @param value new value of the property. 121 */ 122 public void setCheckLastCaseGroup(boolean value) { 123 checkLastCaseGroup = value; 124 } 125 126 @Override 127 public void init() { 128 super.init(); 129 regExp = Pattern.compile(reliefPattern); 130 } 131 132 @Override 133 public void visitToken(DetailAST ast) { 134 final DetailAST nextGroup = ast.getNextSibling(); 135 final boolean isLastGroup = nextGroup.getType() != TokenTypes.CASE_GROUP; 136 if (isLastGroup && !checkLastCaseGroup) { 137 // we do not need to check last group 138 return; 139 } 140 141 final DetailAST slist = ast.findFirstToken(TokenTypes.SLIST); 142 143 if (slist != null && !isTerminated(slist, true, true) 144 && !hasFallThroughComment(ast, nextGroup)) { 145 if (isLastGroup) { 146 log(ast, MSG_FALL_THROUGH_LAST); 147 } 148 else { 149 log(nextGroup, MSG_FALL_THROUGH); 150 } 151 } 152 } 153 154 /** 155 * Checks if a given subtree terminated by return, throw or, 156 * if allowed break, continue. 157 * @param ast root of given subtree 158 * @param useBreak should we consider break as terminator. 159 * @param useContinue should we consider continue as terminator. 160 * @return true if the subtree is terminated. 161 */ 162 private boolean isTerminated(final DetailAST ast, boolean useBreak, 163 boolean useContinue) { 164 boolean terminated; 165 166 switch (ast.getType()) { 167 case TokenTypes.LITERAL_RETURN: 168 case TokenTypes.LITERAL_THROW: 169 terminated = true; 170 break; 171 case TokenTypes.LITERAL_BREAK: 172 terminated = useBreak; 173 break; 174 case TokenTypes.LITERAL_CONTINUE: 175 terminated = useContinue; 176 break; 177 case TokenTypes.SLIST: 178 terminated = checkSlist(ast, useBreak, useContinue); 179 break; 180 case TokenTypes.LITERAL_IF: 181 terminated = checkIf(ast, useBreak, useContinue); 182 break; 183 case TokenTypes.LITERAL_FOR: 184 case TokenTypes.LITERAL_WHILE: 185 case TokenTypes.LITERAL_DO: 186 terminated = checkLoop(ast); 187 break; 188 case TokenTypes.LITERAL_TRY: 189 terminated = checkTry(ast, useBreak, useContinue); 190 break; 191 case TokenTypes.LITERAL_SWITCH: 192 terminated = checkSwitch(ast, useContinue); 193 break; 194 default: 195 terminated = false; 196 } 197 return terminated; 198 } 199 200 /** 201 * Checks if a given SLIST terminated by return, throw or, 202 * if allowed break, continue. 203 * @param slistAst SLIST to check 204 * @param useBreak should we consider break as terminator. 205 * @param useContinue should we consider continue as terminator. 206 * @return true if SLIST is terminated. 207 */ 208 private boolean checkSlist(final DetailAST slistAst, boolean useBreak, 209 boolean useContinue) { 210 DetailAST lastStmt = slistAst.getLastChild(); 211 212 if (lastStmt.getType() == TokenTypes.RCURLY) { 213 lastStmt = lastStmt.getPreviousSibling(); 214 } 215 216 return lastStmt != null 217 && isTerminated(lastStmt, useBreak, useContinue); 218 } 219 220 /** 221 * Checks if a given IF terminated by return, throw or, 222 * if allowed break, continue. 223 * @param ast IF to check 224 * @param useBreak should we consider break as terminator. 225 * @param useContinue should we consider continue as terminator. 226 * @return true if IF is terminated. 227 */ 228 private boolean checkIf(final DetailAST ast, boolean useBreak, 229 boolean useContinue) { 230 final DetailAST thenStmt = ast.findFirstToken(TokenTypes.RPAREN) 231 .getNextSibling(); 232 final DetailAST elseStmt = thenStmt.getNextSibling(); 233 boolean isTerminated = isTerminated(thenStmt, useBreak, useContinue); 234 235 if (isTerminated && elseStmt != null) { 236 isTerminated = isTerminated(elseStmt.getFirstChild(), 237 useBreak, useContinue); 238 } 239 else if (elseStmt == null) { 240 isTerminated = false; 241 } 242 return isTerminated; 243 } 244 245 /** 246 * Checks if a given loop terminated by return, throw or, 247 * if allowed break, continue. 248 * @param ast loop to check 249 * @return true if loop is terminated. 250 */ 251 private boolean checkLoop(final DetailAST ast) { 252 DetailAST loopBody; 253 if (ast.getType() == TokenTypes.LITERAL_DO) { 254 final DetailAST lparen = ast.findFirstToken(TokenTypes.DO_WHILE); 255 loopBody = lparen.getPreviousSibling(); 256 } 257 else { 258 final DetailAST rparen = ast.findFirstToken(TokenTypes.RPAREN); 259 loopBody = rparen.getNextSibling(); 260 } 261 return isTerminated(loopBody, false, false); 262 } 263 264 /** 265 * Checks if a given try/catch/finally block terminated by return, throw or, 266 * if allowed break, continue. 267 * @param ast loop to check 268 * @param useBreak should we consider break as terminator. 269 * @param useContinue should we consider continue as terminator. 270 * @return true if try/catch/finally block is terminated. 271 */ 272 private boolean checkTry(final DetailAST ast, boolean useBreak, 273 boolean useContinue) { 274 final DetailAST finalStmt = ast.getLastChild(); 275 if (finalStmt.getType() == TokenTypes.LITERAL_FINALLY) { 276 return isTerminated(finalStmt.findFirstToken(TokenTypes.SLIST), 277 useBreak, useContinue); 278 } 279 280 boolean isTerminated = isTerminated(ast.getFirstChild(), 281 useBreak, useContinue); 282 283 DetailAST catchStmt = ast.findFirstToken(TokenTypes.LITERAL_CATCH); 284 while (catchStmt != null && isTerminated) { 285 final DetailAST catchBody = 286 catchStmt.findFirstToken(TokenTypes.SLIST); 287 isTerminated &= isTerminated(catchBody, useBreak, useContinue); 288 catchStmt = catchStmt.getNextSibling(); 289 } 290 return isTerminated; 291 } 292 293 /** 294 * Checks if a given switch terminated by return, throw or, 295 * if allowed break, continue. 296 * @param literalSwitchAst loop to check 297 * @param useContinue should we consider continue as terminator. 298 * @return true if switch is terminated. 299 */ 300 private boolean checkSwitch(final DetailAST literalSwitchAst, boolean useContinue) { 301 DetailAST caseGroup = literalSwitchAst.findFirstToken(TokenTypes.CASE_GROUP); 302 boolean isTerminated = caseGroup != null; 303 while (isTerminated && caseGroup.getType() != TokenTypes.RCURLY) { 304 final DetailAST caseBody = 305 caseGroup.findFirstToken(TokenTypes.SLIST); 306 isTerminated = caseBody != null && isTerminated(caseBody, false, useContinue); 307 caseGroup = caseGroup.getNextSibling(); 308 } 309 return isTerminated; 310 } 311 312 /** 313 * Determines if the fall through case between {@code currentCase} and 314 * {@code nextCase} is relieved by a appropriate comment. 315 * 316 * @param currentCase AST of the case that falls through to the next case. 317 * @param nextCase AST of the next case. 318 * @return True if a relief comment was found 319 */ 320 private boolean hasFallThroughComment(DetailAST currentCase, DetailAST nextCase) { 321 boolean allThroughComment = false; 322 final int endLineNo = nextCase.getLineNo(); 323 final int endColNo = nextCase.getColumnNo(); 324 325 /* 326 * Remember: The lines number returned from the AST is 1-based, but 327 * the lines number in this array are 0-based. So you will often 328 * see a "lineNo-1" etc. 329 */ 330 final String[] lines = getLines(); 331 332 /* 333 * Handle: 334 * case 1: 335 * /+ FALLTHRU +/ case 2: 336 * .... 337 * and 338 * switch(i) { 339 * default: 340 * /+ FALLTHRU +/} 341 */ 342 final String linePart = lines[endLineNo - 1].substring(0, endColNo); 343 if (matchesComment(regExp, linePart, endLineNo)) { 344 allThroughComment = true; 345 } 346 else { 347 /* 348 * Handle: 349 * case 1: 350 * ..... 351 * // FALLTHRU 352 * case 2: 353 * .... 354 * and 355 * switch(i) { 356 * default: 357 * // FALLTHRU 358 * } 359 */ 360 final int startLineNo = currentCase.getLineNo(); 361 for (int i = endLineNo - 2; i > startLineNo - 1; i--) { 362 if (!lines[i].trim().isEmpty()) { 363 allThroughComment = matchesComment(regExp, lines[i], i + 1); 364 break; 365 } 366 } 367 } 368 return allThroughComment; 369 } 370 371 /** 372 * Does a regular expression match on the given line and checks that a 373 * possible match is within a comment. 374 * @param pattern The regular expression pattern to use. 375 * @param line The line of test to do the match on. 376 * @param lineNo The line number in the file. 377 * @return True if a match was found inside a comment. 378 */ 379 private boolean matchesComment(Pattern pattern, String line, int lineNo 380 ) { 381 final Matcher matcher = pattern.matcher(line); 382 383 final boolean hit = matcher.find(); 384 385 if (hit) { 386 final int startMatch = matcher.start(); 387 // -1 because it returns the char position beyond the match 388 final int endMatch = matcher.end() - 1; 389 return getFileContents().hasIntersectionWithComment(lineNo, 390 startMatch, lineNo, endMatch); 391 } 392 return false; 393 } 394}