-
Notifications
You must be signed in to change notification settings - Fork 107
/
Annotation.java
1436 lines (1334 loc) · 62.7 KB
/
Annotation.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
/*******************************************************************************
* Copyright (c) 2000, 2021 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Stephan Herrmann - Contributions for
* bug 186342 - [compiler][null] Using annotations for null checking
* bug 365662 - [compiler][null] warn on contradictory and redundant null annotations
* bug 331649 - [compiler][null] consider null annotations for fields
* Bug 392099 - [1.8][compiler][null] Apply null annotation on types for null analysis
* Bug 415043 - [1.8][null] Follow-up re null type annotations after bug 392099
* Bug 392238 - [1.8][compiler][null] Detect semantically invalid null type annotations
* Bug 415850 - [1.8] Ensure RunJDTCoreTests can cope with null annotations enabled
* Bug 417295 - [1.8[[null] Massage type annotated null analysis to gel well with deep encoded type bindings.
* Bug 424728 - [1.8][null] Unexpected error: The nullness annotation 'XXXX' is not applicable at this location
* Bug 392245 - [1.8][compiler][null] Define whether / how @NonNullByDefault applies to TYPE_USE locations
* Bug 429958 - [1.8][null] evaluate new DefaultLocation attribute of @NonNullByDefault
* Bug 435805 - [1.8][compiler][null] Java 8 compiler does not recognize declaration style null annotations
* Bug 457210 - [1.8][compiler][null] Wrong Nullness errors given on full build build but not on incremental build?
* Bug 469584 - ClassCastException in Annotation.detectStandardAnnotation (320)
* Andy Clement (GoPivotal, Inc) aclement@gopivotal.com - Contributions for
* Bug 383624 - [1.8][compiler] Revive code generation support for type annotations (from Olivier's work)
* Bug 409517 - [1.8][compiler] Type annotation problems on more elaborate array references
* Bug 415397 - [1.8][compiler] Type Annotations on wildcard type argument dropped
* Bug 414384 - [1.8] type annotation on abbreviated inner class is not marked as inner type
* Jesper S Moller <jesper@selskabet.org> - Contributions for
* Bug 412153 - [1.8][compiler] Check validity of annotations which may be repeatable
* Bug 412151 - [1.8][compiler] Check repeating annotation's collection type
* Bug 412149 - [1.8][compiler] Emit repeated annotations into the designated container
* Bug 419209 - [1.8] Repeating container annotations should be rejected in the presence of annotation it contains
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
import java.util.Stack;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.EnumConstantSignature;
import org.eclipse.jdt.internal.compiler.impl.BooleanConstant;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.impl.IrritantSet;
import org.eclipse.jdt.internal.compiler.lookup.*;
/**
* Annotation
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class Annotation extends Expression {
Annotation persistibleAnnotation = this; // Emit this into class file, unless this is a repeating annotation, in which case package this into the designated container.
/**
* Return the location for the corresponding annotation inside the type reference, <code>null</code> if none.
*/
public static int[] getLocations(
final Expression reference,
final Annotation annotation) {
class LocationCollector extends ASTVisitor {
Stack typePathEntries;
Annotation searchedAnnotation;
boolean continueSearch = true;
public LocationCollector(Annotation currentAnnotation) {
this.typePathEntries = new Stack();
this.searchedAnnotation = currentAnnotation;
}
private int[] computeNestingDepth(TypeReference typeReference) {
TypeBinding type = typeReference.resolvedType == null ? null : typeReference.resolvedType.leafComponentType();
int[] nestingDepths = new int[typeReference.getAnnotatableLevels()];
if (type != null && type.isNestedType()) {
int depth = 0;
TypeBinding currentType = type;
while (currentType != null) {
depth += (currentType.isStatic()) ? 0 : 1;
currentType = currentType.enclosingType();
}
// Work backwards computing whether a INNER_TYPE entry is required for each level
int counter = nestingDepths.length - 1;
while (type != null && counter >= 0) {
nestingDepths[counter--] = depth;
depth -= type.isStatic() ? 0 : 1;
type = type.enclosingType();
}
}
return nestingDepths;
}
private void inspectAnnotations(Annotation [] annotations) {
for (int i = 0, length = annotations == null ? 0 : annotations.length; this.continueSearch && i < length; i++) {
if (annotations[i] == this.searchedAnnotation) {
this.continueSearch = false;
break;
}
}
}
private void inspectArrayDimensions(Annotation [][] annotationsOnDimensions, int dimensions) {
for (int i = 0; this.continueSearch && i < dimensions; i++) {
Annotation[] annotations = annotationsOnDimensions == null ? null : annotationsOnDimensions[i];
inspectAnnotations(annotations);
if (!this.continueSearch) return;
this.typePathEntries.push(TYPE_PATH_ELEMENT_ARRAY);
}
}
private void inspectTypeArguments(TypeReference[] typeReferences) {
for (int i = 0, length = typeReferences == null ? 0 : typeReferences.length; this.continueSearch && i < length; i++) {
int size = this.typePathEntries.size();
this.typePathEntries.add(new int[]{3,i});
typeReferences[i].traverse(this, (BlockScope) null);
if (!this.continueSearch) return;
this.typePathEntries.setSize(size);
}
}
public boolean visit(TypeReference typeReference, BlockScope scope) {
if (this.continueSearch) {
inspectArrayDimensions(typeReference.getAnnotationsOnDimensions(), typeReference.dimensions());
if (this.continueSearch) {
int[] nestingDepths = computeNestingDepth(typeReference);
Annotation[][] annotations = typeReference.annotations;
TypeReference [][] typeArguments = typeReference.getTypeArguments();
int levels = typeReference.getAnnotatableLevels();
int size = this.typePathEntries.size();
for (int i = levels - 1; this.continueSearch && i >= 0; i--) { // traverse outwards, see comment below about type annotations from SE7 locations.
this.typePathEntries.setSize(size);
for (int j = 0, depth = nestingDepths[i]; j < depth; j++)
this.typePathEntries.add(TYPE_PATH_INNER_TYPE);
if (annotations != null)
inspectAnnotations(annotations[i]);
if (this.continueSearch && typeArguments != null) {
inspectTypeArguments(typeArguments[i]);
}
}
}
}
return false; // if annotation is not found in the type reference, it must be one from SE7 location, typePathEntries captures the proper path entries for them.
}
@Override
public boolean visit(SingleTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(ArrayTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(ParameterizedSingleTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(QualifiedTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(ArrayQualifiedTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(ParameterizedQualifiedTypeReference typeReference, BlockScope scope) {
return visit((TypeReference) typeReference, scope);
}
@Override
public boolean visit(Wildcard typeReference, BlockScope scope) {
visit((TypeReference) typeReference, scope);
if (this.continueSearch) {
TypeReference bound = typeReference.bound;
if (bound != null) {
int size = this.typePathEntries.size();
this.typePathEntries.push(TYPE_PATH_ANNOTATION_ON_WILDCARD_BOUND);
bound.traverse(this, scope);
if (this.continueSearch)
this.typePathEntries.setSize(size);
}
}
return false;
}
@Override
public boolean visit(ArrayAllocationExpression allocationExpression, BlockScope scope) {
if (this.continueSearch) {
inspectArrayDimensions(allocationExpression.getAnnotationsOnDimensions(), allocationExpression.dimensions.length);
if (this.continueSearch) {
allocationExpression.type.traverse(this, scope);
}
if (this.continueSearch) throw new IllegalStateException();
}
return false;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer
.append("search location for ") //$NON-NLS-1$
.append(this.searchedAnnotation)
.append("\ncurrent type_path entries : "); //$NON-NLS-1$
for (Object entry : this.typePathEntries) {
int[] typePathEntry = (int[]) entry;
buffer
.append('(')
.append(typePathEntry[0])
.append(',')
.append(typePathEntry[1])
.append(')');
}
return String.valueOf(buffer);
}
}
if (reference == null) return null;
LocationCollector collector = new LocationCollector(annotation);
reference.traverse(collector, (BlockScope) null);
if (collector.typePathEntries.isEmpty()) {
return null;
}
int size = collector.typePathEntries.size();
int[] result = new int[size*2];
int offset=0;
for (int i = 0; i < size; i++) {
int[] pathElement = (int[])collector.typePathEntries.get(i);
result[offset++] = pathElement[0];
result[offset++] = pathElement[1];
}
return result;
}
final static MemberValuePair[] NoValuePairs = new MemberValuePair[0];
static final int[] TYPE_PATH_ELEMENT_ARRAY = new int[]{0,0};
static final int[] TYPE_PATH_INNER_TYPE = new int[]{1,0};
static final int[] TYPE_PATH_ANNOTATION_ON_WILDCARD_BOUND = new int[]{2,0};
public int declarationSourceEnd;
public Binding recipient;
public TypeReference type;
/**
* The representation of this annotation in the type system.
*/
protected AnnotationBinding compilerAnnotation = null;
public static long getRetentionPolicy(char[] policyName) {
if (policyName == null || policyName.length == 0)
return 0;
switch(policyName[0]) {
case 'C' :
if (CharOperation.equals(policyName, TypeConstants.UPPER_CLASS))
return TagBits.AnnotationClassRetention;
break;
case 'S' :
if (CharOperation.equals(policyName, TypeConstants.UPPER_SOURCE))
return TagBits.AnnotationSourceRetention;
break;
case 'R' :
if (CharOperation.equals(policyName, TypeConstants.UPPER_RUNTIME))
return TagBits.AnnotationRuntimeRetention;
break;
}
return 0; // unknown
}
public static long getTargetElementType(char[] elementName) {
if (elementName == null || elementName.length == 0)
return 0;
switch(elementName[0]) {
case 'A' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_ANNOTATION_TYPE))
return TagBits.AnnotationForAnnotationType;
break;
case 'C' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_CONSTRUCTOR))
return TagBits.AnnotationForConstructor;
break;
case 'F' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_FIELD))
return TagBits.AnnotationForField;
break;
case 'L' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_LOCAL_VARIABLE))
return TagBits.AnnotationForLocalVariable;
break;
case 'M' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_METHOD))
return TagBits.AnnotationForMethod;
else if (CharOperation.equals(elementName, TypeConstants.UPPER_MODULE))
return TagBits.AnnotationForModule;
break;
case 'P' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_PARAMETER))
return TagBits.AnnotationForParameter;
else if (CharOperation.equals(elementName, TypeConstants.UPPER_PACKAGE))
return TagBits.AnnotationForPackage;
break;
case 'R' :
if (CharOperation.equals(elementName, TypeConstants.UPPER_RECORD_COMPONENT))
return TagBits.AnnotationForRecordComponent;
break;
case 'T' :
if (CharOperation.equals(elementName, TypeConstants.TYPE))
return TagBits.AnnotationForType;
if (CharOperation.equals(elementName, TypeConstants.TYPE_USE_TARGET))
return TagBits.AnnotationForTypeUse;
if (CharOperation.equals(elementName, TypeConstants.TYPE_PARAMETER_TARGET))
return TagBits.AnnotationForTypeParameter;
break;
}
return 0; // unknown
}
public ElementValuePair[] computeElementValuePairs() {
return Binding.NO_ELEMENT_VALUE_PAIRS;
}
/**
* Compute the bit pattern for recognized standard annotations the compiler may need to act upon.
* The lower bits (Binding.NullnessDefaultMASK) do not belong in tagBits, but in defaultNullness.
*/
private long detectStandardAnnotation(Scope scope, ReferenceBinding annotationType, MemberValuePair valueAttribute) {
long tagBits = 0;
switch (annotationType.id) {
// retention annotation
case TypeIds.T_JavaLangAnnotationRetention :
if (valueAttribute != null) {
Expression expr = valueAttribute.value;
if ((expr.bits & Binding.VARIABLE) == Binding.FIELD && expr instanceof Reference) { // anything but Reference would be a type error anyway
FieldBinding field = ((Reference)expr).fieldBinding();
if (field != null && field.declaringClass.id == T_JavaLangAnnotationRetentionPolicy) {
tagBits |= getRetentionPolicy(field.name);
}
}
}
break;
// target annotation
case TypeIds.T_JavaLangAnnotationTarget :
tagBits |= TagBits.AnnotationTarget; // target specified (could be empty)
if (valueAttribute != null) {
Expression expr = valueAttribute.value;
if (expr instanceof ArrayInitializer) {
ArrayInitializer initializer = (ArrayInitializer) expr;
final Expression[] expressions = initializer.expressions;
if (expressions != null) {
for (Expression initExpr : expressions) {
if ((initExpr.bits & Binding.VARIABLE) == Binding.FIELD) {
FieldBinding field = ((Reference) initExpr).fieldBinding();
if (field != null && field.declaringClass.id == T_JavaLangAnnotationElementType) {
long element = getTargetElementType(field.name);
if ((tagBits & element) != 0) {
scope.problemReporter().duplicateTargetInTargetAnnotation(annotationType, (NameReference)initExpr);
} else {
tagBits |= element;
}
}
}
}
}
} else if ((expr.bits & Binding.VARIABLE) == Binding.FIELD) {
FieldBinding field = ((Reference) expr).fieldBinding();
if (field != null && field.declaringClass.id == T_JavaLangAnnotationElementType) {
tagBits |= getTargetElementType(field.name);
}
}
}
break;
case TypeIds.T_JdkInternalPreviewFeature :
tagBits |= TagBits.AnnotationPreviewFeature;
for (MemberValuePair memberValuePair : memberValuePairs()) {
if (CharOperation.equals(memberValuePair.name, TypeConstants.ESSENTIAL_API)) {
if (memberValuePair.value instanceof TrueLiteral) {
tagBits |= TagBits.EssentialAPI;
}
}
}
break;
// marker annotations
case TypeIds.T_JavaLangDeprecated :
tagBits |= TagBits.AnnotationDeprecated;
if (scope.compilerOptions().complianceLevel >= ClassFileConstants.JDK9) {
for (MemberValuePair memberValuePair : memberValuePairs()) {
if (CharOperation.equals(memberValuePair.name, TypeConstants.FOR_REMOVAL)) {
if (memberValuePair.value instanceof TrueLiteral)
tagBits |= TagBits.AnnotationTerminallyDeprecated;
break;
}
}
}
break;
case TypeIds.T_JavaLangAnnotationDocumented :
tagBits |= TagBits.AnnotationDocumented;
break;
case TypeIds.T_JavaLangAnnotationInherited :
tagBits |= TagBits.AnnotationInherited;
break;
case TypeIds.T_JavaLangOverride :
tagBits |= TagBits.AnnotationOverride;
break;
case TypeIds.T_JavaLangFunctionalInterface :
tagBits |= TagBits.AnnotationFunctionalInterface;
break;
case TypeIds.T_JavaLangAnnotationRepeatable:
tagBits |= TagBits.AnnotationRepeatable;
break;
case TypeIds.T_JavaLangSuppressWarnings :
tagBits |= TagBits.AnnotationSuppressWarnings;
break;
case TypeIds.T_JavaLangSafeVarargs :
tagBits |= TagBits.AnnotationSafeVarargs;
break;
case TypeIds.T_JavaLangInvokeMethodHandlePolymorphicSignature :
tagBits |= TagBits.AnnotationPolymorphicSignature;
break;
}
CompilerOptions compilerOptions = scope.compilerOptions();
if (compilerOptions.isAnnotationBasedNullAnalysisEnabled) {
if (annotationType.hasNullBit(TypeIds.BitNullableAnnotation)) {
tagBits |= TagBits.AnnotationNullable;
} else if (annotationType.hasNullBit(TypeIds.BitNonNullAnnotation)) {
tagBits |= TagBits.AnnotationNonNull;
} else if (annotationType.hasNullBit(TypeIds.BitNonNullByDefaultAnnotation)) {
tagBits |= determineNonNullByDefaultTagBits(annotationType, valueAttribute);
}
}
if (compilerOptions.isAnnotationBasedResourceAnalysisEnabled) {
if (annotationType.hasTypeBit(TypeIds.BitOwningAnnotation)) {
tagBits |= TagBits.AnnotationOwning;
} else if (annotationType.hasTypeBit(TypeIds.BitNotOwningAnnotation)) {
tagBits |= TagBits.AnnotationNotOwning;
}
}
return tagBits;
}
private long determineNonNullByDefaultTagBits(ReferenceBinding annotationType, MemberValuePair valueAttribute) {
long tagBits = 0;
Object value = null;
if (valueAttribute != null) {
if (valueAttribute.compilerElementPair != null)
value = valueAttribute.compilerElementPair.value;
} else { // fetch default value - TODO: cache it?
MethodBinding[] methods = annotationType.methods();
if (methods != null && methods.length == 1)
value = methods[0].getDefaultValue();
else
tagBits |= Binding.DefaultLocationsForTrueValue; // custom unconfigurable NNBD
}
if (value instanceof BooleanConstant) {
// boolean value is used for declaration annotations, signal using the annotation tag bit:
tagBits |= ((BooleanConstant)value).booleanValue() ? Binding.DefaultLocationsForTrueValue : Binding.NULL_UNSPECIFIED_BY_DEFAULT;
} else if (value != null) {
// non-boolean value signals type annotations, evaluate from DefaultLocation[] to bitvector a la Binding#NullnessDefaultMASK:
tagBits |= nullLocationBitsFromAnnotationValue(value);
} else {
int result = BinaryTypeBinding.evaluateTypeQualifierDefault(annotationType);
if(result != 0) {
return result;
}
}
return tagBits;
}
/**
* Convert the value() attribute of @NonNullByDefault into a bitvector a la {@link Binding#NullnessDefaultMASK}.
* This method understands value encodings from source and binary types.
*
* <b>pre:</b> null annotation analysis is enabled
*/
public static int nullLocationBitsFromAnnotationValue(Object value) {
if (value instanceof Object[]) {
if (((Object[]) value).length == 0) { // ({})
return Binding.NULL_UNSPECIFIED_BY_DEFAULT;
} else { // ({vals...})
int bits = 0;
for (Object single : (Object[])value)
bits |= evaluateDefaultNullnessLocation(single);
return bits;
}
} else { // (val)
return evaluateDefaultNullnessLocation(value);
}
}
private static int evaluateDefaultNullnessLocation(Object value) {
char[] name = null;
if (value instanceof FieldBinding) {
name = ((FieldBinding) value).name;
} else if (value instanceof EnumConstantSignature) {
name = ((EnumConstantSignature) value).getEnumConstantName();
} else if (value instanceof ElementValuePair.UnresolvedEnumConstant) {
name = ((ElementValuePair.UnresolvedEnumConstant) value).getEnumConstantName();
} else if (value instanceof BooleanConstant) {
return ((BooleanConstant)value).booleanValue() ? Binding.DefaultLocationsForTrueValue : Binding.NULL_UNSPECIFIED_BY_DEFAULT;
}
if (name != null) {
switch (name.length) {
case 5:
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__FIELD))
return Binding.DefaultLocationField;
break;
case 9:
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__PARAMETER))
return Binding.DefaultLocationParameter;
break;
case 10:
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__TYPE_BOUND))
return Binding.DefaultLocationTypeBound;
break;
case 11:
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__RETURN_TYPE))
return Binding.DefaultLocationReturnType;
break;
case 13 :
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__TYPE_ARGUMENT))
return Binding.DefaultLocationTypeArgument;
break;
case 14 :
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__TYPE_PARAMETER))
return Binding.DefaultLocationTypeParameter;
if (CharOperation.equals(name, TypeConstants.DEFAULT_LOCATION__ARRAY_CONTENTS))
return Binding.DefaultLocationArrayContents;
break;
}
}
return 0;
}
public static int nullLocationBitsFromElementTypeAnnotationValue(Object value) {
if (value instanceof Object[]) {
if (((Object[]) value).length == 0) { // ({})
return Binding.NULL_UNSPECIFIED_BY_DEFAULT;
} else { // ({vals...})
int bits = 0;
for (Object single : (Object[])value)
bits |= evaluateElementTypeNullnessLocation(single);
return bits;
}
} else { // (val)
return evaluateElementTypeNullnessLocation(value);
}
}
private static int evaluateElementTypeNullnessLocation(Object value) {
char[] name = null;
if (value instanceof FieldBinding) {
name = ((FieldBinding) value).name;
} else if (value instanceof EnumConstantSignature) {
name = ((EnumConstantSignature) value).getEnumConstantName();
} else if (value instanceof ElementValuePair.UnresolvedEnumConstant) {
name = ((ElementValuePair.UnresolvedEnumConstant) value).getEnumConstantName();
}
if (name != null) {
switch (name.length) {
case 5:
if (CharOperation.equals(name, TypeConstants.UPPER_FIELD))
return Binding.DefaultLocationField;
break;
case 6:
if (CharOperation.equals(name, TypeConstants.UPPER_METHOD))
return Binding.DefaultLocationReturnType;
break;
case 9:
if (CharOperation.equals(name, TypeConstants.UPPER_PARAMETER))
return Binding.DefaultLocationParameter;
break;
}
}
return 0;
}
static String getRetentionName(long tagBits) {
if ((tagBits & TagBits.AnnotationRuntimeRetention) == TagBits.AnnotationRuntimeRetention) {
// TagBits.AnnotationRuntimeRetention combines both TagBits.AnnotationClassRetention & TagBits.AnnotationSourceRetention
return new String(UPPER_RUNTIME);
} else if ((tagBits & TagBits.AnnotationSourceRetention) != 0) {
return new String(UPPER_SOURCE);
} else {
return new String(TypeConstants.UPPER_CLASS);
}
}
private static long getAnnotationRetention(ReferenceBinding binding) {
long retention = binding.getAnnotationTagBits() & TagBits.AnnotationRetentionMASK;
// Retention defaults to CLASS
return retention != 0 ? retention : TagBits.AnnotationClassRetention;
}
public void checkRepeatableMetaAnnotation(BlockScope scope) {
// `this' is the @Repeatable meta annotation, its recipient is the *repeatable* annotation type - we are at the declaration site, not the repeating use site.
ReferenceBinding repeatableAnnotationType = (ReferenceBinding) this.recipient; // know it to be an annotation type. On target miss we don't get here
MemberValuePair[] valuePairs = this.memberValuePairs();
if (valuePairs == null || valuePairs.length != 1)
return;
Object value = valuePairs[0].compilerElementPair.value;
if (!(value instanceof ReferenceBinding))
return; // Has deeper problems, will bark elsewhere.
ReferenceBinding containerAnnotationType = (ReferenceBinding) value;
if (!containerAnnotationType.isAnnotationType())
return; // Has deeper problems, will bark elsewhere.
repeatableAnnotationType.setContainerAnnotationType(containerAnnotationType); // For now. May be reset later to PRB in case of problems.
checkContainerAnnotationType(valuePairs[0], scope, containerAnnotationType, repeatableAnnotationType, false); // false => not use site, i.e declaration site error reporting requested.
}
public static void checkContainerAnnotationType(ASTNode culpritNode, BlockScope scope, ReferenceBinding containerAnnotationType, ReferenceBinding repeatableAnnotationType, boolean useSite) {
MethodBinding[] annotationMethods = containerAnnotationType.methods();
boolean sawValue = false;
for (MethodBinding method : annotationMethods) {
if (CharOperation.equals(method.selector, TypeConstants.VALUE)) {
sawValue = true;
if (method.returnType.isArrayType() && method.returnType.dimensions() == 1) {
ArrayBinding array = (ArrayBinding) method.returnType;
if (TypeBinding.equalsEquals(array.elementsType(), repeatableAnnotationType)) continue;
}
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().containerAnnotationTypeHasWrongValueType(culpritNode, containerAnnotationType, repeatableAnnotationType, method.returnType);
} else {
// Not the value() - must have default (or else isn't suitable as container)
if ((method.modifiers & ClassFileConstants.AccAnnotationDefault) == 0) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().containerAnnotationTypeHasNonDefaultMembers(culpritNode, containerAnnotationType, method.selector);
}
}
}
if (!sawValue) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().containerAnnotationTypeMustHaveValue(culpritNode, containerAnnotationType);
}
if (useSite)
checkContainingAnnotationTargetAtUse((Annotation) culpritNode, scope, containerAnnotationType, repeatableAnnotationType);
else
checkContainerAnnotationTypeTarget(culpritNode, scope, containerAnnotationType, repeatableAnnotationType);
long annotationTypeBits = getAnnotationRetention(repeatableAnnotationType);
long containerTypeBits = getAnnotationRetention(containerAnnotationType);
// Due to clever layout of the bits, we can compare the absolute value directly
if (containerTypeBits < annotationTypeBits) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().containerAnnotationTypeHasShorterRetention(culpritNode, repeatableAnnotationType, getRetentionName(annotationTypeBits), containerAnnotationType, getRetentionName(containerTypeBits));
}
if ((repeatableAnnotationType.getAnnotationTagBits() & TagBits.AnnotationDocumented) != 0 && (containerAnnotationType.getAnnotationTagBits() & TagBits.AnnotationDocumented) == 0) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().repeatableAnnotationTypeIsDocumented(culpritNode, repeatableAnnotationType, containerAnnotationType);
}
if ((repeatableAnnotationType.getAnnotationTagBits() & TagBits.AnnotationInherited) != 0 && (containerAnnotationType.getAnnotationTagBits() & TagBits.AnnotationInherited) == 0) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().repeatableAnnotationTypeIsInherited(culpritNode, repeatableAnnotationType, containerAnnotationType);
}
}
// This is for error reporting for bad targets at annotation type declaration site (as opposed to the repeat site)
private static void checkContainerAnnotationTypeTarget(ASTNode culpritNode, Scope scope, ReferenceBinding containerType, ReferenceBinding repeatableAnnotationType) {
long tagBits = repeatableAnnotationType.getAnnotationTagBits();
if ((tagBits & TagBits.AnnotationTargetMASK) == 0)
tagBits = TagBits.AnnotationForDeclarationMASK; // absence of @Target meta-annotation implies all declaration targets not all targets.
long containerAnnotationTypeTypeTagBits = containerType.getAnnotationTagBits();
if ((containerAnnotationTypeTypeTagBits & TagBits.AnnotationTargetMASK) == 0)
containerAnnotationTypeTypeTagBits = TagBits.AnnotationForDeclarationMASK;
final long targets = tagBits & TagBits.AnnotationTargetMASK;
final long containerAnnotationTypeTargets = containerAnnotationTypeTypeTagBits & TagBits.AnnotationTargetMASK;
if ((containerAnnotationTypeTargets & ~targets) != 0) {
class MissingTargetBuilder {
StringBuilder targetBuffer = new StringBuilder();
void check(long targetMask, char[] targetName) {
if ((containerAnnotationTypeTargets & targetMask & ~targets) != 0) {
// if targetMask equals TagBits.AnnotationForType implies
// TagBits.AnnotationForType is part of containerAnnotationTypeTargets
if (targetMask == TagBits.AnnotationForType &&
(targets & TagBits.AnnotationForTypeUse) != 0) {
return;
}
add(targetName);
}
}
void checkAnnotationType(char[] targetName) {
if ((containerAnnotationTypeTargets & TagBits.AnnotationForAnnotationType) != 0 &&
((targets & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))) == 0) {
add(targetName);
}
}
private void add(char[] targetName) {
if (this.targetBuffer.length() != 0) {
this.targetBuffer.append(", "); //$NON-NLS-1$
}
this.targetBuffer.append(targetName);
}
@Override
public String toString() {
return this.targetBuffer.toString();
}
public boolean hasError() {
return this.targetBuffer.length() != 0;
}
}
MissingTargetBuilder builder = new MissingTargetBuilder();
builder.check(TagBits.AnnotationForType, TypeConstants.TYPE);
builder.check(TagBits.AnnotationForField, TypeConstants.UPPER_FIELD);
builder.check(TagBits.AnnotationForMethod, TypeConstants.UPPER_METHOD);
builder.check(TagBits.AnnotationForParameter, TypeConstants.UPPER_PARAMETER);
builder.check(TagBits.AnnotationForConstructor, TypeConstants.UPPER_CONSTRUCTOR);
builder.check(TagBits.AnnotationForLocalVariable, TypeConstants.UPPER_LOCAL_VARIABLE);
builder.checkAnnotationType(TypeConstants.UPPER_ANNOTATION_TYPE);
builder.check(TagBits.AnnotationForPackage, TypeConstants.UPPER_PACKAGE);
builder.check(TagBits.AnnotationForTypeParameter, TypeConstants.TYPE_PARAMETER_TARGET);
builder.check(TagBits.AnnotationForTypeUse, TypeConstants.TYPE_USE_TARGET);
builder.check(TagBits.AnnotationForModule, TypeConstants.UPPER_MODULE);
builder.check(TagBits.AnnotationForRecordComponent, TypeConstants.UPPER_RECORD_COMPONENT);
if (builder.hasError()) {
repeatableAnnotationType.tagAsHavingDefectiveContainerType();
scope.problemReporter().repeatableAnnotationTypeTargetMismatch(culpritNode, repeatableAnnotationType, containerType, builder.toString());
}
}
}
// This is for error reporting for bad targets at the repeated annotation use site (as opposed to repeatable annotation type declaration site) - Leads to better message.
public static void checkContainingAnnotationTargetAtUse(Annotation repeatingAnnotation, BlockScope scope, TypeBinding containerAnnotationType, TypeBinding repeatingAnnotationType) {
// check (meta)target compatibility
if (!repeatingAnnotationType.isValidBinding()) {
// no need to check annotation usage if missing
return;
}
if (isAnnotationTargetAllowed(repeatingAnnotation, scope, containerAnnotationType, repeatingAnnotation.recipient.kind()) != AnnotationTargetAllowed.YES) {
scope.problemReporter().disallowedTargetForContainerAnnotation(repeatingAnnotation, containerAnnotationType);
}
}
public AnnotationBinding getCompilerAnnotation() {
return this.compilerAnnotation;
}
public boolean isRuntimeInvisible() {
final TypeBinding annotationBinding = this.resolvedType;
if (annotationBinding == null) {
return false;
}
long metaTagBits = annotationBinding.getAnnotationTagBits(); // could be forward reference
if ((metaTagBits & TagBits.AnnotationRetentionMASK) == 0)
return true; // by default the retention is CLASS
return (metaTagBits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention;
}
public boolean isRuntimeTypeInvisible(boolean targetingTypeParameter) {
final TypeBinding annotationBinding = this.resolvedType;
if (annotationBinding == null) {
return false;
}
long metaTagBits = annotationBinding.getAnnotationTagBits(); // could be forward reference
if ((metaTagBits & (TagBits.AnnotationTargetMASK)) == 0) { // In the absence of explicit target, applicable only to declaration sites
if (!targetingTypeParameter)
return false;
} else if ((metaTagBits & (TagBits.AnnotationForTypeParameter | TagBits.AnnotationForTypeUse)) == 0) {
return false;
}
if ((metaTagBits & TagBits.AnnotationRetentionMASK) == 0)
return true; // by default the retention is CLASS
return (metaTagBits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationClassRetention;
}
public boolean isRuntimeTypeVisible(boolean targetingTypeParameter) {
final TypeBinding annotationBinding = this.resolvedType;
if (annotationBinding == null) {
return false;
}
long metaTagBits = annotationBinding.getAnnotationTagBits();
if ((metaTagBits & (TagBits.AnnotationTargetMASK)) == 0) { // In the absence of explicit target, applicable only to declaration sites
if (!targetingTypeParameter)
return false;
} else if ((metaTagBits & (TagBits.AnnotationForTypeParameter | TagBits.AnnotationForTypeUse)) == 0) {
return false;
}
if ((metaTagBits & TagBits.AnnotationRetentionMASK) == 0)
return false; // by default the retention is CLASS
return (metaTagBits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention;
}
public boolean isRuntimeVisible() {
final TypeBinding annotationBinding = this.resolvedType;
if (annotationBinding == null) {
return false;
}
long metaTagBits = annotationBinding.getAnnotationTagBits();
if ((metaTagBits & TagBits.AnnotationRetentionMASK) == 0)
return false; // by default the retention is CLASS
return (metaTagBits & TagBits.AnnotationRetentionMASK) == TagBits.AnnotationRuntimeRetention;
}
public abstract MemberValuePair[] memberValuePairs();
@Override
public StringBuilder printExpression(int indent, StringBuilder output) {
output.append('@');
this.type.printExpression(0, output);
return output;
}
public void recordSuppressWarnings(Scope scope, int startSuppresss, int endSuppress, boolean isSuppressingWarnings) {
IrritantSet suppressWarningIrritants = null;
MemberValuePair[] pairs = memberValuePairs();
pairLoop: for (int i = 0, length = pairs.length; i < length; i++) {
MemberValuePair pair = pairs[i];
if (CharOperation.equals(pair.name, TypeConstants.VALUE)) {
Expression value = pair.value;
if (value instanceof ArrayInitializer) {
ArrayInitializer initializer = (ArrayInitializer) value;
Expression[] inits = initializer.expressions;
if (inits != null) {
for (Expression init : inits) {
Constant cst = init.constant;
if (cst != Constant.NotAConstant && cst.typeID() == T_JavaLangString) {
IrritantSet irritants = CompilerOptions.warningTokenToIrritants(cst.stringValue());
if (irritants != null) {
if (suppressWarningIrritants == null) {
suppressWarningIrritants = new IrritantSet(irritants);
} else if (suppressWarningIrritants.set(irritants) == null) {
scope.problemReporter().unusedWarningToken(init);
}
} else {
scope.problemReporter().unhandledWarningToken(init);
}
}
}
}
} else {
Constant cst = value.constant;
if (cst != Constant.NotAConstant && cst.typeID() == T_JavaLangString) {
IrritantSet irritants = CompilerOptions.warningTokenToIrritants(cst.stringValue());
if (irritants != null) {
suppressWarningIrritants = new IrritantSet(irritants);
// TODO: should check for unused warning token against enclosing annotation as well ?
} else {
scope.problemReporter().unhandledWarningToken(value);
}
}
}
break pairLoop;
}
}
if (isSuppressingWarnings && suppressWarningIrritants != null) {
scope.referenceCompilationUnit().recordSuppressWarnings(suppressWarningIrritants, this, startSuppresss, endSuppress, scope.referenceContext());
}
}
@Override
public TypeBinding resolveType(BlockScope scope) {
if (this.compilerAnnotation != null)
return this.resolvedType;
this.constant = Constant.NotAConstant;
TypeBinding typeBinding;
if (this.resolvedType == null) {
typeBinding = this.type.resolveType(scope);
if (typeBinding == null) {
this.resolvedType = new ProblemReferenceBinding(this.type.getTypeName(), null, ProblemReasons.NotFound);
return null;
}
this.resolvedType = typeBinding;
} else {
typeBinding = this.resolvedType;
}
// ensure type refers to an annotation type
if (!typeBinding.isAnnotationType() && typeBinding.isValidBinding()) {
scope.problemReporter().notAnnotationType(typeBinding, this.type);
return null;
}
ReferenceBinding annotationType = (ReferenceBinding) this.resolvedType;
MethodBinding[] methods = annotationType.methods();
// clone valuePairs to keep track of unused ones
MemberValuePair[] originalValuePairs = memberValuePairs();
MemberValuePair valueAttribute = null; // remember the first 'value' pair
MemberValuePair[] pairs;
int pairsLength = originalValuePairs.length;
if (pairsLength > 0) {
System.arraycopy(originalValuePairs, 0, pairs = new MemberValuePair[pairsLength], 0, pairsLength);
} else {
pairs = originalValuePairs;
}
nextMember: for (int i = 0, requiredLength = methods.length; i < requiredLength; i++) {
MethodBinding method = methods[i];
char[] selector = method.selector;
boolean foundValue = false;
nextPair: for (int j = 0; j < pairsLength; j++) {
MemberValuePair pair = pairs[j];
if (pair == null) continue nextPair;
char[] name = pair.name;
if (CharOperation.equals(name, selector)) {
if (valueAttribute == null && CharOperation.equals(name, TypeConstants.VALUE)) {
valueAttribute = pair;
}
pair.binding = method;
pair.resolveTypeExpecting(scope, method.returnType);
pairs[j] = null; // consumed
foundValue = true;
// check duplicates
boolean foundDuplicate = false;
for (int k = j+1; k < pairsLength; k++) {
MemberValuePair otherPair = pairs[k];
if (otherPair == null) continue;
if (CharOperation.equals(otherPair.name, selector)) {
foundDuplicate = true;
scope.problemReporter().duplicateAnnotationValue(annotationType, otherPair);
otherPair.binding = method;
otherPair.resolveTypeExpecting(scope, method.returnType);
pairs[k] = null;
}
}
if (foundDuplicate) {
scope.problemReporter().duplicateAnnotationValue(annotationType, pair);
continue nextMember;
}
}
}
if (!foundValue
&& (method.modifiers & ClassFileConstants.AccAnnotationDefault) == 0
&& (this.bits & IsRecovered) == 0
&& annotationType.isValidBinding()) {
scope.problemReporter().missingValueForAnnotationMember(this, selector);
}
}
// check unused pairs
for (int i = 0; i < pairsLength; i++) {
if (pairs[i] != null) {
if (annotationType.isValidBinding()) {
scope.problemReporter().undefinedAnnotationValue(annotationType, pairs[i]);
}
pairs[i].resolveTypeExpecting(scope, null); // resilient
}
}
this.compilerAnnotation = scope.environment().createAnnotation((ReferenceBinding) this.resolvedType, computeElementValuePairs());
// recognize standard annotations ?
long tagBits = detectStandardAnnotation(scope, annotationType, valueAttribute);
int defaultNullness = (int)(tagBits & Binding.NullnessDefaultMASK);
tagBits &= ~Binding.NullnessDefaultMASK;
CompilerOptions compilerOptions = scope.compilerOptions();
if ((tagBits & TagBits.AnnotationDeprecated) != 0 && compilerOptions.complianceLevel >= ClassFileConstants.JDK9 && !compilerOptions.storeAnnotations) {
this.recipient.setAnnotations(new AnnotationBinding[] {this.compilerAnnotation}, true); // force storing enhanced deprecation
}
// record annotation positions in the compilation result
scope.referenceCompilationUnit().recordSuppressWarnings(IrritantSet.NLS, null, this.sourceStart, this.declarationSourceEnd, scope.referenceContext());
if (this.recipient != null) {
int kind = this.recipient.kind();
if (tagBits != 0 || defaultNullness != 0) {
// tag bits onto recipient
switch (kind) {
case Binding.MODULE :
SourceModuleBinding module = (SourceModuleBinding) this.recipient;
module.tagBits |= tagBits;
if ((tagBits & TagBits.AnnotationSuppressWarnings) != 0) {
ModuleDeclaration moduleDeclaration = module.scope.referenceContext.moduleDeclaration;
recordSuppressWarnings(scope, 0, moduleDeclaration.declarationSourceEnd, compilerOptions.suppressWarnings);
}
module.defaultNullness |= defaultNullness;
break;
case Binding.PACKAGE :
((PackageBinding)this.recipient).tagBits |= tagBits;
break;
case Binding.TYPE :
case Binding.GENERIC_TYPE :
SourceTypeBinding sourceType = (SourceTypeBinding) this.recipient;
if ((tagBits & TagBits.AnnotationRepeatable) == 0 || sourceType.isAnnotationType()) // don't set AnnotationRepeatable on non-annotation types.
sourceType.tagBits |= tagBits;
if ((tagBits & TagBits.AnnotationSuppressWarnings) != 0) {