001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2016 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.HashMap;
026import java.util.Iterator;
027import java.util.Map;
028import java.util.Optional;
029
030import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
031import com.puppycrawl.tools.checkstyle.api.DetailAST;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.ScopeUtils;
034
035/**
036 * <p>
037 * Ensures that local variables that never get their values changed,
038 * must be declared final.
039 * </p>
040 * <p>
041 * An example of how to configure the check to validate variable definition is:
042 * </p>
043 * <pre>
044 * &lt;module name="FinalLocalVariable"&gt;
045 *     &lt;property name="tokens" value="VARIABLE_DEF"/&gt;
046 * &lt;/module&gt;
047 * </pre>
048 * <p>
049 * By default, this Check skip final validation on
050 *  <a href = "http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2">
051 * Enhanced For-Loop</a>
052 * </p>
053 * <p>
054 * Option 'validateEnhancedForLoopVariable' could be used to make Check to validate even variable
055 *  from Enhanced For Loop.
056 * </p>
057 * <p>
058 * An example of how to configure the check so that it also validates enhanced For Loop Variable is:
059 * </p>
060 * <pre>
061 * &lt;module name="FinalLocalVariable"&gt;
062 *     &lt;property name="tokens" value="VARIABLE_DEF"/&gt;
063 *     &lt;property name="validateEnhancedForLoopVariable" value="true"/&gt;
064 * &lt;/module&gt;
065 * </pre>
066 * <p>Example:</p>
067 * <p>
068 * {@code
069 * for (int number : myNumbers) { // violation
070 *    System.out.println(number);
071 * }
072 * }
073 * </p>
074 * @author k_gibbs, r_auckenthaler
075 * @author Vladislav Lisetskiy
076 */
077public class FinalLocalVariableCheck extends AbstractCheck {
078
079    /**
080     * A key is pointing to the warning message text in "messages.properties"
081     * file.
082     */
083    public static final String MSG_KEY = "final.variable";
084
085    /**
086     * Assign operator types.
087     */
088    private static final int[] ASSIGN_OPERATOR_TYPES = {
089        TokenTypes.POST_INC,
090        TokenTypes.POST_DEC,
091        TokenTypes.ASSIGN,
092        TokenTypes.PLUS_ASSIGN,
093        TokenTypes.MINUS_ASSIGN,
094        TokenTypes.STAR_ASSIGN,
095        TokenTypes.DIV_ASSIGN,
096        TokenTypes.MOD_ASSIGN,
097        TokenTypes.SR_ASSIGN,
098        TokenTypes.BSR_ASSIGN,
099        TokenTypes.SL_ASSIGN,
100        TokenTypes.BAND_ASSIGN,
101        TokenTypes.BXOR_ASSIGN,
102        TokenTypes.BOR_ASSIGN,
103        TokenTypes.INC,
104        TokenTypes.DEC,
105    };
106
107    /**
108     * Loop types.
109     */
110    private static final int[] LOOP_TYPES = {
111        TokenTypes.LITERAL_FOR,
112        TokenTypes.LITERAL_WHILE,
113        TokenTypes.LITERAL_DO,
114    };
115
116    /** Scope Deque. */
117    private final Deque<ScopeData> scopeStack = new ArrayDeque<>();
118
119    /** Uninitialized variables of previous scope. */
120    private final Deque<Deque<DetailAST>> prevScopeUninitializedVariables =
121            new ArrayDeque<>();
122
123    /** Controls whether to check enhanced for-loop variable. */
124    private boolean validateEnhancedForLoopVariable;
125
126    static {
127        // Array sorting for binary search
128        Arrays.sort(ASSIGN_OPERATOR_TYPES);
129        Arrays.sort(LOOP_TYPES);
130    }
131
132    /**
133     * Whether to check enhanced for-loop variable or not.
134     * @param validateEnhancedForLoopVariable whether to check for-loop variable
135     */
136    public final void setValidateEnhancedForLoopVariable(boolean validateEnhancedForLoopVariable) {
137        this.validateEnhancedForLoopVariable = validateEnhancedForLoopVariable;
138    }
139
140    @Override
141    public int[] getRequiredTokens() {
142        return new int[] {
143            TokenTypes.IDENT,
144            TokenTypes.CTOR_DEF,
145            TokenTypes.METHOD_DEF,
146            TokenTypes.SLIST,
147            TokenTypes.OBJBLOCK,
148        };
149    }
150
151    @Override
152    public int[] getDefaultTokens() {
153        return new int[] {
154            TokenTypes.IDENT,
155            TokenTypes.CTOR_DEF,
156            TokenTypes.METHOD_DEF,
157            TokenTypes.SLIST,
158            TokenTypes.OBJBLOCK,
159            TokenTypes.VARIABLE_DEF,
160        };
161    }
162
163    @Override
164    public int[] getAcceptableTokens() {
165        return new int[] {
166            TokenTypes.IDENT,
167            TokenTypes.CTOR_DEF,
168            TokenTypes.METHOD_DEF,
169            TokenTypes.SLIST,
170            TokenTypes.OBJBLOCK,
171            TokenTypes.VARIABLE_DEF,
172            TokenTypes.PARAMETER_DEF,
173        };
174    }
175
176    @Override
177    public void visitToken(DetailAST ast) {
178        switch (ast.getType()) {
179            case TokenTypes.OBJBLOCK:
180            case TokenTypes.METHOD_DEF:
181            case TokenTypes.CTOR_DEF:
182                scopeStack.push(new ScopeData());
183                break;
184            case TokenTypes.SLIST:
185                if (ast.getParent().getType() != TokenTypes.CASE_GROUP
186                    || ast.getParent().getParent().findFirstToken(TokenTypes.CASE_GROUP)
187                    == ast.getParent()) {
188                    storePrevScopeUninitializedVariableData();
189                    scopeStack.push(new ScopeData());
190                }
191                break;
192            case TokenTypes.PARAMETER_DEF:
193                if (!isInLambda(ast)
194                        && !ast.branchContains(TokenTypes.FINAL)
195                        && !isInAbstractOrNativeMethod(ast)
196                        && !ScopeUtils.isInInterfaceBlock(ast)) {
197                    insertParameter(ast);
198                }
199                break;
200            case TokenTypes.VARIABLE_DEF:
201                if (ast.getParent().getType() != TokenTypes.OBJBLOCK
202                        && !ast.branchContains(TokenTypes.FINAL)
203                        && !isVariableInForInit(ast)
204                        && shouldCheckEnhancedForLoopVariable(ast)) {
205                    insertVariable(ast);
206                }
207                break;
208
209            case TokenTypes.IDENT:
210                final int parentType = ast.getParent().getType();
211                if (isAssignOperator(parentType) && isFirstChild(ast)) {
212                    final Optional<FinalVariableCandidate> candidate = getFinalCandidate(ast);
213                    if (candidate.isPresent()) {
214                        determineAssignmentConditions(ast, candidate.get());
215                    }
216                    removeFinalVariableCandidateFromStack(ast);
217                }
218                break;
219
220            default:
221                throw new IllegalStateException("Incorrect token type");
222        }
223    }
224
225    @Override
226    public void leaveToken(DetailAST ast) {
227        Map<String, FinalVariableCandidate> scope = null;
228        switch (ast.getType()) {
229            case TokenTypes.OBJBLOCK:
230            case TokenTypes.CTOR_DEF:
231            case TokenTypes.METHOD_DEF:
232                scope = scopeStack.pop().scope;
233                break;
234            case TokenTypes.SLIST:
235                final Deque<DetailAST> prevScopeUnitializedVariableData =
236                    prevScopeUninitializedVariables.peek();
237                if (ast.getParent().getType() != TokenTypes.CASE_GROUP
238                    || findLastChildWhichContainsSpecifiedToken(ast.getParent().getParent(),
239                            TokenTypes.CASE_GROUP, TokenTypes.SLIST) == ast.getParent()) {
240                    scope = scopeStack.pop().scope;
241                    prevScopeUninitializedVariables.pop();
242                }
243                final DetailAST parent = ast.getParent();
244                if (shouldUpdateUninitializedVariables(parent)) {
245                    updateUninitializedVariables(prevScopeUnitializedVariableData);
246                }
247                break;
248            default:
249                // do nothing
250        }
251        if (scope != null) {
252            for (FinalVariableCandidate candidate : scope.values()) {
253                final DetailAST ident = candidate.variableIdent;
254                log(ident.getLineNo(), ident.getColumnNo(), MSG_KEY, ident.getText());
255            }
256        }
257    }
258
259    /**
260     * Determines identifier assignment conditions (assigned or already assigned).
261     * @param ident identifier.
262     * @param candidate final local variable candidate.
263     */
264    private static void determineAssignmentConditions(DetailAST ident,
265                                                      FinalVariableCandidate candidate) {
266        if (candidate.assigned) {
267            if (!isInSpecificCodeBlock(ident, TokenTypes.LITERAL_ELSE)
268                    && !isInSpecificCodeBlock(ident, TokenTypes.CASE_GROUP)) {
269                candidate.alreadyAssigned = true;
270            }
271        }
272        else {
273            candidate.assigned = true;
274        }
275    }
276
277    /**
278     * Checks whether the scope of a node is restricted to a specific code block.
279     * @param node node.
280     * @param blockType block type.
281     * @return true if the scope of a node is restricted to a specific code block.
282     */
283    private static boolean isInSpecificCodeBlock(DetailAST node, int blockType) {
284        boolean returnValue = false;
285        for (DetailAST token = node.getParent(); token != null; token = token.getParent()) {
286            final int type = token.getType();
287            if (type == blockType) {
288                returnValue = true;
289                break;
290            }
291        }
292        return returnValue;
293    }
294
295    /**
296     * Gets final variable candidate for ast.
297     * @param ast ast.
298     * @return Optional of {@link FinalVariableCandidate} for ast from scopeStack.
299     */
300    private Optional<FinalVariableCandidate> getFinalCandidate(DetailAST ast) {
301        Optional<FinalVariableCandidate> result = Optional.empty();
302        final Iterator<ScopeData> iterator = scopeStack.descendingIterator();
303        while (iterator.hasNext() && !result.isPresent()) {
304            final ScopeData scopeData = iterator.next();
305            result = scopeData.findFinalVariableCandidateForAst(ast);
306        }
307        return result;
308    }
309
310    /**
311     * Store un-initialized variables in a temporary stack for future use.
312     */
313    private void storePrevScopeUninitializedVariableData() {
314        final ScopeData scopeData = scopeStack.peek();
315        final Deque<DetailAST> prevScopeUnitializedVariableData =
316                new ArrayDeque<>();
317        for (DetailAST variable : scopeData.uninitializedVariables) {
318            prevScopeUnitializedVariableData.push(variable);
319        }
320        prevScopeUninitializedVariables.push(prevScopeUnitializedVariableData);
321    }
322
323    /**
324     * Update current scope data uninitialized variable according to the previous scope data.
325     * @param prevScopeUnitializedVariableData variable for previous stack of uninitialized
326     *     variables
327     */
328    private void updateUninitializedVariables(Deque<DetailAST> prevScopeUnitializedVariableData) {
329        // Check for only previous scope
330        for (DetailAST variable : prevScopeUnitializedVariableData) {
331            for (ScopeData scopeData : scopeStack) {
332                final FinalVariableCandidate candidate = scopeData.scope.get(variable.getText());
333                DetailAST storedVariable = null;
334                if (candidate != null) {
335                    storedVariable = candidate.variableIdent;
336                }
337                if (storedVariable != null && isSameVariables(storedVariable, variable)
338                        && !scopeData.uninitializedVariables.contains(storedVariable)) {
339                    scopeData.uninitializedVariables.push(variable);
340                }
341            }
342        }
343        // Check for rest of the scope
344        for (Deque<DetailAST> unitializedVariableData : prevScopeUninitializedVariables) {
345            for (DetailAST variable : unitializedVariableData) {
346                for (ScopeData scopeData : scopeStack) {
347                    final FinalVariableCandidate candidate =
348                        scopeData.scope.get(variable.getText());
349                    DetailAST storedVariable = null;
350                    if (candidate != null) {
351                        storedVariable = candidate.variableIdent;
352                    }
353                    if (storedVariable != null
354                            && isSameVariables(storedVariable, variable)
355                            && !scopeData.uninitializedVariables.contains(storedVariable)) {
356                        scopeData.uninitializedVariables.push(variable);
357                    }
358                }
359            }
360        }
361    }
362
363    /**
364     * If token is LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, or LITERAL_ELSE, then do not
365     * update the uninitialized variables.
366     * @param ast token to be checked
367     * @return true if should be updated, else false
368     */
369    private boolean shouldUpdateUninitializedVariables(DetailAST ast) {
370        return ast.getType() != TokenTypes.LITERAL_TRY
371                && ast.getType() != TokenTypes.LITERAL_CATCH
372                && ast.getType() != TokenTypes.LITERAL_FINALLY
373                && ast.getType() != TokenTypes.LITERAL_ELSE;
374    }
375
376    /**
377     * Returns the last child token that makes a specified type and contains containType in
378     * its branch.
379     * @param ast token to be tested
380     * @param childType the token type to match
381     * @param containType the token type which has to be present in the branch
382     * @return the matching token, or null if no match
383     */
384    public DetailAST findLastChildWhichContainsSpecifiedToken(DetailAST ast, int childType,
385                                                              int containType) {
386        DetailAST returnValue = null;
387        for (DetailAST astIterator = ast.getFirstChild(); astIterator != null;
388                astIterator = astIterator.getNextSibling()) {
389            if (astIterator.getType() == childType && astIterator.branchContains(containType)) {
390                returnValue = astIterator;
391            }
392        }
393        return returnValue;
394    }
395
396    /**
397     * Determines whether enhanced for-loop variable should be checked or not.
398     * @param ast The ast to compare.
399     * @return true if enhanced for-loop variable should be checked.
400     */
401    private boolean shouldCheckEnhancedForLoopVariable(DetailAST ast) {
402        return validateEnhancedForLoopVariable
403                || ast.getParent().getType() != TokenTypes.FOR_EACH_CLAUSE;
404    }
405
406    /**
407     * Insert a parameter at the topmost scope stack.
408     * @param ast the variable to insert.
409     */
410    private void insertParameter(DetailAST ast) {
411        final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope;
412        final DetailAST astNode = ast.findFirstToken(TokenTypes.IDENT);
413        scope.put(astNode.getText(), new FinalVariableCandidate(astNode));
414    }
415
416    /**
417     * Insert a variable at the topmost scope stack.
418     * @param ast the variable to insert.
419     */
420    private void insertVariable(DetailAST ast) {
421        final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope;
422        final DetailAST astNode = ast.findFirstToken(TokenTypes.IDENT);
423        scope.put(astNode.getText(), new FinalVariableCandidate(astNode));
424        if (!isInitialized(astNode)) {
425            scopeStack.peek().uninitializedVariables.add(astNode);
426        }
427    }
428
429    /**
430     * Check if VARIABLE_DEF is initialized or not.
431     * @param ast VARIABLE_DEF to be checked
432     * @return true if initialized
433     */
434    private static boolean isInitialized(DetailAST ast) {
435        return ast.getParent().getLastChild().getType() == TokenTypes.ASSIGN;
436    }
437
438    /**
439     * Whether the ast is the first child of its parent.
440     * @param ast the ast to check.
441     * @return true if the ast is the first child of its parent.
442     */
443    private static boolean isFirstChild(DetailAST ast) {
444        return ast.getPreviousSibling() == null;
445    }
446
447    /**
448     * Removes the final variable candidate from the Stack.
449     * @param ast variable to remove.
450     */
451    private void removeFinalVariableCandidateFromStack(DetailAST ast) {
452        final Iterator<ScopeData> iterator = scopeStack.descendingIterator();
453        while (iterator.hasNext()) {
454            final ScopeData scopeData = iterator.next();
455            final Map<String, FinalVariableCandidate> scope = scopeData.scope;
456            final FinalVariableCandidate candidate = scope.get(ast.getText());
457            DetailAST storedVariable = null;
458            if (candidate != null) {
459                storedVariable = candidate.variableIdent;
460            }
461            if (storedVariable != null && isSameVariables(storedVariable, ast)) {
462                if (shouldRemoveFinalVariableCandidate(scopeData, ast)) {
463                    scope.remove(ast.getText());
464                }
465                break;
466            }
467        }
468    }
469
470    /**
471     * Whether the final variable candidate should be removed from the list of final local variable
472     * candidates.
473     * @param scopeData the scope data of the variable.
474     * @param ast the variable ast.
475     * @return true, if the variable should be removed.
476     */
477    private static boolean shouldRemoveFinalVariableCandidate(ScopeData scopeData, DetailAST ast) {
478        boolean shouldRemove = true;
479        for (DetailAST variable : scopeData.uninitializedVariables) {
480            if (variable.getText().equals(ast.getText())) {
481                // if the variable is declared outside the loop and initialized inside
482                // the loop, then it cannot be declared final, as it can be initialized
483                // more than once in this case
484                if (isInTheSameLoop(variable, ast) || !isUseOfExternalVariableInsideLoop(ast)) {
485                    final FinalVariableCandidate candidate = scopeData.scope.get(ast.getText());
486                    shouldRemove = candidate.alreadyAssigned;
487                }
488                scopeData.uninitializedVariables.remove(variable);
489                break;
490            }
491        }
492        return shouldRemove;
493    }
494
495    /**
496     * Checks whether a variable which is declared outside loop is used inside loop.
497     * For example:
498     * <p>
499     * {@code
500     * int x;
501     * for (int i = 0, j = 0; i < j; i++) {
502     *     x = 5;
503     * }
504     * }
505     * </p>
506     * @param variable variable.
507     * @return true if a variable which is declared ouside loop is used inside loop.
508     */
509    private static boolean isUseOfExternalVariableInsideLoop(DetailAST variable) {
510        DetailAST loop2 = variable.getParent();
511        while (loop2 != null
512            && !isLoopAst(loop2.getType())) {
513            loop2 = loop2.getParent();
514        }
515        return loop2 != null;
516    }
517
518    /**
519     * Is Arithmetic operator.
520     * @param parentType token AST
521     * @return true is token type is in arithmetic operator
522     */
523    private static boolean isAssignOperator(int parentType) {
524        return Arrays.binarySearch(ASSIGN_OPERATOR_TYPES, parentType) >= 0;
525    }
526
527    /**
528     * Checks if current variable is defined in
529     *  {@link TokenTypes#FOR_INIT for-loop init}, e.g.:
530     * <p>
531     * {@code
532     * for (int i = 0, j = 0; i < j; i++) { . . . }
533     * }
534     * </p>
535     * {@code i, j} are defined in {@link TokenTypes#FOR_INIT for-loop init}
536     * @param variableDef variable definition node.
537     * @return true if variable is defined in {@link TokenTypes#FOR_INIT for-loop init}
538     */
539    private static boolean isVariableInForInit(DetailAST variableDef) {
540        return variableDef.getParent().getType() == TokenTypes.FOR_INIT;
541    }
542
543    /**
544     * Determines whether an AST is a descendant of an abstract or native method.
545     * @param ast the AST to check.
546     * @return true if ast is a descendant of an abstract or native method.
547     */
548    private static boolean isInAbstractOrNativeMethod(DetailAST ast) {
549        boolean abstractOrNative = false;
550        DetailAST parent = ast.getParent();
551        while (parent != null && !abstractOrNative) {
552            if (parent.getType() == TokenTypes.METHOD_DEF) {
553                final DetailAST modifiers =
554                    parent.findFirstToken(TokenTypes.MODIFIERS);
555                abstractOrNative = modifiers.branchContains(TokenTypes.ABSTRACT)
556                        || modifiers.branchContains(TokenTypes.LITERAL_NATIVE);
557            }
558            parent = parent.getParent();
559        }
560        return abstractOrNative;
561    }
562
563    /**
564     * Check if current param is lambda's param.
565     * @param paramDef {@link TokenTypes#PARAMETER_DEF parameter def}.
566     * @return true if current param is lambda's param.
567     */
568    private static boolean isInLambda(DetailAST paramDef) {
569        return paramDef.getParent().getParent().getType() == TokenTypes.LAMBDA;
570    }
571
572    /**
573     * Find the Class, Constructor, Enum, Method, or Field in which it is defined.
574     * @param ast Variable for which we want to find the scope in which it is defined
575     * @return ast The Class or Constructor or Method in which it is defined.
576     */
577    private static DetailAST findFirstUpperNamedBlock(DetailAST ast) {
578        DetailAST astTraverse = ast;
579        while (astTraverse.getType() != TokenTypes.METHOD_DEF
580                && astTraverse.getType() != TokenTypes.CLASS_DEF
581                && astTraverse.getType() != TokenTypes.ENUM_DEF
582                && astTraverse.getType() != TokenTypes.CTOR_DEF
583                && !ScopeUtils.isClassFieldDef(astTraverse)) {
584            astTraverse = astTraverse.getParent();
585        }
586        return astTraverse;
587    }
588
589    /**
590     * Check if both the Variables are same.
591     * @param ast1 Variable to compare
592     * @param ast2 Variable to compare
593     * @return true if both the variables are same, otherwise false
594     */
595    private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) {
596        final DetailAST classOrMethodOfAst1 =
597            findFirstUpperNamedBlock(ast1);
598        final DetailAST classOrMethodOfAst2 =
599            findFirstUpperNamedBlock(ast2);
600        return classOrMethodOfAst1 == classOrMethodOfAst2;
601    }
602
603    /**
604     * Check if both the variables are in the same loop.
605     * @param ast1 variable to compare.
606     * @param ast2 variable to compare.
607     * @return true if both the variables are in the same loop.
608     */
609    private static boolean isInTheSameLoop(DetailAST ast1, DetailAST ast2) {
610        DetailAST loop1 = ast1.getParent();
611        while (loop1 != null && !isLoopAst(loop1.getType())) {
612            loop1 = loop1.getParent();
613        }
614        DetailAST loop2 = ast2.getParent();
615        while (loop2 != null && !isLoopAst(loop2.getType())) {
616            loop2 = loop2.getParent();
617        }
618        return loop1 != null && loop1 == loop2;
619    }
620
621    /**
622     * Checks whether the ast is a loop.
623     * @param ast the ast to check.
624     * @return true if the ast is a loop.
625     */
626    private static boolean isLoopAst(int ast) {
627        return Arrays.binarySearch(LOOP_TYPES, ast) >= 0;
628    }
629
630    /**
631     * Holder for the scope data.
632     */
633    private static class ScopeData {
634        /** Contains variable definitions. */
635        private final Map<String, FinalVariableCandidate> scope = new HashMap<>();
636
637        /** Contains definitions of uninitialized variables. */
638        private final Deque<DetailAST> uninitializedVariables = new ArrayDeque<>();
639
640        /**
641         * Searches for final local variable candidate for ast in the scope.
642         * @param ast ast.
643         * @return Optional of {@link FinalVariableCandidate}.
644         */
645        public Optional<FinalVariableCandidate> findFinalVariableCandidateForAst(DetailAST ast) {
646            Optional<FinalVariableCandidate> result = Optional.empty();
647            DetailAST storedVariable = null;
648            final Optional<FinalVariableCandidate> candidate =
649                Optional.ofNullable(scope.get(ast.getText()));
650            if (candidate.isPresent()) {
651                storedVariable = candidate.get().variableIdent;
652            }
653            if (storedVariable != null && isSameVariables(storedVariable, ast)) {
654                result = candidate;
655            }
656            return result;
657        }
658    }
659
660    /**Represents information about final local variable candidate. */
661    private static class FinalVariableCandidate {
662        /** Identifier token. */
663        private final DetailAST variableIdent;
664        /** Whether the variable is assigned. */
665        private boolean assigned;
666        /** Whether the variable is already assigned. */
667        private boolean alreadyAssigned;
668
669        /**
670         * Creates new instance.
671         * @param variableIdent variable identifier.
672         */
673        FinalVariableCandidate(DetailAST variableIdent) {
674            this.variableIdent = variableIdent;
675        }
676    }
677}