001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 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.ArrayDeque; 023import java.util.Arrays; 024import java.util.Deque; 025import java.util.HashSet; 026import java.util.LinkedList; 027import java.util.List; 028import java.util.Set; 029import java.util.stream.Collectors; 030 031import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 032import com.puppycrawl.tools.checkstyle.api.DetailAST; 033import com.puppycrawl.tools.checkstyle.api.TokenTypes; 034 035/** 036 * Check for ensuring that for loop control variables are not modified 037 * inside the for block. An example is: 038 * 039 * <pre> 040 * {@code 041 * for (int i = 0; i < 1; i++) { 042 * i++;//violation 043 * } 044 * } 045 * </pre> 046 * Rationale: If the control variable is modified inside the loop 047 * body, the program flow becomes more difficult to follow.<br> 048 * See <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14"> 049 * FOR statement</a> specification for more details. 050 * <p>Examples:</p> 051 * 052 * <pre> 053 * <module name="ModifiedControlVariable"> 054 * </module> 055 * </pre> 056 * 057 * <p>Such loop would be suppressed: 058 * 059 * <pre> 060 * {@code 061 * for(int i=0; i < 10;) { 062 * i++; 063 * } 064 * } 065 * </pre> 066 * 067 * <p> 068 * By default, This Check validates 069 * <a href = "http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2"> 070 * Enhanced For-Loop</a>. 071 * </p> 072 * <p> 073 * Option 'skipEnhancedForLoopVariable' could be used to skip check of variable 074 * from Enhanced For Loop. 075 * </p> 076 * <p> 077 * An example of how to configure the check so that it skips enhanced For Loop Variable is: 078 * </p> 079 * <pre> 080 * <module name="ModifiedControlVariable"> 081 * <property name="skipEnhancedForLoopVariable" value="true"/> 082 * </module> 083 * </pre> 084 * <p>Example:</p> 085 * 086 * <pre> 087 * {@code 088 * for (String line: lines) { 089 * line = line.trim(); // it will skip this violation 090 * } 091 * } 092 * </pre> 093 * 094 * 095 * @author Daniel Grenner 096 * @author <a href="mailto:piotr.listkiewicz@gmail.com">liscju</a> 097 */ 098public final class ModifiedControlVariableCheck extends AbstractCheck { 099 100 /** 101 * A key is pointing to the warning message text in "messages.properties" 102 * file. 103 */ 104 public static final String MSG_KEY = "modified.control.variable"; 105 106 /** 107 * Message thrown with IllegalStateException. 108 */ 109 private static final String ILLEGAL_TYPE_OF_TOKEN = "Illegal type of token: "; 110 111 /** Operations which can change control variable in update part of the loop. */ 112 private static final Set<Integer> MUTATION_OPERATIONS = 113 Arrays.stream(new Integer[] { 114 TokenTypes.POST_INC, 115 TokenTypes.POST_DEC, 116 TokenTypes.DEC, 117 TokenTypes.INC, 118 TokenTypes.ASSIGN, 119 }).collect(Collectors.toSet()); 120 121 /** Stack of block parameters. */ 122 private final Deque<Deque<String>> variableStack = new ArrayDeque<>(); 123 124 /** Controls whether to skip enhanced for-loop variable. */ 125 private boolean skipEnhancedForLoopVariable; 126 127 /** 128 * Whether to skip enhanced for-loop variable or not. 129 * @param skipEnhancedForLoopVariable whether to skip enhanced for-loop variable 130 */ 131 public void setSkipEnhancedForLoopVariable(boolean skipEnhancedForLoopVariable) { 132 this.skipEnhancedForLoopVariable = skipEnhancedForLoopVariable; 133 } 134 135 @Override 136 public int[] getDefaultTokens() { 137 return getAcceptableTokens(); 138 } 139 140 @Override 141 public int[] getRequiredTokens() { 142 return getAcceptableTokens(); 143 } 144 145 @Override 146 public int[] getAcceptableTokens() { 147 return new int[] { 148 TokenTypes.OBJBLOCK, 149 TokenTypes.LITERAL_FOR, 150 TokenTypes.FOR_ITERATOR, 151 TokenTypes.FOR_EACH_CLAUSE, 152 TokenTypes.ASSIGN, 153 TokenTypes.PLUS_ASSIGN, 154 TokenTypes.MINUS_ASSIGN, 155 TokenTypes.STAR_ASSIGN, 156 TokenTypes.DIV_ASSIGN, 157 TokenTypes.MOD_ASSIGN, 158 TokenTypes.SR_ASSIGN, 159 TokenTypes.BSR_ASSIGN, 160 TokenTypes.SL_ASSIGN, 161 TokenTypes.BAND_ASSIGN, 162 TokenTypes.BXOR_ASSIGN, 163 TokenTypes.BOR_ASSIGN, 164 TokenTypes.INC, 165 TokenTypes.POST_INC, 166 TokenTypes.DEC, 167 TokenTypes.POST_DEC, 168 }; 169 } 170 171 @Override 172 public void beginTree(DetailAST rootAST) { 173 // clear data 174 variableStack.clear(); 175 } 176 177 @Override 178 public void visitToken(DetailAST ast) { 179 switch (ast.getType()) { 180 case TokenTypes.OBJBLOCK: 181 enterBlock(); 182 break; 183 case TokenTypes.LITERAL_FOR: 184 case TokenTypes.FOR_ITERATOR: 185 case TokenTypes.FOR_EACH_CLAUSE: 186 //we need that Tokens only at leaveToken() 187 break; 188 case TokenTypes.ASSIGN: 189 case TokenTypes.PLUS_ASSIGN: 190 case TokenTypes.MINUS_ASSIGN: 191 case TokenTypes.STAR_ASSIGN: 192 case TokenTypes.DIV_ASSIGN: 193 case TokenTypes.MOD_ASSIGN: 194 case TokenTypes.SR_ASSIGN: 195 case TokenTypes.BSR_ASSIGN: 196 case TokenTypes.SL_ASSIGN: 197 case TokenTypes.BAND_ASSIGN: 198 case TokenTypes.BXOR_ASSIGN: 199 case TokenTypes.BOR_ASSIGN: 200 case TokenTypes.INC: 201 case TokenTypes.POST_INC: 202 case TokenTypes.DEC: 203 case TokenTypes.POST_DEC: 204 checkIdent(ast); 205 break; 206 default: 207 throw new IllegalStateException(ILLEGAL_TYPE_OF_TOKEN + ast); 208 } 209 } 210 211 @Override 212 public void leaveToken(DetailAST ast) { 213 switch (ast.getType()) { 214 case TokenTypes.FOR_ITERATOR: 215 leaveForIter(ast.getParent()); 216 break; 217 case TokenTypes.FOR_EACH_CLAUSE: 218 if (!skipEnhancedForLoopVariable) { 219 final DetailAST paramDef = ast.findFirstToken(TokenTypes.VARIABLE_DEF); 220 leaveForEach(paramDef); 221 } 222 break; 223 case TokenTypes.LITERAL_FOR: 224 if (!getCurrentVariables().isEmpty()) { 225 leaveForDef(ast); 226 } 227 break; 228 case TokenTypes.OBJBLOCK: 229 exitBlock(); 230 break; 231 case TokenTypes.ASSIGN: 232 case TokenTypes.PLUS_ASSIGN: 233 case TokenTypes.MINUS_ASSIGN: 234 case TokenTypes.STAR_ASSIGN: 235 case TokenTypes.DIV_ASSIGN: 236 case TokenTypes.MOD_ASSIGN: 237 case TokenTypes.SR_ASSIGN: 238 case TokenTypes.BSR_ASSIGN: 239 case TokenTypes.SL_ASSIGN: 240 case TokenTypes.BAND_ASSIGN: 241 case TokenTypes.BXOR_ASSIGN: 242 case TokenTypes.BOR_ASSIGN: 243 case TokenTypes.INC: 244 case TokenTypes.POST_INC: 245 case TokenTypes.DEC: 246 case TokenTypes.POST_DEC: 247 //we need that Tokens only at visitToken() 248 break; 249 default: 250 throw new IllegalStateException(ILLEGAL_TYPE_OF_TOKEN + ast); 251 } 252 } 253 254 /** 255 * Enters an inner class, which requires a new variable set. 256 */ 257 private void enterBlock() { 258 variableStack.push(new ArrayDeque<>()); 259 } 260 261 /** 262 * Leave an inner class, so restore variable set. 263 */ 264 private void exitBlock() { 265 variableStack.pop(); 266 } 267 268 /** 269 * Get current variable stack. 270 * @return current variable stack 271 */ 272 private Deque<String> getCurrentVariables() { 273 return variableStack.peek(); 274 } 275 276 /** 277 * Check if ident is parameter. 278 * @param ast ident to check. 279 */ 280 private void checkIdent(DetailAST ast) { 281 final Deque<String> currentVariables = getCurrentVariables(); 282 if (currentVariables != null && !currentVariables.isEmpty()) { 283 final DetailAST identAST = ast.getFirstChild(); 284 285 if (identAST != null && identAST.getType() == TokenTypes.IDENT 286 && getCurrentVariables().contains(identAST.getText())) { 287 log(ast.getLineNo(), ast.getColumnNo(), 288 MSG_KEY, identAST.getText()); 289 } 290 } 291 } 292 293 /** 294 * Push current variables to the stack. 295 * @param ast a for definition. 296 */ 297 private void leaveForIter(DetailAST ast) { 298 final Set<String> variablesToPutInScope = getVariablesManagedByForLoop(ast); 299 for (String variableName : variablesToPutInScope) { 300 getCurrentVariables().push(variableName); 301 } 302 } 303 304 /** 305 * Determines which variable are specific to for loop and should not be 306 * change by inner loop body. 307 * @param ast For Loop 308 * @return Set of Variable Name which are managed by for 309 */ 310 private static Set<String> getVariablesManagedByForLoop(DetailAST ast) { 311 final Set<String> initializedVariables = getForInitVariables(ast); 312 final Set<String> iteratingVariables = getForIteratorVariables(ast); 313 return initializedVariables.stream().filter(iteratingVariables::contains) 314 .collect(Collectors.toSet()); 315 } 316 317 /** 318 * Push current variables to the stack. 319 * @param paramDef a for-each clause variable 320 */ 321 private void leaveForEach(DetailAST paramDef) { 322 final DetailAST paramName = paramDef.findFirstToken(TokenTypes.IDENT); 323 getCurrentVariables().push(paramName.getText()); 324 } 325 326 /** 327 * Pops the variables from the stack. 328 * @param ast a for definition. 329 */ 330 private void leaveForDef(DetailAST ast) { 331 final DetailAST forInitAST = ast.findFirstToken(TokenTypes.FOR_INIT); 332 if (forInitAST == null) { 333 if (!skipEnhancedForLoopVariable) { 334 // this is for-each loop, just pop variables 335 getCurrentVariables().pop(); 336 } 337 } 338 else { 339 final Set<String> variablesManagedByForLoop = getVariablesManagedByForLoop(ast); 340 popCurrentVariables(variablesManagedByForLoop.size()); 341 } 342 } 343 344 /** 345 * Pops given number of variables from currentVariables. 346 * @param count Count of variables to be popped from currentVariables 347 */ 348 private void popCurrentVariables(int count) { 349 for (int i = 0; i < count; i++) { 350 getCurrentVariables().pop(); 351 } 352 } 353 354 /** 355 * Get all variables initialized In init part of for loop. 356 * @param ast for loop token 357 * @return set of variables initialized in for loop 358 */ 359 private static Set<String> getForInitVariables(DetailAST ast) { 360 final Set<String> initializedVariables = new HashSet<>(); 361 final DetailAST forInitAST = ast.findFirstToken(TokenTypes.FOR_INIT); 362 363 for (DetailAST parameterDefAST = forInitAST.findFirstToken(TokenTypes.VARIABLE_DEF); 364 parameterDefAST != null; 365 parameterDefAST = parameterDefAST.getNextSibling()) { 366 if (parameterDefAST.getType() == TokenTypes.VARIABLE_DEF) { 367 final DetailAST param = 368 parameterDefAST.findFirstToken(TokenTypes.IDENT); 369 370 initializedVariables.add(param.getText()); 371 } 372 } 373 return initializedVariables; 374 } 375 376 /** 377 * Get all variables which for loop iterating part change in every loop. 378 * @param ast for loop literal(TokenTypes.LITERAL_FOR) 379 * @return names of variables change in iterating part of for 380 */ 381 private static Set<String> getForIteratorVariables(DetailAST ast) { 382 final Set<String> iteratorVariables = new HashSet<>(); 383 final DetailAST forIteratorAST = ast.findFirstToken(TokenTypes.FOR_ITERATOR); 384 final DetailAST forUpdateListAST = forIteratorAST.findFirstToken(TokenTypes.ELIST); 385 386 findChildrenOfExpressionType(forUpdateListAST).stream() 387 .filter(iteratingExpressionAST -> { 388 return MUTATION_OPERATIONS.contains(iteratingExpressionAST.getType()); 389 }).forEach(iteratingExpressionAST -> { 390 final DetailAST oneVariableOperatorChild = iteratingExpressionAST.getFirstChild(); 391 if (oneVariableOperatorChild.getType() == TokenTypes.IDENT) { 392 iteratorVariables.add(oneVariableOperatorChild.getText()); 393 } 394 }); 395 396 return iteratorVariables; 397 } 398 399 /** 400 * Find all child of given AST of type TokenType.EXPR 401 * @param ast parent of expressions to find 402 * @return all child of given ast 403 */ 404 private static List<DetailAST> findChildrenOfExpressionType(DetailAST ast) { 405 final List<DetailAST> foundExpressions = new LinkedList<>(); 406 if (ast != null) { 407 for (DetailAST iteratingExpressionAST = ast.findFirstToken(TokenTypes.EXPR); 408 iteratingExpressionAST != null; 409 iteratingExpressionAST = iteratingExpressionAST.getNextSibling()) { 410 if (iteratingExpressionAST.getType() == TokenTypes.EXPR) { 411 foundExpressions.add(iteratingExpressionAST.getFirstChild()); 412 } 413 } 414 } 415 return foundExpressions; 416 } 417}