001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2023 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 final boolean isNestedClassInitialization = 372 TokenUtil.isOfType(identAst.getNextSibling(), TokenTypes.LITERAL_NEW) 373 && parent.getType() == TokenTypes.DOT; 374 375 if (isNestedClassInitialization || !isMethodReferenceMethodName 376 && !isConstructorReference 377 && !TokenUtil.isOfType(parent, UNACCEPTABLE_PARENT_OF_IDENT)) { 378 checkIdentifierAst(identAst, variablesStack); 379 } 380 } 381 382 /** 383 * Visit the type declaration token. 384 * 385 * @param typeDeclAst type declaration ast 386 */ 387 private void visitTypeDeclarationToken(DetailAST typeDeclAst) { 388 if (isNonLocalTypeDeclaration(typeDeclAst)) { 389 final String qualifiedName = getQualifiedTypeDeclarationName(typeDeclAst); 390 final TypeDeclDesc currTypeDecl = new TypeDeclDesc(qualifiedName, depth, typeDeclAst); 391 depth++; 392 typeDeclarations.push(currTypeDecl); 393 typeDeclAstToTypeDeclDesc.put(typeDeclAst, currTypeDecl); 394 } 395 } 396 397 /** 398 * Visit the local anon inner class. 399 * 400 * @param literalNewAst literalNewAst 401 */ 402 private void visitLocalAnonInnerClass(DetailAST literalNewAst) { 403 anonInnerAstToTypeDeclDesc.put(literalNewAst, typeDeclarations.peek()); 404 anonInnerClassHolders.add(getBlockContainingLocalAnonInnerClass(literalNewAst)); 405 } 406 407 /** 408 * Whether ast node of type {@link TokenTypes#LITERAL_NEW} is a part of a local 409 * anonymous inner class. 410 * 411 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 412 * @return true if variableDefAst is an instance variable in local anonymous inner class 413 */ 414 private static boolean isInsideLocalAnonInnerClass(DetailAST literalNewAst) { 415 boolean result = false; 416 final DetailAST lastChild = literalNewAst.getLastChild(); 417 if (lastChild != null && lastChild.getType() == TokenTypes.OBJBLOCK) { 418 DetailAST parentAst = literalNewAst.getParent(); 419 while (parentAst.getType() != TokenTypes.SLIST) { 420 if (TokenUtil.isTypeDeclaration(parentAst.getParent().getType())) { 421 break; 422 } 423 parentAst = parentAst.getParent(); 424 } 425 result = parentAst.getType() == TokenTypes.SLIST; 426 } 427 return result; 428 } 429 430 /** 431 * Traverse {@code variablesStack} stack and log the violations. 432 * 433 * @param scopeAst ast node of type {@link UnusedLocalVariableCheck#SCOPES} 434 * @param variablesStack stack of all the relevant variables in the scope 435 */ 436 private void logViolations(DetailAST scopeAst, Deque<VariableDesc> variablesStack) { 437 while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) { 438 final VariableDesc variableDesc = variablesStack.pop(); 439 if (!variableDesc.isUsed() 440 && !variableDesc.isInstVarOrClassVar()) { 441 final DetailAST typeAst = variableDesc.getTypeAst(); 442 log(typeAst, MSG_UNUSED_LOCAL_VARIABLE, variableDesc.getName()); 443 } 444 } 445 } 446 447 /** 448 * We process all the blocks containing local anonymous inner classes 449 * separately after processing all the other nodes. This is being done 450 * due to the fact the instance variables of local anon inner classes can 451 * cast a shadow on local variables. 452 */ 453 private void leaveCompilationUnit() { 454 anonInnerClassHolders.forEach(holder -> { 455 iterateOverBlockContainingLocalAnonInnerClass(holder, new ArrayDeque<>()); 456 }); 457 } 458 459 /** 460 * Whether a type declaration is non-local. Annotated interfaces are always non-local. 461 * 462 * @param typeDeclAst type declaration ast 463 * @return true if type declaration is non-local 464 */ 465 private static boolean isNonLocalTypeDeclaration(DetailAST typeDeclAst) { 466 return TokenUtil.isTypeDeclaration(typeDeclAst.getType()) 467 && typeDeclAst.getParent().getType() != TokenTypes.SLIST; 468 } 469 470 /** 471 * Get the block containing local anon inner class. 472 * 473 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 474 * @return the block containing local anon inner class 475 */ 476 private static DetailAST getBlockContainingLocalAnonInnerClass(DetailAST literalNewAst) { 477 DetailAST parentAst = literalNewAst.getParent(); 478 DetailAST result = null; 479 while (!TokenUtil.isOfType(parentAst, CONTAINERS_FOR_ANON_INNERS)) { 480 if (parentAst.getType() == TokenTypes.LAMBDA 481 && parentAst.getParent() 482 .getParent().getParent().getType() == TokenTypes.OBJBLOCK) { 483 result = parentAst; 484 break; 485 } 486 parentAst = parentAst.getParent(); 487 result = parentAst; 488 } 489 return result; 490 } 491 492 /** 493 * Add local variables to the {@code variablesStack} stack. 494 * Also adds the instance variables defined in a local anonymous inner class. 495 * 496 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 497 * @param variablesStack stack of all the relevant variables in the scope 498 */ 499 private static void addLocalVariables(DetailAST varDefAst, Deque<VariableDesc> variablesStack) { 500 final DetailAST parentAst = varDefAst.getParent(); 501 final DetailAST grandParent = parentAst.getParent(); 502 final boolean isInstanceVarInAnonymousInnerClass = 503 grandParent.getType() == TokenTypes.LITERAL_NEW; 504 if (isInstanceVarInAnonymousInnerClass 505 || parentAst.getType() != TokenTypes.OBJBLOCK) { 506 final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT); 507 final VariableDesc desc = new VariableDesc(ident.getText(), 508 varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst)); 509 if (isInstanceVarInAnonymousInnerClass) { 510 desc.registerAsInstOrClassVar(); 511 } 512 variablesStack.push(desc); 513 } 514 } 515 516 /** 517 * Add instance variables and class variables to the 518 * {@link TypeDeclDesc#instanceAndClassVarStack}. 519 * 520 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 521 */ 522 private void addInstanceOrClassVar(DetailAST varDefAst) { 523 final DetailAST parentAst = varDefAst.getParent(); 524 if (isNonLocalTypeDeclaration(parentAst.getParent()) 525 && !isPrivateInstanceVariable(varDefAst)) { 526 final DetailAST ident = varDefAst.findFirstToken(TokenTypes.IDENT); 527 final VariableDesc desc = new VariableDesc(ident.getText(), 528 varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst)); 529 typeDeclAstToTypeDeclDesc.get(parentAst.getParent()).addInstOrClassVar(desc); 530 } 531 } 532 533 /** 534 * Whether instance variable or class variable have private access modifier. 535 * 536 * @param varDefAst ast node of type {@link TokenTypes#VARIABLE_DEF} 537 * @return true if instance variable or class variable have private access modifier 538 */ 539 private static boolean isPrivateInstanceVariable(DetailAST varDefAst) { 540 final AccessModifierOption varAccessModifier = 541 CheckUtil.getAccessModifierFromModifiersToken(varDefAst); 542 return varAccessModifier == AccessModifierOption.PRIVATE; 543 } 544 545 /** 546 * Get the {@link TypeDeclDesc} of the super class of anonymous inner class. 547 * 548 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 549 * @return {@link TypeDeclDesc} of the super class of anonymous inner class 550 */ 551 private TypeDeclDesc getSuperClassOfAnonInnerClass(DetailAST literalNewAst) { 552 TypeDeclDesc obtainedClass = null; 553 final String shortNameOfClass = CheckUtil.getShortNameOfAnonInnerClass(literalNewAst); 554 if (packageName != null && shortNameOfClass.startsWith(packageName)) { 555 final Optional<TypeDeclDesc> classWithCompletePackageName = 556 typeDeclAstToTypeDeclDesc.values() 557 .stream() 558 .filter(typeDeclDesc -> { 559 return typeDeclDesc.getQualifiedName().equals(shortNameOfClass); 560 }) 561 .findFirst(); 562 if (classWithCompletePackageName.isPresent()) { 563 obtainedClass = classWithCompletePackageName.get(); 564 } 565 } 566 else { 567 final List<TypeDeclDesc> typeDeclWithSameName = typeDeclWithSameName(shortNameOfClass); 568 if (!typeDeclWithSameName.isEmpty()) { 569 obtainedClass = getTheNearestClass( 570 anonInnerAstToTypeDeclDesc.get(literalNewAst).getQualifiedName(), 571 typeDeclWithSameName); 572 } 573 } 574 return obtainedClass; 575 } 576 577 /** 578 * Add non-private instance and class variables of the super class of the anonymous class 579 * to the variables stack. 580 * 581 * @param obtainedClass super class of the anon inner class 582 * @param variablesStack stack of all the relevant variables in the scope 583 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 584 */ 585 private void modifyVariablesStack(TypeDeclDesc obtainedClass, 586 Deque<VariableDesc> variablesStack, 587 DetailAST literalNewAst) { 588 if (obtainedClass != null) { 589 final Deque<VariableDesc> instAndClassVarDeque = typeDeclAstToTypeDeclDesc 590 .get(obtainedClass.getTypeDeclAst()) 591 .getUpdatedCopyOfVarStack(literalNewAst); 592 instAndClassVarDeque.forEach(variablesStack::push); 593 } 594 } 595 596 /** 597 * Checks if there is a type declaration with same name as the super class. 598 * 599 * @param superClassName name of the super class 600 * @return true if there is another type declaration with same name. 601 */ 602 private List<TypeDeclDesc> typeDeclWithSameName(String superClassName) { 603 return typeDeclAstToTypeDeclDesc.values().stream() 604 .filter(typeDeclDesc -> { 605 return hasSameNameAsSuperClass(superClassName, typeDeclDesc); 606 }) 607 .collect(Collectors.toList()); 608 } 609 610 /** 611 * Whether the qualified name of {@code typeDeclDesc} matches the super class name. 612 * 613 * @param superClassName name of the super class 614 * @param typeDeclDesc type declaration description 615 * @return {@code true} if the qualified name of {@code typeDeclDesc} 616 * matches the super class name 617 */ 618 private boolean hasSameNameAsSuperClass(String superClassName, TypeDeclDesc typeDeclDesc) { 619 final boolean result; 620 if (packageName == null && typeDeclDesc.getDepth() == 0) { 621 result = typeDeclDesc.getQualifiedName().equals(superClassName); 622 } 623 else { 624 result = typeDeclDesc.getQualifiedName() 625 .endsWith(PACKAGE_SEPARATOR + superClassName); 626 } 627 return result; 628 } 629 630 /** 631 * For all type declarations with the same name as the superclass, gets the nearest type 632 * declaration. 633 * 634 * @param outerTypeDeclName outer type declaration of anonymous inner class 635 * @param typeDeclWithSameName typeDeclarations which have the same name as the super class 636 * @return the nearest class 637 */ 638 private static TypeDeclDesc getTheNearestClass(String outerTypeDeclName, 639 List<TypeDeclDesc> typeDeclWithSameName) { 640 return Collections.min(typeDeclWithSameName, (first, second) -> { 641 return getTypeDeclarationNameMatchingCountDiff(outerTypeDeclName, first, second); 642 }); 643 } 644 645 /** 646 * Get the difference between type declaration name matching count. If the 647 * difference between them is zero, then their depth is compared to obtain the result. 648 * 649 * @param outerTypeDeclName outer type declaration of anonymous inner class 650 * @param firstTypeDecl first input type declaration 651 * @param secondTypeDecl second input type declaration 652 * @return difference between type declaration name matching count 653 */ 654 private static int getTypeDeclarationNameMatchingCountDiff(String outerTypeDeclName, 655 TypeDeclDesc firstTypeDecl, 656 TypeDeclDesc secondTypeDecl) { 657 int diff = Integer.compare( 658 CheckUtil.typeDeclarationNameMatchingCount( 659 outerTypeDeclName, secondTypeDecl.getQualifiedName()), 660 CheckUtil.typeDeclarationNameMatchingCount( 661 outerTypeDeclName, firstTypeDecl.getQualifiedName())); 662 if (diff == 0) { 663 diff = Integer.compare(firstTypeDecl.getDepth(), secondTypeDecl.getDepth()); 664 } 665 return diff; 666 } 667 668 /** 669 * Get qualified type declaration name from type ast. 670 * 671 * @param typeDeclAst type declaration ast 672 * @return qualified name of type declaration 673 */ 674 private String getQualifiedTypeDeclarationName(DetailAST typeDeclAst) { 675 final String className = typeDeclAst.findFirstToken(TokenTypes.IDENT).getText(); 676 String outerClassQualifiedName = null; 677 if (!typeDeclarations.isEmpty()) { 678 outerClassQualifiedName = typeDeclarations.peek().getQualifiedName(); 679 } 680 return CheckUtil 681 .getQualifiedTypeDeclarationName(packageName, outerClassQualifiedName, className); 682 } 683 684 /** 685 * Iterate over all the ast nodes present under {@code ast}. 686 * 687 * @param ast ast 688 * @param variablesStack stack of all the relevant variables in the scope 689 */ 690 private void iterateOverBlockContainingLocalAnonInnerClass( 691 DetailAST ast, Deque<VariableDesc> variablesStack) { 692 DetailAST currNode = ast; 693 while (currNode != null) { 694 customVisitToken(currNode, variablesStack); 695 DetailAST toVisit = currNode.getFirstChild(); 696 while (currNode != ast && toVisit == null) { 697 customLeaveToken(currNode, variablesStack); 698 toVisit = currNode.getNextSibling(); 699 currNode = currNode.getParent(); 700 } 701 currNode = toVisit; 702 } 703 } 704 705 /** 706 * Visit all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once 707 * again. 708 * 709 * @param ast ast 710 * @param variablesStack stack of all the relevant variables in the scope 711 */ 712 private void customVisitToken(DetailAST ast, Deque<VariableDesc> variablesStack) { 713 final int type = ast.getType(); 714 if (type == TokenTypes.DOT) { 715 visitDotToken(ast, variablesStack); 716 } 717 else if (type == TokenTypes.VARIABLE_DEF) { 718 addLocalVariables(ast, variablesStack); 719 } 720 else if (type == TokenTypes.IDENT) { 721 visitIdentToken(ast, variablesStack); 722 } 723 else if (isInsideLocalAnonInnerClass(ast)) { 724 final TypeDeclDesc obtainedClass = getSuperClassOfAnonInnerClass(ast); 725 modifyVariablesStack(obtainedClass, variablesStack, ast); 726 } 727 } 728 729 /** 730 * Leave all ast nodes under {@link UnusedLocalVariableCheck#anonInnerClassHolders} once 731 * again. 732 * 733 * @param ast ast 734 * @param variablesStack stack of all the relevant variables in the scope 735 */ 736 private void customLeaveToken(DetailAST ast, Deque<VariableDesc> variablesStack) { 737 logViolations(ast, variablesStack); 738 } 739 740 /** 741 * Whether to check identifier token nested under dotAst. 742 * 743 * @param dotAst dotAst 744 * @return true if ident nested under dotAst should be checked 745 */ 746 private static boolean shouldCheckIdentTokenNestedUnderDot(DetailAST dotAst) { 747 748 return TokenUtil.findFirstTokenByPredicate(dotAst, 749 childAst -> { 750 return TokenUtil.isOfType(childAst, 751 UNACCEPTABLE_CHILD_OF_DOT); 752 }) 753 .isEmpty(); 754 } 755 756 /** 757 * Checks the identifier ast. 758 * 759 * @param identAst ast of type {@link TokenTypes#IDENT} 760 * @param variablesStack stack of all the relevant variables in the scope 761 */ 762 private static void checkIdentifierAst(DetailAST identAst, Deque<VariableDesc> variablesStack) { 763 for (VariableDesc variableDesc : variablesStack) { 764 if (identAst.getText().equals(variableDesc.getName()) 765 && !isLeftHandSideValue(identAst)) { 766 variableDesc.registerAsUsed(); 767 break; 768 } 769 } 770 } 771 772 /** 773 * Find the scope of variable. 774 * 775 * @param variableDef ast of type {@link TokenTypes#VARIABLE_DEF} 776 * @return scope of variableDef 777 */ 778 private static DetailAST findScopeOfVariable(DetailAST variableDef) { 779 final DetailAST result; 780 final DetailAST parentAst = variableDef.getParent(); 781 if (TokenUtil.isOfType(parentAst, TokenTypes.SLIST, TokenTypes.OBJBLOCK)) { 782 result = parentAst; 783 } 784 else { 785 result = parentAst.getParent(); 786 } 787 return result; 788 } 789 790 /** 791 * Checks whether the ast of type {@link TokenTypes#IDENT} is 792 * used as left-hand side value. An identifier is being used as a left-hand side 793 * value if it is used as the left operand of an assignment or as an 794 * operand of a stand-alone increment or decrement. 795 * 796 * @param identAst ast of type {@link TokenTypes#IDENT} 797 * @return true if identAst is used as a left-hand side value 798 */ 799 private static boolean isLeftHandSideValue(DetailAST identAst) { 800 final DetailAST parent = identAst.getParent(); 801 return isStandAloneIncrementOrDecrement(identAst) 802 || parent.getType() == TokenTypes.ASSIGN 803 && identAst != parent.getLastChild(); 804 } 805 806 /** 807 * Checks whether the ast of type {@link TokenTypes#IDENT} is used as 808 * an operand of a stand-alone increment or decrement. 809 * 810 * @param identAst ast of type {@link TokenTypes#IDENT} 811 * @return true if identAst is used as an operand of stand-alone 812 * increment or decrement 813 */ 814 private static boolean isStandAloneIncrementOrDecrement(DetailAST identAst) { 815 final DetailAST parent = identAst.getParent(); 816 final DetailAST grandParent = parent.getParent(); 817 return TokenUtil.isOfType(parent, INCREMENT_AND_DECREMENT_TOKENS) 818 && TokenUtil.isOfType(grandParent, TokenTypes.EXPR) 819 && !isIncrementOrDecrementVariableUsed(grandParent); 820 } 821 822 /** 823 * A variable with increment or decrement operator is considered used if it 824 * is used as an argument or as an array index or for assigning value 825 * to a variable. 826 * 827 * @param exprAst ast of type {@link TokenTypes#EXPR} 828 * @return true if variable nested in exprAst is used 829 */ 830 private static boolean isIncrementOrDecrementVariableUsed(DetailAST exprAst) { 831 return TokenUtil.isOfType(exprAst.getParent(), 832 TokenTypes.ELIST, TokenTypes.INDEX_OP, TokenTypes.ASSIGN) 833 && exprAst.getParent().getParent().getType() != TokenTypes.FOR_ITERATOR; 834 } 835 836 /** 837 * Maintains information about the variable. 838 */ 839 private static final class VariableDesc { 840 841 /** 842 * The name of the variable. 843 */ 844 private final String name; 845 846 /** 847 * Ast of type {@link TokenTypes#TYPE}. 848 */ 849 private final DetailAST typeAst; 850 851 /** 852 * The scope of variable is determined by the ast of type 853 * {@link TokenTypes#SLIST} or {@link TokenTypes#LITERAL_FOR} 854 * or {@link TokenTypes#OBJBLOCK} which is enclosing the variable. 855 */ 856 private final DetailAST scope; 857 858 /** 859 * Is an instance variable or a class variable. 860 */ 861 private boolean instVarOrClassVar; 862 863 /** 864 * Is the variable used. 865 */ 866 private boolean used; 867 868 /** 869 * Create a new VariableDesc instance. 870 * 871 * @param name name of the variable 872 * @param typeAst ast of type {@link TokenTypes#TYPE} 873 * @param scope ast of type {@link TokenTypes#SLIST} or 874 * {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK} 875 * which is enclosing the variable 876 */ 877 private VariableDesc(String name, DetailAST typeAst, DetailAST scope) { 878 this.name = name; 879 this.typeAst = typeAst; 880 this.scope = scope; 881 } 882 883 /** 884 * Get the name of variable. 885 * 886 * @return name of variable 887 */ 888 public String getName() { 889 return name; 890 } 891 892 /** 893 * Get the associated ast node of type {@link TokenTypes#TYPE}. 894 * 895 * @return the associated ast node of type {@link TokenTypes#TYPE} 896 */ 897 public DetailAST getTypeAst() { 898 return typeAst; 899 } 900 901 /** 902 * Get ast of type {@link TokenTypes#SLIST} 903 * or {@link TokenTypes#LITERAL_FOR} or {@link TokenTypes#OBJBLOCK} 904 * which is enclosing the variable i.e. its scope. 905 * 906 * @return the scope associated with the variable 907 */ 908 public DetailAST getScope() { 909 return scope; 910 } 911 912 /** 913 * Register the variable as used. 914 */ 915 public void registerAsUsed() { 916 used = true; 917 } 918 919 /** 920 * Register the variable as an instance variable or 921 * class variable. 922 */ 923 public void registerAsInstOrClassVar() { 924 instVarOrClassVar = true; 925 } 926 927 /** 928 * Is the variable used or not. 929 * 930 * @return true if variable is used 931 */ 932 public boolean isUsed() { 933 return used; 934 } 935 936 /** 937 * Is an instance variable or a class variable. 938 * 939 * @return true if is an instance variable or a class variable 940 */ 941 public boolean isInstVarOrClassVar() { 942 return instVarOrClassVar; 943 } 944 } 945 946 /** 947 * Maintains information about the type declaration. 948 * Any ast node of type {@link TokenTypes#CLASS_DEF} or {@link TokenTypes#INTERFACE_DEF} 949 * or {@link TokenTypes#ENUM_DEF} or {@link TokenTypes#ANNOTATION_DEF} 950 * or {@link TokenTypes#RECORD_DEF} is considered as a type declaration. 951 */ 952 private static final class TypeDeclDesc { 953 954 /** 955 * Complete type declaration name with package name and outer type declaration name. 956 */ 957 private final String qualifiedName; 958 959 /** 960 * Depth of nesting of type declaration. 961 */ 962 private final int depth; 963 964 /** 965 * Type declaration ast node. 966 */ 967 private final DetailAST typeDeclAst; 968 969 /** 970 * A stack of type declaration's instance and static variables. 971 */ 972 private final Deque<VariableDesc> instanceAndClassVarStack; 973 974 /** 975 * Create a new TypeDeclDesc instance. 976 * 977 * @param qualifiedName qualified name 978 * @param depth depth of nesting 979 * @param typeDeclAst type declaration ast node 980 */ 981 private TypeDeclDesc(String qualifiedName, int depth, 982 DetailAST typeDeclAst) { 983 this.qualifiedName = qualifiedName; 984 this.depth = depth; 985 this.typeDeclAst = typeDeclAst; 986 instanceAndClassVarStack = new ArrayDeque<>(); 987 } 988 989 /** 990 * Get the complete type declaration name i.e. type declaration name with package name 991 * and outer type declaration name. 992 * 993 * @return qualified class name 994 */ 995 public String getQualifiedName() { 996 return qualifiedName; 997 } 998 999 /** 1000 * Get the depth of type declaration. 1001 * 1002 * @return the depth of nesting of type declaration 1003 */ 1004 public int getDepth() { 1005 return depth; 1006 } 1007 1008 /** 1009 * Get the type declaration ast node. 1010 * 1011 * @return ast node of the type declaration 1012 */ 1013 public DetailAST getTypeDeclAst() { 1014 return typeDeclAst; 1015 } 1016 1017 /** 1018 * Get the copy of variables in instanceAndClassVar stack with updated scope. 1019 * 1020 * @param literalNewAst ast node of type {@link TokenTypes#LITERAL_NEW} 1021 * @return copy of variables in instanceAndClassVar stack with updated scope. 1022 */ 1023 public Deque<VariableDesc> getUpdatedCopyOfVarStack(DetailAST literalNewAst) { 1024 final DetailAST updatedScope = literalNewAst.getLastChild(); 1025 final Deque<VariableDesc> instAndClassVarDeque = new ArrayDeque<>(); 1026 instanceAndClassVarStack.forEach(instVar -> { 1027 final VariableDesc variableDesc = new VariableDesc(instVar.getName(), 1028 instVar.getTypeAst(), updatedScope); 1029 variableDesc.registerAsInstOrClassVar(); 1030 instAndClassVarDeque.push(variableDesc); 1031 }); 1032 return instAndClassVarDeque; 1033 } 1034 1035 /** 1036 * Add an instance variable or class variable to the stack. 1037 * 1038 * @param variableDesc variable to be added 1039 */ 1040 public void addInstOrClassVar(VariableDesc variableDesc) { 1041 instanceAndClassVarStack.push(variableDesc); 1042 } 1043 } 1044}