001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 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.Objects; 023import java.util.regex.Pattern; 024import java.util.stream.Stream; 025 026import com.puppycrawl.tools.checkstyle.StatelessCheck; 027import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 028import com.puppycrawl.tools.checkstyle.api.DetailAST; 029import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 031 032/** 033 * <div> 034 * Checks for fall-through in {@code switch} statements. 035 * Finds locations where a {@code case} <b>contains</b> Java code but lacks a 036 * {@code break}, {@code return}, {@code yield}, {@code throw} or {@code continue} statement. 037 * </div> 038 * 039 * <p> 040 * The check honors special comments to suppress the warning. 041 * By default, the texts "fallthru", "fall thru", "fall-thru", 042 * "fallthrough", "fall through", "fall-through" 043 * "fallsthrough", "falls through", "falls-through" (case-sensitive). 044 * The comment containing these words must be all on one line, 045 * and must be on the last non-empty line before the {@code case} triggering 046 * the warning or on the same line before the {@code case}(ugly, but possible). 047 * Any other comment may follow on the same line. 048 * </p> 049 * 050 * <p> 051 * Note: 052 * The check assumes that there is no unreachable code in the {@code case}. 053 * </p> 054 * 055 * <p> 056 * A {@code case} whose code ends in an infinite loop is not flagged, e.g. 057 * {@code while (true) {}}, {@code for (;;) {}}, {@code for (;true;) {}} 058 * or {@code do {} while (true);}. 059 * </p> 060 * 061 * @since 3.4 062 */ 063@StatelessCheck 064public class FallThroughCheck extends AbstractCheck { 065 066 /** 067 * A key is pointing to the warning message text in "messages.properties" file. 068 */ 069 public static final String MSG_FALL_THROUGH = "fall.through"; 070 071 /** 072 * A key is pointing to the warning message text in "messages.properties" file. 073 */ 074 public static final String MSG_FALL_THROUGH_LAST = "fall.through.last"; 075 076 /** Control whether the last case group must be checked. */ 077 private boolean checkLastCaseGroup; 078 079 /** 080 * Define the RegExp to match the relief comment that suppresses 081 * the warning about a fall through. 082 */ 083 private Pattern reliefPattern = Pattern.compile("falls?[ -]?thr(u|ough)"); 084 085 /** 086 * Creates a new {@code FallThroughCheck} instance. 087 */ 088 public FallThroughCheck() { 089 // no code by default 090 } 091 092 @Override 093 public int[] getDefaultTokens() { 094 return getRequiredTokens(); 095 } 096 097 @Override 098 public int[] getRequiredTokens() { 099 return new int[] {TokenTypes.CASE_GROUP}; 100 } 101 102 @Override 103 public int[] getAcceptableTokens() { 104 return getRequiredTokens(); 105 } 106 107 @Override 108 public boolean isCommentNodesRequired() { 109 return true; 110 } 111 112 /** 113 * Setter to define the RegExp to match the relief comment that suppresses 114 * the warning about a fall through. 115 * 116 * @param pattern 117 * The regular expression pattern. 118 * @since 4.0 119 */ 120 public void setReliefPattern(Pattern pattern) { 121 reliefPattern = pattern; 122 } 123 124 /** 125 * Setter to control whether the last case group must be checked. 126 * 127 * @param value new value of the property. 128 * @since 4.0 129 */ 130 public void setCheckLastCaseGroup(boolean value) { 131 checkLastCaseGroup = value; 132 } 133 134 @Override 135 public void visitToken(DetailAST ast) { 136 final DetailAST nextGroup = ast.getNextSibling(); 137 final boolean isLastGroup = nextGroup.getType() != TokenTypes.CASE_GROUP; 138 if (!isLastGroup || checkLastCaseGroup) { 139 final DetailAST slist = ast.findFirstToken(TokenTypes.SLIST); 140 141 if (slist != null && !CheckUtil.isTerminated(slist) && !hasFallThroughComment(ast)) { 142 if (isLastGroup) { 143 log(ast, MSG_FALL_THROUGH_LAST); 144 } 145 else { 146 log(nextGroup, MSG_FALL_THROUGH); 147 } 148 } 149 } 150 } 151 152 /** 153 * Determines if the fall through case between {@code currentCase} and 154 * {@code nextCase} is relieved by an appropriate comment. 155 * 156 * <p>Handles</p> 157 * <pre> 158 * case 1: 159 * /* FALLTHRU */ case 2: 160 * 161 * switch(i) { 162 * default: 163 * /* FALLTHRU */} 164 * 165 * case 1: 166 * // FALLTHRU 167 * case 2: 168 * 169 * switch(i) { 170 * default: 171 * // FALLTHRU 172 * </pre> 173 * 174 * @param currentCase AST of the case that falls through to the next case. 175 * @return True if a relief comment was found 176 */ 177 private boolean hasFallThroughComment(DetailAST currentCase) { 178 final DetailAST nextSibling = currentCase.getNextSibling(); 179 final DetailAST ast; 180 if (nextSibling.getType() == TokenTypes.CASE_GROUP) { 181 ast = nextSibling.getFirstChild(); 182 } 183 else { 184 ast = currentCase; 185 } 186 return hasReliefComment(ast); 187 } 188 189 /** 190 * Check if there is any fall through comment. 191 * 192 * @param ast ast to check 193 * @return true if relief comment found 194 */ 195 private boolean hasReliefComment(DetailAST ast) { 196 final DetailAST nonCommentAst = CheckUtil.getNextNonCommentAst(ast); 197 boolean result = false; 198 if (nonCommentAst != null) { 199 final int prevLineNumber = nonCommentAst.getPreviousSibling().getLineNo(); 200 result = Stream.iterate(nonCommentAst.getPreviousSibling(), 201 Objects::nonNull, 202 DetailAST::getPreviousSibling) 203 .takeWhile(sibling -> sibling.getLineNo() == prevLineNumber) 204 .map(DetailAST::getFirstChild) 205 .filter(Objects::nonNull) 206 .anyMatch(firstChild -> reliefPattern.matcher(firstChild.getText()).find()); 207 } 208 return result; 209 } 210 211}