-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
FinalLocalVariableCheck.java
817 lines (760 loc) · 30.8 KB
/
FinalLocalVariableCheck.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
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2020 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.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
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.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
/**
* <p>
* Checks that local variables that never have their values changed are declared final.
* The check can be configured to also check that unchanged parameters are declared final.
* </p>
* <p>
* When configured to check parameters, the check ignores parameters of interface
* methods and abstract methods.
* </p>
* <ul>
* <li>
* Property {@code validateEnhancedForLoopVariable} - Control whether to check
* <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.14.2">
* enhanced for-loop</a> variable.
* Default value is {@code false}.
* </li>
* <li>
* Property {@code tokens} - tokens to check
* Default value is:
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF">
* VARIABLE_DEF</a>.
* </li>
* </ul>
* <p>
* To configure the check:
* </p>
* <pre>
* <module name="FinalLocalVariable"/>
* </pre>
* <p>
* To configure the check so that it checks local variables and parameters:
* </p>
* <pre>
* <module name="FinalLocalVariable">
* <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/>
* </module>
* </pre>
* <p>
* By default, this Check skip final validation on
* <a href = "https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.14.2">
* Enhanced For-Loop</a>.
* </p>
* <p>
* Option 'validateEnhancedForLoopVariable' could be used to make Check to validate even variable
* from Enhanced For Loop.
* </p>
* <p>
* An example of how to configure the check so that it also validates enhanced For Loop Variable is:
* </p>
* <pre>
* <module name="FinalLocalVariable">
* <property name="tokens" value="VARIABLE_DEF"/>
* <property name="validateEnhancedForLoopVariable" value="true"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* for (int number : myNumbers) { // violation
* System.out.println(number);
* }
* </pre>
* <p>
* An example of how to configure check on local variables and parameters
* but do not validate loop variables:
* </p>
* <pre>
* <module name="FinalLocalVariable">
* <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/>
* <property name="validateEnhancedForLoopVariable" value="false"/>
* </module>
* </pre>
* <p>
* Example:
* </p>
* <pre>
* public class MyClass {
* static int foo(int x, int y) { //violations, parameters should be final
* return x+y;
* }
* public static void main (String []args) { //violation, parameters should be final
* for (String i : args) {
* System.out.println(i);
* }
* int result=foo(1,2); // violation
* }
* }
* </pre>
*
* @since 3.2
*/
@FileStatefulCheck
public class FinalLocalVariableCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "final.variable";
/**
* Assign operator types.
*/
private static final int[] ASSIGN_OPERATOR_TYPES = {
TokenTypes.POST_INC,
TokenTypes.POST_DEC,
TokenTypes.ASSIGN,
TokenTypes.PLUS_ASSIGN,
TokenTypes.MINUS_ASSIGN,
TokenTypes.STAR_ASSIGN,
TokenTypes.DIV_ASSIGN,
TokenTypes.MOD_ASSIGN,
TokenTypes.SR_ASSIGN,
TokenTypes.BSR_ASSIGN,
TokenTypes.SL_ASSIGN,
TokenTypes.BAND_ASSIGN,
TokenTypes.BXOR_ASSIGN,
TokenTypes.BOR_ASSIGN,
TokenTypes.INC,
TokenTypes.DEC,
};
/**
* Loop types.
*/
private static final int[] LOOP_TYPES = {
TokenTypes.LITERAL_FOR,
TokenTypes.LITERAL_WHILE,
TokenTypes.LITERAL_DO,
};
/** Scope Deque. */
private final Deque<ScopeData> scopeStack = new ArrayDeque<>();
/** Uninitialized variables of previous scope. */
private final Deque<Deque<DetailAST>> prevScopeUninitializedVariables =
new ArrayDeque<>();
/** Assigned variables of current scope. */
private final Deque<Deque<DetailAST>> currentScopeAssignedVariables =
new ArrayDeque<>();
/**
* Control whether to check
* <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.14.2">
* enhanced for-loop</a> variable.
*/
private boolean validateEnhancedForLoopVariable;
static {
// Array sorting for binary search
Arrays.sort(ASSIGN_OPERATOR_TYPES);
Arrays.sort(LOOP_TYPES);
}
/**
* Setter to control whether to check
* <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-14.html#jls-14.14.2">
* enhanced for-loop</a> variable.
* @param validateEnhancedForLoopVariable whether to check for-loop variable
*/
public final void setValidateEnhancedForLoopVariable(boolean validateEnhancedForLoopVariable) {
this.validateEnhancedForLoopVariable = validateEnhancedForLoopVariable;
}
@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.IDENT,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.SLIST,
TokenTypes.OBJBLOCK,
TokenTypes.LITERAL_BREAK,
TokenTypes.LITERAL_FOR,
};
}
@Override
public int[] getDefaultTokens() {
return new int[] {
TokenTypes.IDENT,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.SLIST,
TokenTypes.OBJBLOCK,
TokenTypes.LITERAL_BREAK,
TokenTypes.LITERAL_FOR,
TokenTypes.VARIABLE_DEF,
};
}
@Override
public int[] getAcceptableTokens() {
return new int[] {
TokenTypes.IDENT,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.SLIST,
TokenTypes.OBJBLOCK,
TokenTypes.LITERAL_BREAK,
TokenTypes.LITERAL_FOR,
TokenTypes.VARIABLE_DEF,
TokenTypes.PARAMETER_DEF,
};
}
// -@cs[CyclomaticComplexity] The only optimization which can be done here is moving CASE-block
// expressions to separate methods, but that will not increase readability.
@Override
public void visitToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.OBJBLOCK:
case TokenTypes.METHOD_DEF:
case TokenTypes.CTOR_DEF:
case TokenTypes.LITERAL_FOR:
scopeStack.push(new ScopeData());
break;
case TokenTypes.SLIST:
currentScopeAssignedVariables.push(new ArrayDeque<>());
if (ast.getParent().getType() != TokenTypes.CASE_GROUP
|| ast.getParent().getParent().findFirstToken(TokenTypes.CASE_GROUP)
== ast.getParent()) {
storePrevScopeUninitializedVariableData();
scopeStack.push(new ScopeData());
}
break;
case TokenTypes.PARAMETER_DEF:
if (!isInLambda(ast)
&& ast.findFirstToken(TokenTypes.MODIFIERS)
.findFirstToken(TokenTypes.FINAL) == null
&& !isInAbstractOrNativeMethod(ast)
&& !ScopeUtil.isInInterfaceBlock(ast)
&& !isMultipleTypeCatch(ast)
&& !CheckUtil.isReceiverParameter(ast)) {
insertParameter(ast);
}
break;
case TokenTypes.VARIABLE_DEF:
if (ast.getParent().getType() != TokenTypes.OBJBLOCK
&& ast.findFirstToken(TokenTypes.MODIFIERS)
.findFirstToken(TokenTypes.FINAL) == null
&& !isVariableInForInit(ast)
&& shouldCheckEnhancedForLoopVariable(ast)) {
insertVariable(ast);
}
break;
case TokenTypes.IDENT:
final int parentType = ast.getParent().getType();
if (isAssignOperator(parentType) && isFirstChild(ast)) {
final Optional<FinalVariableCandidate> candidate = getFinalCandidate(ast);
if (candidate.isPresent()) {
determineAssignmentConditions(ast, candidate.get());
currentScopeAssignedVariables.peek().add(ast);
}
removeFinalVariableCandidateFromStack(ast);
}
break;
case TokenTypes.LITERAL_BREAK:
scopeStack.peek().containsBreak = true;
break;
default:
throw new IllegalStateException("Incorrect token type");
}
}
@Override
public void leaveToken(DetailAST ast) {
Map<String, FinalVariableCandidate> scope = null;
switch (ast.getType()) {
case TokenTypes.OBJBLOCK:
case TokenTypes.CTOR_DEF:
case TokenTypes.METHOD_DEF:
case TokenTypes.LITERAL_FOR:
scope = scopeStack.pop().scope;
break;
case TokenTypes.SLIST:
// -@cs[MoveVariableInsideIf] assignment value is modified later so it can't be
// moved
final Deque<DetailAST> prevScopeUninitializedVariableData =
prevScopeUninitializedVariables.peek();
boolean containsBreak = false;
if (ast.getParent().getType() != TokenTypes.CASE_GROUP
|| findLastChildWhichContainsSpecifiedToken(ast.getParent().getParent(),
TokenTypes.CASE_GROUP, TokenTypes.SLIST) == ast.getParent()) {
containsBreak = scopeStack.peek().containsBreak;
scope = scopeStack.pop().scope;
prevScopeUninitializedVariables.pop();
}
final DetailAST parent = ast.getParent();
if (containsBreak || shouldUpdateUninitializedVariables(parent)) {
updateAllUninitializedVariables(prevScopeUninitializedVariableData);
}
updateCurrentScopeAssignedVariables();
break;
default:
// do nothing
}
if (scope != null) {
for (FinalVariableCandidate candidate : scope.values()) {
final DetailAST ident = candidate.variableIdent;
log(ident, MSG_KEY, ident.getText());
}
}
}
/**
* Update assigned variables in a temporary stack.
*/
private void updateCurrentScopeAssignedVariables() {
// -@cs[MoveVariableInsideIf] assignment value is a modification call so it can't be moved
final Deque<DetailAST> poppedScopeAssignedVariableData =
currentScopeAssignedVariables.pop();
final Deque<DetailAST> currentScopeAssignedVariableData =
currentScopeAssignedVariables.peek();
if (currentScopeAssignedVariableData != null) {
currentScopeAssignedVariableData.addAll(poppedScopeAssignedVariableData);
}
}
/**
* Determines identifier assignment conditions (assigned or already assigned).
* @param ident identifier.
* @param candidate final local variable candidate.
*/
private static void determineAssignmentConditions(DetailAST ident,
FinalVariableCandidate candidate) {
if (candidate.assigned) {
if (!isInSpecificCodeBlock(ident, TokenTypes.LITERAL_ELSE)
&& !isInSpecificCodeBlock(ident, TokenTypes.CASE_GROUP)) {
candidate.alreadyAssigned = true;
}
}
else {
candidate.assigned = true;
}
}
/**
* Checks whether the scope of a node is restricted to a specific code block.
* @param node node.
* @param blockType block type.
* @return true if the scope of a node is restricted to a specific code block.
*/
private static boolean isInSpecificCodeBlock(DetailAST node, int blockType) {
boolean returnValue = false;
for (DetailAST token = node.getParent(); token != null; token = token.getParent()) {
final int type = token.getType();
if (type == blockType) {
returnValue = true;
break;
}
}
return returnValue;
}
/**
* Gets final variable candidate for ast.
* @param ast ast.
* @return Optional of {@link FinalVariableCandidate} for ast from scopeStack.
*/
private Optional<FinalVariableCandidate> getFinalCandidate(DetailAST ast) {
Optional<FinalVariableCandidate> result = Optional.empty();
final Iterator<ScopeData> iterator = scopeStack.descendingIterator();
while (iterator.hasNext() && !result.isPresent()) {
final ScopeData scopeData = iterator.next();
result = scopeData.findFinalVariableCandidateForAst(ast);
}
return result;
}
/**
* Store un-initialized variables in a temporary stack for future use.
*/
private void storePrevScopeUninitializedVariableData() {
final ScopeData scopeData = scopeStack.peek();
final Deque<DetailAST> prevScopeUninitializedVariableData =
new ArrayDeque<>();
scopeData.uninitializedVariables.forEach(prevScopeUninitializedVariableData::push);
prevScopeUninitializedVariables.push(prevScopeUninitializedVariableData);
}
/**
* Update current scope data uninitialized variable according to the whole scope data.
* @param prevScopeUninitializedVariableData variable for previous stack of uninitialized
* variables
* @noinspection MethodParameterNamingConvention
*/
private void updateAllUninitializedVariables(
Deque<DetailAST> prevScopeUninitializedVariableData) {
// Check for only previous scope
updateUninitializedVariables(prevScopeUninitializedVariableData);
// Check for rest of the scope
prevScopeUninitializedVariables.forEach(this::updateUninitializedVariables);
}
/**
* Update current scope data uninitialized variable according to the specific scope data.
* @param scopeUninitializedVariableData variable for specific stack of uninitialized variables
*/
private void updateUninitializedVariables(Deque<DetailAST> scopeUninitializedVariableData) {
final Iterator<DetailAST> iterator = currentScopeAssignedVariables.peek().iterator();
while (iterator.hasNext()) {
final DetailAST assignedVariable = iterator.next();
boolean shouldRemove = false;
for (DetailAST variable : scopeUninitializedVariableData) {
for (ScopeData scopeData : scopeStack) {
final FinalVariableCandidate candidate =
scopeData.scope.get(variable.getText());
DetailAST storedVariable = null;
if (candidate != null) {
storedVariable = candidate.variableIdent;
}
if (storedVariable != null
&& isSameVariables(storedVariable, variable)
&& isSameVariables(assignedVariable, variable)) {
scopeData.uninitializedVariables.push(variable);
shouldRemove = true;
}
}
}
if (shouldRemove) {
iterator.remove();
}
}
}
/**
* If token is LITERAL_IF and there is an {@code else} following or token is CASE_GROUP and
* there is another {@code case} following, then update the uninitialized variables.
* @param ast token to be checked
* @return true if should be updated, else false
*/
private static boolean shouldUpdateUninitializedVariables(DetailAST ast) {
return isIfTokenWithAnElseFollowing(ast) || isCaseTokenWithAnotherCaseFollowing(ast);
}
/**
* If token is LITERAL_IF and there is an {@code else} following.
* @param ast token to be checked
* @return true if token is LITERAL_IF and there is an {@code else} following, else false
*/
private static boolean isIfTokenWithAnElseFollowing(DetailAST ast) {
return ast.getType() == TokenTypes.LITERAL_IF
&& ast.getLastChild().getType() == TokenTypes.LITERAL_ELSE;
}
/**
* If token is CASE_GROUP and there is another {@code case} following.
* @param ast token to be checked
* @return true if token is CASE_GROUP and there is another {@code case} following, else false
*/
private static boolean isCaseTokenWithAnotherCaseFollowing(DetailAST ast) {
return ast.getType() == TokenTypes.CASE_GROUP
&& findLastChildWhichContainsSpecifiedToken(
ast.getParent(), TokenTypes.CASE_GROUP, TokenTypes.SLIST) != ast;
}
/**
* Returns the last child token that makes a specified type and contains containType in
* its branch.
* @param ast token to be tested
* @param childType the token type to match
* @param containType the token type which has to be present in the branch
* @return the matching token, or null if no match
*/
private static DetailAST findLastChildWhichContainsSpecifiedToken(DetailAST ast, int childType,
int containType) {
DetailAST returnValue = null;
for (DetailAST astIterator = ast.getFirstChild(); astIterator != null;
astIterator = astIterator.getNextSibling()) {
if (astIterator.getType() == childType
&& astIterator.findFirstToken(containType) != null) {
returnValue = astIterator;
}
}
return returnValue;
}
/**
* Determines whether enhanced for-loop variable should be checked or not.
* @param ast The ast to compare.
* @return true if enhanced for-loop variable should be checked.
*/
private boolean shouldCheckEnhancedForLoopVariable(DetailAST ast) {
return validateEnhancedForLoopVariable
|| ast.getParent().getType() != TokenTypes.FOR_EACH_CLAUSE;
}
/**
* Insert a parameter at the topmost scope stack.
* @param ast the variable to insert.
*/
private void insertParameter(DetailAST ast) {
final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope;
final DetailAST astNode = ast.findFirstToken(TokenTypes.IDENT);
scope.put(astNode.getText(), new FinalVariableCandidate(astNode));
}
/**
* Insert a variable at the topmost scope stack.
* @param ast the variable to insert.
*/
private void insertVariable(DetailAST ast) {
final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope;
final DetailAST astNode = ast.findFirstToken(TokenTypes.IDENT);
final FinalVariableCandidate candidate = new FinalVariableCandidate(astNode);
// for-each variables are implicitly assigned
candidate.assigned = ast.getParent().getType() == TokenTypes.FOR_EACH_CLAUSE;
scope.put(astNode.getText(), candidate);
if (!isInitialized(astNode)) {
scopeStack.peek().uninitializedVariables.add(astNode);
}
}
/**
* Check if VARIABLE_DEF is initialized or not.
* @param ast VARIABLE_DEF to be checked
* @return true if initialized
*/
private static boolean isInitialized(DetailAST ast) {
return ast.getParent().getLastChild().getType() == TokenTypes.ASSIGN;
}
/**
* Whether the ast is the first child of its parent.
* @param ast the ast to check.
* @return true if the ast is the first child of its parent.
*/
private static boolean isFirstChild(DetailAST ast) {
return ast.getPreviousSibling() == null;
}
/**
* Removes the final variable candidate from the Stack.
* @param ast variable to remove.
*/
private void removeFinalVariableCandidateFromStack(DetailAST ast) {
final Iterator<ScopeData> iterator = scopeStack.descendingIterator();
while (iterator.hasNext()) {
final ScopeData scopeData = iterator.next();
final Map<String, FinalVariableCandidate> scope = scopeData.scope;
final FinalVariableCandidate candidate = scope.get(ast.getText());
DetailAST storedVariable = null;
if (candidate != null) {
storedVariable = candidate.variableIdent;
}
if (storedVariable != null && isSameVariables(storedVariable, ast)) {
if (shouldRemoveFinalVariableCandidate(scopeData, ast)) {
scope.remove(ast.getText());
}
break;
}
}
}
/**
* Check if given parameter definition is a multiple type catch.
* @param parameterDefAst parameter definition
* @return true if it is a multiple type catch, false otherwise
*/
private static boolean isMultipleTypeCatch(DetailAST parameterDefAst) {
final DetailAST typeAst = parameterDefAst.findFirstToken(TokenTypes.TYPE);
return typeAst.getFirstChild().getType() == TokenTypes.BOR;
}
/**
* Whether the final variable candidate should be removed from the list of final local variable
* candidates.
* @param scopeData the scope data of the variable.
* @param ast the variable ast.
* @return true, if the variable should be removed.
*/
private static boolean shouldRemoveFinalVariableCandidate(ScopeData scopeData, DetailAST ast) {
boolean shouldRemove = true;
for (DetailAST variable : scopeData.uninitializedVariables) {
if (variable.getText().equals(ast.getText())) {
// if the variable is declared outside the loop and initialized inside
// the loop, then it cannot be declared final, as it can be initialized
// more than once in this case
if (isInTheSameLoop(variable, ast) || !isUseOfExternalVariableInsideLoop(ast)) {
final FinalVariableCandidate candidate = scopeData.scope.get(ast.getText());
shouldRemove = candidate.alreadyAssigned;
}
scopeData.uninitializedVariables.remove(variable);
break;
}
}
return shouldRemove;
}
/**
* Checks whether a variable which is declared outside loop is used inside loop.
* For example:
* <p>
* {@code
* int x;
* for (int i = 0, j = 0; i < j; i++) {
* x = 5;
* }
* }
* </p>
* @param variable variable.
* @return true if a variable which is declared outside loop is used inside loop.
*/
private static boolean isUseOfExternalVariableInsideLoop(DetailAST variable) {
DetailAST loop2 = variable.getParent();
while (loop2 != null
&& !isLoopAst(loop2.getType())) {
loop2 = loop2.getParent();
}
return loop2 != null;
}
/**
* Is Arithmetic operator.
* @param parentType token AST
* @return true is token type is in arithmetic operator
*/
private static boolean isAssignOperator(int parentType) {
return Arrays.binarySearch(ASSIGN_OPERATOR_TYPES, parentType) >= 0;
}
/**
* Checks if current variable is defined in
* {@link TokenTypes#FOR_INIT for-loop init}, e.g.:
* <p>
* {@code
* for (int i = 0, j = 0; i < j; i++) { . . . }
* }
* </p>
* {@code i, j} are defined in {@link TokenTypes#FOR_INIT for-loop init}
* @param variableDef variable definition node.
* @return true if variable is defined in {@link TokenTypes#FOR_INIT for-loop init}
*/
private static boolean isVariableInForInit(DetailAST variableDef) {
return variableDef.getParent().getType() == TokenTypes.FOR_INIT;
}
/**
* Determines whether an AST is a descendant of an abstract or native method.
* @param ast the AST to check.
* @return true if ast is a descendant of an abstract or native method.
*/
private static boolean isInAbstractOrNativeMethod(DetailAST ast) {
boolean abstractOrNative = false;
DetailAST parent = ast.getParent();
while (parent != null && !abstractOrNative) {
if (parent.getType() == TokenTypes.METHOD_DEF) {
final DetailAST modifiers =
parent.findFirstToken(TokenTypes.MODIFIERS);
abstractOrNative = modifiers.findFirstToken(TokenTypes.ABSTRACT) != null
|| modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null;
}
parent = parent.getParent();
}
return abstractOrNative;
}
/**
* Check if current param is lambda's param.
* @param paramDef {@link TokenTypes#PARAMETER_DEF parameter def}.
* @return true if current param is lambda's param.
*/
private static boolean isInLambda(DetailAST paramDef) {
return paramDef.getParent().getParent().getType() == TokenTypes.LAMBDA;
}
/**
* Find the Class, Constructor, Enum, Method, or Field in which it is defined.
* @param ast Variable for which we want to find the scope in which it is defined
* @return ast The Class or Constructor or Method in which it is defined.
*/
private static DetailAST findFirstUpperNamedBlock(DetailAST ast) {
DetailAST astTraverse = ast;
while (astTraverse.getType() != TokenTypes.METHOD_DEF
&& astTraverse.getType() != TokenTypes.CLASS_DEF
&& astTraverse.getType() != TokenTypes.ENUM_DEF
&& astTraverse.getType() != TokenTypes.CTOR_DEF
&& !ScopeUtil.isClassFieldDef(astTraverse)) {
astTraverse = astTraverse.getParent();
}
return astTraverse;
}
/**
* Check if both the Variables are same.
* @param ast1 Variable to compare
* @param ast2 Variable to compare
* @return true if both the variables are same, otherwise false
*/
private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) {
final DetailAST classOrMethodOfAst1 =
findFirstUpperNamedBlock(ast1);
final DetailAST classOrMethodOfAst2 =
findFirstUpperNamedBlock(ast2);
return classOrMethodOfAst1 == classOrMethodOfAst2 && ast1.getText().equals(ast2.getText());
}
/**
* Check if both the variables are in the same loop.
* @param ast1 variable to compare.
* @param ast2 variable to compare.
* @return true if both the variables are in the same loop.
*/
private static boolean isInTheSameLoop(DetailAST ast1, DetailAST ast2) {
DetailAST loop1 = ast1.getParent();
while (loop1 != null && !isLoopAst(loop1.getType())) {
loop1 = loop1.getParent();
}
DetailAST loop2 = ast2.getParent();
while (loop2 != null && !isLoopAst(loop2.getType())) {
loop2 = loop2.getParent();
}
return loop1 != null && loop1 == loop2;
}
/**
* Checks whether the ast is a loop.
* @param ast the ast to check.
* @return true if the ast is a loop.
*/
private static boolean isLoopAst(int ast) {
return Arrays.binarySearch(LOOP_TYPES, ast) >= 0;
}
/**
* Holder for the scope data.
*/
private static class ScopeData {
/** Contains variable definitions. */
private final Map<String, FinalVariableCandidate> scope = new HashMap<>();
/** Contains definitions of uninitialized variables. */
private final Deque<DetailAST> uninitializedVariables = new ArrayDeque<>();
/** Whether there is a {@code break} in the scope. */
private boolean containsBreak;
/**
* Searches for final local variable candidate for ast in the scope.
* @param ast ast.
* @return Optional of {@link FinalVariableCandidate}.
*/
public Optional<FinalVariableCandidate> findFinalVariableCandidateForAst(DetailAST ast) {
Optional<FinalVariableCandidate> result = Optional.empty();
DetailAST storedVariable = null;
final Optional<FinalVariableCandidate> candidate =
Optional.ofNullable(scope.get(ast.getText()));
if (candidate.isPresent()) {
storedVariable = candidate.get().variableIdent;
}
if (storedVariable != null && isSameVariables(storedVariable, ast)) {
result = candidate;
}
return result;
}
}
/** Represents information about final local variable candidate. */
private static class FinalVariableCandidate {
/** Identifier token. */
private final DetailAST variableIdent;
/** Whether the variable is assigned. */
private boolean assigned;
/** Whether the variable is already assigned. */
private boolean alreadyAssigned;
/**
* Creates new instance.
* @param variableIdent variable identifier.
*/
/* package */ FinalVariableCandidate(DetailAST variableIdent) {
this.variableIdent = variableIdent;
}
}
}