/
ValueAttribute.java
1811 lines (1527 loc) · 56.9 KB
/
ValueAttribute.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 2013-2018 Immutables Authors and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.immutables.value.processor.meta;
import com.google.common.base.Ascii;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.lang.annotation.ElementType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.immutables.generator.AnnotationMirrors;
import org.immutables.generator.StringLiterals;
import org.immutables.generator.TypeHierarchyCollector;
import org.immutables.value.processor.encode.Instantiation;
import org.immutables.value.processor.encode.Instantiator.InstantiationCreator;
import org.immutables.value.processor.meta.AnnotationInjections.AnnotationInjection;
import org.immutables.value.processor.meta.AnnotationInjections.InjectAnnotation.Where;
import org.immutables.value.processor.meta.AnnotationInjections.InjectionInfo;
import org.immutables.value.processor.meta.Generics.Parameter;
import org.immutables.value.processor.meta.Proto.DeclaringType;
import org.immutables.value.processor.meta.Proto.Environment;
import org.immutables.value.processor.meta.Proto.MetaAnnotated;
import org.immutables.value.processor.meta.Proto.Protoclass;
import org.immutables.value.processor.meta.Reporter.About;
import org.immutables.value.processor.meta.Styles.UsingName.AttributeNames;
import org.immutables.value.processor.meta.ValueMirrors.Style.ImplementationVisibility;
import org.immutables.value.processor.meta.ValueMirrors.Style.ValidationMethod;
/**
* It's pointless to refactor this mess until
* 1) Some sort of type calculus toolkit used/created
* 2) Facets/Implicits in Generator toolkit with auto-memoising implemented
*/
public final class ValueAttribute extends TypeIntrospectionBase implements HasStyleInfo {
private static final WholeTypeVariable NON_WHOLE_TYPE_VARIABLE = new WholeTypeVariable(-1);
private static final int CONSTRUCTOR_PARAMETER_DEFAULT_ORDER = 0;
private static final int CONSTRUCTOR_NOT_A_PARAMETER = -1;
private static final String GUAVA_IMMUTABLE_PREFIX = UnshadeGuava.typeString("collect.Immutable");
private static final String VALUE_ATTRIBUTE_NAME = "value";
private static final String ID_ATTRIBUTE_NAME = "_id";
private static final String[] EMPTY_SERIALIZED_NAMES = {};
public AttributeNames names;
public boolean isGenerateDefault;
public boolean isGenerateDerived;
public boolean isGenerateAbstract;
public boolean isGenerateLazy;
public boolean isAttributeBuilder;
public ImmutableList<String> typeParameters = ImmutableList.of();
public ImmutableList<AnnotationInjection> annotationInjections = ImmutableList.of();
// Replace with delegation?
public Reporter reporter;
public ValueType containingType;
@Nullable
public ValueType attributeValueType;
TypeMirror returnType;
Element element;
String returnTypeName;
// Set only if isAttributeBuilder is true
@Nullable
private AttributeBuilderDescriptor attributeBuilderDescriptor;
public boolean hasEnumFirstTypeParameter;
@Nullable
TypeElement containedTypeElement;
@Nullable
private TypeElement containedSecondaryTypeElement;
private boolean generateOrdinalValueSet;
private TypeMirror arrayComponent;
@Nullable
private NullabilityAnnotationInfo nullability;
@Nullable
private NullabilityAnnotationInfo nullabilityInSupertype;
@Nullable
private String rawTypeName;
public String name() {
return names.var;
}
public boolean isBoolean() {
return returnType.getKind() == TypeKind.BOOLEAN;
}
public boolean isInt() {
return returnType.getKind() == TypeKind.INT;
}
public boolean isShort() {
return returnType.getKind() == TypeKind.SHORT;
}
public boolean isChar() {
return returnType.getKind() == TypeKind.CHAR;
}
public boolean isByte() {
return returnType.getKind() == TypeKind.BYTE;
}
public boolean isLong() {
return returnType.getKind() == TypeKind.LONG;
}
public boolean isStringType() {
return String.class.getName().equals(rawTypeName);
}
public boolean charType() {
return returnType.getKind() == TypeKind.CHAR;
}
public String atNullability() {
return nullability != null ? nullability.asPrefix() : "";
}
public String atNullabilityOriginal() {
return nullability != null ? nullability.asPrefixOriginal() : "";
}
public String atNullabilityLocal() {
return nullability != null ? nullability.asLocalPrefix() : "";
}
public boolean isSimpleLiteralType() {
return isPrimitive()
|| isStringType()
|| isEnumType();
}
public boolean hasSimpleScalarElementType() {
ensureTypeIntrospected();
String type = getWrappedElementType();
return isStringType()
|| String.class.getName().equals(type)
|| isPrimitiveWrappedType(type)
|| hasEnumContainedElementType()
|| isEnumType()
|| isJdkSpecializedOptional()
|| extendedClassesNames.contains(Number.class.getName());
}
public boolean requiresAlternativeStrictConstructor() {
return typeKind.isCollectionKind()
|| (typeKind.isMappingKind()
&& !typeKind.isPlainMapKind()
&& !typeKind.isMultimap());
}
public boolean isMandatory() {
return isGenerateAbstract
&& !isGenerateDefault // is the case for defaulted abstract annotation attribute
&& !isContainerType()
&& !isNullable()
&& !isEncoding()
&& !hasBuilderSwitcherDefault()
&& !(isPrimitive() && protoclass().styles().style().validationMethod() != ValidationMethod.SIMPLE);
}
public boolean isNullable() {
return nullability != null;
}
public ImmutableList<String> docComment = ImmutableList.of();
public boolean deprecated;
public boolean isMaybeComparableKey() {
return isContainerType()
&& (super.isComparable() || this.containedTypeElement == null);
}
@Override
public boolean isComparable() {
return isNumberType()
|| isStringType()
|| (!(isCollectionType() || isMapType()) && super.isComparable());
}
private List<CharSequence> jsonQualifierAnnotations;
public List<CharSequence> getJsonQualiferAnnotations() {
if (jsonQualifierAnnotations == null) {
List<CharSequence> annotationStrings = Collections.emptyList();
for (AnnotationMirror m : element.getAnnotationMirrors()) {
if (MetaAnnotated.from(m, protoclass().environment()).isJsonQualifier()) {
if (annotationStrings.isEmpty()) {
annotationStrings = Lists.newArrayList();
}
annotationStrings.add(AnnotationMirrors.toCharSequence(m));
}
}
jsonQualifierAnnotations = annotationStrings;
}
return jsonQualifierAnnotations;
}
@Nullable
private String serializedName;
private String[] alternateSerializedNames = EMPTY_SERIALIZED_NAMES;
public String[] getAlternateSerializedNames() {
getSerializedName();// trigger lazy init
return alternateSerializedNames;
}
/**
* Serialized name, actully specified via annotation
* @return name for JSON as overriden.
*/
public String getSerializedName() {
if (serializedName == null) {
Optional<SerializedNameMirror> serializedNameAnnotation = SerializedNameMirror.find(element);
if (serializedNameAnnotation.isPresent()) {
SerializedNameMirror m = serializedNameAnnotation.get();
serializedName = m.value();
alternateSerializedNames = m.alternate();
return serializedName;
}
Optional<NamedMirror> namedAnnotation = NamedMirror.find(element);
if (namedAnnotation.isPresent()) {
String value = namedAnnotation.get().value();
if (!value.isEmpty()) {
serializedName = value;
return serializedName;
}
}
Optional<OkNamedMirror> okNamedAnnotation = OkNamedMirror.find(element);
if (okNamedAnnotation.isPresent()) {
String value = okNamedAnnotation.get().name();
if (!value.isEmpty()) {
serializedName = value;
return serializedName;
}
}
if (isMarkedAsMongoId()) {
serializedName = ID_ATTRIBUTE_NAME;
return serializedName;
}
serializedName = "";
return serializedName;
}
return serializedName;
}
/**
* Marshaled name for compatibility with repository.
* @return get JSON name either specified or default.
*/
public String getMarshaledName() {
String serializedName = getSerializedName();
if (!serializedName.isEmpty()) {
return serializedName;
}
return names.raw;
}
private @Nullable Boolean isGsonOther = null;
public boolean isGsonOther() {
if (isGsonOther == null) {
if (GsonOtherMirror.isPresent(element)) {
if (!isGenerateAbstract || !rawTypeName.equals(GsonMirrors.JSON_OBJECT_TYPE)) {
report().error(
"@Gson.Other attribute must be abstract accessor of type %s",
GsonMirrors.JSON_OBJECT_TYPE);
isGsonOther = false;
} else {
isGsonOther = true;
}
} else {
isGsonOther = false;
}
}
return isGsonOther;
}
public boolean isForcedEmpty() {
return !containingType.gsonTypeAdapters().emptyAsNulls();
}
@Override
protected TypeMirror internalTypeMirror() {
return returnType;
}
public String getType() {
return returnTypeName;
}
public List<CharSequence> getAnnotations() {
if (containingType.isGenerateJacksonProperties()) {
return extractAnnotationsForElement(
ElementType.METHOD,
protoclass().styles().style().passAnnotationsNames());
}
return Annotations.getAnnotationLines(element,
protoclass().styles().style().passAnnotationsNames(),
false,
ElementType.METHOD,
importsResolver,
nullability);
}
public List<CharSequence> getFieldAnnotations() {
return Annotations.getAnnotationLines(element,
protoclass().styles().style().passAnnotationsNames(),
false,
ElementType.FIELD,
importsResolver,
null/* do not propagate nullable here */);
}
public CharSequence getConstructorParameterAnnotations() {
List<CharSequence> annotations =
Annotations.getAnnotationLines(element,
protoclass().styles().style().passAnnotationsNames(),
false,
ElementType.PARAMETER,
importsResolver,
nullability);
if (!annotations.isEmpty()) {
return Joiner.on(' ').join(annotations).concat(" ");
}
return "";
}
public List<CharSequence> getJacksonFieldsAnnotations() {
return extractAnnotationsForElement(ElementType.FIELD, Collections.<String>emptySet());
}
private CharSequence jacksonPropertyAnnotation() {
StringBuilder propertyAnnotation = new StringBuilder("@").append(Annotations.JACKSON_PROPERTY);
if (protoclass().styles().style().forceJacksonPropertyNames()) {
propertyAnnotation.append('(').append(StringLiterals.toLiteral(names.raw)).append(')');
}
return propertyAnnotation;
}
public List<CharSequence> getBuilderAttributeAnnotation() {
if (containingType.isGenerateJacksonProperties()
&& protoclass().isJacksonDeserialized()) {
List<CharSequence> jacksonPropertyAnnotation = Annotations.getAnnotationLines(element,
Collections.singleton(Annotations.JACKSON_PROPERTY),
false,
ElementType.METHOD,
importsResolver,
nullability);
List<CharSequence> annotations = Lists.newArrayList();
if (jacksonPropertyAnnotation.isEmpty()) {
annotations.add(jacksonPropertyAnnotation());
}
annotations.addAll(Annotations.getAnnotationLines(element,
Collections.<String>emptySet(),
protoclass().environment().hasJacksonLib(),
ElementType.METHOD,
importsResolver,
nullability));
return annotations;
}
return ImmutableList.of();
}
private List<CharSequence> extractAnnotationsForElement(ElementType elementType, Set<String> additionalAnnotations) {
List<CharSequence> allAnnotations = Lists.newArrayListWithCapacity(1);
boolean dontHaveJsonPropetyAnnotationAlready = Annotations.getAnnotationLines(element,
Collections.singleton(Annotations.JACKSON_PROPERTY),
false,
elementType,
importsResolver,
nullability).isEmpty();
if (dontHaveJsonPropetyAnnotationAlready) {
allAnnotations.add(jacksonPropertyAnnotation());
}
allAnnotations.addAll(
Annotations.getAnnotationLines(element,
Sets.union(additionalAnnotations,
protoclass().styles().style().additionalJsonAnnotationsNames()),
protoclass().environment().hasJacksonLib(),
elementType,
importsResolver,
nullability));
return allAnnotations;
}
public boolean isJsonIgnore() {
return IgnoreMirror.isPresent(element)
|| OkIgnoreMirror.isPresent(element);
}
public List<String> typeParameters() {
ensureTypeIntrospected();
return arrayComponent != null ? ImmutableList.of(arrayComponent.toString()) : typeParameters;
}
public boolean isMapType() {
return typeKind.isMappingKind();
}
public boolean isMultimapType() {
return typeKind.isMultimapKind();
}
public boolean isListType() {
return typeKind.isList();
}
private OrderKind orderKind = OrderKind.NONE;
private enum OrderKind {
NONE, NATURAL, REVERSE
}
public boolean isSetType() {
return typeKind.isSet();
}
public boolean hasNaturalOrder() {
return orderKind == OrderKind.NATURAL;
}
public boolean hasReverseOrder() {
return orderKind == OrderKind.REVERSE;
}
public boolean isSortedSetType() {
return typeKind.isSortedSet();
}
public boolean isSortedMapType() {
return typeKind.isSortedMap();
}
public boolean isGenerateSortedSet() {
return typeKind.isSortedSet();
}
public boolean isGenerateSortedMap() {
return typeKind.isSortedMap();
}
public boolean isGenerateSortedMultiset() {
return typeKind.isSortedMultiset();
}
private void checkOrderAnnotations() {
Optional<NaturalOrderMirror> naturalOrderAnnotation = NaturalOrderMirror.find(element);
Optional<ReverseOrderMirror> reverseOrderAnnotation = ReverseOrderMirror.find(element);
if (naturalOrderAnnotation.isPresent() && reverseOrderAnnotation.isPresent()) {
report()
.error("@Value.Natural and @Value.Reverse annotations cannot be used on the same attribute");
} else if (naturalOrderAnnotation.isPresent()) {
configureOrdering(OrderKind.NATURAL, NaturalOrderMirror.simpleName());
} else if (reverseOrderAnnotation.isPresent()) {
configureOrdering(OrderKind.REVERSE, ReverseOrderMirror.simpleName());
}
}
private void configureOrdering(OrderKind orderKind, String annotationName) {
if (typeKind.isSortedKind()) {
if (isMaybeComparableKey()) {
this.orderKind = orderKind;
} else {
reportOrderingError(annotationName, "requires that a (multi)set's elements or a map's keys are Comparable");
}
} else {
reportOrderingError(annotationName, "can be applied only to SortedSet, SortedMap and SortedMultiset attributes");
}
}
private void reportOrderingError(String annotationName, String msg) {
report().annotationNamed(annotationName).error(String.format("@Value.%s %s", annotationName, msg));
}
public boolean isJdkOptional() {
return typeKind.isOptionalKind() && typeKind.isJdkOnlyContainerKind();
}
public boolean isFugueOptional() {
return typeKind.isOptionFugue();
}
public boolean isGuavaOptional() {
return typeKind.isOptionalGuava();
}
public boolean isJavaslangOptional() {
return typeKind.isOptionJavaslang();
}
public boolean isJdkSpecializedOptional() {
return typeKind.isOptionalSpecializedJdk();
}
public boolean isOptionalType() {
return typeKind.isOptionalKind();
}
public boolean isCollectionType() {
return typeKind.isCollectionKind();
}
public boolean isGenerateEnumSet() {
return typeKind.isEnumSet();
}
public boolean isGuavaImmutableDeclared() {
return typeKind.isContainerKind() && rawTypeName.startsWith(GUAVA_IMMUTABLE_PREFIX);
}
@Nullable
private String defaultInterface;
public String defaultInterface() {
if (defaultInterface == null) {
defaultInterface = inferDefaultInterface();
}
return defaultInterface;
}
private String inferDefaultInterface() {
if (isInterfaceDefaultMethod()) {
if (containingType.element.getKind() == ElementKind.INTERFACE) {
return containingType.typeAbstract().relativeRaw();
}
}
return "";
}
public boolean isInterfaceDefaultMethod() {
return element.getEnclosingElement().getKind() == ElementKind.INTERFACE
&& !element.getModifiers().contains(Modifier.ABSTRACT);
}
public boolean isGenerateTransientDerived() {
return isGenerateDerived
&& style().transientDerivedFields()
&& !containingType.serial.isSimple();
}
public boolean isGenerateEnumMap() {
return typeKind.isEnumMap();
}
public boolean hasVirtualImpl() {
return isEncoding() && instantiation.hasVirtualImpl();
}
public String getUnwrappedElementType() {
return isContainerType() && nullElements.ban()
? unwrapType(firstTypeParameter())
: getElementType();
}
public String getUnwrappedValueElementType() {
return isMapType()
? getUnwrappedSecondaryElementType()
: getUnwrappedElementType();
}
public String getWrappedElementType() {
if (returnType.getKind().isPrimitive()) {
return wrapType(Ascii.toLowerCase(returnType.getKind().name()));
}
return wrapType(hasContainedElementType()
? firstTypeParameter()
: returnTypeName);
}
private boolean hasContainedElementType() {
return isArrayType() || isContainerType();
}
public String getRawType() {
return rawTypeName;
}
public String getConsumedElementType() {
return (isUnwrappedElementPrimitiveType()
|| isStringType()
|| (hasContainedElementType() && firstTypeParameter().equals(String.class.getName()))
|| hasEnumFirstTypeParameter())
? getWrappedElementType()
: "? extends " + getWrappedElementType();
}
public boolean hasEnumFirstTypeParameter() {
return typeKind().isEnumKeyed()
&& containedTypeElement.getKind() == ElementKind.ENUM;
}
private String extractRawType(String className) {
String rawType = className;
int indexOfGenerics = rawType.indexOf('<');
if (indexOfGenerics > 0) {
rawType = rawType.substring(0, indexOfGenerics);
}
int endOfTypeAnnotations = rawType.lastIndexOf(' ');
if (endOfTypeAnnotations > 0) {
rawType = rawType.substring(endOfTypeAnnotations + 1);
}
return rawType;
}
public boolean isUnwrappedElementPrimitiveType() {
return isPrimitiveType(getUnwrappedElementType());
}
public boolean isUnwrappedSecondaryElementPrimitiveType() {
return isPrimitiveType(getUnwrappedSecondaryElementType());
}
public String firstTypeParameter() {
return Iterables.getFirst(typeParameters(), "");
}
public String secondTypeParameter() {
return Iterables.get(typeParameters(), 1);
}
public String getElementType() {
return hasContainedElementType() ? firstTypeParameter() : returnTypeName;
}
@Nullable
private List<String> expectedSubtypes;
public List<String> getExpectedSubtypes() {
if (expectedSubtypes == null) {
ensureTypeIntrospected();
if (containedTypeElement != null || containedSecondaryTypeElement != null) {
TypeElement supertypeElement = MoreObjects.firstNonNull(containedSecondaryTypeElement, containedTypeElement);
Optional<ExpectedSubtypesMirror> annotationOnAttribute = ExpectedSubtypesMirror.find(element);
if (annotationOnAttribute.isPresent()) {
expectedSubtypes = ImmutableList.copyOf(annotationOnAttribute.get().valueName());
if (expectedSubtypes.isEmpty()) {
expectedSubtypes = tryFindSubtypes(supertypeElement);
}
} else {
Optional<ExpectedSubtypesMirror> annotationOnType = ExpectedSubtypesMirror.find(supertypeElement);
if (annotationOnType.isPresent()) {
expectedSubtypes = ImmutableList.copyOf(annotationOnType.get().valueName());
if (expectedSubtypes.isEmpty()) {
expectedSubtypes = tryFindSubtypes(supertypeElement);
}
}
}
}
if (expectedSubtypes == null) {
expectedSubtypes = ImmutableList.of();
}
}
return expectedSubtypes;
}
private ImmutableList<String> tryFindSubtypes(TypeElement supertypeElement) {
ValueType surroundingType =
MoreObjects.firstNonNull(containingType.enclosingValue, containingType);
Set<ValueType> subtypes =
surroundingType.getCases().knownSubtypesOf(supertypeElement.getQualifiedName().toString());
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (ValueType valueType : subtypes) {
builder.add(valueType.typeAbstract().toString());
}
return builder.build();
}
public boolean isGenerateJdkOnly() {
return containingType.isGenerateJdkOnly()
&& !typeKind.isGuavaContainerKind()
&& !isGuavaImmutableDeclared()
&& !isCustomCollectionType();
}
public boolean isGenerateOrdinalValueSet() {
if (!isSetType()) {
return false;
}
ensureTypeIntrospected();
return generateOrdinalValueSet;
}
public boolean isArrayType() {
return typeKind.isArray();
}
public boolean isReferenceArrayType() {
return isArrayType() && !isPrimitiveType(firstTypeParameter());
}
public boolean isPrimitiveArrayType() {
return isArrayType() && isPrimitiveType(firstTypeParameter());
}
public boolean isOptionalAcceptNullable() {
return isOptionalType()
&& !typeKind.isOptionalSpecializedJdk()
&& containingType.isOptionalAcceptNullable();
}
@Override
protected void introspectType() {
TypeMirror typeMirror = returnType;
// Special case for primitive Optional, may become a pattern for specialized types
if (typeKind.isOptionalSpecializedJdk()) {
typeParameters = ImmutableList.of(optionalSpecializedType());
// no delegation to introspect further
return;
}
if (isContainerType()) {
if (typeMirror.getKind() == TypeKind.DECLARED
|| typeMirror.getKind() == TypeKind.ERROR) {
DeclaredType declaredType = (DeclaredType) typeMirror;
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (!typeArguments.isEmpty()) {
final TypeMirror typeArgument = typeArguments.get(0);
if (isSetType() && protoclass().environment().hasOrdinalModule()) {
this.generateOrdinalValueSet = new TypeIntrospectionBase() {
@Override
protected TypeMirror internalTypeMirror() {
return typeArgument;
}
@Override
protected TypeHierarchyCollector collectTypeHierarchy(TypeMirror typeMirror) {
TypeHierarchyCollector collector = containingType.createTypeHierarchyCollector(reporter, element);
collector.collectFrom(typeMirror);
return collector;
}
}.isOrdinalValue();
}
if (isMapType()) {
TypeMirror typeSecondArgument = typeArguments.get(1);
if (typeSecondArgument.getKind() == TypeKind.DECLARED) {
TypeElement typeElement = (TypeElement) ((DeclaredType) typeSecondArgument).asElement();
this.containedSecondaryTypeElement = typeElement;
}
}
typeMirror = typeArgument;
}
}
} else if (isArrayType()) {
arrayComponent = ((ArrayType) typeMirror).getComponentType();
typeMirror = arrayComponent;
}
if (typeMirror.getKind() == TypeKind.DECLARED) {
TypeElement typeElement = (TypeElement) ((DeclaredType) typeMirror).asElement();
this.containedTypeElement = typeElement;
}
introspectTypeMirror(typeMirror);
introspectSupertypes();
}
private String optionalSpecializedType() {
switch (typeKind) {
case OPTIONAL_INT_JDK:
return int.class.getName();
case OPTIONAL_LONG_JDK:
return long.class.getName();
case OPTIONAL_DOUBLE_JDK:
return double.class.getName();
default:
throw new AssertionError();
}
}
public AttributeTypeKind typeKind() {
return typeKind;
}
public boolean isPrimitiveWrapperType() {
return isPrimitiveWrappedType(returnTypeName);
}
private static boolean isRegularMarshalableType(String name) {
return String.class.getName().equals(name)
|| isPrimitiveType(name);
}
public boolean isRequiresMarshalingAdapter() {
return !isRegularMarshalableType(getElementType())
|| isPrimitiveArrayType();
}
public boolean isRequiresMarshalingSecondaryAdapter() {
return isMapType() && !isRegularMarshalableType(getSecondaryElementType());
}
public boolean wrapArrayToIterable() {
return containingType.isGenerateJdkOnly()
|| isUnwrappedElementPrimitiveType()
|| !(typeKind.isList() || typeKind.isSet() || typeKind.isMultiset());
}
/**
* Suitable for JavaDocs, intemediate name mangling and for Guava intergration.
* @return the raw collection type
*/
public String getRawCollectionType() {
return typeKind.rawSimpleName(rawTypeName);
}
public boolean isMultisetType() {
return typeKind.isMultisetKind();
}
public boolean isCustomCollectionType() {
return typeKind.isCustomCollection();
}
public String getRawMapType() {
return typeKind.rawSimpleName(rawTypeName);
}
public String getSecondaryElementType() {
return secondTypeParameter();
}
public String getUnwrappedSecondaryElementType() {
return nullElements.ban()
? unwrapType(secondTypeParameter())
: getSecondaryElementType();
}
public String getWrappedSecondaryElementType() {
return wrapType(secondTypeParameter());
}
public String getUnwrapperOrRawSecondaryElementType() {
return extractRawType(getWrappedSecondaryElementType());
}
public String getUnwrapperOrRawElementType() {
return extractRawType(getWrappedElementType());
}
public boolean isNumberType() {
TypeKind kind = returnType.getKind();
return kind.isPrimitive()
&& kind != TypeKind.CHAR
&& kind != TypeKind.BOOLEAN;
}
public boolean isFloatType() {
return isFloat() || isDouble();
}
public boolean isFloat() {
return returnType.getKind() == TypeKind.FLOAT;
}
public boolean isDouble() {
return returnType.getKind() == TypeKind.DOUBLE;
}
public boolean hasTypeAnnotations() {
return returnTypeName.indexOf('@') >= 0;
}
public boolean isNonRawElementType() {
return getElementType().indexOf('<') > 0;
}
public boolean isNonRawSecondaryElementType() {
return getSecondaryElementType().indexOf('<') > 0;
}
public boolean isContainerType() {
// TBD replace with typeKind.isContainerKind() ?
return isCollectionType()
|| isOptionalType()
|| isMapType();
}
public String getWrapperType() {
return isPrimitive()
? wrapType(rawTypeName)
: returnTypeName;
}
public boolean isPrimitive() {
return returnType.getKind().isPrimitive();
}
public boolean isAttributeBuilder() {
return isAttributeBuilder;
}
// undefined value is any less than CONSTRUCTOR_NOT_A_PARAMETER
private int parameterOrder = Integer.MIN_VALUE;
private AttributeTypeKind typeKind;
public boolean jacksonAnyGetter;
public boolean jacksonValue;
public boolean hasTypeVariables;
private ImportsTypeStringResolver importsResolver;
public @Nullable Instantiation instantiation;
int getConstructorParameterOrder() {
boolean parameterOrderIsUndefined = parameterOrder < CONSTRUCTOR_NOT_A_PARAMETER;
if (parameterOrderIsUndefined) {
parameterOrder = computeConstructorParameterOrder();
}
return parameterOrder;
}
private int computeConstructorParameterOrder() {
boolean enabledAsAllParameters =
style().allParameters();
boolean enabledAsAllMandatoryParameters =
style().allMandatoryParameters() && isMandatory();
Optional<ParameterMirror> parameterAnnotation = ParameterMirror.find(element);
if (parameterAnnotation.isPresent()) {
if (!parameterAnnotation.get().value()) {
// Cancelled out parameter identified, can return immediately
return CONSTRUCTOR_NOT_A_PARAMETER;
}
int order = parameterAnnotation.get().order();
boolean orderActuallySpecified = order >= CONSTRUCTOR_PARAMETER_DEFAULT_ORDER;
// when order is unspecified it would be -1, but we should not treat is as
// CONSTRUCTOR_NOT_A_PARAMETER, so we assign CONSTRUCTOR_PARAMETER_DEFAULT_ORDER
// in this case
if (orderActuallySpecified) {
return order;
}
// We issue this warning only when order is not specified explicitly
// and it is not a cancelling-out annotation thus the annoation
// is truly superfluos when allParameters enabled
if (enabledAsAllParameters) {
report().annotationNamed(ParameterMirror.simpleName())
.warning(About.INCOMPAT,