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