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 &lt; 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 * &lt;module name=&quot;ModifiedControlVariable&quot;&gt;
054 * &lt;/module&gt;
055 * </pre>
056 *
057 * <p>Such loop would be suppressed:
058 *
059 * <pre>
060 * {@code
061 * for(int i=0; i &lt; 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 * &lt;module name="ModifiedControlVariable"&gt;
081 *     &lt;property name="skipEnhancedForLoopVariable" value="true"/&gt;
082 * &lt;/module&gt;
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        variableStack.push(new ArrayDeque<>());
176    }
177
178    @Override
179    public void visitToken(DetailAST ast) {
180        switch (ast.getType()) {
181            case TokenTypes.OBJBLOCK:
182                enterBlock();
183                break;
184            case TokenTypes.LITERAL_FOR:
185            case TokenTypes.FOR_ITERATOR:
186            case TokenTypes.FOR_EACH_CLAUSE:
187                //we need that Tokens only at leaveToken()
188                break;
189            case TokenTypes.ASSIGN:
190            case TokenTypes.PLUS_ASSIGN:
191            case TokenTypes.MINUS_ASSIGN:
192            case TokenTypes.STAR_ASSIGN:
193            case TokenTypes.DIV_ASSIGN:
194            case TokenTypes.MOD_ASSIGN:
195            case TokenTypes.SR_ASSIGN:
196            case TokenTypes.BSR_ASSIGN:
197            case TokenTypes.SL_ASSIGN:
198            case TokenTypes.BAND_ASSIGN:
199            case TokenTypes.BXOR_ASSIGN:
200            case TokenTypes.BOR_ASSIGN:
201            case TokenTypes.INC:
202            case TokenTypes.POST_INC:
203            case TokenTypes.DEC:
204            case TokenTypes.POST_DEC:
205                checkIdent(ast);
206                break;
207            default:
208                throw new IllegalStateException(ILLEGAL_TYPE_OF_TOKEN + ast);
209        }
210    }
211
212    @Override
213    public void leaveToken(DetailAST ast) {
214        switch (ast.getType()) {
215            case TokenTypes.FOR_ITERATOR:
216                leaveForIter(ast.getParent());
217                break;
218            case TokenTypes.FOR_EACH_CLAUSE:
219                if (!skipEnhancedForLoopVariable) {
220                    final DetailAST paramDef = ast.findFirstToken(TokenTypes.VARIABLE_DEF);
221                    leaveForEach(paramDef);
222                }
223                break;
224            case TokenTypes.LITERAL_FOR:
225                if (!getCurrentVariables().isEmpty()) {
226                    leaveForDef(ast);
227                }
228                break;
229            case TokenTypes.OBJBLOCK:
230                exitBlock();
231                break;
232            case TokenTypes.ASSIGN:
233            case TokenTypes.PLUS_ASSIGN:
234            case TokenTypes.MINUS_ASSIGN:
235            case TokenTypes.STAR_ASSIGN:
236            case TokenTypes.DIV_ASSIGN:
237            case TokenTypes.MOD_ASSIGN:
238            case TokenTypes.SR_ASSIGN:
239            case TokenTypes.BSR_ASSIGN:
240            case TokenTypes.SL_ASSIGN:
241            case TokenTypes.BAND_ASSIGN:
242            case TokenTypes.BXOR_ASSIGN:
243            case TokenTypes.BOR_ASSIGN:
244            case TokenTypes.INC:
245            case TokenTypes.POST_INC:
246            case TokenTypes.DEC:
247            case TokenTypes.POST_DEC:
248                //we need that Tokens only at visitToken()
249                break;
250            default:
251                throw new IllegalStateException(ILLEGAL_TYPE_OF_TOKEN + ast);
252        }
253    }
254
255    /**
256     * Enters an inner class, which requires a new variable set.
257     */
258    private void enterBlock() {
259        variableStack.push(new ArrayDeque<>());
260    }
261
262    /**
263     * Leave an inner class, so restore variable set.
264     */
265    private void exitBlock() {
266        variableStack.pop();
267    }
268
269    /**
270     * Get current variable stack.
271     * @return current variable stack
272     */
273    private Deque<String> getCurrentVariables() {
274        return variableStack.peek();
275    }
276
277    /**
278     * Check if ident is parameter.
279     * @param ast ident to check.
280     */
281    private void checkIdent(DetailAST ast) {
282        if (!getCurrentVariables().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            // this is for-each loop, just pop variables
334            getCurrentVariables().pop();
335        }
336        else {
337            final Set<String> variablesManagedByForLoop = getVariablesManagedByForLoop(ast);
338            popCurrentVariables(variablesManagedByForLoop.size());
339        }
340    }
341
342    /**
343     * Pops given number of variables from currentVariables.
344     * @param count Count of variables to be popped from currentVariables
345     */
346    private void popCurrentVariables(int count) {
347        for (int i = 0; i < count; i++) {
348            getCurrentVariables().pop();
349        }
350    }
351
352    /**
353     * Get all variables initialized In init part of for loop.
354     * @param ast for loop token
355     * @return set of variables initialized in for loop
356     */
357    private static Set<String> getForInitVariables(DetailAST ast) {
358        final Set<String> initializedVariables = new HashSet<>();
359        final DetailAST forInitAST = ast.findFirstToken(TokenTypes.FOR_INIT);
360
361        for (DetailAST parameterDefAST = forInitAST.findFirstToken(TokenTypes.VARIABLE_DEF);
362             parameterDefAST != null;
363             parameterDefAST = parameterDefAST.getNextSibling()) {
364            if (parameterDefAST.getType() == TokenTypes.VARIABLE_DEF) {
365                final DetailAST param =
366                        parameterDefAST.findFirstToken(TokenTypes.IDENT);
367
368                initializedVariables.add(param.getText());
369            }
370        }
371        return initializedVariables;
372    }
373
374    /**
375     * Get all variables which for loop iterating part change in every loop.
376     * @param ast for loop literal(TokenTypes.LITERAL_FOR)
377     * @return names of variables change in iterating part of for
378     */
379    private static Set<String> getForIteratorVariables(DetailAST ast) {
380        final Set<String> iteratorVariables = new HashSet<>();
381        final DetailAST forIteratorAST = ast.findFirstToken(TokenTypes.FOR_ITERATOR);
382        final DetailAST forUpdateListAST = forIteratorAST.findFirstToken(TokenTypes.ELIST);
383
384        findChildrenOfExpressionType(forUpdateListAST).stream()
385            .filter(iteratingExpressionAST -> {
386                return MUTATION_OPERATIONS.contains(iteratingExpressionAST.getType());
387            }).forEach(iteratingExpressionAST -> {
388                final DetailAST oneVariableOperatorChild = iteratingExpressionAST.getFirstChild();
389                if (oneVariableOperatorChild.getType() == TokenTypes.IDENT) {
390                    iteratorVariables.add(oneVariableOperatorChild.getText());
391                }
392            });
393
394        return iteratorVariables;
395    }
396
397    /**
398     * Find all child of given AST of type TokenType.EXPR
399     * @param ast parent of expressions to find
400     * @return all child of given ast
401     */
402    private static List<DetailAST> findChildrenOfExpressionType(DetailAST ast) {
403        final List<DetailAST> foundExpressions = new LinkedList<>();
404        if (ast != null) {
405            for (DetailAST iteratingExpressionAST = ast.findFirstToken(TokenTypes.EXPR);
406                 iteratingExpressionAST != null;
407                 iteratingExpressionAST = iteratingExpressionAST.getNextSibling()) {
408                if (iteratingExpressionAST.getType() == TokenTypes.EXPR) {
409                    foundExpressions.add(iteratingExpressionAST.getFirstChild());
410                }
411            }
412        }
413        return foundExpressions;
414    }
415}