View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import java.util.ArrayDeque;
23  import java.util.Collections;
24  import java.util.Deque;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.LinkedHashMap;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Optional;
31  import java.util.Set;
32  
33  import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
34  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
35  import com.puppycrawl.tools.checkstyle.api.DetailAST;
36  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
37  import com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption;
38  import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
39  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
40  
41  /**
42   * <div>
43   * Checks that a local variable is declared and/or assigned, but not used.
44   * Doesn't support
45   * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.30">
46   * pattern variables yet</a>.
47   * Doesn't check
48   * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.12.3">
49   * array components</a> as array
50   * components are classified as different kind of variables by
51   * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/index.html">JLS</a>.
52   * </div>
53   *
54   * @since 9.3
55   */
56  @FileStatefulCheck
57  public class UnusedLocalVariableCheck extends AbstractCheck {
58  
59      /**
60       * A key is pointing to the warning message text in "messages.properties"
61       * file.
62       */
63      public static final String MSG_UNUSED_LOCAL_VARIABLE = "unused.local.var";
64  
65      /**
66       * A key is pointing to the warning message text in "messages.properties"
67       * file.
68       */
69      public static final String MSG_UNUSED_NAMED_LOCAL_VARIABLE = "unused.named.local.var";
70  
71      /**
72       * An array of increment and decrement tokens.
73       */
74      private static final int[] INCREMENT_AND_DECREMENT_TOKENS = {
75          TokenTypes.POST_INC,
76          TokenTypes.POST_DEC,
77          TokenTypes.INC,
78          TokenTypes.DEC,
79      };
80  
81      /**
82       * An array of scope tokens.
83       */
84      private static final int[] SCOPES = {
85          TokenTypes.SLIST,
86          TokenTypes.LITERAL_FOR,
87          TokenTypes.OBJBLOCK,
88      };
89  
90      /**
91       * An array of unacceptable children of ast of type {@link TokenTypes#DOT}.
92       */
93      private static final int[] UNACCEPTABLE_CHILD_OF_DOT = {
94          TokenTypes.DOT,
95          TokenTypes.METHOD_CALL,
96          TokenTypes.LITERAL_NEW,
97          TokenTypes.LITERAL_SUPER,
98          TokenTypes.LITERAL_CLASS,
99          TokenTypes.LITERAL_THIS,
100     };
101 
102     /**
103      * An array of unacceptable parent of ast of type {@link TokenTypes#IDENT}.
104      */
105     private static final int[] UNACCEPTABLE_PARENT_OF_IDENT = {
106         TokenTypes.VARIABLE_DEF,
107         TokenTypes.DOT,
108         TokenTypes.LITERAL_NEW,
109         TokenTypes.PATTERN_VARIABLE_DEF,
110         TokenTypes.METHOD_CALL,
111         TokenTypes.TYPE,
112     };
113 
114     /**
115      * An array of blocks in which local anon inner classes can exist.
116      */
117     private static final int[] ANONYMOUS_CLASS_PARENT_TOKENS = {
118         TokenTypes.METHOD_DEF,
119         TokenTypes.CTOR_DEF,
120         TokenTypes.STATIC_INIT,
121         TokenTypes.INSTANCE_INIT,
122         TokenTypes.COMPACT_CTOR_DEF,
123     };
124 
125     /**
126      * An array of token types that indicate a variable is being used within
127      * an expression involving increment or decrement operators, or within a switch statement.
128      * When a token of one of these types is the parent of an expression, it indicates that the
129      * variable associated with the increment or decrement operation is being used.
130      * Ex:- TokenTypes.LITERAL_SWITCH: Indicates a switch statement. Variables used within the
131      * switch expression are considered to be used
132      */
133     private static final int[] INCREMENT_DECREMENT_VARIABLE_USAGE_TYPES = {
134         TokenTypes.ELIST,
135         TokenTypes.INDEX_OP,
136         TokenTypes.ASSIGN,
137         TokenTypes.LITERAL_SWITCH,
138     };
139 
140     /** Package separator. */
141     private static final String PACKAGE_SEPARATOR = ".";
142 
143     /**
144      * Keeps tracks of the variables declared in file.
145      */
146     private final Deque<VariableDesc> variables = new ArrayDeque<>();
147 
148     /**
149      * Keeps track of all the type declarations present in the file.
150      * Pops the type out of the stack while leaving the type
151      * in visitor pattern.
152      */
153     private final Deque<TypeDeclDesc> typeDeclarations = new ArrayDeque<>();
154 
155     /**
156      * Maps type declaration ast to their respective TypeDeclDesc objects.
157      */
158     private final Map<DetailAST, TypeDeclDesc> typeDeclAstToTypeDeclDesc = new LinkedHashMap<>();
159 
160     /**
161      * Maps local anonymous inner class to the TypeDeclDesc object
162      * containing it.
163      */
164     private final Map<DetailAST, TypeDeclDesc> anonInnerAstToTypeDeclDesc = new HashMap<>();
165 
166     /**
167      * Set of tokens of type {@link UnusedLocalVariableCheck#ANONYMOUS_CLASS_PARENT_TOKENS}
168      * and {@link TokenTypes#LAMBDA} in some cases.
169      */
170     private final Set<DetailAST> anonInnerClassHolders = new HashSet<>();
171 
172     /**
173      * Allow variables named with a single underscore
174      * (known as  <a href="https://docs.oracle.com/en/java/javase/21/docs/specs/unnamed-jls.html">
175      *  unnamed variables</a> in Java 21+).
176      */
177     private boolean allowUnnamedVariables = true;
178 
179     /**
180      * Name of the package.
181      */
182     private String packageName;
183 
184     /**
185      * Depth at which a type declaration is nested, 0 for top level type declarations.
186      */
187     private int depth;
188 
189     /**
190      * Setter to allow variables named with a single underscore
191      * (known as <a href="https://docs.oracle.com/en/java/javase/21/docs/specs/unnamed-jls.html">
192      * unnamed variables</a> in Java 21+).
193      *
194      * @param allowUnnamedVariables true or false.
195      * @since 10.18.0
196      */
197     public void setAllowUnnamedVariables(boolean allowUnnamedVariables) {
198         this.allowUnnamedVariables = allowUnnamedVariables;
199     }
200 
201     @Override
202     public int[] getDefaultTokens() {
203         return new int[] {
204             TokenTypes.DOT,
205             TokenTypes.VARIABLE_DEF,
206             TokenTypes.IDENT,
207             TokenTypes.SLIST,
208             TokenTypes.LITERAL_FOR,
209             TokenTypes.OBJBLOCK,
210             TokenTypes.CLASS_DEF,
211             TokenTypes.INTERFACE_DEF,
212             TokenTypes.ANNOTATION_DEF,
213             TokenTypes.PACKAGE_DEF,
214             TokenTypes.LITERAL_NEW,
215             TokenTypes.METHOD_DEF,
216             TokenTypes.CTOR_DEF,
217             TokenTypes.STATIC_INIT,
218             TokenTypes.INSTANCE_INIT,
219             TokenTypes.COMPILATION_UNIT,
220             TokenTypes.LAMBDA,
221             TokenTypes.ENUM_DEF,
222             TokenTypes.RECORD_DEF,
223             TokenTypes.COMPACT_CTOR_DEF,
224         };
225     }
226 
227     @Override
228     public int[] getAcceptableTokens() {
229         return getDefaultTokens();
230     }
231 
232     @Override
233     public int[] getRequiredTokens() {
234         return getDefaultTokens();
235     }
236 
237     @Override
238     public void beginTree(DetailAST root) {
239         variables.clear();
240         typeDeclarations.clear();
241         typeDeclAstToTypeDeclDesc.clear();
242         anonInnerAstToTypeDeclDesc.clear();
243         anonInnerClassHolders.clear();
244         packageName = null;
245         depth = 0;
246     }
247 
248     @Override
249     public void visitToken(DetailAST ast) {
250         final int type = ast.getType();
251         if (type == TokenTypes.DOT) {
252             visitDotToken(ast, variables);
253         }
254         else if (type == TokenTypes.VARIABLE_DEF && !skipUnnamedVariables(ast)) {
255             visitVariableDefToken(ast);
256         }
257         else if (type == TokenTypes.IDENT) {
258             visitIdentToken(ast, variables);
259         }
260         else if (isInsideLocalAnonInnerClass(ast)) {
261             visitLocalAnonInnerClass(ast);
262         }
263         else if (isNonLocalTypeDeclaration(ast)) {
264             visitNonLocalTypeDeclarationToken(ast);
265         }
266         else if (type == TokenTypes.PACKAGE_DEF) {
267             packageName = CheckUtil.extractQualifiedName(ast.getFirstChild().getNextSibling());
268         }
269     }
270 
271     @Override
272     public void leaveToken(DetailAST ast) {
273         if (TokenUtil.isOfType(ast, SCOPES)) {
274             logViolations(ast, variables);
275         }
276         else if (ast.getType() == TokenTypes.COMPILATION_UNIT) {
277             leaveCompilationUnit();
278         }
279         else if (isNonLocalTypeDeclaration(ast)) {
280             depth--;
281             typeDeclarations.pop();
282         }
283     }
284 
285     /**
286      * Visit ast of type {@link TokenTypes#DOT}.
287      *
288      * @param dotAst dotAst
289      * @param variablesStack stack of all the relevant variables in the scope
290      */
291     private static void visitDotToken(DetailAST dotAst, Deque<VariableDesc> variablesStack) {
292         if (dotAst.getParent().getType() != TokenTypes.LITERAL_NEW
293                 && shouldCheckIdentTokenNestedUnderDot(dotAst)) {
294             final DetailAST identifier = dotAst.findFirstToken(TokenTypes.IDENT);
295             if (identifier != null) {
296                 checkIdentifierAst(identifier, variablesStack);
297             }
298         }
299     }
300 
301     /**
302      * Visit ast of type {@link TokenTypes#VARIABLE_DEF}.
303      *
304      * @param varDefAst varDefAst
305      */
306     private void visitVariableDefToken(DetailAST varDefAst) {
307         addLocalVariables(varDefAst, variables);
308         addInstanceOrClassVar(varDefAst);
309     }
310 
311     /**
312      * Visit ast of type {@link TokenTypes#IDENT}.
313      *
314      * @param identAst identAst
315      * @param variablesStack stack of all the relevant variables in the scope
316      */
317     private static void visitIdentToken(DetailAST identAst, Deque<VariableDesc> variablesStack) {
318         final DetailAST parent = identAst.getParent();
319         final boolean isMethodReferenceMethodName = parent.getType() == TokenTypes.METHOD_REF
320                 && parent.getFirstChild() != identAst;
321         final boolean isConstructorReference = parent.getType() == TokenTypes.METHOD_REF
322                 && parent.getLastChild().getType() == TokenTypes.LITERAL_NEW;
323         final boolean isNestedClassInitialization =
324                 TokenUtil.isOfType(identAst.getNextSibling(), TokenTypes.LITERAL_NEW)
325                 && parent.getType() == TokenTypes.DOT;
326 
327         if (isNestedClassInitialization || !isMethodReferenceMethodName
328                 && !isConstructorReference
329                 && !TokenUtil.isOfType(parent, UNACCEPTABLE_PARENT_OF_IDENT)) {
330             checkIdentifierAst(identAst, variablesStack);
331         }
332     }
333 
334     /**
335      * Visit the non-local type declaration token.
336      *
337      * @param typeDeclAst type declaration ast
338      */
339     private void visitNonLocalTypeDeclarationToken(DetailAST typeDeclAst) {
340         final String qualifiedName = getQualifiedTypeDeclarationName(typeDeclAst);
341         final TypeDeclDesc currTypeDecl = new TypeDeclDesc(qualifiedName, depth, typeDeclAst);
342         depth++;
343         typeDeclarations.push(currTypeDecl);
344         typeDeclAstToTypeDeclDesc.put(typeDeclAst, currTypeDecl);
345     }
346 
347     /**
348      * Visit the local anon inner class.
349      *
350      * @param literalNewAst literalNewAst
351      */
352     private void visitLocalAnonInnerClass(DetailAST literalNewAst) {
353         anonInnerAstToTypeDeclDesc.put(literalNewAst, typeDeclarations.peek());
354         anonInnerClassHolders.add(getBlockContainingLocalAnonInnerClass(literalNewAst));
355     }
356 
357     /**
358      * Check for skip current {@link TokenTypes#VARIABLE_DEF}
359      * due to <b>allowUnnamedVariable</b> option.
360      *
361      * @param varDefAst varDefAst variable to check
362      * @return true if the current variable should be skipped.
363      */
364     private boolean skipUnnamedVariables(DetailAST varDefAst) {
365         final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT);
366         return allowUnnamedVariables && "_".equals(ident.getText());
367     }
368 
369     /**
370      * Whether ast node of type {@link TokenTypes#LITERAL_NEW} is a part of a local
371      * anonymous inner class.
372      *
373      * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW}
374      * @return true if variableDefAst is an instance variable in local anonymous inner class
375      */
376     private static boolean isInsideLocalAnonInnerClass(DetailAST literalNewAst) {
377         boolean result = false;
378         final DetailAST lastChild = literalNewAst.getLastChild();
379         if (lastChild != null && lastChild.getType() == TokenTypes.OBJBLOCK) {
380             DetailAST currentAst = literalNewAst;
381             while (!TokenUtil.isTypeDeclaration(currentAst.getType())) {
382                 if (currentAst.getType() == TokenTypes.SLIST) {
383                     result = true;
384                     break;
385                 }
386                 currentAst = currentAst.getParent();
387             }
388         }
389         return result;
390     }
391 
392     /**
393      * Traverse {@code variablesStack} stack and log the violations.
394      *
395      * @param scopeAst ast node of type {@link UnusedLocalVariableCheck#SCOPES}
396      * @param variablesStack stack of all the relevant variables in the scope
397      */
398     private void logViolations(DetailAST scopeAst, Deque<VariableDesc> variablesStack) {
399         while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) {
400             final VariableDesc variableDesc = variablesStack.pop();
401             if (!variableDesc.isUsed()
402                     && !variableDesc.isInstVarOrClassVar()) {
403                 final DetailAST typeAst = variableDesc.getTypeAst();
404                 if (allowUnnamedVariables) {
405                     log(typeAst, MSG_UNUSED_NAMED_LOCAL_VARIABLE, variableDesc.getName());
406                 }
407                 else {
408                     log(typeAst, MSG_UNUSED_LOCAL_VARIABLE, variableDesc.getName());
409                 }
410             }
411         }
412     }
413 
414     /**
415      * We process all the blocks containing local anonymous inner classes
416      * separately after processing all the other nodes. This is being done
417      * due to the fact the instance variables of local anon inner classes can
418      * cast a shadow on local variables.
419      */
420     private void leaveCompilationUnit() {
421         anonInnerClassHolders.forEach(holder -> {
422             iterateOverBlockContainingLocalAnonInnerClass(holder, new ArrayDeque<>());
423         });
424     }
425 
426     /**
427      * Whether a type declaration is non-local. Annotated interfaces are always non-local.
428      *
429      * @param typeDeclAst type declaration ast
430      * @return true if type declaration is non-local
431      */
432     private static boolean isNonLocalTypeDeclaration(DetailAST typeDeclAst) {
433         return TokenUtil.isTypeDeclaration(typeDeclAst.getType())
434                 && typeDeclAst.getParent().getType() != TokenTypes.SLIST;
435     }
436 
437     /**
438      * Get the block containing local anon inner class.
439      *
440      * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW}
441      * @return the block containing local anon inner class
442      */
443     private static DetailAST getBlockContainingLocalAnonInnerClass(DetailAST literalNewAst) {
444         DetailAST currentAst = literalNewAst;
445         DetailAST result = null;
446         DetailAST topMostLambdaAst = null;
447         while (currentAst != null && !TokenUtil.isOfType(currentAst,
448                 ANONYMOUS_CLASS_PARENT_TOKENS)) {
449             if (currentAst.getType() == TokenTypes.LAMBDA) {
450                 topMostLambdaAst = currentAst;
451             }
452             currentAst = currentAst.getParent();
453             result = currentAst;
454         }
455 
456         if (currentAst == null) {
457             result = topMostLambdaAst;
458         }
459         return result;
460     }
461 
462     /**
463      * Add local variables to the {@code variablesStack} stack.
464      * Also adds the instance variables defined in a local anonymous inner class.
465      *
466      * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF}
467      * @param variablesStack stack of all the relevant variables in the scope
468      */
469     private static void addLocalVariables(DetailAST varDefAst, Deque<VariableDesc> variablesStack) {
470         final DetailAST parentAst = varDefAst.getParent();
471         final DetailAST grandParent = parentAst.getParent();
472         final boolean isInstanceVarInInnerClass =
473                 grandParent.getType() == TokenTypes.LITERAL_NEW
474                 || grandParent.getType() == TokenTypes.CLASS_DEF;
475         if (isInstanceVarInInnerClass
476                 || parentAst.getType() != TokenTypes.OBJBLOCK) {
477             final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT);
478             final VariableDesc desc = new VariableDesc(ident.getText(),
479                     varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst));
480             if (isInstanceVarInInnerClass) {
481                 desc.registerAsInstOrClassVar();
482             }
483             variablesStack.push(desc);
484         }
485     }
486 
487     /**
488      * Add instance variables and class variables to the
489      * {@link TypeDeclDesc#instanceAndClassVarStack}.
490      *
491      * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF}
492      */
493     private void addInstanceOrClassVar(DetailAST varDefAst) {
494         final DetailAST parentAst = varDefAst.getParent();
495         if (isNonLocalTypeDeclaration(parentAst.getParent())
496                 && !isPrivateInstanceVariable(varDefAst)) {
497             final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT);
498             final VariableDesc desc = new VariableDesc(ident.getText());
499             typeDeclAstToTypeDeclDesc.get(parentAst.getParent()).addInstOrClassVar(desc);
500         }
501     }
502 
503     /**
504      * Whether instance variable or class variable have private access modifier.
505      *
506      * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF}
507      * @return true if instance variable or class variable have private access modifier
508      */
509     private static boolean isPrivateInstanceVariable(DetailAST varDefAst) {
510         final AccessModifierOption varAccessModifier =
511                 CheckUtil.getAccessModifierFromModifiersToken(varDefAst);
512         return varAccessModifier == AccessModifierOption.PRIVATE;
513     }
514 
515     /**
516      * Get the {@link TypeDeclDesc} of the super class of anonymous inner class.
517      *
518      * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW}
519      * @return {@link TypeDeclDesc} of the super class of anonymous inner class
520      */
521     private TypeDeclDesc getSuperClassOfAnonInnerClass(DetailAST literalNewAst) {
522         TypeDeclDesc obtainedClass = null;
523         final String shortNameOfClass = CheckUtil.getShortNameOfAnonInnerClass(literalNewAst);
524         if (packageName != null && shortNameOfClass.startsWith(packageName)) {
525             final Optional<TypeDeclDesc> classWithCompletePackageName =
526                     typeDeclAstToTypeDeclDesc.values()
527                     .stream()
528                     .filter(typeDeclDesc -> {
529                         return typeDeclDesc.getQualifiedName().equals(shortNameOfClass);
530                     })
531                     .findFirst();
532             if (classWithCompletePackageName.isPresent()) {
533                 obtainedClass = classWithCompletePackageName.orElseThrow();
534             }
535         }
536         else {
537             final List<TypeDeclDesc> typeDeclWithSameName = typeDeclWithSameName(shortNameOfClass);
538             if (!typeDeclWithSameName.isEmpty()) {
539                 obtainedClass = getClosestMatchingTypeDeclaration(
540                         anonInnerAstToTypeDeclDesc.get(literalNewAst).getQualifiedName(),
541                         typeDeclWithSameName);
542             }
543         }
544         return obtainedClass;
545     }
546 
547     /**
548      * Add non-private instance and class variables of the super class of the anonymous class
549      * to the variables stack.
550      *
551      * @param obtainedClass super class of the anon inner class
552      * @param variablesStack stack of all the relevant variables in the scope
553      * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW}
554      */
555     private void modifyVariablesStack(TypeDeclDesc obtainedClass,
556             Deque<VariableDesc> variablesStack,
557             DetailAST literalNewAst) {
558         if (obtainedClass != null) {
559             final Deque<VariableDesc> instAndClassVarDeque = typeDeclAstToTypeDeclDesc
560                     .get(obtainedClass.getTypeDeclAst())
561                     .getUpdatedCopyOfVarStack(literalNewAst);
562             instAndClassVarDeque.forEach(variablesStack::push);
563         }
564     }
565 
566     /**
567      * Checks if there is a type declaration with same name as the super class.
568      *
569      * @param superClassName name of the super class
570      * @return list if there is another type declaration with same name.
571      */
572     private List<TypeDeclDesc> typeDeclWithSameName(String superClassName) {
573         return typeDeclAstToTypeDeclDesc.values().stream()
574                 .filter(typeDeclDesc -> {
575                     return hasSameNameAsSuperClass(superClassName, typeDeclDesc);
576                 })
577                 .toList();
578     }
579 
580     /**
581      * Whether the qualified name of {@code typeDeclDesc} matches the super class name.
582      *
583      * @param superClassName name of the super class
584      * @param typeDeclDesc type declaration description
585      * @return {@code true} if the qualified name of {@code typeDeclDesc}
586      *         matches the super class name
587      */
588     private boolean hasSameNameAsSuperClass(String superClassName, TypeDeclDesc typeDeclDesc) {
589         final boolean result;
590         if (packageName == null && typeDeclDesc.getDepth() == 0) {
591             result = typeDeclDesc.getQualifiedName().equals(superClassName);
592         }
593         else {
594             result = typeDeclDesc.getQualifiedName()
595                     .endsWith(PACKAGE_SEPARATOR + superClassName);
596         }
597         return result;
598     }
599 
600     /**
601      * For all type declarations with the same name as the superclass, gets the nearest type
602      * declaration.
603      *
604      * @param outerTypeDeclName outer type declaration of anonymous inner class
605      * @param typeDeclWithSameName typeDeclarations which have the same name as the super class
606      * @return the nearest class
607      */
608     private static TypeDeclDesc getClosestMatchingTypeDeclaration(String outerTypeDeclName,
609             List<TypeDeclDesc> typeDeclWithSameName) {
610         return Collections.min(typeDeclWithSameName, (first, second) -> {
611             return calculateTypeDeclarationDistance(outerTypeDeclName, first, second);
612         });
613     }
614 
615     /**
616      * Get the difference between type declaration name matching count. If the
617      * difference between them is zero, then their depth is compared to obtain the result.
618      *
619      * @param outerTypeName outer type declaration of anonymous inner class
620      * @param firstType first input type declaration
621      * @param secondType second input type declaration
622      * @return difference between type declaration name matching count
623      */
624     private static int calculateTypeDeclarationDistance(String outerTypeName,
625                                                         TypeDeclDesc firstType,
626                                                         TypeDeclDesc secondType) {
627         final int firstMatchCount =
628                 countMatchingQualifierChars(outerTypeName, firstType.getQualifiedName());
629         final int secondMatchCount =
630                 countMatchingQualifierChars(outerTypeName, secondType.getQualifiedName());
631         final int matchDistance = Integer.compare(secondMatchCount, firstMatchCount);
632 
633         final int distance;
634         if (matchDistance == 0) {
635             distance = Integer.compare(firstType.getDepth(), secondType.getDepth());
636         }
637         else {
638             distance = matchDistance;
639         }
640 
641         return distance;
642     }
643 
644     /**
645      * Calculates the type declaration matching count for the superclass of an anonymous inner
646      * class.
647      *
648      * <p>
649      * For example, if the pattern class is {@code Main.ClassOne} and the class to be matched is
650      * {@code Main.ClassOne.ClassTwo.ClassThree}, then the matching count would be calculated by
651      * comparing the characters at each position, and updating the count whenever a '.'
652      * is encountered.
653      * This is necessary because pattern class can include anonymous inner classes, unlike regular
654      * inheritance where nested classes cannot be extended.
655      * </p>
656      *
657      * @param pattern type declaration to match against
658      * @param candidate type declaration to be matched
659      * @return the type declaration matching count
660      */
661     private static int countMatchingQualifierChars(String pattern,
662                                                    String candidate) {
663         final int typeDeclarationToBeMatchedLength = candidate.length();
664         final int minLength = Math
665                 .min(typeDeclarationToBeMatchedLength, pattern.length());
666         final boolean shouldCountBeUpdatedAtLastCharacter =
667                 typeDeclarationToBeMatchedLength > minLength
668                 && candidate.charAt(minLength) == PACKAGE_SEPARATOR.charAt(0);
669 
670         int result = 0;
671         for (int idx = 0;
672              idx < minLength
673                 && pattern.charAt(idx) == candidate.charAt(idx);
674              idx++) {
675 
676             if (shouldCountBeUpdatedAtLastCharacter
677                     || pattern.charAt(idx) == PACKAGE_SEPARATOR.charAt(0)) {
678                 result = idx;
679             }
680         }
681         return result;
682     }
683 
684     /**
685      * Get qualified type declaration name from type ast.
686      *
687      * @param typeDeclAst type declaration ast
688      * @return qualified name of type declaration
689      */
690     private String getQualifiedTypeDeclarationName(DetailAST typeDeclAst) {
691         final String className = typeDeclAst.findFirstToken(TokenTypes.IDENT).getText();
692         String outerClassQualifiedName = null;
693         if (!typeDeclarations.isEmpty()) {
694             outerClassQualifiedName = typeDeclarations.peek().getQualifiedName();
695         }
696         return CheckUtil
697             .getQualifiedTypeDeclarationName(packageName, outerClassQualifiedName, className);
698     }
699 
700     /**
701      * Iterate over all the ast nodes present under {@code ast}.
702      *
703      * @param ast ast
704      * @param variablesStack stack of all the relevant variables in the scope
705      */
706     private void iterateOverBlockContainingLocalAnonInnerClass(
707             DetailAST ast, Deque<VariableDesc> variablesStack) {
708         DetailAST currNode = ast;
709         while (currNode != null) {
710             customVisitToken(currNode, variablesStack);
711             DetailAST toVisit = currNode.getFirstChild();
712             while (currNode != ast && toVisit == null) {
713                 customLeaveToken(currNode, variablesStack);
714                 toVisit = currNode.getNextSibling();
715                 currNode = currNode.getParent();
716             }
717             currNode = toVisit;
718         }
719     }
720 
721     /**
722      * Visit all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once
723      * again.
724      *
725      * @param ast ast
726      * @param variablesStack stack of all the relevant variables in the scope
727      */
728     private void customVisitToken(DetailAST ast, Deque<VariableDesc> variablesStack) {
729         final int type = ast.getType();
730         if (type == TokenTypes.DOT) {
731             visitDotToken(ast, variablesStack);
732         }
733         else if (type == TokenTypes.VARIABLE_DEF) {
734             addLocalVariables(ast, variablesStack);
735         }
736         else if (type == TokenTypes.IDENT) {
737             visitIdentToken(ast, variablesStack);
738         }
739         else if (isInsideLocalAnonInnerClass(ast)) {
740             final TypeDeclDesc obtainedClass = getSuperClassOfAnonInnerClass(ast);
741             modifyVariablesStack(obtainedClass, variablesStack, ast);
742         }
743     }
744 
745     /**
746      * Leave all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once
747      * again.
748      *
749      * @param ast ast
750      * @param variablesStack stack of all the relevant variables in the scope
751      */
752     private void customLeaveToken(DetailAST ast, Deque<VariableDesc> variablesStack) {
753         logViolations(ast, variablesStack);
754     }
755 
756     /**
757      * Whether to check identifier token nested under dotAst.
758      *
759      * @param dotAst dotAst
760      * @return true if ident nested under dotAst should be checked
761      */
762     private static boolean shouldCheckIdentTokenNestedUnderDot(DetailAST dotAst) {
763 
764         return TokenUtil.findFirstTokenByPredicate(dotAst,
765                         childAst -> {
766                             return TokenUtil.isOfType(childAst,
767                                     UNACCEPTABLE_CHILD_OF_DOT);
768                         })
769                 .isEmpty();
770     }
771 
772     /**
773      * Checks the identifier ast.
774      *
775      * @param identAst ast of type {@link TokenTypes#IDENT}
776      * @param variablesStack stack of all the relevant variables in the scope
777      */
778     private static void checkIdentifierAst(DetailAST identAst, Deque<VariableDesc> variablesStack) {
779         for (VariableDesc variableDesc : variablesStack) {
780             if (identAst.getText().equals(variableDesc.getName())
781                     && !isLeftHandSideValue(identAst)) {
782                 variableDesc.registerAsUsed();
783                 break;
784             }
785         }
786     }
787 
788     /**
789      * Find the scope of variable.
790      *
791      * @param variableDef ast of type {@link TokenTypes#VARIABLE_DEF}
792      * @return scope of variableDef
793      */
794     private static DetailAST findScopeOfVariable(DetailAST variableDef) {
795         final DetailAST result;
796         final DetailAST parentAst = variableDef.getParent();
797         if (TokenUtil.isOfType(parentAst, TokenTypes.SLIST, TokenTypes.OBJBLOCK)) {
798             result = parentAst;
799         }
800         else {
801             result = parentAst.getParent();
802         }
803         return result;
804     }
805 
806     /**
807      * Checks whether the ast of type {@link TokenTypes#IDENT} is
808      * used as left-hand side value. An identifier is being used as a left-hand side
809      * value if it is used as the left operand of an assignment or as an
810      * operand of a stand-alone increment or decrement.
811      *
812      * @param identAst ast of type {@link TokenTypes#IDENT}
813      * @return true if identAst is used as a left-hand side value
814      */
815     private static boolean isLeftHandSideValue(DetailAST identAst) {
816         final DetailAST parent = identAst.getParent();
817         return isStandAloneIncrementOrDecrement(identAst)
818                 || parent.getType() == TokenTypes.ASSIGN
819                 && identAst != parent.getLastChild();
820     }
821 
822     /**
823      * Checks whether the ast of type {@link TokenTypes#IDENT} is used as
824      * an operand of a stand-alone increment or decrement.
825      *
826      * @param identAst ast of type {@link TokenTypes#IDENT}
827      * @return true if identAst is used as an operand of stand-alone
828      *         increment or decrement
829      */
830     private static boolean isStandAloneIncrementOrDecrement(DetailAST identAst) {
831         final DetailAST parent = identAst.getParent();
832         final DetailAST grandParent = parent.getParent();
833         return TokenUtil.isOfType(parent, INCREMENT_AND_DECREMENT_TOKENS)
834                 && TokenUtil.isOfType(grandParent, TokenTypes.EXPR)
835                 && !isIncrementOrDecrementVariableUsed(grandParent);
836     }
837 
838     /**
839      * A variable with increment or decrement operator is considered used if it
840      * is used as an argument or as an array index or for assigning value
841      * to a variable.
842      *
843      * @param exprAst ast of type {@link TokenTypes#EXPR}
844      * @return true if variable nested in exprAst is used
845      */
846     private static boolean isIncrementOrDecrementVariableUsed(DetailAST exprAst) {
847         return TokenUtil.isOfType(exprAst.getParent(), INCREMENT_DECREMENT_VARIABLE_USAGE_TYPES)
848                 && exprAst.getParent().getParent().getType() != TokenTypes.FOR_ITERATOR;
849     }
850 
851     /**
852      * Maintains information about the variable.
853      */
854     private static final class VariableDesc {
855 
856         /**
857          * The name of the variable.
858          */
859         private final String name;
860 
861         /**
862          * Ast of type {@link TokenTypes#TYPE}.
863          */
864         private final DetailAST typeAst;
865 
866         /**
867          * The scope of variable is determined by the ast of type
868          * {@link TokenTypes#SLIST} or {@link TokenTypes#LITERAL_FOR}
869          * or {@link TokenTypes#OBJBLOCK} which is enclosing the variable.
870          */
871         private final DetailAST scope;
872 
873         /**
874          * Is an instance variable or a class variable.
875          */
876         private boolean instVarOrClassVar;
877 
878         /**
879          * Is the variable used.
880          */
881         private boolean used;
882 
883         /**
884          * Create a new VariableDesc instance.
885          *
886          * @param name name of the variable
887          * @param typeAst ast of type {@link TokenTypes#TYPE}
888          * @param scope ast of type {@link TokenTypes#SLIST} or
889          *              {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK}
890          *              which is enclosing the variable
891          */
892         private VariableDesc(String name, DetailAST typeAst, DetailAST scope) {
893             this.name = name;
894             this.typeAst = typeAst;
895             this.scope = scope;
896         }
897 
898         /**
899          * Create a new VariableDesc instance.
900          *
901          * @param name name of the variable
902          */
903         private VariableDesc(String name) {
904             this(name, null, null);
905         }
906 
907         /**
908          * Create a new VariableDesc instance.
909          *
910          * @param name name of the variable
911          * @param scope ast of type {@link TokenTypes#SLIST} or
912          *              {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK}
913          *              which is enclosing the variable
914          */
915         private VariableDesc(String name, DetailAST scope) {
916             this(name, null, scope);
917         }
918 
919         /**
920          * Get the name of variable.
921          *
922          * @return name of variable
923          */
924         public String getName() {
925             return name;
926         }
927 
928         /**
929          * Get the associated ast node of type {@link TokenTypes#TYPE}.
930          *
931          * @return the associated ast node of type {@link TokenTypes#TYPE}
932          */
933         public DetailAST getTypeAst() {
934             return typeAst;
935         }
936 
937         /**
938          * Get ast of type {@link TokenTypes#SLIST}
939          * or {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK}
940          * which is enclosing the variable i.e. its scope.
941          *
942          * @return the scope associated with the variable
943          */
944         public DetailAST getScope() {
945             return scope;
946         }
947 
948         /**
949          * Register the variable as used.
950          */
951         public void registerAsUsed() {
952             used = true;
953         }
954 
955         /**
956          * Register the variable as an instance variable or
957          * class variable.
958          */
959         public void registerAsInstOrClassVar() {
960             instVarOrClassVar = true;
961         }
962 
963         /**
964          * Is the variable used or not.
965          *
966          * @return true if variable is used
967          */
968         public boolean isUsed() {
969             return used;
970         }
971 
972         /**
973          * Is an instance variable or a class variable.
974          *
975          * @return true if is an instance variable or a class variable
976          */
977         public boolean isInstVarOrClassVar() {
978             return instVarOrClassVar;
979         }
980     }
981 
982     /**
983      * Maintains information about the type declaration.
984      * Any ast node of type {@link TokenTypes#CLASS_DEF} or {@link TokenTypes#INTERFACE_DEF}
985      * or {@link TokenTypes#ENUM_DEF} or {@link TokenTypes#ANNOTATION_DEF}
986      * or {@link TokenTypes#RECORD_DEF} is considered as a type declaration.
987      */
988     private static final class TypeDeclDesc {
989 
990         /**
991          * Complete type declaration name with package name and outer type declaration name.
992          */
993         private final String qualifiedName;
994 
995         /**
996          * Depth of nesting of type declaration.
997          */
998         private final int depth;
999 
1000         /**
1001          * Type declaration ast node.
1002          */
1003         private final DetailAST typeDeclAst;
1004 
1005         /**
1006          * A stack of type declaration's instance and static variables.
1007          */
1008         private final Deque<VariableDesc> instanceAndClassVarStack;
1009 
1010         /**
1011          * Create a new TypeDeclDesc instance.
1012          *
1013          * @param qualifiedName qualified name
1014          * @param depth depth of nesting
1015          * @param typeDeclAst type declaration ast node
1016          */
1017         private TypeDeclDesc(String qualifiedName, int depth,
1018                 DetailAST typeDeclAst) {
1019             this.qualifiedName = qualifiedName;
1020             this.depth = depth;
1021             this.typeDeclAst = typeDeclAst;
1022             instanceAndClassVarStack = new ArrayDeque<>();
1023         }
1024 
1025         /**
1026          * Get the complete type declaration name i.e. type declaration name with package name
1027          * and outer type declaration name.
1028          *
1029          * @return qualified class name
1030          */
1031         public String getQualifiedName() {
1032             return qualifiedName;
1033         }
1034 
1035         /**
1036          * Get the depth of type declaration.
1037          *
1038          * @return the depth of nesting of type declaration
1039          */
1040         public int getDepth() {
1041             return depth;
1042         }
1043 
1044         /**
1045          * Get the type declaration ast node.
1046          *
1047          * @return ast node of the type declaration
1048          */
1049         public DetailAST getTypeDeclAst() {
1050             return typeDeclAst;
1051         }
1052 
1053         /**
1054          * Get the copy of variables in instanceAndClassVar stack with updated scope.
1055          *
1056          * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW}
1057          * @return copy of variables in instanceAndClassVar stack with updated scope.
1058          */
1059         public Deque<VariableDesc> getUpdatedCopyOfVarStack(DetailAST literalNewAst) {
1060             final DetailAST updatedScope = literalNewAst;
1061             final Deque<VariableDesc> instAndClassVarDeque = new ArrayDeque<>();
1062             instanceAndClassVarStack.forEach(instVar -> {
1063                 final VariableDesc variableDesc = new VariableDesc(instVar.getName(),
1064                         updatedScope);
1065                 variableDesc.registerAsInstOrClassVar();
1066                 instAndClassVarDeque.push(variableDesc);
1067             });
1068             return instAndClassVarDeque;
1069         }
1070 
1071         /**
1072          * Add an instance variable or class variable to the stack.
1073          *
1074          * @param variableDesc variable to be added
1075          */
1076         public void addInstOrClassVar(VariableDesc variableDesc) {
1077             instanceAndClassVarStack.push(variableDesc);
1078         }
1079     }
1080 }