001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2022 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.Collections; 024import java.util.Deque; 025import java.util.HashMap; 026import java.util.HashSet; 027import java.util.LinkedHashMap; 028import java.util.List; 029import java.util.Map; 030import java.util.Optional; 031import java.util.Set; 032import java.util.stream.Collectors; 033 034import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 035import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 036import com.puppycrawl.tools.checkstyle.api.DetailAST; 037import com.puppycrawl.tools.checkstyle.api.TokenTypes; 038import com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption; 039import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 040import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 041 042/** 043 * <p> 044 * Checks that a local variable is declared and/or assigned, but not used. 045 * Doesn't support 046 * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-14.30"> 047 * pattern variables yet</a>. 048 * Doesn't check 049 * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.12.3"> 050 * array components</a> as array 051 * components are classified as different kind of variables by 052 * <a href="https://docs.oracle.com/javase/specs/jls/se17/html/index.html">JLS</a>. 053 * </p> 054 * <p> 055 * To configure the check: 056 * </p> 057 * <pre> 058 * <module name="UnusedLocalVariable"/> 059 * </pre> 060 * <p> 061 * Example: 062 * </p> 063 * <pre> 064 * class Test { 065 * 066 * int a; 067 * 068 * { 069 * int k = 12; // violation, assigned and updated but never used 070 * k++; 071 * } 072 * 073 * Test(int a) { // ok as 'a' is a constructor parameter not a local variable 074 * this.a = 12; 075 * } 076 * 077 * void method(int b) { 078 * int a = 10; // violation 079 * int[] arr = {1, 2, 3}; // violation 080 * int[] anotherArr = {1}; // ok 081 * anotherArr[0] = 4; 082 * } 083 * 084 * String convertValue(String newValue) { 085 * String s = newValue.toLowerCase(); // violation 086 * return newValue.toLowerCase(); 087 * } 088 * 089 * void read() throws IOException { 090 * BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 091 * String s; // violation 092 * while ((s = reader.readLine()) != null) { 093 * } 094 * try (BufferedReader reader1 // ok as 'reader1' is a resource and resources are closed 095 * // at the end of the statement 096 * = new BufferedReader(new FileReader("abc.txt"))) { 097 * } 098 * try { 099 * } catch (Exception e) { // ok as e is an exception parameter 100 * } 101 * } 102 * 103 * void loops() { 104 * int j = 12; 105 * for (int i = 0; j < 11; i++) { // violation, unused local variable 'i'. 106 * } 107 * for (int p = 0; j < 11; p++) // ok 108 * p /= 2; 109 * } 110 * 111 * void lambdas() { 112 * Predicate<String> obj = (String str) -> { // ok as 'str' is a lambda parameter 113 * return true; 114 * }; 115 * obj.test("test"); 116 * } 117 * } 118 * </pre> 119 * <p> 120 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 121 * </p> 122 * <p> 123 * Violation Message Keys: 124 * </p> 125 * <ul> 126 * <li> 127 * {@code unused.local.var} 128 * </li> 129 * </ul> 130 * 131 * @since 9.3 132 */ 133@FileStatefulCheck 134public class UnusedLocalVariableCheck extends AbstractCheck { 135 136 /** 137 * A key is pointing to the warning message text in "messages.properties" 138 * file. 139 */ 140 public static final String MSG_UNUSED_LOCAL_VARIABLE = "unused.local.var"; 141 142 /** 143 * An array of increment and decrement tokens. 144 */ 145 private static final int[] INCREMENT_AND_DECREMENT_TOKENS = { 146 TokenTypes.POST_INC, 147 TokenTypes.POST_DEC, 148 TokenTypes.INC, 149 TokenTypes.DEC, 150 }; 151 152 /** 153 * An array of scope tokens. 154 */ 155 private static final int[] SCOPES = { 156 TokenTypes.SLIST, 157 TokenTypes.LITERAL_FOR, 158 TokenTypes.OBJBLOCK, 159 }; 160 161 /** 162 * An array of unacceptable children of ast of type {@link TokenTypes#DOT}. 163 */ 164 private static final int[] UNACCEPTABLE_CHILD_OF_DOT = { 165 TokenTypes.DOT, 166 TokenTypes.METHOD_CALL, 167 TokenTypes.LITERAL_NEW, 168 TokenTypes.LITERAL_SUPER, 169 TokenTypes.LITERAL_CLASS, 170 TokenTypes.LITERAL_THIS, 171 }; 172 173 /** 174 * An array of unacceptable parent of ast of type {@link TokenTypes#IDENT}. 175 */ 176 private static final int[] UNACCEPTABLE_PARENT_OF_IDENT = { 177 TokenTypes.VARIABLE_DEF, 178 TokenTypes.DOT, 179 TokenTypes.LITERAL_NEW, 180 TokenTypes.PATTERN_VARIABLE_DEF, 181 TokenTypes.METHOD_CALL, 182 TokenTypes.TYPE, 183 }; 184 185 /** 186 * An array of blocks in which local anon inner classes can exist. 187 */ 188 private static final int[] CONTAINERS_FOR_ANON_INNERS = { 189 TokenTypes.METHOD_DEF, 190 TokenTypes.CTOR_DEF, 191 TokenTypes.STATIC_INIT, 192 TokenTypes.INSTANCE_INIT, 193 TokenTypes.COMPACT_CTOR_DEF, 194 }; 195 196 /** Package separator. */ 197 private static final String PACKAGE_SEPARATOR = "."; 198 199 /** 200 * Keeps tracks of the variables declared in file. 201 */ 202 private final Deque<VariableDesc> variables; 203 204 /** 205 * Keeps track of all the type declarations present in the file. 206 * Pops the type out of the stack while leaving the type 207 * in visitor pattern. 208 */ 209 private final Deque<TypeDeclDesc> typeDeclarations; 210 211 /** 212 * Maps type declaration ast to their respective TypeDeclDesc objects. 213 */ 214 private final Map<DetailAST, TypeDeclDesc> typeDeclAstToTypeDeclDesc; 215 216 /** 217 * Maps local anonymous inner class to the TypeDeclDesc object 218 * containing it. 219 */ 220 private final Map<DetailAST, TypeDeclDesc> anonInnerAstToTypeDeclDesc; 221 222 /** 223 * Set of tokens of type {@link UnusedLocalVariableCheck#CONTAINERS_FOR_ANON_INNERS} 224 * and {@link TokenTypes#LAMBDA} in some cases. 225 */ 226 private final Set<DetailAST> anonInnerClassHolders; 227 228 /** 229 * Name of the package. 230 */ 231 private String packageName; 232 233 /** 234 * Depth at which a type declaration is nested, 0 for top level type declarations. 235 */ 236 private int depth; 237 238 /** 239 * Creates a new {@code UnusedLocalVariableCheck} instance. 240 */ 241 public UnusedLocalVariableCheck() { 242 variables = new ArrayDeque<>(); 243 typeDeclarations = new ArrayDeque<>(); 244 typeDeclAstToTypeDeclDesc = new LinkedHashMap<>(); 245 anonInnerAstToTypeDeclDesc = new HashMap<>(); 246 anonInnerClassHolders = new HashSet<>(); 247 packageName = null; 248 depth = 0; 249 } 250 251 @Override 252 public int[] getDefaultTokens() { 253 return new int[] { 254 TokenTypes.DOT, 255 TokenTypes.VARIABLE_DEF, 256 TokenTypes.IDENT, 257 TokenTypes.SLIST, 258 TokenTypes.LITERAL_FOR, 259 TokenTypes.OBJBLOCK, 260 TokenTypes.CLASS_DEF, 261 TokenTypes.INTERFACE_DEF, 262 TokenTypes.ANNOTATION_DEF, 263 TokenTypes.PACKAGE_DEF, 264 TokenTypes.LITERAL_NEW, 265 TokenTypes.METHOD_DEF, 266 TokenTypes.CTOR_DEF, 267 TokenTypes.STATIC_INIT, 268 TokenTypes.INSTANCE_INIT, 269 TokenTypes.COMPILATION_UNIT, 270 TokenTypes.LAMBDA, 271 TokenTypes.ENUM_DEF, 272 TokenTypes.RECORD_DEF, 273 TokenTypes.COMPACT_CTOR_DEF, 274 }; 275 } 276 277 @Override 278 public int[] getAcceptableTokens() { 279 return getDefaultTokens(); 280 } 281 282 @Override 283 public int[] getRequiredTokens() { 284 return getDefaultTokens(); 285 } 286 287 @Override 288 public void beginTree(DetailAST root) { 289 variables.clear(); 290 typeDeclarations.clear(); 291 typeDeclAstToTypeDeclDesc.clear(); 292 anonInnerAstToTypeDeclDesc.clear(); 293 anonInnerClassHolders.clear(); 294 packageName = null; 295 depth = 0; 296 } 297 298 @Override 299 public void visitToken(DetailAST ast) { 300 final int type = ast.getType(); 301 if (type == TokenTypes.DOT) { 302 visitDotToken(ast, variables); 303 } 304 else if (type == TokenTypes.VARIABLE_DEF) { 305 visitVariableDefToken(ast); 306 } 307 else if (type == TokenTypes.IDENT) { 308 visitIdentToken(ast, variables); 309 } 310 else if (type == TokenTypes.LITERAL_NEW 311 && isInsideLocalAnonInnerClass(ast)) { 312 visitLocalAnonInnerClass(ast); 313 } 314 else if (TokenUtil.isTypeDeclaration(type)) { 315 visitTypeDeclarationToken(ast); 316 } 317 else if (type == TokenTypes.PACKAGE_DEF) { 318 packageName = CheckUtil.extractQualifiedName(ast.getFirstChild().getNextSibling()); 319 } 320 } 321 322 @Override 323 public void leaveToken(DetailAST ast) { 324 if (TokenUtil.isOfType(ast, SCOPES)) { 325 logViolations(ast, variables); 326 } 327 else if (ast.getType() == TokenTypes.COMPILATION_UNIT) { 328 leaveCompilationUnit(); 329 } 330 else if (isNonLocalTypeDeclaration(ast)) { 331 depth--; 332 typeDeclarations.pop(); 333 } 334 } 335 336 /** 337 * Visit ast of type {@link TokenTypes#DOT}. 338 * 339 * @param dotAst dotAst 340 * @param variablesStack stack of all the relevant variables in the scope 341 */ 342 private static void visitDotToken(DetailAST dotAst, Deque<VariableDesc> variablesStack) { 343 if (dotAst.getParent().getType() != TokenTypes.LITERAL_NEW 344 && shouldCheckIdentTokenNestedUnderDot(dotAst)) { 345 checkIdentifierAst(dotAst.findFirstToken(TokenTypes.IDENT), variablesStack); 346 } 347 } 348 349 /** 350 * Visit ast of type {@link TokenTypes#VARIABLE_DEF}. 351 * 352 * @param varDefAst varDefAst 353 */ 354 private void visitVariableDefToken(DetailAST varDefAst) { 355 addLocalVariables(varDefAst, variables); 356 addInstanceOrClassVar(varDefAst); 357 } 358 359 /** 360 * Visit ast of type {@link TokenTypes#IDENT}. 361 * 362 * @param identAst identAst 363 * @param variablesStack stack of all the relevant variables in the scope 364 */ 365 private static void visitIdentToken(DetailAST identAst, Deque<VariableDesc> variablesStack) { 366 final DetailAST parent = identAst.getParent(); 367 final boolean isMethodReferenceMethodName = parent.getType() == TokenTypes.METHOD_REF 368 && parent.getFirstChild() != identAst; 369 final boolean isConstructorReference = parent.getType() == TokenTypes.METHOD_REF 370 && parent.getLastChild().getType() == TokenTypes.LITERAL_NEW; 371 372 if (!isMethodReferenceMethodName 373 && !isConstructorReference 374 && !TokenUtil.isOfType(parent, UNACCEPTABLE_PARENT_OF_IDENT)) { 375 checkIdentifierAst(identAst, variablesStack); 376 } 377 } 378 379 /** 380 * Visit the type declaration token. 381 * 382 * @param typeDeclAst type declaration ast 383 */ 384 private void visitTypeDeclarationToken(DetailAST typeDeclAst) { 385 if (isNonLocalTypeDeclaration(typeDeclAst)) { 386 final String qualifiedName = getQualifiedTypeDeclarationName(typeDeclAst); 387 final TypeDeclDesc currTypeDecl = new TypeDeclDesc(qualifiedName, depth, typeDeclAst); 388 depth++; 389 typeDeclarations.push(currTypeDecl); 390 typeDeclAstToTypeDeclDesc.put(typeDeclAst, currTypeDecl); 391 } 392 } 393 394 /** 395 * Visit the local anon inner class. 396 * 397 * @param literalNewAst literalNewAst 398 */ 399 private void visitLocalAnonInnerClass(DetailAST literalNewAst) { 400 anonInnerAstToTypeDeclDesc.put(literalNewAst, typeDeclarations.peek()); 401 anonInnerClassHolders.add(getBlockContainingLocalAnonInnerClass(literalNewAst)); 402 } 403 404 /** 405 * Whether ast node of type {@link TokenTypes#LITERAL_NEW} is a part of a local 406 * anonymous inner class. 407 * 408 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 409 * @return true if variableDefAst is an instance variable in local anonymous inner class 410 */ 411 private static boolean isInsideLocalAnonInnerClass(DetailAST literalNewAst) { 412 boolean result = false; 413 final DetailAST lastChild = literalNewAst.getLastChild(); 414 if (lastChild != null && lastChild.getType() == TokenTypes.OBJBLOCK) { 415 DetailAST parentAst = literalNewAst.getParent(); 416 while (parentAst.getType() != TokenTypes.SLIST) { 417 if (TokenUtil.isTypeDeclaration(parentAst.getParent().getType())) { 418 break; 419 } 420 parentAst = parentAst.getParent(); 421 } 422 result = parentAst.getType() == TokenTypes.SLIST; 423 } 424 return result; 425 } 426 427 /** 428 * Traverse {@code variablesStack} stack and log the violations. 429 * 430 * @param scopeAst ast node of type {@link UnusedLocalVariableCheck#SCOPES} 431 * @param variablesStack stack of all the relevant variables in the scope 432 */ 433 private void logViolations(DetailAST scopeAst, Deque<VariableDesc> variablesStack) { 434 while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) { 435 final VariableDesc variableDesc = variablesStack.pop(); 436 if (!variableDesc.isUsed() 437 && !variableDesc.isInstVarOrClassVar()) { 438 final DetailAST typeAst = variableDesc.getTypeAst(); 439 log(typeAst, MSG_UNUSED_LOCAL_VARIABLE, variableDesc.getName()); 440 } 441 } 442 } 443 444 /** 445 * We process all the blocks containing local anonymous inner classes 446 * separately after processing all the other nodes. This is being done 447 * due to the fact the instance variables of local anon inner classes can 448 * cast a shadow on local variables. 449 */ 450 private void leaveCompilationUnit() { 451 anonInnerClassHolders.forEach(holder -> { 452 iterateOverBlockContainingLocalAnonInnerClass(holder, new ArrayDeque<>()); 453 }); 454 } 455 456 /** 457 * Whether a type declaration is non-local. Annotated interfaces are always non-local. 458 * 459 * @param typeDeclAst type declaration ast 460 * @return true if type declaration is non-local 461 */ 462 private static boolean isNonLocalTypeDeclaration(DetailAST typeDeclAst) { 463 return TokenUtil.isTypeDeclaration(typeDeclAst.getType()) 464 && typeDeclAst.getParent().getType() != TokenTypes.SLIST; 465 } 466 467 /** 468 * Get the block containing local anon inner class. 469 * 470 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 471 * @return the block containing local anon inner class 472 */ 473 private static DetailAST getBlockContainingLocalAnonInnerClass(DetailAST literalNewAst) { 474 DetailAST parentAst = literalNewAst.getParent(); 475 DetailAST result = null; 476 while (!TokenUtil.isOfType(parentAst, CONTAINERS_FOR_ANON_INNERS)) { 477 if (parentAst.getType() == TokenTypes.LAMBDA 478 && parentAst.getParent() 479 .getParent().getParent().getType() == TokenTypes.OBJBLOCK) { 480 result = parentAst; 481 break; 482 } 483 parentAst = parentAst.getParent(); 484 result = parentAst; 485 } 486 return result; 487 } 488 489 /** 490 * Add local variables to the {@code variablesStack} stack. 491 * Also adds the instance variables defined in a local anonymous inner class. 492 * 493 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 494 * @param variablesStack stack of all the relevant variables in the scope 495 */ 496 private static void addLocalVariables(DetailAST varDefAst, Deque<VariableDesc> variablesStack) { 497 final DetailAST parentAst = varDefAst.getParent(); 498 final DetailAST grandParent = parentAst.getParent(); 499 final boolean isInstanceVarInAnonymousInnerClass = 500 grandParent.getType() == TokenTypes.LITERAL_NEW; 501 if (isInstanceVarInAnonymousInnerClass 502 || parentAst.getType() != TokenTypes.OBJBLOCK) { 503 final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT); 504 final VariableDesc desc = new VariableDesc(ident.getText(), 505 varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst)); 506 if (isInstanceVarInAnonymousInnerClass) { 507 desc.registerAsInstOrClassVar(); 508 } 509 variablesStack.push(desc); 510 } 511 } 512 513 /** 514 * Add instance variables and class variables to the 515 * {@link TypeDeclDesc#instanceAndClassVarStack}. 516 * 517 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 518 */ 519 private void addInstanceOrClassVar(DetailAST varDefAst) { 520 final DetailAST parentAst = varDefAst.getParent(); 521 if (isNonLocalTypeDeclaration(parentAst.getParent()) 522 && !isPrivateInstanceVariable(varDefAst)) { 523 final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT); 524 final VariableDesc desc = new VariableDesc(ident.getText(), 525 varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst)); 526 typeDeclAstToTypeDeclDesc.get(parentAst.getParent()).addInstOrClassVar(desc); 527 } 528 } 529 530 /** 531 * Whether instance variable or class variable have private access modifier. 532 * 533 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 534 * @return true if instance variable or class variable have private access modifier 535 */ 536 private static boolean isPrivateInstanceVariable(DetailAST varDefAst) { 537 final AccessModifierOption varAccessModifier = 538 CheckUtil.getAccessModifierFromModifiersToken(varDefAst); 539 return varAccessModifier == AccessModifierOption.PRIVATE; 540 } 541 542 /** 543 * Get the {@link TypeDeclDesc} of the super class of anonymous inner class. 544 * 545 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 546 * @return {@link TypeDeclDesc} of the super class of anonymous inner class 547 */ 548 private TypeDeclDesc getSuperClassOfAnonInnerClass(DetailAST literalNewAst) { 549 TypeDeclDesc obtainedClass = null; 550 final String shortNameOfClass = CheckUtil.getShortNameOfAnonInnerClass(literalNewAst); 551 if (packageName != null && shortNameOfClass.startsWith(packageName)) { 552 final Optional<TypeDeclDesc> classWithCompletePackageName = 553 typeDeclAstToTypeDeclDesc.values() 554 .stream() 555 .filter(typeDeclDesc -> { 556 return typeDeclDesc.getQualifiedName().equals(shortNameOfClass); 557 }) 558 .findFirst(); 559 if (classWithCompletePackageName.isPresent()) { 560 obtainedClass = classWithCompletePackageName.get(); 561 } 562 } 563 else { 564 final List<TypeDeclDesc> typeDeclWithSameName = typeDeclWithSameName(shortNameOfClass); 565 if (!typeDeclWithSameName.isEmpty()) { 566 obtainedClass = getTheNearestClass( 567 anonInnerAstToTypeDeclDesc.get(literalNewAst).getQualifiedName(), 568 typeDeclWithSameName); 569 } 570 } 571 return obtainedClass; 572 } 573 574 /** 575 * Add non-private instance and class variables of the super class of the anonymous class 576 * to the variables stack. 577 * 578 * @param obtainedClass super class of the anon inner class 579 * @param variablesStack stack of all the relevant variables in the scope 580 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 581 */ 582 private void modifyVariablesStack(TypeDeclDesc obtainedClass, 583 Deque<VariableDesc> variablesStack, 584 DetailAST literalNewAst) { 585 if (obtainedClass != null) { 586 final Deque<VariableDesc> instAndClassVarDeque = typeDeclAstToTypeDeclDesc 587 .get(obtainedClass.getTypeDeclAst()) 588 .getUpdatedCopyOfVarStack(literalNewAst); 589 instAndClassVarDeque.forEach(variablesStack::push); 590 } 591 } 592 593 /** 594 * Checks if there is a type declaration with same name as the super class. 595 * 596 * @param superClassName name of the super class 597 * @return true if there is another type declaration with same name. 598 */ 599 private List<TypeDeclDesc> typeDeclWithSameName(String superClassName) { 600 return typeDeclAstToTypeDeclDesc.values().stream() 601 .filter(typeDeclDesc -> { 602 return hasSameNameAsSuperClass(superClassName, typeDeclDesc); 603 }) 604 .collect(Collectors.toList()); 605 } 606 607 /** 608 * Whether the qualified name of {@code typeDeclDesc} matches the super class name. 609 * 610 * @param superClassName name of the super class 611 * @param typeDeclDesc type declaration description 612 * @return {@code true} if the qualified name of {@code typeDeclDesc} 613 * matches the super class name 614 */ 615 private boolean hasSameNameAsSuperClass(String superClassName, TypeDeclDesc typeDeclDesc) { 616 final boolean result; 617 if (packageName == null && typeDeclDesc.getDepth() == 0) { 618 result = typeDeclDesc.getQualifiedName().equals(superClassName); 619 } 620 else { 621 result = typeDeclDesc.getQualifiedName() 622 .endsWith(PACKAGE_SEPARATOR + superClassName); 623 } 624 return result; 625 } 626 627 /** 628 * For all type declarations with the same name as the superclass, gets the nearest type 629 * declaration. 630 * 631 * @param outerTypeDeclName outer type declaration of anonymous inner class 632 * @param typeDeclWithSameName typeDeclarations which have the same name as the super class 633 * @return the nearest class 634 */ 635 private static TypeDeclDesc getTheNearestClass(String outerTypeDeclName, 636 List<TypeDeclDesc> typeDeclWithSameName) { 637 return Collections.min(typeDeclWithSameName, (first, second) -> { 638 return getTypeDeclarationNameMatchingCountDiff(outerTypeDeclName, first, second); 639 }); 640 } 641 642 /** 643 * Get the difference between type declaration name matching count. If the 644 * difference between them is zero, then their depth is compared to obtain the result. 645 * 646 * @param outerTypeDeclName outer type declaration of anonymous inner class 647 * @param firstTypeDecl first input type declaration 648 * @param secondTypeDecl second input type declaration 649 * @return difference between type declaration name matching count 650 */ 651 private static int getTypeDeclarationNameMatchingCountDiff(String outerTypeDeclName, 652 TypeDeclDesc firstTypeDecl, 653 TypeDeclDesc secondTypeDecl) { 654 int diff = Integer.compare( 655 CheckUtil.typeDeclarationNameMatchingCount( 656 outerTypeDeclName, secondTypeDecl.getQualifiedName()), 657 CheckUtil.typeDeclarationNameMatchingCount( 658 outerTypeDeclName, firstTypeDecl.getQualifiedName())); 659 if (diff == 0) { 660 diff = Integer.compare(firstTypeDecl.getDepth(), secondTypeDecl.getDepth()); 661 } 662 return diff; 663 } 664 665 /** 666 * Get qualified type declaration name from type ast. 667 * 668 * @param typeDeclAst type declaration ast 669 * @return qualified name of type declaration 670 */ 671 private String getQualifiedTypeDeclarationName(DetailAST typeDeclAst) { 672 final String className = typeDeclAst.findFirstToken(TokenTypes.IDENT).getText(); 673 String outerClassQualifiedName = null; 674 if (!typeDeclarations.isEmpty()) { 675 outerClassQualifiedName = typeDeclarations.peek().getQualifiedName(); 676 } 677 return CheckUtil 678 .getQualifiedTypeDeclarationName(packageName, outerClassQualifiedName, className); 679 } 680 681 /** 682 * Iterate over all the ast nodes present under {@code ast}. 683 * 684 * @param ast ast 685 * @param variablesStack stack of all the relevant variables in the scope 686 */ 687 private void iterateOverBlockContainingLocalAnonInnerClass( 688 DetailAST ast, Deque<VariableDesc> variablesStack) { 689 DetailAST currNode = ast; 690 while (currNode != null) { 691 customVisitToken(currNode, variablesStack); 692 DetailAST toVisit = currNode.getFirstChild(); 693 while (currNode != ast && toVisit == null) { 694 customLeaveToken(currNode, variablesStack); 695 toVisit = currNode.getNextSibling(); 696 currNode = currNode.getParent(); 697 } 698 currNode = toVisit; 699 } 700 } 701 702 /** 703 * Visit all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once 704 * again. 705 * 706 * @param ast ast 707 * @param variablesStack stack of all the relevant variables in the scope 708 */ 709 private void customVisitToken(DetailAST ast, Deque<VariableDesc> variablesStack) { 710 final int type = ast.getType(); 711 if (type == TokenTypes.DOT) { 712 visitDotToken(ast, variablesStack); 713 } 714 else if (type == TokenTypes.VARIABLE_DEF) { 715 addLocalVariables(ast, variablesStack); 716 } 717 else if (type == TokenTypes.IDENT) { 718 visitIdentToken(ast, variablesStack); 719 } 720 else if (isInsideLocalAnonInnerClass(ast)) { 721 final TypeDeclDesc obtainedClass = getSuperClassOfAnonInnerClass(ast); 722 modifyVariablesStack(obtainedClass, variablesStack, ast); 723 } 724 } 725 726 /** 727 * Leave all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once 728 * again. 729 * 730 * @param ast ast 731 * @param variablesStack stack of all the relevant variables in the scope 732 */ 733 private void customLeaveToken(DetailAST ast, Deque<VariableDesc> variablesStack) { 734 logViolations(ast, variablesStack); 735 } 736 737 /** 738 * Whether to check identifier token nested under dotAst. 739 * 740 * @param dotAst dotAst 741 * @return true if ident nested under dotAst should be checked 742 */ 743 private static boolean shouldCheckIdentTokenNestedUnderDot(DetailAST dotAst) { 744 745 return TokenUtil.findFirstTokenByPredicate(dotAst, 746 childAst -> { 747 return TokenUtil.isOfType(childAst, 748 UNACCEPTABLE_CHILD_OF_DOT); 749 }) 750 .isEmpty(); 751 } 752 753 /** 754 * Checks the identifier ast. 755 * 756 * @param identAst ast of type {@link TokenTypes#IDENT} 757 * @param variablesStack stack of all the relevant variables in the scope 758 */ 759 private static void checkIdentifierAst(DetailAST identAst, Deque<VariableDesc> variablesStack) { 760 for (VariableDesc variableDesc : variablesStack) { 761 if (identAst.getText().equals(variableDesc.getName()) 762 && !isLeftHandSideValue(identAst)) { 763 variableDesc.registerAsUsed(); 764 break; 765 } 766 } 767 } 768 769 /** 770 * Find the scope of variable. 771 * 772 * @param variableDef ast of type {@link TokenTypes#VARIABLE_DEF} 773 * @return scope of variableDef 774 */ 775 private static DetailAST findScopeOfVariable(DetailAST variableDef) { 776 final DetailAST result; 777 final DetailAST parentAst = variableDef.getParent(); 778 if (TokenUtil.isOfType(parentAst, TokenTypes.SLIST, TokenTypes.OBJBLOCK)) { 779 result = parentAst; 780 } 781 else { 782 result = parentAst.getParent(); 783 } 784 return result; 785 } 786 787 /** 788 * Checks whether the ast of type {@link TokenTypes#IDENT} is 789 * used as left-hand side value. An identifier is being used as a left-hand side 790 * value if it is used as the left operand of an assignment or as an 791 * operand of a stand-alone increment or decrement. 792 * 793 * @param identAst ast of type {@link TokenTypes#IDENT} 794 * @return true if identAst is used as a left-hand side value 795 */ 796 private static boolean isLeftHandSideValue(DetailAST identAst) { 797 final DetailAST parent = identAst.getParent(); 798 return isStandAloneIncrementOrDecrement(identAst) 799 || parent.getType() == TokenTypes.ASSIGN 800 && identAst != parent.getLastChild(); 801 } 802 803 /** 804 * Checks whether the ast of type {@link TokenTypes#IDENT} is used as 805 * an operand of a stand-alone increment or decrement. 806 * 807 * @param identAst ast of type {@link TokenTypes#IDENT} 808 * @return true if identAst is used as an operand of stand-alone 809 * increment or decrement 810 */ 811 private static boolean isStandAloneIncrementOrDecrement(DetailAST identAst) { 812 final DetailAST parent = identAst.getParent(); 813 final DetailAST grandParent = parent.getParent(); 814 return TokenUtil.isOfType(parent, INCREMENT_AND_DECREMENT_TOKENS) 815 && TokenUtil.isOfType(grandParent, TokenTypes.EXPR) 816 && !isIncrementOrDecrementVariableUsed(grandParent); 817 } 818 819 /** 820 * A variable with increment or decrement operator is considered used if it 821 * is used as an argument or as an array index or for assigning value 822 * to a variable. 823 * 824 * @param exprAst ast of type {@link TokenTypes#EXPR} 825 * @return true if variable nested in exprAst is used 826 */ 827 private static boolean isIncrementOrDecrementVariableUsed(DetailAST exprAst) { 828 return TokenUtil.isOfType(exprAst.getParent(), 829 TokenTypes.ELIST, TokenTypes.INDEX_OP, TokenTypes.ASSIGN) 830 && exprAst.getParent().getParent().getType() != TokenTypes.FOR_ITERATOR; 831 } 832 833 /** 834 * Maintains information about the variable. 835 */ 836 private static final class VariableDesc { 837 838 /** 839 * The name of the variable. 840 */ 841 private final String name; 842 843 /** 844 * Ast of type {@link TokenTypes#TYPE}. 845 */ 846 private final DetailAST typeAst; 847 848 /** 849 * The scope of variable is determined by the ast of type 850 * {@link TokenTypes#SLIST} or {@link TokenTypes#LITERAL_FOR} 851 * or {@link TokenTypes#OBJBLOCK} which is enclosing the variable. 852 */ 853 private final DetailAST scope; 854 855 /** 856 * Is an instance variable or a class variable. 857 */ 858 private boolean instVarOrClassVar; 859 860 /** 861 * Is the variable used. 862 */ 863 private boolean used; 864 865 /** 866 * Create a new VariableDesc instance. 867 * 868 * @param name name of the variable 869 * @param typeAst ast of type {@link TokenTypes#TYPE} 870 * @param scope ast of type {@link TokenTypes#SLIST} or 871 * {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK} 872 * which is enclosing the variable 873 */ 874 /* package */ VariableDesc(String name, DetailAST typeAst, DetailAST scope) { 875 this.name = name; 876 this.typeAst = typeAst; 877 this.scope = scope; 878 } 879 880 /** 881 * Get the name of variable. 882 * 883 * @return name of variable 884 */ 885 public String getName() { 886 return name; 887 } 888 889 /** 890 * Get the associated ast node of type {@link TokenTypes#TYPE}. 891 * 892 * @return the associated ast node of type {@link TokenTypes#TYPE} 893 */ 894 public DetailAST getTypeAst() { 895 return typeAst; 896 } 897 898 /** 899 * Get ast of type {@link TokenTypes#SLIST} 900 * or {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK} 901 * which is enclosing the variable i.e. its scope. 902 * 903 * @return the scope associated with the variable 904 */ 905 public DetailAST getScope() { 906 return scope; 907 } 908 909 /** 910 * Register the variable as used. 911 */ 912 public void registerAsUsed() { 913 used = true; 914 } 915 916 /** 917 * Register the variable as an instance variable or 918 * class variable. 919 */ 920 public void registerAsInstOrClassVar() { 921 instVarOrClassVar = true; 922 } 923 924 /** 925 * Is the variable used or not. 926 * 927 * @return true if variable is used 928 */ 929 public boolean isUsed() { 930 return used; 931 } 932 933 /** 934 * Is an instance variable or a class variable. 935 * 936 * @return true if is an instance variable or a class variable 937 */ 938 public boolean isInstVarOrClassVar() { 939 return instVarOrClassVar; 940 } 941 } 942 943 /** 944 * Maintains information about the type declaration. 945 * Any ast node of type {@link TokenTypes#CLASS_DEF} or {@link TokenTypes#INTERFACE_DEF} 946 * or {@link TokenTypes#ENUM_DEF} or {@link TokenTypes#ANNOTATION_DEF} 947 * or {@link TokenTypes#RECORD_DEF} is considered as a type declaration. 948 */ 949 private static class TypeDeclDesc { 950 951 /** 952 * Complete type declaration name with package name and outer type declaration name. 953 */ 954 private final String qualifiedName; 955 956 /** 957 * Depth of nesting of type declaration. 958 */ 959 private final int depth; 960 961 /** 962 * Type declaration ast node. 963 */ 964 private final DetailAST typeDeclAst; 965 966 /** 967 * A stack of type declaration's instance and static variables. 968 */ 969 private final Deque<VariableDesc> instanceAndClassVarStack; 970 971 /** 972 * Create a new TypeDeclDesc instance. 973 * 974 * @param qualifiedName qualified name 975 * @param depth depth of nesting 976 * @param typeDeclAst type declaration ast node 977 */ 978 /* package */ TypeDeclDesc(String qualifiedName, int depth, 979 DetailAST typeDeclAst) { 980 this.qualifiedName = qualifiedName; 981 this.depth = depth; 982 this.typeDeclAst = typeDeclAst; 983 instanceAndClassVarStack = new ArrayDeque<>(); 984 } 985 986 /** 987 * Get the complete type declaration name i.e. type declaration name with package name 988 * and outer type declaration name. 989 * 990 * @return qualified class name 991 */ 992 public String getQualifiedName() { 993 return qualifiedName; 994 } 995 996 /** 997 * Get the depth of type declaration. 998 * 999 * @return the depth of nesting of type declaration 1000 */ 1001 public int getDepth() { 1002 return depth; 1003 } 1004 1005 /** 1006 * Get the type declaration ast node. 1007 * 1008 * @return ast node of the type declaration 1009 */ 1010 public DetailAST getTypeDeclAst() { 1011 return typeDeclAst; 1012 } 1013 1014 /** 1015 * Get the copy of variables in instanceAndClassVar stack with updated scope. 1016 * 1017 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 1018 * @return copy of variables in instanceAndClassVar stack with updated scope. 1019 */ 1020 public Deque<VariableDesc> getUpdatedCopyOfVarStack(DetailAST literalNewAst) { 1021 final DetailAST updatedScope = literalNewAst.getLastChild(); 1022 final Deque<VariableDesc> instAndClassVarDeque = new ArrayDeque<>(); 1023 instanceAndClassVarStack.forEach(instVar -> { 1024 final VariableDesc variableDesc = new VariableDesc(instVar.getName(), 1025 instVar.getTypeAst(), updatedScope); 1026 variableDesc.registerAsInstOrClassVar(); 1027 instAndClassVarDeque.push(variableDesc); 1028 }); 1029 return instAndClassVarDeque; 1030 } 1031 1032 /** 1033 * Add an instance variable or class variable to the stack. 1034 * 1035 * @param variableDesc variable to be added 1036 */ 1037 public void addInstOrClassVar(VariableDesc variableDesc) { 1038 instanceAndClassVarStack.push(variableDesc); 1039 } 1040 } 1041}