1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.design;
21
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30
31 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
32 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
33 import com.puppycrawl.tools.checkstyle.api.DetailAST;
34 import com.puppycrawl.tools.checkstyle.api.FullIdent;
35 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
36 import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
37 import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
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 @FileStatefulCheck
239 public class VisibilityModifierCheck
240 extends AbstractCheck {
241
242
243
244
245
246 public static final String MSG_KEY = "variable.notPrivate";
247
248
249 private static final List<String> DEFAULT_IMMUTABLE_TYPES = Collections.unmodifiableList(
250 Arrays.stream(new String[] {
251 "java.lang.String",
252 "java.lang.Integer",
253 "java.lang.Byte",
254 "java.lang.Character",
255 "java.lang.Short",
256 "java.lang.Boolean",
257 "java.lang.Long",
258 "java.lang.Double",
259 "java.lang.Float",
260 "java.lang.StackTraceElement",
261 "java.math.BigInteger",
262 "java.math.BigDecimal",
263 "java.io.File",
264 "java.util.Locale",
265 "java.util.UUID",
266 "java.net.URL",
267 "java.net.URI",
268 "java.net.Inet4Address",
269 "java.net.Inet6Address",
270 "java.net.InetSocketAddress",
271 }).collect(Collectors.toList()));
272
273
274 private static final List<String> DEFAULT_IGNORE_ANNOTATIONS = Collections.unmodifiableList(
275 Arrays.stream(new String[] {
276 "org.junit.Rule",
277 "org.junit.ClassRule",
278 "com.google.common.annotations.VisibleForTesting",
279 }).collect(Collectors.toList()));
280
281
282 private static final String PUBLIC_ACCESS_MODIFIER = "public";
283
284
285 private static final String PRIVATE_ACCESS_MODIFIER = "private";
286
287
288 private static final String PROTECTED_ACCESS_MODIFIER = "protected";
289
290
291 private static final String PACKAGE_ACCESS_MODIFIER = "package";
292
293
294 private static final String STATIC_KEYWORD = "static";
295
296
297 private static final String FINAL_KEYWORD = "final";
298
299
300 private static final String[] EXPLICIT_MODS = {
301 PUBLIC_ACCESS_MODIFIER,
302 PRIVATE_ACCESS_MODIFIER,
303 PROTECTED_ACCESS_MODIFIER,
304 };
305
306
307
308
309
310
311
312 private Pattern publicMemberPattern = Pattern.compile("^serialVersionUID$");
313
314
315 private final List<String> ignoreAnnotationShortNames =
316 getClassShortNames(DEFAULT_IGNORE_ANNOTATIONS);
317
318
319 private final List<String> immutableClassShortNames =
320 getClassShortNames(DEFAULT_IMMUTABLE_TYPES);
321
322
323 private List<String> ignoreAnnotationCanonicalNames =
324 new ArrayList<>(DEFAULT_IGNORE_ANNOTATIONS);
325
326
327 private boolean protectedAllowed;
328
329
330 private boolean packageAllowed;
331
332
333 private boolean allowPublicImmutableFields;
334
335
336 private boolean allowPublicFinalFields;
337
338
339 private List<String> immutableClassCanonicalNames = new ArrayList<>(DEFAULT_IMMUTABLE_TYPES);
340
341
342
343
344
345 public void setIgnoreAnnotationCanonicalNames(String... annotationNames) {
346 ignoreAnnotationCanonicalNames = Arrays.asList(annotationNames);
347 }
348
349
350
351
352
353 public void setProtectedAllowed(boolean protectedAllowed) {
354 this.protectedAllowed = protectedAllowed;
355 }
356
357
358
359
360
361 public void setPackageAllowed(boolean packageAllowed) {
362 this.packageAllowed = packageAllowed;
363 }
364
365
366
367
368
369
370 public void setPublicMemberPattern(Pattern pattern) {
371 publicMemberPattern = pattern;
372 }
373
374
375
376
377
378 public void setAllowPublicImmutableFields(boolean allow) {
379 allowPublicImmutableFields = allow;
380 }
381
382
383
384
385
386 public void setAllowPublicFinalFields(boolean allow) {
387 allowPublicFinalFields = allow;
388 }
389
390
391
392
393
394 public void setImmutableClassCanonicalNames(String... classNames) {
395 immutableClassCanonicalNames = Arrays.asList(classNames);
396 }
397
398 @Override
399 public int[] getDefaultTokens() {
400 return getRequiredTokens();
401 }
402
403 @Override
404 public int[] getAcceptableTokens() {
405 return getRequiredTokens();
406 }
407
408 @Override
409 public int[] getRequiredTokens() {
410 return new int[] {
411 TokenTypes.VARIABLE_DEF,
412 TokenTypes.IMPORT,
413 };
414 }
415
416 @Override
417 public void beginTree(DetailAST rootAst) {
418 immutableClassShortNames.clear();
419 final List<String> classShortNames =
420 getClassShortNames(immutableClassCanonicalNames);
421 immutableClassShortNames.addAll(classShortNames);
422
423 ignoreAnnotationShortNames.clear();
424 final List<String> annotationShortNames =
425 getClassShortNames(ignoreAnnotationCanonicalNames);
426 ignoreAnnotationShortNames.addAll(annotationShortNames);
427 }
428
429 @Override
430 public void visitToken(DetailAST ast) {
431 switch (ast.getType()) {
432 case TokenTypes.VARIABLE_DEF:
433 if (!isAnonymousClassVariable(ast)) {
434 visitVariableDef(ast);
435 }
436 break;
437 case TokenTypes.IMPORT:
438 visitImport(ast);
439 break;
440 default:
441 final String exceptionMsg = "Unexpected token type: " + ast.getText();
442 throw new IllegalArgumentException(exceptionMsg);
443 }
444 }
445
446
447
448
449
450
451 private static boolean isAnonymousClassVariable(DetailAST variableDef) {
452 return variableDef.getParent().getType() != TokenTypes.OBJBLOCK;
453 }
454
455
456
457
458
459
460 private void visitVariableDef(DetailAST variableDef) {
461 final boolean inInterfaceOrAnnotationBlock =
462 ScopeUtil.isInInterfaceOrAnnotationBlock(variableDef);
463
464 if (!inInterfaceOrAnnotationBlock && !hasIgnoreAnnotation(variableDef)) {
465 final DetailAST varNameAST = variableDef.findFirstToken(TokenTypes.TYPE)
466 .getNextSibling();
467 final String varName = varNameAST.getText();
468 if (!hasProperAccessModifier(variableDef, varName)) {
469 log(varNameAST, MSG_KEY, varName);
470 }
471 }
472 }
473
474
475
476
477
478
479 private boolean hasIgnoreAnnotation(DetailAST variableDef) {
480 final DetailAST firstIgnoreAnnotation =
481 findMatchingAnnotation(variableDef);
482 return firstIgnoreAnnotation != null;
483 }
484
485
486
487
488
489
490
491 private void visitImport(DetailAST importAst) {
492 if (!isStarImport(importAst)) {
493 final DetailAST type = importAst.getFirstChild();
494 final String canonicalName = getCanonicalName(type);
495 final String shortName = getClassShortName(canonicalName);
496
497
498
499
500 if (!immutableClassCanonicalNames.contains(canonicalName)) {
501 immutableClassShortNames.remove(shortName);
502 }
503 if (!ignoreAnnotationCanonicalNames.contains(canonicalName)) {
504 ignoreAnnotationShortNames.remove(shortName);
505 }
506 }
507 }
508
509
510
511
512
513
514
515
516
517
518
519 private static boolean isStarImport(DetailAST importAst) {
520 boolean result = false;
521 DetailAST toVisit = importAst;
522 while (toVisit != null) {
523 toVisit = getNextSubTreeNode(toVisit, importAst);
524 if (toVisit != null && toVisit.getType() == TokenTypes.STAR) {
525 result = true;
526 break;
527 }
528 }
529 return result;
530 }
531
532
533
534
535
536
537
538 private boolean hasProperAccessModifier(DetailAST variableDef, String variableName) {
539 boolean result = true;
540
541 final String variableScope = getVisibilityScope(variableDef);
542
543 if (!PRIVATE_ACCESS_MODIFIER.equals(variableScope)) {
544 result =
545 isStaticFinalVariable(variableDef)
546 || packageAllowed && PACKAGE_ACCESS_MODIFIER.equals(variableScope)
547 || protectedAllowed && PROTECTED_ACCESS_MODIFIER.equals(variableScope)
548 || isIgnoredPublicMember(variableName, variableScope)
549 || isAllowedPublicField(variableDef);
550 }
551
552 return result;
553 }
554
555
556
557
558
559
560 private static boolean isStaticFinalVariable(DetailAST variableDef) {
561 final Set<String> modifiers = getModifiers(variableDef);
562 return modifiers.contains(STATIC_KEYWORD)
563 && modifiers.contains(FINAL_KEYWORD);
564 }
565
566
567
568
569
570
571
572 private boolean isIgnoredPublicMember(String variableName, String variableScope) {
573 return PUBLIC_ACCESS_MODIFIER.equals(variableScope)
574 && publicMemberPattern.matcher(variableName).find();
575 }
576
577
578
579
580
581
582 private boolean isAllowedPublicField(DetailAST variableDef) {
583 return allowPublicFinalFields && isFinalField(variableDef)
584 || allowPublicImmutableFields && isImmutableFieldDefinedInFinalClass(variableDef);
585 }
586
587
588
589
590
591
592 private boolean isImmutableFieldDefinedInFinalClass(DetailAST variableDef) {
593 final DetailAST classDef = variableDef.getParent().getParent();
594 final Set<String> classModifiers = getModifiers(classDef);
595 return (classModifiers.contains(FINAL_KEYWORD) || classDef.getType() == TokenTypes.ENUM_DEF)
596 && isImmutableField(variableDef);
597 }
598
599
600
601
602
603
604 private static Set<String> getModifiers(DetailAST defAST) {
605 final DetailAST modifiersAST = defAST.findFirstToken(TokenTypes.MODIFIERS);
606 final Set<String> modifiersSet = new HashSet<>();
607 if (modifiersAST != null) {
608 DetailAST modifier = modifiersAST.getFirstChild();
609 while (modifier != null) {
610 modifiersSet.add(modifier.getText());
611 modifier = modifier.getNextSibling();
612 }
613 }
614 return modifiersSet;
615 }
616
617
618
619
620
621
622 private static String getVisibilityScope(DetailAST variableDef) {
623 final Set<String> modifiers = getModifiers(variableDef);
624 String accessModifier = PACKAGE_ACCESS_MODIFIER;
625 for (final String modifier : EXPLICIT_MODS) {
626 if (modifiers.contains(modifier)) {
627 accessModifier = modifier;
628 break;
629 }
630 }
631 return accessModifier;
632 }
633
634
635
636
637
638
639
640
641
642
643 private boolean isImmutableField(DetailAST variableDef) {
644 boolean result = false;
645 if (isFinalField(variableDef)) {
646 final DetailAST type = variableDef.findFirstToken(TokenTypes.TYPE);
647 final boolean isCanonicalName = isCanonicalName(type);
648 final String typeName = getTypeName(type, isCanonicalName);
649 if (immutableClassShortNames.contains(typeName)
650 || isCanonicalName && immutableClassCanonicalNames.contains(typeName)) {
651 final DetailAST typeArgs = getGenericTypeArgs(type, isCanonicalName);
652
653 if (typeArgs == null) {
654 result = true;
655 }
656 else {
657 final List<String> argsClassNames = getTypeArgsClassNames(typeArgs);
658 result = areImmutableTypeArguments(argsClassNames);
659 }
660 }
661 else {
662 result = !isCanonicalName && isPrimitive(type);
663 }
664 }
665 return result;
666 }
667
668
669
670
671
672
673 private static boolean isCanonicalName(DetailAST type) {
674 return type.getFirstChild().getType() == TokenTypes.DOT;
675 }
676
677
678
679
680
681
682
683 private static DetailAST getGenericTypeArgs(DetailAST type, boolean isCanonicalName) {
684 final DetailAST typeArgs;
685 if (isCanonicalName) {
686
687 typeArgs = type.getFirstChild().findFirstToken(TokenTypes.TYPE_ARGUMENTS);
688 }
689 else {
690 typeArgs = type.findFirstToken(TokenTypes.TYPE_ARGUMENTS);
691 }
692 return typeArgs;
693 }
694
695
696
697
698
699
700 private static List<String> getTypeArgsClassNames(DetailAST typeArgs) {
701 final List<String> typeClassNames = new ArrayList<>();
702 DetailAST type = typeArgs.findFirstToken(TokenTypes.TYPE_ARGUMENT);
703 boolean isCanonicalName = isCanonicalName(type);
704 String typeName = getTypeName(type, isCanonicalName);
705 typeClassNames.add(typeName);
706 DetailAST sibling = type.getNextSibling();
707 while (sibling.getType() == TokenTypes.COMMA) {
708 type = sibling.getNextSibling();
709 isCanonicalName = isCanonicalName(type);
710 typeName = getTypeName(type, isCanonicalName);
711 typeClassNames.add(typeName);
712 sibling = type.getNextSibling();
713 }
714 return typeClassNames;
715 }
716
717
718
719
720
721
722
723
724 private boolean areImmutableTypeArguments(List<String> typeArgsClassNames) {
725 return typeArgsClassNames.stream().noneMatch(
726 typeName -> {
727 return !immutableClassShortNames.contains(typeName)
728 && !immutableClassCanonicalNames.contains(typeName);
729 });
730 }
731
732
733
734
735
736
737 private static boolean isFinalField(DetailAST variableDef) {
738 final DetailAST modifiers = variableDef.findFirstToken(TokenTypes.MODIFIERS);
739 return modifiers.findFirstToken(TokenTypes.FINAL) != null;
740 }
741
742
743
744
745
746
747
748
749
750 private static String getTypeName(DetailAST type, boolean isCanonicalName) {
751 final String typeName;
752 if (isCanonicalName) {
753 typeName = getCanonicalName(type);
754 }
755 else {
756 typeName = type.getFirstChild().getText();
757 }
758 return typeName;
759 }
760
761
762
763
764
765
766
767
768
769
770 private static boolean isPrimitive(DetailAST type) {
771 return type.getFirstChild().getType() != TokenTypes.IDENT;
772 }
773
774
775
776
777
778
779 private static String getCanonicalName(DetailAST type) {
780 final StringBuilder canonicalNameBuilder = new StringBuilder(256);
781 DetailAST toVisit = type.getFirstChild();
782 while (toVisit != null) {
783 toVisit = getNextSubTreeNode(toVisit, type);
784 if (toVisit != null && toVisit.getType() == TokenTypes.IDENT) {
785 if (canonicalNameBuilder.length() > 0) {
786 canonicalNameBuilder.append('.');
787 }
788 canonicalNameBuilder.append(toVisit.getText());
789 final DetailAST nextSubTreeNode = getNextSubTreeNode(toVisit, type);
790 if (nextSubTreeNode != null
791 && nextSubTreeNode.getType() == TokenTypes.TYPE_ARGUMENTS) {
792 break;
793 }
794 }
795 }
796 return canonicalNameBuilder.toString();
797 }
798
799
800
801
802
803
804
805
806
807 private static DetailAST
808 getNextSubTreeNode(DetailAST currentNodeAst, DetailAST subTreeRootAst) {
809 DetailAST currentNode = currentNodeAst;
810 DetailAST toVisitAst = currentNode.getFirstChild();
811 while (toVisitAst == null) {
812 toVisitAst = currentNode.getNextSibling();
813 if (currentNode.getParent().getColumnNo() == subTreeRootAst.getColumnNo()) {
814 break;
815 }
816 currentNode = currentNode.getParent();
817 }
818 return toVisitAst;
819 }
820
821
822
823
824
825
826
827 private static List<String> getClassShortNames(List<String> canonicalClassNames) {
828 final List<String> shortNames = new ArrayList<>();
829 for (String canonicalClassName : canonicalClassNames) {
830 final String shortClassName = canonicalClassName
831 .substring(canonicalClassName.lastIndexOf('.') + 1);
832 shortNames.add(shortClassName);
833 }
834 return shortNames;
835 }
836
837
838
839
840
841
842 private static String getClassShortName(String canonicalClassName) {
843 return canonicalClassName
844 .substring(canonicalClassName.lastIndexOf('.') + 1);
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 private DetailAST findMatchingAnnotation(DetailAST variableDef) {
871 DetailAST matchingAnnotation = null;
872
873 final DetailAST holder = AnnotationUtil.getAnnotationHolder(variableDef);
874
875 for (DetailAST child = holder.getFirstChild();
876 child != null; child = child.getNextSibling()) {
877 if (child.getType() == TokenTypes.ANNOTATION) {
878 final DetailAST ast = child.getFirstChild();
879 final String name =
880 FullIdent.createFullIdent(ast.getNextSibling()).getText();
881 if (ignoreAnnotationCanonicalNames.contains(name)
882 || ignoreAnnotationShortNames.contains(name)) {
883 matchingAnnotation = child;
884 break;
885 }
886 }
887 }
888
889 return matchingAnnotation;
890 }
891
892 }