forked from checkstyle/checkstyle
/
VariableDeclarationUsageDistanceCheck.java
1007 lines (922 loc) · 35 KB
/
VariableDeclarationUsageDistanceCheck.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 and other text files 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.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.StatelessCheck;
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.utils.TokenUtil;
/**
* <p>
* Checks the distance between declaration of variable and its first usage.
* Note : Variable declaration/initialization statements are not counted while calculating length.
* </p>
* <ul>
* <li>
* Property {@code allowedDistance} - Specify distance between declaration
* of variable and its first usage. Values should be greater than 0.
* Type is {@code int}.
* Default value is {@code 3}.
* </li>
* <li>
* Property {@code ignoreVariablePattern} - Define RegExp to ignore distance calculation
* for variables listed in this pattern.
* Type is {@code java.util.regex.Pattern}.
* Default value is {@code ""}.
* </li>
* <li>
* Property {@code validateBetweenScopes} - Allow to calculate the distance between
* declaration of variable and its first usage in the different scopes.
* Type is {@code boolean}.
* Default value is {@code false}.
* </li>
* <li>
* Property {@code ignoreFinal} - Allow to ignore variables with a 'final' modifier.
* Type is {@code boolean}.
* Default value is {@code true}.
* </li>
* </ul>
* <p>
* To configure the check with default config:
* </p>
* <pre>
* <module name="VariableDeclarationUsageDistance"/>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
*
* public void foo1() {
* int num; // violation, distance = 4
* final int PI; // OK, final variables not checked
* System.out.println("Statement 1");
* System.out.println("Statement 2");
* System.out.println("Statement 3");
* num = 1;
* PI = 3.14;
* }
*
* public void foo2() {
* int a; // OK, used in different scope
* int b; // OK, used in different scope
* int count = 0; // OK, used in different scope
*
* {
* System.out.println("Inside inner scope");
* a = 1;
* b = 2;
* count++;
* }
* }
* }
* </pre>
* <p>
* Check can detect a block of initialization methods. If a variable is used in
* such a block and there are no other statements after variable declaration, then distance = 1.
* </p>
* <p>Case #1:</p>
* <pre>
* int minutes = 5;
* Calendar cal = Calendar.getInstance();
* cal.setTimeInMillis(timeNow);
* cal.set(Calendar.SECOND, 0);
* cal.set(Calendar.MILLISECOND, 0);
* cal.set(Calendar.HOUR_OF_DAY, hh);
* cal.set(Calendar.MINUTE, minutes);
* </pre>
* <p>
* The distance for the variable "minutes" is 1 even
* though this variable is used in the fifth method's call.
* </p>
* <p>Case #2:</p>
* <pre>
* int minutes = 5;
* Calendar cal = Calendar.getInstance();
* cal.setTimeInMillis(timeNow);
* cal.set(Calendar.SECOND, 0);
* cal.set(Calendar.MILLISECOND, 0);
* <i>System.out.println(cal);</i>
* cal.set(Calendar.HOUR_OF_DAY, hh);
* cal.set(Calendar.MINUTE, minutes);
* </pre>
* <p>
* The distance for the variable "minutes" is 6 because there is one more expression
* (except the initialization block) between the declaration of this variable and its usage.
* </p>
* <p>
* To configure the check to set allowed distance:
* </p>
* <pre>
* <module name="VariableDeclarationUsageDistance">
* <property name="allowedDistance" value="4"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
*
* public void foo1() {
* int num; // OK, distance = 4
* final int PI; // OK, final variables not checked
* System.out.println("Statement 1");
* System.out.println("Statement 2");
* System.out.println("Statement 3");
* num = 1;
* PI = 3.14;
* }
*
* public void foo2() {
* int a; // OK, used in different scope
* int b; // OK, used in different scope
* int count = 0; // OK, used in different scope
*
* {
* System.out.println("Inside inner scope");
* a = 1;
* b = 2;
* count++;
* }
* }
* }
* </pre>
* <p>
* To configure the check to ignore certain variables:
* </p>
* <pre>
* <module name="VariableDeclarationUsageDistance">
* <property name="ignoreVariablePattern" value="^num$"/>
* </module>
* </pre>
* <p>
* This configuration ignores variables named "num".
* </p>
* <p>Example:</p>
* <pre>
* public class Test {
*
* public void foo1() {
* int num; // OK, variable ignored
* final int PI; // OK, final variables not checked
* System.out.println("Statement 1");
* System.out.println("Statement 2");
* System.out.println("Statement 3");
* num = 1;
* PI = 3.14;
* }
*
* public void foo2() {
* int a; // OK, used in different scope
* int b; // OK, used in different scope
* int count = 0; // OK, used in different scope
*
* {
* System.out.println("Inside inner scope");
* a = 1;
* b = 2;
* count++;
* }
* }
* }
* </pre>
* <p>
* To configure the check to force validation between scopes:
* </p>
* <pre>
* <module name="VariableDeclarationUsageDistance">
* <property name="validateBetweenScopes" value="true"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
*
* public void foo1() {
* int num; // violation, distance = 4
* final int PI; // OK, final variables not checked
* System.out.println("Statement 1");
* System.out.println("Statement 2");
* System.out.println("Statement 3");
* num = 1;
* PI = 3.14;
* }
*
* public void foo2() {
* int a; // OK, distance = 2
* int b; // OK, distance = 3
* int count = 0; // violation, distance = 4
*
* {
* System.out.println("Inside inner scope");
* a = 1;
* b = 2;
* count++;
* }
* }
* }
* </pre>
* <p>
* To configure the check to check final variables:
* </p>
* <pre>
* <module name="VariableDeclarationUsageDistance">
* <property name="ignoreFinal" value="false"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
*
* public void foo1() {
* int num; // violation, distance = 4
* final int PI; // violation, distance = 5
* System.out.println("Statement 1");
* System.out.println("Statement 2");
* System.out.println("Statement 3");
* num = 1;
* PI = 3.14;
* }
*
* public void foo2() {
* int a; // OK, used in different scope
* int b; // OK, used in different scope
* int count = 0; // OK, used in different scope
*
* {
* System.out.println("Inside inner scope");
* a = 1;
* b = 2;
* count++;
* }
* }
* }
* </pre>
* <p>
* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
* </p>
* <p>
* Violation Message Keys:
* </p>
* <ul>
* <li>
* {@code variable.declaration.usage.distance}
* </li>
* <li>
* {@code variable.declaration.usage.distance.extend}
* </li>
* </ul>
*
* @since 5.8
*/
@StatelessCheck
public class VariableDeclarationUsageDistanceCheck extends AbstractCheck {
/**
* Warning message key.
*/
public static final String MSG_KEY = "variable.declaration.usage.distance";
/**
* Warning message key.
*/
public static final String MSG_KEY_EXT = "variable.declaration.usage.distance.extend";
/**
* Default value of distance between declaration of variable and its first
* usage.
*/
private static final int DEFAULT_DISTANCE = 3;
/**
* Specify distance between declaration of variable and its first usage.
* Values should be greater than 0.
*/
private int allowedDistance = DEFAULT_DISTANCE;
/**
* Define RegExp to ignore distance calculation for variables listed in
* this pattern.
*/
private Pattern ignoreVariablePattern = Pattern.compile("");
/**
* Allow to calculate the distance between declaration of variable and its
* first usage in the different scopes.
*/
private boolean validateBetweenScopes;
/** Allow to ignore variables with a 'final' modifier. */
private boolean ignoreFinal = true;
/**
* Setter to specify distance between declaration of variable and its first usage.
* Values should be greater than 0.
*
* @param allowedDistance
* Allowed distance between declaration of variable and its first
* usage.
*/
public void setAllowedDistance(int allowedDistance) {
this.allowedDistance = allowedDistance;
}
/**
* Setter to define RegExp to ignore distance calculation for variables listed in this pattern.
*
* @param pattern a pattern.
*/
public void setIgnoreVariablePattern(Pattern pattern) {
ignoreVariablePattern = pattern;
}
/**
* Setter to allow to calculate the distance between declaration of
* variable and its first usage in the different scopes.
*
* @param validateBetweenScopes
* Defines if allow to calculate distance between declaration of
* variable and its first usage in different scopes or not.
*/
public void setValidateBetweenScopes(boolean validateBetweenScopes) {
this.validateBetweenScopes = validateBetweenScopes;
}
/**
* Setter to allow to ignore variables with a 'final' modifier.
*
* @param ignoreFinal
* Defines if ignore variables with 'final' modifier or not.
*/
public void setIgnoreFinal(boolean ignoreFinal) {
this.ignoreFinal = ignoreFinal;
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.VARIABLE_DEF};
}
@Override
public void visitToken(DetailAST ast) {
final int parentType = ast.getParent().getType();
final DetailAST modifiers = ast.getFirstChild();
if (parentType != TokenTypes.OBJBLOCK
&& (!ignoreFinal || modifiers.findFirstToken(TokenTypes.FINAL) == null)) {
final DetailAST variable = ast.findFirstToken(TokenTypes.IDENT);
if (!isVariableMatchesIgnorePattern(variable.getText())) {
final DetailAST semicolonAst = ast.getNextSibling();
final Entry<DetailAST, Integer> entry;
if (validateBetweenScopes) {
entry = calculateDistanceBetweenScopes(semicolonAst, variable);
}
else {
entry = calculateDistanceInSingleScope(semicolonAst, variable);
}
final DetailAST variableUsageAst = entry.getKey();
final int dist = entry.getValue();
if (dist > allowedDistance
&& !isInitializationSequence(variableUsageAst, variable.getText())) {
if (ignoreFinal) {
log(ast, MSG_KEY_EXT, variable.getText(), dist, allowedDistance);
}
else {
log(ast, MSG_KEY, variable.getText(), dist, allowedDistance);
}
}
}
}
}
/**
* Get name of instance whose method is called.
*
* @param methodCallAst
* DetailAST of METHOD_CALL.
* @return name of instance.
*/
private static String getInstanceName(DetailAST methodCallAst) {
final String methodCallName =
FullIdent.createFullIdentBelow(methodCallAst).getText();
final int lastDotIndex = methodCallName.lastIndexOf('.');
String instanceName = "";
if (lastDotIndex != -1) {
instanceName = methodCallName.substring(0, lastDotIndex);
}
return instanceName;
}
/**
* Processes statements until usage of variable to detect sequence of
* initialization methods.
*
* @param variableUsageAst
* DetailAST of expression that uses variable named variableName.
* @param variableName
* name of considered variable.
* @return true if statements between declaration and usage of variable are
* initialization methods.
*/
private static boolean isInitializationSequence(
DetailAST variableUsageAst, String variableName) {
boolean result = true;
boolean isUsedVariableDeclarationFound = false;
DetailAST currentSiblingAst = variableUsageAst;
String initInstanceName = "";
while (result
&& !isUsedVariableDeclarationFound
&& currentSiblingAst != null) {
switch (currentSiblingAst.getType()) {
case TokenTypes.EXPR:
final DetailAST methodCallAst = currentSiblingAst.getFirstChild();
if (methodCallAst.getType() == TokenTypes.METHOD_CALL) {
final String instanceName =
getInstanceName(methodCallAst);
// method is called without instance
if (instanceName.isEmpty()) {
result = false;
}
// differs from previous instance
else if (!instanceName.equals(initInstanceName)) {
if (initInstanceName.isEmpty()) {
initInstanceName = instanceName;
}
else {
result = false;
}
}
}
else {
// is not method call
result = false;
}
break;
case TokenTypes.VARIABLE_DEF:
final String currentVariableName = currentSiblingAst
.findFirstToken(TokenTypes.IDENT).getText();
isUsedVariableDeclarationFound = variableName.equals(currentVariableName);
break;
case TokenTypes.SEMI:
break;
default:
result = false;
}
currentSiblingAst = currentSiblingAst.getPreviousSibling();
}
return result;
}
/**
* Calculates distance between declaration of variable and its first usage
* in single scope.
*
* @param semicolonAst
* Regular node of Ast which is checked for content of checking
* variable.
* @param variableIdentAst
* Variable which distance is calculated for.
* @return entry which contains expression with variable usage and distance.
* If variable usage is not found, then the expression node is null,
* although the distance can be greater than zero.
*/
private static Entry<DetailAST, Integer> calculateDistanceInSingleScope(
DetailAST semicolonAst, DetailAST variableIdentAst) {
int dist = 0;
boolean firstUsageFound = false;
DetailAST currentAst = semicolonAst;
DetailAST variableUsageAst = null;
while (!firstUsageFound && currentAst != null) {
if (currentAst.getFirstChild() != null) {
if (isChild(currentAst, variableIdentAst)) {
dist = getDistToVariableUsageInChildNode(currentAst, variableIdentAst, dist);
variableUsageAst = currentAst;
firstUsageFound = true;
}
else if (currentAst.getType() != TokenTypes.VARIABLE_DEF) {
dist++;
}
}
currentAst = currentAst.getNextSibling();
}
return new SimpleEntry<>(variableUsageAst, dist);
}
/**
* Returns the distance to variable usage for in the child node.
*
* @param childNode child node.
* @param varIdent variable variable identifier.
* @param currentDistToVarUsage current distance to the variable usage.
* @return the distance to variable usage for in the child node.
*/
private static int getDistToVariableUsageInChildNode(DetailAST childNode, DetailAST varIdent,
int currentDistToVarUsage) {
DetailAST examineNode = childNode;
if (examineNode.getType() == TokenTypes.LABELED_STAT) {
examineNode = examineNode.getFirstChild().getNextSibling();
}
int resultDist = currentDistToVarUsage;
switch (examineNode.getType()) {
case TokenTypes.VARIABLE_DEF:
resultDist++;
break;
case TokenTypes.SLIST:
resultDist = 0;
break;
case TokenTypes.LITERAL_FOR:
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF:
case TokenTypes.LITERAL_SWITCH:
if (isVariableInOperatorExpr(examineNode, varIdent)) {
resultDist++;
}
else {
// variable usage is in inner scope
// reset counters, because we can't determine distance
resultDist = 0;
}
break;
default:
if (examineNode.findFirstToken(TokenTypes.SLIST) == null) {
resultDist++;
}
else {
resultDist = 0;
}
}
return resultDist;
}
/**
* Calculates distance between declaration of variable and its first usage
* in multiple scopes.
*
* @param ast
* Regular node of Ast which is checked for content of checking
* variable.
* @param variable
* Variable which distance is calculated for.
* @return entry which contains expression with variable usage and distance.
*/
private static Entry<DetailAST, Integer> calculateDistanceBetweenScopes(
DetailAST ast, DetailAST variable) {
int dist = 0;
DetailAST currentScopeAst = ast;
DetailAST variableUsageAst = null;
while (currentScopeAst != null) {
final Entry<List<DetailAST>, Integer> searchResult =
searchVariableUsageExpressions(variable, currentScopeAst);
currentScopeAst = null;
final List<DetailAST> variableUsageExpressions = searchResult.getKey();
dist += searchResult.getValue();
// If variable usage exists in a single scope, then look into
// this scope and count distance until variable usage.
if (variableUsageExpressions.size() == 1) {
final DetailAST blockWithVariableUsage = variableUsageExpressions
.get(0);
DetailAST exprWithVariableUsage = null;
switch (blockWithVariableUsage.getType()) {
case TokenTypes.VARIABLE_DEF:
case TokenTypes.EXPR:
dist++;
break;
case TokenTypes.LITERAL_FOR:
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_DO:
exprWithVariableUsage = getFirstNodeInsideForWhileDoWhileBlocks(
blockWithVariableUsage, variable);
break;
case TokenTypes.LITERAL_IF:
exprWithVariableUsage = getFirstNodeInsideIfBlock(
blockWithVariableUsage, variable);
break;
case TokenTypes.LITERAL_SWITCH:
exprWithVariableUsage = getFirstNodeInsideSwitchBlock(
blockWithVariableUsage, variable);
break;
case TokenTypes.LITERAL_TRY:
exprWithVariableUsage =
getFirstNodeInsideTryCatchFinallyBlocks(blockWithVariableUsage,
variable);
break;
default:
exprWithVariableUsage = blockWithVariableUsage.getFirstChild();
}
currentScopeAst = exprWithVariableUsage;
variableUsageAst =
Objects.requireNonNullElse(exprWithVariableUsage, blockWithVariableUsage);
}
// If there's no any variable usage, then distance = 0.
else if (variableUsageExpressions.isEmpty()) {
variableUsageAst = null;
}
// If variable usage exists in different scopes, then distance =
// distance until variable first usage.
else {
dist++;
variableUsageAst = variableUsageExpressions.get(0);
}
}
return new SimpleEntry<>(variableUsageAst, dist);
}
/**
* Searches variable usages starting from specified statement.
*
* @param variableAst Variable that is used.
* @param statementAst DetailAST to start searching from.
* @return entry which contains list with found expressions that use the variable
* and distance from specified statement to first found expression.
*/
private static Entry<List<DetailAST>, Integer>
searchVariableUsageExpressions(final DetailAST variableAst, final DetailAST statementAst) {
final List<DetailAST> variableUsageExpressions = new ArrayList<>();
int distance = 0;
DetailAST currentStatementAst = statementAst;
while (currentStatementAst != null) {
if (currentStatementAst.getFirstChild() != null) {
if (isChild(currentStatementAst, variableAst)) {
variableUsageExpressions.add(currentStatementAst);
}
// If expression doesn't contain variable and this variable
// hasn't been met yet, then distance + 1.
else if (variableUsageExpressions.isEmpty()
&& currentStatementAst.getType() != TokenTypes.VARIABLE_DEF) {
distance++;
}
}
currentStatementAst = currentStatementAst.getNextSibling();
}
return new SimpleEntry<>(variableUsageExpressions, distance);
}
/**
* Gets first Ast node inside FOR, WHILE or DO-WHILE blocks if variable
* usage is met only inside the block (not in its declaration!).
*
* @param block
* Ast node represents FOR, WHILE or DO-WHILE block.
* @param variable
* Variable which is checked for content in block.
* @return If variable usage is met only inside the block
* (not in its declaration!) then return the first Ast node
* of this block, otherwise - null.
*/
private static DetailAST getFirstNodeInsideForWhileDoWhileBlocks(
DetailAST block, DetailAST variable) {
DetailAST firstNodeInsideBlock = null;
if (!isVariableInOperatorExpr(block, variable)) {
final DetailAST currentNode;
// Find currentNode for DO-WHILE block.
if (block.getType() == TokenTypes.LITERAL_DO) {
currentNode = block.getFirstChild();
}
// Find currentNode for FOR or WHILE block.
else {
// Looking for RPAREN ( ')' ) token to mark the end of operator
// expression.
currentNode = block.findFirstToken(TokenTypes.RPAREN).getNextSibling();
}
final int currentNodeType = currentNode.getType();
if (currentNodeType != TokenTypes.EXPR) {
firstNodeInsideBlock = currentNode;
}
}
return firstNodeInsideBlock;
}
/**
* Gets first Ast node inside IF block if variable usage is met
* only inside the block (not in its declaration!).
*
* @param block
* Ast node represents IF block.
* @param variable
* Variable which is checked for content in block.
* @return If variable usage is met only inside the block
* (not in its declaration!) then return the first Ast node
* of this block, otherwise - null.
*/
private static DetailAST getFirstNodeInsideIfBlock(
DetailAST block, DetailAST variable) {
DetailAST firstNodeInsideBlock = null;
if (!isVariableInOperatorExpr(block, variable)) {
final Optional<DetailAST> slistToken = TokenUtil
.findFirstTokenByPredicate(block, token -> token.getType() == TokenTypes.SLIST);
final DetailAST currentNode = block.getLastChild();
DetailAST previousNode = currentNode.getPreviousSibling();
// Is if statement without '{}' and has a following else branch,
// then change previousNode to the if statement body.
if (slistToken.isEmpty()
&& currentNode.getType() == TokenTypes.LITERAL_ELSE) {
previousNode = previousNode.getPreviousSibling();
}
final List<DetailAST> variableUsageExpressions = new ArrayList<>();
if (isChild(previousNode, variable)) {
variableUsageExpressions.add(previousNode);
}
if (isChild(currentNode, variable)) {
variableUsageExpressions.add(currentNode);
}
// If variable usage exists in several related blocks, then
// firstNodeInsideBlock = null, otherwise if variable usage exists
// only inside one block, then get node from
// variableUsageExpressions.
if (variableUsageExpressions.size() == 1) {
firstNodeInsideBlock = variableUsageExpressions.get(0);
}
}
return firstNodeInsideBlock;
}
/**
* Gets first Ast node inside SWITCH block if variable usage is met
* only inside the block (not in its declaration!).
*
* @param block
* Ast node represents SWITCH block.
* @param variable
* Variable which is checked for content in block.
* @return If variable usage is met only inside the block
* (not in its declaration!) then return the first Ast node
* of this block, otherwise - null.
*/
private static DetailAST getFirstNodeInsideSwitchBlock(
DetailAST block, DetailAST variable) {
final DetailAST currentNode = getFirstCaseGroupOrSwitchRule(block);
final List<DetailAST> variableUsageExpressions =
new ArrayList<>();
// Checking variable usage inside all CASE_GROUP and SWITCH_RULE ast's.
TokenUtil.forEachChild(block, currentNode.getType(), node -> {
final DetailAST lastNodeInCaseGroup =
node.getLastChild();
if (isChild(lastNodeInCaseGroup, variable)) {
variableUsageExpressions.add(lastNodeInCaseGroup);
}
});
// If variable usage exists in several related blocks, then
// firstNodeInsideBlock = null, otherwise if variable usage exists
// only inside one block, then get node from
// variableUsageExpressions.
DetailAST firstNodeInsideBlock = null;
if (variableUsageExpressions.size() == 1) {
firstNodeInsideBlock = variableUsageExpressions.get(0);
}
return firstNodeInsideBlock;
}
/**
* Helper method for getFirstNodeInsideSwitchBlock to return the first CASE_GROUP or
* SWITCH_RULE ast.
*
* @param block the switch block to check.
* @return DetailAST of the first CASE_GROUP or SWITCH_RULE.
*/
private static DetailAST getFirstCaseGroupOrSwitchRule(DetailAST block) {
return Optional.ofNullable(block.findFirstToken(TokenTypes.CASE_GROUP))
.orElseGet(() -> block.findFirstToken(TokenTypes.SWITCH_RULE));
}
/**
* Gets first Ast node inside TRY-CATCH-FINALLY blocks if variable usage is
* met only inside the block (not in its declaration!).
*
* @param block
* Ast node represents TRY-CATCH-FINALLY block.
* @param variable
* Variable which is checked for content in block.
* @return If variable usage is met only inside the block
* (not in its declaration!) then return the first Ast node
* of this block, otherwise - null.
*/
private static DetailAST getFirstNodeInsideTryCatchFinallyBlocks(
DetailAST block, DetailAST variable) {
DetailAST currentNode = block.getFirstChild();
final List<DetailAST> variableUsageExpressions =
new ArrayList<>();
// Checking variable usage inside TRY block.
if (isChild(currentNode, variable)) {
variableUsageExpressions.add(currentNode);
}
// Switch on CATCH block.
currentNode = currentNode.getNextSibling();
// Checking variable usage inside all CATCH blocks.
while (currentNode != null
&& currentNode.getType() == TokenTypes.LITERAL_CATCH) {
final DetailAST catchBlock = currentNode.getLastChild();
if (isChild(catchBlock, variable)) {
variableUsageExpressions.add(catchBlock);
}
currentNode = currentNode.getNextSibling();
}
// Checking variable usage inside FINALLY block.
if (currentNode != null) {
final DetailAST finalBlock = currentNode.getLastChild();
if (isChild(finalBlock, variable)) {
variableUsageExpressions.add(finalBlock);
}
}
DetailAST variableUsageNode = null;
// If variable usage exists in several related blocks, then
// firstNodeInsideBlock = null, otherwise if variable usage exists
// only inside one block, then get node from
// variableUsageExpressions.
if (variableUsageExpressions.size() == 1) {
variableUsageNode = variableUsageExpressions.get(0).getFirstChild();
}
return variableUsageNode;
}
/**
* Checks if variable is in operator declaration. For instance:
* <pre>
* boolean b = true;
* if (b) {...}
* </pre>
* Variable 'b' is in declaration of operator IF.
*
* @param operator
* Ast node which represents operator.
* @param variable
* Variable which is checked for content in operator.
* @return true if operator contains variable in its declaration, otherwise
* - false.
*/
private static boolean isVariableInOperatorExpr(
DetailAST operator, DetailAST variable) {
boolean isVarInOperatorDeclaration = false;
final DetailAST openingBracket =
operator.findFirstToken(TokenTypes.LPAREN);
// Get EXPR between brackets
DetailAST exprBetweenBrackets = openingBracket.getNextSibling();
// Look if variable is in operator expression
while (exprBetweenBrackets.getType() != TokenTypes.RPAREN) {
if (isChild(exprBetweenBrackets, variable)) {
isVarInOperatorDeclaration = true;
break;
}
exprBetweenBrackets = exprBetweenBrackets.getNextSibling();
}
// Variable may be met in ELSE declaration
// So, check variable usage in these declarations.
if (!isVarInOperatorDeclaration) {
final DetailAST elseBlock = operator.getLastChild();
if (elseBlock.getType() == TokenTypes.LITERAL_ELSE) {
// Get IF followed by ELSE
final DetailAST firstNodeInsideElseBlock = elseBlock.getFirstChild();
if (firstNodeInsideElseBlock.getType() == TokenTypes.LITERAL_IF) {
isVarInOperatorDeclaration =
isVariableInOperatorExpr(firstNodeInsideElseBlock, variable);
}
}
}
return isVarInOperatorDeclaration;
}
/**
* Checks if Ast node contains given element.
*
* @param parent
* Node of AST.
* @param ast
* Ast element which is checked for content in Ast node.
* @return true if Ast element was found in Ast node, otherwise - false.
*/
private static boolean isChild(DetailAST parent, DetailAST ast) {
boolean isChild = false;
DetailAST curNode = parent.getFirstChild();
while (curNode != null) {
if (curNode.getType() == ast.getType() && curNode.getText().equals(ast.getText())) {
isChild = true;
break;
}
DetailAST toVisit = curNode.getFirstChild();
while (toVisit == null) {
toVisit = curNode.getNextSibling();
curNode = curNode.getParent();
if (curNode == parent) {
break;
}
}
curNode = toVisit;
}
return isChild;
}
/**
* Checks if entrance variable is contained in ignored pattern.
*
* @param variable
* Variable which is checked for content in ignored pattern.
* @return true if variable was found, otherwise - false.