forked from checkstyle/checkstyle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequireThisCheck.java
1713 lines (1580 loc) · 59.3 KB
/
RequireThisCheck.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.ArrayDeque;
import java.util.BitSet;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
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;
import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
/**
* <p>
* Checks that references to instance variables and methods of the present
* object are explicitly of the form "this.varName" or "this.methodName(args)"
* and that those references don't rely on the default behavior when "this." is absent.
* </p>
* <p>Warning: the Check is very controversial if 'validateOnlyOverlapping' option is set to 'false'
* and not that actual nowadays.</p>
* <p>Rationale:</p>
* <ol>
* <li>
* The same notation/habit for C++ and Java (C++ have global methods, so having
* "this." do make sense in it to distinguish call of method of class
* instead of global).
* </li>
* <li>
* Non-IDE development (ease of refactoring, some clearness to distinguish
* static and non-static methods).
* </li>
* </ol>
* <p>Limitations: Nothing is currently done about static variables
* or catch-blocks. Static methods invoked on a class name seem to be OK;
* both the class name and the method name have a DOT parent.
* Non-static methods invoked on either this or a variable name seem to be
* OK, likewise.
* </p>
* <ul>
* <li>
* Property {@code checkFields} - Control whether to check references to fields.
* Type is {@code boolean}.
* Default value is {@code true}.
* </li>
* <li>
* Property {@code checkMethods} - Control whether to check references to methods.
* Type is {@code boolean}.
* Default value is {@code true}.
* </li>
* <li>
* Property {@code validateOnlyOverlapping} - Control whether to check only
* overlapping by variables or arguments.
* Type is {@code boolean}.
* Default value is {@code true}.
* </li>
* </ul>
* <p>
* To configure the default check:
* </p>
* <pre>
* <module name="RequireThis"/>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
* private int a;
* private int b;
* private int c;
*
* public Test(int a) {
* // overlapping by constructor argument
* this.a = a; // OK, this keyword used
* b = 0; // OK, no overlap
* foo(5); // OK
* }
*
* public void foo(int c) {
* // overlapping by method argument
* c = c; // violation, reference to instance variable "c" requires "this"
* }
* }
* </pre>
* <p>
* To configure the check for fields only:
* </p>
* <pre>
* <module name="RequireThis">
* <property name="checkMethods" value="false"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
* private int a;
* private int b;
* private int c;
*
* public Test(int a) {
* // overlapping by constructor argument
* this.a = a; // OK, this keyword used
* b = 0; // OK, no overlap
* foo(5); // OK, no validation for methods
* }
*
* public void foo(int c) {
* // overlapping by method argument
* c = c; // violation, reference to instance variable "c" requires "this"
* }
* }
* </pre>
* <p>
* To configure the check for methods only:
* </p>
* <pre>
* <module name="RequireThis">
* <property name="checkFields" value="false"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
* private int a;
* private int b;
* private int c;
*
* public Test(int a) {
* // overlapping by constructor argument
* this.a = a; // OK, no validation for fields
* b = 0; // OK, no validation for fields
* foo(5); // OK, no overlap
* }
*
* public void foo(int c) {
* // overlapping by method argument
* c = c; // OK, no validation for fields
* }
* }
* </pre>
* <p>
* Note that method call foo(5) does not raise a violation
* because methods cannot be overlapped in java.
* </p>
* <p>
* To configure the check to validate for non-overlapping fields and methods:
* </p>
* <pre>
* <module name="RequireThis">
* <property name="validateOnlyOverlapping" value="false"/>
* </module>
* </pre>
* <p>Example:</p>
* <pre>
* public class Test {
* private int a;
* private int b;
* private int c;
*
* public Test(int a) {
* // overlapping by constructor argument
* this.a = a; // OK, no validation for fields
* b = 0; // violation, reference to instance variable "b" requires "this"
* foo(5); // violation, method call "foo(5)" requires "this"
* }
*
* public void foo(int c) {
* // overlapping by method argument
* c = c; // violation, reference to instance variable "c" requires "this"
* }
* }
* </pre>
* <p>
* Please, be aware of the following logic, which is implemented in the check:
* </p>
* <p>
* 1) If you arrange 'this' in your code on your own, the check will not raise violation for
* variables which use 'this' to reference a class field, for example:
* </p>
* <pre>
* public class C {
* private int scale;
* private int x;
*
* public void foo(int scale) {
* scale = this.scale; // no violation
*
* if (scale > 0) {
* scale = -scale; // no violation
* }
* x *= scale;
* }
* }
* </pre>
* <p>
* 2) If method parameter is returned from the method, the check will not raise violation for
* returned variable/parameter, for example:
* </p>
* <pre>
* public class D {
* private String prefix;
*
* public String modifyPrefix(String prefix) {
* prefix = "^" + prefix + "$"; // no violation, because method parameter is returned
* return prefix;
* }
* }
* </pre>
* <p>
* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
* </p>
* <p>
* Violation Message Keys:
* </p>
* <ul>
* <li>
* {@code require.this.method}
* </li>
* <li>
* {@code require.this.variable}
* </li>
* </ul>
*
* @since 3.4
*/
// -@cs[ClassDataAbstractionCoupling] This check requires to work with and identify many frames.
@FileStatefulCheck
public class RequireThisCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_METHOD = "require.this.method";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_VARIABLE = "require.this.variable";
/** Set of all declaration tokens. */
private static final BitSet DECLARATION_TOKENS = TokenUtil.asBitSet(
TokenTypes.VARIABLE_DEF,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.CLASS_DEF,
TokenTypes.ENUM_DEF,
TokenTypes.ANNOTATION_DEF,
TokenTypes.INTERFACE_DEF,
TokenTypes.PARAMETER_DEF,
TokenTypes.TYPE_ARGUMENT,
TokenTypes.RECORD_DEF,
TokenTypes.RECORD_COMPONENT_DEF
);
/** Set of all assign tokens. */
private static final BitSet ASSIGN_TOKENS = TokenUtil.asBitSet(
TokenTypes.ASSIGN,
TokenTypes.PLUS_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
);
/** Set of all compound assign tokens. */
private static final BitSet COMPOUND_ASSIGN_TOKENS = TokenUtil.asBitSet(
TokenTypes.PLUS_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
);
/** Frame for the currently processed AST. */
private final Deque<AbstractFrame> current = new ArrayDeque<>();
/** Tree of all the parsed frames. */
private Map<DetailAST, AbstractFrame> frames;
/** Control whether to check references to fields. */
private boolean checkFields = true;
/** Control whether to check references to methods. */
private boolean checkMethods = true;
/** Control whether to check only overlapping by variables or arguments. */
private boolean validateOnlyOverlapping = true;
/**
* Setter to control whether to check references to fields.
*
* @param checkFields should we check fields usage or not
*/
public void setCheckFields(boolean checkFields) {
this.checkFields = checkFields;
}
/**
* Setter to control whether to check references to methods.
*
* @param checkMethods should we check methods usage or not
*/
public void setCheckMethods(boolean checkMethods) {
this.checkMethods = checkMethods;
}
/**
* Setter to control whether to check only overlapping by variables or arguments.
*
* @param validateOnlyOverlapping should we check only overlapping by variables or arguments
*/
public void setValidateOnlyOverlapping(boolean validateOnlyOverlapping) {
this.validateOnlyOverlapping = validateOnlyOverlapping;
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {
TokenTypes.CLASS_DEF,
TokenTypes.INTERFACE_DEF,
TokenTypes.ENUM_DEF,
TokenTypes.ANNOTATION_DEF,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.LITERAL_FOR,
TokenTypes.SLIST,
TokenTypes.IDENT,
TokenTypes.RECORD_DEF,
TokenTypes.COMPACT_CTOR_DEF,
};
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public void beginTree(DetailAST rootAST) {
frames = new HashMap<>();
current.clear();
final Deque<AbstractFrame> frameStack = new LinkedList<>();
DetailAST curNode = rootAST;
while (curNode != null) {
collectDeclarations(frameStack, curNode);
DetailAST toVisit = curNode.getFirstChild();
while (curNode != null && toVisit == null) {
endCollectingDeclarations(frameStack, curNode);
toVisit = curNode.getNextSibling();
curNode = curNode.getParent();
}
curNode = toVisit;
}
}
@Override
public void visitToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.IDENT:
processIdent(ast);
break;
case TokenTypes.CLASS_DEF:
case TokenTypes.INTERFACE_DEF:
case TokenTypes.ENUM_DEF:
case TokenTypes.ANNOTATION_DEF:
case TokenTypes.SLIST:
case TokenTypes.METHOD_DEF:
case TokenTypes.CTOR_DEF:
case TokenTypes.LITERAL_FOR:
case TokenTypes.RECORD_DEF:
current.push(frames.get(ast));
break;
default:
// do nothing
}
}
@Override
public void leaveToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.CLASS_DEF:
case TokenTypes.INTERFACE_DEF:
case TokenTypes.ENUM_DEF:
case TokenTypes.ANNOTATION_DEF:
case TokenTypes.SLIST:
case TokenTypes.METHOD_DEF:
case TokenTypes.CTOR_DEF:
case TokenTypes.LITERAL_FOR:
case TokenTypes.RECORD_DEF:
current.pop();
break;
default:
// do nothing
}
}
/**
* Checks if a given IDENT is method call or field name which
* requires explicit {@code this} qualifier.
*
* @param ast IDENT to check.
*/
private void processIdent(DetailAST ast) {
int parentType = ast.getParent().getType();
if (parentType == TokenTypes.EXPR
&& ast.getParent().getParent().getParent().getType()
== TokenTypes.ANNOTATION_FIELD_DEF) {
parentType = TokenTypes.ANNOTATION_FIELD_DEF;
}
switch (parentType) {
case TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR:
case TokenTypes.ANNOTATION:
case TokenTypes.ANNOTATION_FIELD_DEF:
// no need to check annotations content
break;
case TokenTypes.METHOD_CALL:
if (checkMethods) {
final AbstractFrame frame = getMethodWithoutThis(ast);
if (frame != null) {
logViolation(MSG_METHOD, ast, frame);
}
}
break;
default:
if (checkFields) {
final AbstractFrame frame = getFieldWithoutThis(ast, parentType);
final boolean canUseThis = !isInCompactConstructor(ast);
if (frame != null && canUseThis) {
logViolation(MSG_VARIABLE, ast, frame);
}
}
break;
}
}
/**
* Helper method to log a Violation.
*
* @param msgKey key to locale message format.
* @param ast a node to get line id column numbers associated with the message.
* @param frame the class frame where the violation is found.
*/
private void logViolation(String msgKey, DetailAST ast, AbstractFrame frame) {
if (frame.getFrameName().equals(getNearestClassFrameName())) {
log(ast, msgKey, ast.getText(), "");
}
else if (!(frame instanceof AnonymousClassFrame)) {
log(ast, msgKey, ast.getText(), frame.getFrameName() + '.');
}
}
/**
* Returns the frame where the field is declared, if the given field is used without
* 'this', and null otherwise.
*
* @param ast field definition ast token.
* @param parentType type of the parent.
* @return the frame where the field is declared, if the given field is used without
* 'this' and null otherwise.
*/
private AbstractFrame getFieldWithoutThis(DetailAST ast, int parentType) {
final boolean importOrPackage = ScopeUtil.getSurroundingScope(ast) == null;
final boolean typeName = parentType == TokenTypes.TYPE
|| parentType == TokenTypes.LITERAL_NEW;
AbstractFrame frame = null;
if (!importOrPackage
&& !typeName
&& !isDeclarationToken(parentType)
&& !isLambdaParameter(ast)) {
final AbstractFrame fieldFrame = findClassFrame(ast, false);
if (fieldFrame != null && ((ClassFrame) fieldFrame).hasInstanceMember(ast)) {
frame = getClassFrameWhereViolationIsFound(ast);
}
}
return frame;
}
/**
* Return whether ast is in a COMPACT_CTOR_DEF.
*
* @param ast The token to check
* @return true if ast is in a COMPACT_CTOR_DEF, false otherwise
*/
private static boolean isInCompactConstructor(DetailAST ast) {
boolean isInCompactCtor = false;
DetailAST parent = ast.getParent();
while (parent != null) {
if (parent.getType() == TokenTypes.COMPACT_CTOR_DEF) {
isInCompactCtor = true;
break;
}
parent = parent.getParent();
}
return isInCompactCtor;
}
/**
* Parses the next AST for declarations.
*
* @param frameStack stack containing the FrameTree being built.
* @param ast AST to parse.
*/
// -@cs[JavaNCSS] This method is a big switch and is too hard to remove.
private static void collectDeclarations(Deque<AbstractFrame> frameStack, DetailAST ast) {
final AbstractFrame frame = frameStack.peek();
switch (ast.getType()) {
case TokenTypes.VARIABLE_DEF:
collectVariableDeclarations(ast, frame);
break;
case TokenTypes.RECORD_COMPONENT_DEF:
final DetailAST componentIdent = ast.findFirstToken(TokenTypes.IDENT);
((ClassFrame) frame).addInstanceMember(componentIdent);
break;
case TokenTypes.PARAMETER_DEF:
if (!CheckUtil.isReceiverParameter(ast)
&& !isLambdaParameter(ast)
&& ast.getParent().getType() != TokenTypes.LITERAL_CATCH) {
final DetailAST parameterIdent = ast.findFirstToken(TokenTypes.IDENT);
frame.addIdent(parameterIdent);
}
break;
case TokenTypes.CLASS_DEF:
case TokenTypes.INTERFACE_DEF:
case TokenTypes.ENUM_DEF:
case TokenTypes.ANNOTATION_DEF:
case TokenTypes.RECORD_DEF:
final DetailAST classFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT);
frameStack.addFirst(new ClassFrame(frame, classFrameNameIdent));
break;
case TokenTypes.SLIST:
frameStack.addFirst(new BlockFrame(frame, ast));
break;
case TokenTypes.METHOD_DEF:
final DetailAST methodFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT);
final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS);
if (mods.findFirstToken(TokenTypes.LITERAL_STATIC) == null) {
((ClassFrame) frame).addInstanceMethod(methodFrameNameIdent);
}
else {
((ClassFrame) frame).addStaticMethod(methodFrameNameIdent);
}
frameStack.addFirst(new MethodFrame(frame, methodFrameNameIdent));
break;
case TokenTypes.CTOR_DEF:
case TokenTypes.COMPACT_CTOR_DEF:
final DetailAST ctorFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT);
frameStack.addFirst(new ConstructorFrame(frame, ctorFrameNameIdent));
break;
case TokenTypes.ENUM_CONSTANT_DEF:
final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
((ClassFrame) frame).addStaticMember(ident);
break;
case TokenTypes.LITERAL_CATCH:
final AbstractFrame catchFrame = new CatchFrame(frame, ast);
catchFrame.addIdent(ast.findFirstToken(TokenTypes.PARAMETER_DEF).findFirstToken(
TokenTypes.IDENT));
frameStack.addFirst(catchFrame);
break;
case TokenTypes.LITERAL_FOR:
final AbstractFrame forFrame = new ForFrame(frame, ast);
frameStack.addFirst(forFrame);
break;
case TokenTypes.LITERAL_NEW:
if (isAnonymousClassDef(ast)) {
frameStack.addFirst(new AnonymousClassFrame(frame,
ast.getFirstChild().toString()));
}
break;
default:
// do nothing
}
}
/**
* Collects variable declarations.
*
* @param ast variable token.
* @param frame current frame.
*/
private static void collectVariableDeclarations(DetailAST ast, AbstractFrame frame) {
final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
if (frame.getType() == FrameType.CLASS_FRAME) {
final DetailAST mods =
ast.findFirstToken(TokenTypes.MODIFIERS);
if (ScopeUtil.isInInterfaceBlock(ast)
|| mods.findFirstToken(TokenTypes.LITERAL_STATIC) != null) {
((ClassFrame) frame).addStaticMember(ident);
}
else {
((ClassFrame) frame).addInstanceMember(ident);
}
}
else {
frame.addIdent(ident);
}
}
/**
* Ends parsing of the AST for declarations.
*
* @param frameStack Stack containing the FrameTree being built.
* @param ast AST that was parsed.
*/
private void endCollectingDeclarations(Queue<AbstractFrame> frameStack, DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.CLASS_DEF:
case TokenTypes.INTERFACE_DEF:
case TokenTypes.ENUM_DEF:
case TokenTypes.ANNOTATION_DEF:
case TokenTypes.SLIST:
case TokenTypes.METHOD_DEF:
case TokenTypes.CTOR_DEF:
case TokenTypes.LITERAL_CATCH:
case TokenTypes.LITERAL_FOR:
case TokenTypes.RECORD_DEF:
case TokenTypes.COMPACT_CTOR_DEF:
frames.put(ast, frameStack.poll());
break;
case TokenTypes.LITERAL_NEW:
if (isAnonymousClassDef(ast)) {
frames.put(ast, frameStack.poll());
}
break;
default:
// do nothing
}
}
/**
* Whether the AST is a definition of an anonymous class.
*
* @param ast the AST to process.
* @return true if the AST is a definition of an anonymous class.
*/
private static boolean isAnonymousClassDef(DetailAST ast) {
final DetailAST lastChild = ast.getLastChild();
return lastChild != null
&& lastChild.getType() == TokenTypes.OBJBLOCK;
}
/**
* Returns the class frame where violation is found (where the field is used without 'this')
* or null otherwise.
*
* @param ast IDENT ast to check.
* @return the class frame where violation is found or null otherwise.
*/
// -@cs[CyclomaticComplexity] Method already invokes too many methods that fully explain
// a logic, additional abstraction will not make logic/algorithm more readable.
private AbstractFrame getClassFrameWhereViolationIsFound(DetailAST ast) {
AbstractFrame frameWhereViolationIsFound = null;
final AbstractFrame variableDeclarationFrame = findFrame(ast, false);
final FrameType variableDeclarationFrameType = variableDeclarationFrame.getType();
final DetailAST prevSibling = ast.getPreviousSibling();
if (variableDeclarationFrameType == FrameType.CLASS_FRAME
&& !validateOnlyOverlapping
&& (prevSibling == null || !isInExpression(ast))
&& canBeReferencedFromStaticContext(ast)) {
frameWhereViolationIsFound = variableDeclarationFrame;
}
else if (variableDeclarationFrameType == FrameType.METHOD_FRAME) {
if (isOverlappingByArgument(ast)) {
if (!isUserDefinedArrangementOfThis(variableDeclarationFrame, ast)
&& !isReturnedVariable(variableDeclarationFrame, ast)
&& canBeReferencedFromStaticContext(ast)
&& canAssignValueToClassField(ast)) {
frameWhereViolationIsFound = findFrame(ast, true);
}
}
else if (!validateOnlyOverlapping
&& prevSibling == null
&& isAssignToken(ast.getParent().getType())
&& !isUserDefinedArrangementOfThis(variableDeclarationFrame, ast)
&& canBeReferencedFromStaticContext(ast)
&& canAssignValueToClassField(ast)) {
frameWhereViolationIsFound = findFrame(ast, true);
}
}
else if (variableDeclarationFrameType == FrameType.CTOR_FRAME
&& isOverlappingByArgument(ast)
&& !isUserDefinedArrangementOfThis(variableDeclarationFrame, ast)) {
frameWhereViolationIsFound = findFrame(ast, true);
}
else if (variableDeclarationFrameType == FrameType.BLOCK_FRAME
&& isOverlappingByLocalVariable(ast)
&& canAssignValueToClassField(ast)
&& !isUserDefinedArrangementOfThis(variableDeclarationFrame, ast)
&& !isReturnedVariable(variableDeclarationFrame, ast)
&& canBeReferencedFromStaticContext(ast)) {
frameWhereViolationIsFound = findFrame(ast, true);
}
return frameWhereViolationIsFound;
}
/**
* Checks ast parent is in expression.
*
* @param ast token to check
* @return true if token is part of expression, false otherwise
*/
private static boolean isInExpression(DetailAST ast) {
return TokenTypes.DOT == ast.getParent().getType()
|| TokenTypes.METHOD_REF == ast.getParent().getType();
}
/**
* Checks whether user arranges 'this' for variable in method, constructor, or block on his own.
*
* @param currentFrame current frame.
* @param ident ident token.
* @return true if user arranges 'this' for variable in method, constructor,
* or block on his own.
*/
private static boolean isUserDefinedArrangementOfThis(AbstractFrame currentFrame,
DetailAST ident) {
final DetailAST blockFrameNameIdent = currentFrame.getFrameNameIdent();
final DetailAST definitionToken = blockFrameNameIdent.getParent();
final DetailAST blockStartToken = definitionToken.findFirstToken(TokenTypes.SLIST);
final DetailAST blockEndToken = getBlockEndToken(blockFrameNameIdent, blockStartToken);
boolean userDefinedArrangementOfThis = false;
final Set<DetailAST> variableUsagesInsideBlock =
getAllTokensWhichAreEqualToCurrent(definitionToken, ident,
blockEndToken.getLineNo());
for (DetailAST variableUsage : variableUsagesInsideBlock) {
final DetailAST prevSibling = variableUsage.getPreviousSibling();
if (prevSibling != null
&& prevSibling.getType() == TokenTypes.LITERAL_THIS) {
userDefinedArrangementOfThis = true;
break;
}
}
return userDefinedArrangementOfThis;
}
/**
* Returns the token which ends the code block.
*
* @param blockNameIdent block name identifier.
* @param blockStartToken token which starts the block.
* @return the token which ends the code block.
*/
private static DetailAST getBlockEndToken(DetailAST blockNameIdent, DetailAST blockStartToken) {
DetailAST blockEndToken = null;
final DetailAST blockNameIdentParent = blockNameIdent.getParent();
if (blockNameIdentParent.getType() == TokenTypes.CASE_GROUP) {
blockEndToken = blockNameIdentParent.getNextSibling();
}
else {
final Set<DetailAST> rcurlyTokens = getAllTokensOfType(blockNameIdent,
TokenTypes.RCURLY);
for (DetailAST currentRcurly : rcurlyTokens) {
final DetailAST parent = currentRcurly.getParent();
if (TokenUtil.areOnSameLine(blockStartToken, parent)) {
blockEndToken = currentRcurly;
}
}
}
return blockEndToken;
}
/**
* Checks whether the current variable is returned from the method.
*
* @param currentFrame current frame.
* @param ident variable ident token.
* @return true if the current variable is returned from the method.
*/
private static boolean isReturnedVariable(AbstractFrame currentFrame, DetailAST ident) {
final DetailAST blockFrameNameIdent = currentFrame.getFrameNameIdent();
final DetailAST definitionToken = blockFrameNameIdent.getParent();
final DetailAST blockStartToken = definitionToken.findFirstToken(TokenTypes.SLIST);
final DetailAST blockEndToken = getBlockEndToken(blockFrameNameIdent, blockStartToken);
final Set<DetailAST> returnsInsideBlock = getAllTokensOfType(definitionToken,
TokenTypes.LITERAL_RETURN, blockEndToken.getLineNo());
return returnsInsideBlock.stream()
.anyMatch(returnToken -> isAstInside(returnToken, ident));
}
/**
* Checks if the given {@code ast} is equal to the {@code tree} or a child of it.
*
* @param tree The tree to search.
* @param ast The AST to look for.
* @return {@code true} if the {@code ast} was found.
*/
private static boolean isAstInside(DetailAST tree, DetailAST ast) {
boolean result = false;
if (isAstSimilar(tree, ast)) {
result = true;
}
else {
for (DetailAST child = tree.getFirstChild(); child != null
&& !result; child = child.getNextSibling()) {
result = isAstInside(child, ast);
}
}
return result;
}
/**
* Checks whether a field can be referenced from a static context.
*
* @param ident ident token.
* @return true if field can be referenced from a static context.
*/
private boolean canBeReferencedFromStaticContext(DetailAST ident) {
AbstractFrame variableDeclarationFrame = findFrame(ident, false);
while (variableDeclarationFrame.getType() == FrameType.BLOCK_FRAME
|| variableDeclarationFrame.getType() == FrameType.FOR_FRAME) {
variableDeclarationFrame = variableDeclarationFrame.getParent();
}
boolean staticContext = false;
if (variableDeclarationFrame.getType() == FrameType.CLASS_FRAME) {
final DetailAST codeBlockDefinition = getCodeBlockDefinitionToken(ident);
if (codeBlockDefinition != null) {
final DetailAST modifiers = codeBlockDefinition.getFirstChild();
staticContext = codeBlockDefinition.getType() == TokenTypes.STATIC_INIT
|| modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
}
}
else {
final DetailAST frameNameIdent = variableDeclarationFrame.getFrameNameIdent();
final DetailAST definitionToken = frameNameIdent.getParent();
staticContext = definitionToken.findFirstToken(TokenTypes.MODIFIERS)
.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
}
return !staticContext;
}
/**
* Returns code block definition token for current identifier.
*
* @param ident ident token.
* @return code block definition token for current identifier or null if code block
* definition was not found.
*/
private static DetailAST getCodeBlockDefinitionToken(DetailAST ident) {
DetailAST parent = ident.getParent();
while (parent != null
&& parent.getType() != TokenTypes.METHOD_DEF
&& parent.getType() != TokenTypes.CTOR_DEF
&& parent.getType() != TokenTypes.STATIC_INIT) {
parent = parent.getParent();
}
return parent;
}
/**
* Checks whether a value can be assigned to a field.
* A value can be assigned to a final field only in constructor block. If there is a method
* block, value assignment can be performed only to non final field.
*
* @param ast an identifier token.
* @return true if a value can be assigned to a field.
*/
private boolean canAssignValueToClassField(DetailAST ast) {
final AbstractFrame fieldUsageFrame = findFrame(ast, false);
final boolean fieldUsageInConstructor = isInsideConstructorFrame(fieldUsageFrame);
final AbstractFrame declarationFrame = findFrame(ast, true);
final boolean finalField = ((ClassFrame) declarationFrame).hasFinalField(ast);
return fieldUsageInConstructor || !finalField;
}
/**
* Checks whether a field usage frame is inside constructor frame.
*
* @param frame frame, where field is used.
* @return true if the field usage frame is inside constructor frame.
*/
private static boolean isInsideConstructorFrame(AbstractFrame frame) {
boolean assignmentInConstructor = false;
AbstractFrame fieldUsageFrame = frame;
if (fieldUsageFrame.getType() == FrameType.BLOCK_FRAME) {
while (fieldUsageFrame.getType() == FrameType.BLOCK_FRAME) {
fieldUsageFrame = fieldUsageFrame.getParent();
}
if (fieldUsageFrame.getType() == FrameType.CTOR_FRAME) {
assignmentInConstructor = true;
}
}
return assignmentInConstructor;
}
/**
* Checks whether an overlapping by method or constructor argument takes place.
*
* @param ast an identifier.
* @return true if an overlapping by method or constructor argument takes place.
*/
private boolean isOverlappingByArgument(DetailAST ast) {
boolean overlapping = false;
final DetailAST parent = ast.getParent();
final DetailAST sibling = ast.getNextSibling();
if (sibling != null && isAssignToken(parent.getType())) {
if (isCompoundAssignToken(parent.getType())) {
overlapping = true;
}
else {
final ClassFrame classFrame = (ClassFrame) findFrame(ast, true);
final Set<DetailAST> exprIdents = getAllTokensOfType(sibling, TokenTypes.IDENT);
overlapping = classFrame.containsFieldOrVariableDef(exprIdents, ast);
}
}
return overlapping;
}
/**
* Checks whether an overlapping by local variable takes place.
*
* @param ast an identifier.
* @return true if an overlapping by local variable takes place.
*/
private boolean isOverlappingByLocalVariable(DetailAST ast) {
boolean overlapping = false;
final DetailAST parent = ast.getParent();
if (isAssignToken(parent.getType())) {
final ClassFrame classFrame = (ClassFrame) findFrame(ast, true);
final Set<DetailAST> exprIdents =
getAllTokensOfType(ast.getNextSibling(), TokenTypes.IDENT);
overlapping = classFrame.containsFieldOrVariableDef(exprIdents, ast);
}
return overlapping;
}
/**
* Collects all tokens of specific type starting with the current ast node.
*
* @param ast ast node.
* @param tokenType token type.
* @return a set of all tokens of specific type starting with the current ast node.
*/
private static Set<DetailAST> getAllTokensOfType(DetailAST ast, int tokenType) {
DetailAST vertex = ast;
final Set<DetailAST> result = new HashSet<>();
final Deque<DetailAST> stack = new ArrayDeque<>();
while (vertex != null || !stack.isEmpty()) {
if (!stack.isEmpty()) {
vertex = stack.pop();
}
while (vertex != null) {
if (vertex.getType() == tokenType) {
result.add(vertex);
}
if (vertex.getNextSibling() != null) {
stack.push(vertex.getNextSibling());
}
vertex = vertex.getFirstChild();
}
}
return result;
}