1 package net.florianschoppmann.java.type;
2
3 import javax.annotation.Nullable;
4 import javax.lang.model.element.Element;
5 import javax.lang.model.element.ElementKind;
6 import javax.lang.model.element.TypeElement;
7 import javax.lang.model.element.TypeParameterElement;
8 import javax.lang.model.type.ArrayType;
9 import javax.lang.model.type.DeclaredType;
10 import javax.lang.model.type.NoType;
11 import javax.lang.model.type.NullType;
12 import javax.lang.model.type.PrimitiveType;
13 import javax.lang.model.type.TypeKind;
14 import javax.lang.model.type.TypeMirror;
15 import javax.lang.model.type.TypeVariable;
16 import javax.lang.model.type.WildcardType;
17 import javax.lang.model.util.Types;
18 import java.io.Serializable;
19 import java.lang.reflect.Type;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedHashMap;
26 import java.util.LinkedHashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Set;
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 public abstract class AbstractTypes implements Types {
59 private static final List<TypeKind> REFERENCE_TYPES = Collections.unmodifiableList(Arrays.asList(
60 TypeKind.ARRAY, TypeKind.DECLARED, TypeKind.NULL, TypeKind.TYPEVAR
61 ));
62 private static final int DEFAULT_STRING_BUILDER_SIZE = 256;
63
64 private final SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor();
65 private final ErasureVisitor erasureVisitor = new ErasureVisitor();
66 private final ToStringVisitor toStringVisitor = new ToStringVisitor();
67 private final SubtypeVisitor subtypeVisitor = new SubtypeVisitor();
68 private final DeclaredTypeSubtypeVisitor declaredTypeSubtypeVisitor = new DeclaredTypeSubtypeVisitor();
69
70
71
72
73
74
75
76
77
78
79
80 protected abstract void requireValidElement(Element element);
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 protected abstract void requireValidType(@Nullable TypeMirror type);
96
97
98
99
100
101
102
103
104
105 protected final void requireValidTypes(TypeMirror[] types) {
106 for (TypeMirror typeArg: types) {
107 Objects.requireNonNull(typeArg, "TypeMirror array must not contain null elements.");
108 requireValidType(typeArg);
109 }
110 }
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132 protected abstract TypeMirror typeMirror(Type type);
133
134
135
136
137
138 private static final class Substitutions {
139 private final Map<TypeParameterElement, ? extends TypeMirror> map;
140 private final Map<TypeParameterElement, TypeVariable> freshTypeVariables;
141
142 private Substitutions(Map<TypeParameterElement, ? extends TypeMirror> map,
143 Map<TypeParameterElement, TypeVariable> freshTypeVariables) {
144 this.map = map;
145 this.freshTypeVariables = freshTypeVariables;
146 }
147 }
148
149
150
151
152
153
154
155
156
157
158
159 private final class SubstitutionVisitor extends ExtendedTypeKindVisitor7<TypeMirror, Substitutions> {
160 private TypeMirror[] substituteInList(List<? extends TypeMirror> types, Substitutions substitutions) {
161 TypeMirror[] substituted = new TypeMirror[types.size()];
162 int i = 0;
163 for (TypeMirror type: types) {
164 substituted[i] = type.accept(this, substitutions);
165 ++i;
166 }
167 return substituted;
168 }
169
170 @Override
171 public TypeMirror visitDeclared(DeclaredType declaredType, @Nullable Substitutions substitutions) {
172 assert substitutions != null;
173 TypeMirror enclosingType = declaredType.getEnclosingType();
174 TypeElement typeDeclaration = (TypeElement) declaredType.asElement();
175 TypeMirror[] substitutedArguments = substituteInList(declaredType.getTypeArguments(), substitutions);
176 if (enclosingType.getKind() == TypeKind.DECLARED) {
177 return getDeclaredType((DeclaredType) enclosingType, typeDeclaration, substitutedArguments);
178 } else {
179 return getDeclaredType(typeDeclaration, substitutedArguments);
180 }
181 }
182
183 @Override
184 public TypeMirror visitArray(ArrayType arrayType, @Nullable Substitutions substitutions) {
185 assert substitutions != null;
186 return getArrayType(arrayType.getComponentType().accept(this, substitutions));
187 }
188
189 @Override
190 public TypeMirror visitTypeVariable(TypeVariable typeVariable, @Nullable Substitutions substitutions) {
191 assert substitutions != null;
192 TypeParameterElement formalTypeParameter = (TypeParameterElement) typeVariable.asElement();
193 @Nullable TypeVariable freshTypeVariable = substitutions.freshTypeVariables.get(formalTypeParameter);
194 if (freshTypeVariable != null && formalTypeParameter.asType().equals(typeVariable)) {
195 return freshTypeVariable;
196 }
197
198 @Nullable TypeMirror substitution = substitutions.map.get(formalTypeParameter);
199 if (substitution != null) {
200 return substitution;
201 }
202
203 return getTypeVariable(
204 formalTypeParameter,
205 typeVariable.getUpperBound().accept(this, substitutions),
206 typeVariable.getLowerBound().accept(this, substitutions),
207 capturedTypeArgument(typeVariable)
208 );
209 }
210
211 @Override
212 public TypeMirror visitWildcard(WildcardType wildcardType, @Nullable Substitutions substitutions) {
213 assert substitutions != null;
214 @Nullable TypeMirror extendsBounds = wildcardType.getExtendsBound();
215 @Nullable TypeMirror superBound = wildcardType.getSuperBound();
216
217 return getWildcardType(
218 extendsBounds != null
219 ? extendsBounds.accept(this, substitutions)
220 : null,
221 superBound != null
222 ? superBound.accept(this, substitutions)
223 : null
224 );
225 }
226
227 @Override
228 public TypeMirror visitIntersection(IntersectionType intersectionType, @Nullable Substitutions substitutions) {
229 assert substitutions != null;
230 return getIntersectionType(substituteInList(intersectionType.getBounds(), substitutions));
231 }
232
233 @Override
234 protected TypeMirror defaultAction(TypeMirror type, Substitutions substitutions) {
235 return type;
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 protected TypeMirror substitute(TypeMirror type, Map<TypeParameterElement, ? extends TypeMirror> substitutionMap) {
265 Objects.requireNonNull(type);
266 Objects.requireNonNull(substitutionMap);
267 requireValidType(type);
268 for (TypeMirror substitutionType: substitutionMap.values()) {
269 Objects.requireNonNull(substitutionType, "Substitution type cannot be null.");
270 requireValidType(substitutionType);
271 }
272
273 Map<TypeParameterElement, TypeVariable> freshTypeVariables = new LinkedHashMap<>();
274 for (Map.Entry<TypeParameterElement, ? extends TypeMirror> entry: substitutionMap.entrySet()) {
275 TypeMirror value = entry.getValue();
276 if (value.getKind() == TypeKind.TYPEVAR) {
277 TypeParameterElement formalTypeParameter = entry.getKey();
278 TypeVariable typeVariable = (TypeVariable) value;
279 if (entry.getKey().equals(typeVariable.asElement())) {
280 assert !freshTypeVariables.containsKey(formalTypeParameter);
281
282 freshTypeVariables.put(
283 formalTypeParameter,
284 createTypeVariable(formalTypeParameter, capturedTypeArgument(typeVariable))
285 );
286 }
287 }
288 }
289
290 Substitutions substitutions = new Substitutions(substitutionMap, freshTypeVariables);
291 for (Map.Entry<TypeParameterElement, TypeVariable> entry: freshTypeVariables.entrySet()) {
292 TypeVariable substitution = (TypeVariable) substitutionMap.get(entry.getKey());
293 setTypeVariableBounds(
294 entry.getValue(),
295 substitution.getUpperBound().accept(substitutionVisitor, substitutions),
296 substitution.getLowerBound().accept(substitutionVisitor, substitutions)
297 );
298 }
299
300 return type.accept(substitutionVisitor, substitutions);
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 @Nullable
339 public final List<? extends TypeMirror> resolveActualTypeArguments(TypeElement typeElement, TypeMirror subType) {
340 requireValidElement(Objects.requireNonNull(typeElement));
341 requireValidType(Objects.requireNonNull(subType));
342
343 if (subType.getKind() != TypeKind.DECLARED) {
344 return null;
345 }
346
347 DeclaredType declaredSubType = (DeclaredType) subType;
348
349
350
351 @Nullable List<DeclaredType> path = getShortestPathToSuperType(typeElement, declaredSubType);
352 if (path == null) {
353 return null;
354 }
355
356
357
358 if (typeElement.getTypeParameters().isEmpty()) {
359 return Collections.emptyList();
360 }
361
362 Iterator<DeclaredType> pathIterator = path.iterator();
363 DeclaredType current = pathIterator.next();
364 while (pathIterator.hasNext()) {
365 TypeElement currentTypeElement = (TypeElement) current.asElement();
366
367
368
369
370
371 if (current.getTypeArguments().isEmpty() && !currentTypeElement.getTypeParameters().isEmpty()) {
372 current = (DeclaredType) currentTypeElement.asType();
373 }
374
375 List<? extends TypeParameterElement> currentFormalParameters = currentTypeElement.getTypeParameters();
376 List<? extends TypeMirror> currentActualParameters = current.getTypeArguments();
377
378 Map<TypeParameterElement, TypeMirror> currentFormalToActual = new LinkedHashMap<>();
379 for (int index = 0; index < currentFormalParameters.size(); ++index) {
380 currentFormalToActual.put(currentFormalParameters.get(index), currentActualParameters.get(index));
381 }
382
383 current = (DeclaredType) substitute(pathIterator.next(), currentFormalToActual);
384 }
385 return current.getTypeArguments();
386 }
387
388
389
390
391
392
393
394
395
396
397
398 private final class DeclaredTypeSubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, DeclaredType> {
399 private DeclaredTypeSubtypeVisitor() {
400 super(false);
401 }
402
403
404
405
406
407
408
409
410 @Override
411 public Boolean visitDeclared(DeclaredType subType, @Nullable DeclaredType superType) {
412 assert superType != null;
413 DeclaredType actualSubType = subType;
414
415
416
417
418
419
420
421
422
423
424 for (TypeMirror subTypeArgument: subType.getTypeArguments()) {
425 if (subTypeArgument.getKind() == TypeKind.WILDCARD) {
426 actualSubType = (DeclaredType) capture(subType);
427 break;
428 }
429 }
430
431
432 TypeElement superTypeDeclaration = (TypeElement) superType.asElement();
433 @Nullable List<? extends TypeMirror> projectedTypeArguments
434 = resolveActualTypeArguments(superTypeDeclaration, actualSubType);
435
436 if (projectedTypeArguments == null) {
437
438 return false;
439 }
440
441 List<? extends TypeMirror> superTypeArguments = superType.getTypeArguments();
442 if (projectedTypeArguments.isEmpty() && !superTypeArguments.isEmpty()) {
443
444
445
446 return false;
447 }
448
449
450
451 Iterator<? extends TypeMirror> projectedTypeArgumentsIterator = projectedTypeArguments.iterator();
452 for (TypeMirror to: superTypeArguments) {
453 TypeMirror from = projectedTypeArgumentsIterator.next();
454 if (!contains(to, from)) {
455 return false;
456 }
457 }
458 return true;
459 }
460
461
462
463
464
465
466
467 @Override
468 public Boolean visitArray(ArrayType subType, @Nullable DeclaredType superType) {
469 assert superType != null;
470 return typeMirror(Object.class).equals(superType)
471 || typeMirror(Cloneable.class).equals(superType)
472 || typeMirror(Serializable.class).equals(superType);
473 }
474
475
476
477
478
479
480
481 @Override
482 public Boolean visitTypeVariable(TypeVariable subType, @Nullable DeclaredType superType) {
483 assert superType != null;
484 return isSubtype(subType.getUpperBound(), superType);
485 }
486
487
488
489
490
491
492
493
494 @Override
495 public Boolean visitIntersection(IntersectionType subType, @Nullable DeclaredType superType) {
496 assert superType != null;
497 for (TypeMirror bound: subType.getBounds()) {
498 if (isSubtype(bound, superType)) {
499 return true;
500 }
501 }
502 return false;
503 }
504 }
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524 private final class SubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, TypeMirror> {
525 private SubtypeVisitor() {
526 super(false);
527 }
528
529
530
531
532
533
534
535
536
537 @Override
538 public Boolean visitArray(ArrayType superType, @Nullable TypeMirror subType) {
539 assert subType != null;
540 return subType.getKind() == TypeKind.ARRAY
541 && isSubtype(((ArrayType) subType).getComponentType(), superType.getComponentType());
542 }
543
544
545
546
547
548
549 @Override
550 public Boolean visitDeclared(DeclaredType superType, @Nullable TypeMirror subType) {
551 assert subType != null;
552 return subType.accept(declaredTypeSubtypeVisitor, superType);
553 }
554
555 private final List<TypeKind> numericKindEnumValues = Collections.unmodifiableList(Arrays.asList(
556 TypeKind.DOUBLE, TypeKind.FLOAT, TypeKind.LONG, TypeKind.INT, TypeKind.SHORT, TypeKind.BYTE
557 ));
558 private final int intIndex = numericKindEnumValues.indexOf(TypeKind.INT);
559
560
561
562
563 @Override
564 public Boolean visitPrimitive(PrimitiveType superType, @Nullable TypeMirror subType) {
565 assert subType != null;
566 if (!subType.getKind().isPrimitive()) {
567 return false;
568 }
569
570 int superTypeIndex = numericKindEnumValues.indexOf(superType.getKind());
571 int subTypeIndex = numericKindEnumValues.indexOf(subType.getKind());
572 return (subType.getKind() == TypeKind.CHAR && 0 <= superTypeIndex && superTypeIndex <= intIndex)
573 || (0 <= superTypeIndex && superTypeIndex <= subTypeIndex);
574 }
575
576
577
578
579
580
581 @Override
582 public Boolean visitTypeVariable(TypeVariable superType, @Nullable TypeMirror subType) {
583 assert subType != null;
584 return isSameType(superType.getLowerBound(), subType);
585 }
586
587
588
589
590
591
592
593
594
595
596
597
598 @Override
599 public Boolean visitIntersection(IntersectionType superType, @Nullable TypeMirror subType) {
600 assert subType != null;
601 return isSameType(superType, subType);
602 }
603 }
604
605
606
607
608
609
610
611
612
613
614
615
616 @Override
617 public final boolean isSubtype(TypeMirror t1, TypeMirror t2) {
618 requireValidType(Objects.requireNonNull(t1));
619 requireValidType(Objects.requireNonNull(t2));
620
621
622 if (t1.getKind() == TypeKind.NULL && REFERENCE_TYPES.contains(t2.getKind())) {
623 return true;
624 }
625
626 return t2.accept(subtypeVisitor, t1);
627 }
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642 @Override
643 public final boolean contains(TypeMirror t1, TypeMirror t2) {
644 Objects.requireNonNull(t1);
645 Objects.requireNonNull(t2);
646 requireValidType(t1);
647 requireValidType(t2);
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665 if (t1.getKind() == TypeKind.WILDCARD) {
666 @Nullable TypeMirror t1ExtendsBound = ((WildcardType) t1).getExtendsBound();
667 @Nullable TypeMirror t1SuperBound = ((WildcardType) t1).getSuperBound();
668 boolean t1HasExtendsBound = t1ExtendsBound != null;
669 boolean t1HasSuperBound = t1SuperBound != null;
670
671 if (t2.getKind() == TypeKind.WILDCARD) {
672
673 @Nullable TypeMirror t2ExtendsBound = ((WildcardType) t2).getExtendsBound();
674 @Nullable TypeMirror t2SuperBound = ((WildcardType) t2).getSuperBound();
675
676 if (t2ExtendsBound != null) {
677 if (t1ExtendsBound != null) {
678
679 return isSubtype(t2ExtendsBound, t1ExtendsBound);
680 } else if (t1SuperBound == null) {
681
682 return true;
683 }
684
685 return false;
686 } else if (t2SuperBound != null) {
687 if (t1SuperBound != null) {
688
689 return isSubtype(t1SuperBound, t2SuperBound);
690 } else {
691
692
693 return t1ExtendsBound == null
694 || isSameType(t1ExtendsBound, typeMirror(Object.class));
695 }
696 } else {
697
698
699
700 return t1SuperBound == null && (
701 t1ExtendsBound == null || isSameType(t1ExtendsBound, typeMirror(Object.class))
702 );
703 }
704 } else {
705
706 if (t1HasExtendsBound) {
707
708 return contains(t1, getWildcardType(t2, null));
709 } else if (t1HasSuperBound) {
710
711 return contains(t1, getWildcardType(null, t2));
712 }
713
714 return true;
715 }
716 } else {
717
718 return isSameType(t1, t2);
719 }
720 }
721
722
723
724
725 private List<DeclaredType> directSupertypesOfTypeDeclaration(TypeElement typeElement) {
726 TypeMirror superClass = typeElement.getSuperclass();
727 List<? extends TypeMirror> interfaces = typeElement.getInterfaces();
728 List<DeclaredType> newSuperTypes = new ArrayList<>(1 + interfaces.size());
729 if (superClass.getKind() == TypeKind.DECLARED) {
730 newSuperTypes.add((DeclaredType) superClass);
731 }
732 for (TypeMirror superInterface: interfaces) {
733 newSuperTypes.add((DeclaredType) superInterface);
734 }
735 if (typeElement.getKind() == ElementKind.INTERFACE && interfaces.isEmpty()) {
736 newSuperTypes.add((DeclaredType) typeMirror(Object.class));
737 }
738 return newSuperTypes;
739 }
740
741
742
743
744
745 private static final class TypeDeclarationVertexState {
746 private int distance;
747 private boolean visited;
748 private final TypeElement typeElement;
749
750
751
752
753 private final DeclaredType declaredType;
754
755 @Nullable private TypeDeclarationVertexState previous;
756
757 private TypeDeclarationVertexState(int distance, boolean visited, TypeElement typeElement,
758 DeclaredType declaredType) {
759 this.distance = distance;
760 this.visited = visited;
761 this.typeElement = typeElement;
762 this.declaredType = declaredType;
763 }
764
765
766
767
768
769
770
771
772
773
774 private List<DeclaredType> toPath(DeclaredType derived) {
775 DeclaredType[] path = new DeclaredType[distance + 1];
776 int count = path.length;
777 TypeDeclarationVertexState pathElement = this;
778 while (pathElement.previous != null) {
779 --count;
780 path[count] = pathElement.declaredType;
781 pathElement = pathElement.previous;
782 }
783 path[0] = derived;
784 return Arrays.asList(path);
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 @Nullable
810 private List<DeclaredType> getShortestPathToSuperType(TypeElement base, DeclaredType derived) {
811 TypeElement typeElement = (TypeElement) derived.asElement();
812
813 Set<TypeElement> boundary = new LinkedHashSet<>();
814 Map<TypeElement, TypeDeclarationVertexState> dijkstraState = new HashMap<>();
815
816
817 dijkstraState.put(typeElement, new TypeDeclarationVertexState(0, false, typeElement, derived));
818
819 boundary.add(typeElement);
820
821
822
823
824 while (!boundary.isEmpty()) {
825
826 @Nullable TypeDeclarationVertexState shortest = null;
827 for (TypeElement currentDeclaration: boundary) {
828 TypeDeclarationVertexState current = dijkstraState.get(currentDeclaration);
829 if (shortest == null || current.distance < shortest.distance) {
830 shortest = current;
831 }
832 }
833
834
835 assert shortest != null && !shortest.visited;
836
837
838
839 if (shortest.typeElement.equals(base)) {
840 return shortest.toPath(derived);
841 }
842
843
844 boundary.remove(shortest.typeElement);
845 shortest.visited = true;
846
847 for (DeclaredType superType: directSupertypesOfTypeDeclaration(shortest.typeElement)) {
848
849
850 TypeElement superDeclaration = (TypeElement) superType.asElement();
851 @Nullable TypeDeclarationVertexState stats = dijkstraState.get(superDeclaration);
852
853 if (stats == null) {
854 stats = new TypeDeclarationVertexState(Integer.MAX_VALUE, false, superDeclaration, superType);
855 dijkstraState.put(superDeclaration, stats);
856 }
857
858 int alt = shortest.distance + 1;
859 if (!stats.visited && alt < stats.distance) {
860 stats.distance = alt;
861 stats.previous = shortest;
862 boundary.add(superDeclaration);
863 }
864 }
865 }
866 return null;
867 }
868
869
870
871
872
873
874 private final class ErasureVisitor extends ExtendedTypeKindVisitor7<TypeMirror, Void> {
875 @Override
876 public TypeMirror visitDeclared(DeclaredType declaredType, @Nullable Void ignored) {
877 TypeMirror originalEnclosingType = declaredType.getEnclosingType();
878 @Nullable DeclaredType newEnclosingType = originalEnclosingType.getKind() == TypeKind.NONE
879 ? null
880 : (DeclaredType) erasure(declaredType.getEnclosingType());
881 return getDeclaredType(newEnclosingType, (TypeElement) declaredType.asElement());
882 }
883
884
885
886
887 @Override
888 public TypeMirror visitArray(ArrayType arrayType, @Nullable Void ignored) {
889 return getArrayType(erasure(arrayType.getComponentType()));
890 }
891
892
893
894
895
896
897
898
899 @Override
900 public TypeMirror visitTypeVariable(TypeVariable typeVariable, @Nullable Void ignored) {
901 return erasure(typeVariable.getUpperBound());
902 }
903
904
905
906
907
908
909
910
911 @Override
912 public TypeMirror visitIntersection(IntersectionType intersectionType, @Nullable Void ignored) {
913 return erasure(intersectionType.getBounds().get(0));
914 }
915
916
917
918
919
920
921 @Override
922 protected TypeMirror defaultAction(TypeMirror type, Void ignored) {
923 return type;
924 }
925 }
926
927
928
929
930
931
932
933
934 @Override
935 public final TypeMirror erasure(TypeMirror type) {
936 Objects.requireNonNull(type);
937 requireValidType(type);
938
939 return type.accept(erasureVisitor, null);
940 }
941
942
943
944
945
946
947
948
949
950
951 @Override
952 public final Element asElement(TypeMirror type) {
953 Objects.requireNonNull(type);
954 requireValidType(type);
955
956 if (type.getKind() == TypeKind.DECLARED) {
957 return ((DeclaredType) type).asElement();
958 } else if (type.getKind() == TypeKind.TYPEVAR) {
959 return ((TypeVariable) type).asElement();
960 } else {
961 return null;
962 }
963 }
964
965
966
967
968
969
970
971
972
973
974
975 @Override
976 public final boolean isSameType(TypeMirror t1, TypeMirror t2) {
977 requireValidType(Objects.requireNonNull(t1));
978 requireValidType(Objects.requireNonNull(t2));
979
980 return t1.getKind() != TypeKind.WILDCARD && t1.equals(t2);
981 }
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996 private static TypeMirror[] greatestLowerBound(TypeMirror wildcardExtendsBound, TypeMirror originalUpperBound) {
997 @Nullable TypeMirror[] result = null;
998 if (originalUpperBound instanceof IntersectionType) {
999 IntersectionType originalIntersectionBound = (IntersectionType) originalUpperBound;
1000 if (originalIntersectionBound.isIntersectionType()) {
1001 List<? extends TypeMirror> originalBounds = originalIntersectionBound.getBounds();
1002 result = new TypeMirror[1 + originalBounds.size()];
1003 int i = 0;
1004 for (TypeMirror originalBound: originalBounds) {
1005 ++i;
1006 result[i] = originalBound;
1007 }
1008 }
1009 }
1010
1011 if (result == null) {
1012 result = new TypeMirror[2];
1013 result[1] = originalUpperBound;
1014 }
1015
1016 result[0] = wildcardExtendsBound;
1017 return result;
1018 }
1019
1020
1021
1022
1023
1024
1025 private TypeVariable captureWildcardArgument(WildcardType wildcardArgument, TypeParameterElement typeParameter) {
1026 TypeVariable originalTypeVariable = (TypeVariable) typeParameter.asType();
1027
1028
1029 TypeMirror originalUpperBound = originalTypeVariable.getUpperBound();
1030
1031
1032 @Nullable TypeMirror wildcardExtendsBound = wildcardArgument.getExtendsBound();
1033 @Nullable TypeMirror wildcardSuperBound = wildcardArgument.getSuperBound();
1034
1035 TypeMirror newUpperBound;
1036 TypeMirror newLowerBound;
1037
1038
1039
1040 if (wildcardExtendsBound == null && wildcardSuperBound == null) {
1041
1042
1043 newUpperBound = originalUpperBound;
1044 newLowerBound = getNullType();
1045 } else if (wildcardSuperBound == null) {
1046
1047
1048
1049
1050
1051
1052 newUpperBound = getIntersectionType(greatestLowerBound(wildcardExtendsBound, originalUpperBound));
1053 newLowerBound = getNullType();
1054 } else {
1055
1056
1057 assert wildcardExtendsBound == null;
1058
1059 newUpperBound = originalUpperBound;
1060 newLowerBound = wildcardSuperBound;
1061 }
1062
1063 return getTypeVariable(typeParameter, newUpperBound, newLowerBound, wildcardArgument);
1064 }
1065
1066
1067
1068
1069
1070
1071
1072
1073 @Override
1074 public final TypeMirror capture(TypeMirror type) {
1075 Objects.requireNonNull(type);
1076 requireValidType(type);
1077
1078
1079
1080 if (type.getKind() != TypeKind.DECLARED) {
1081 return type;
1082 }
1083
1084 DeclaredType declaredType = (DeclaredType) type;
1085 List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
1086 if (typeArguments.isEmpty()) {
1087 return declaredType;
1088 }
1089
1090 TypeElement typeDeclaration = (TypeElement) declaredType.asElement();
1091 Iterator<? extends TypeMirror> typeArgumentIterator = typeArguments.iterator();
1092 Iterator<? extends TypeParameterElement> typeParameterIterator = typeDeclaration.getTypeParameters().iterator();
1093 TypeMirror[] newArguments = new TypeMirror[typeArguments.size()];
1094 Map<TypeParameterElement, TypeMirror> substitutions = new LinkedHashMap<>();
1095 for (int index = 0; index < newArguments.length; ++index) {
1096 TypeMirror typeArgument = typeArgumentIterator.next();
1097 TypeParameterElement typeParameter = typeParameterIterator.next();
1098 TypeMirror substitution;
1099
1100 if (typeArgument.getKind() != TypeKind.WILDCARD) {
1101 newArguments[index] = typeArgument;
1102 substitution = typeArgument;
1103 } else {
1104
1105
1106 newArguments[index] = typeParameter.asType();
1107 substitution = captureWildcardArgument((WildcardType) typeArgument, typeParameter);
1108 }
1109 substitutions.put(typeParameter, substitution);
1110 }
1111
1112 TypeMirror enclosingType = declaredType.getEnclosingType();
1113
1114
1115
1116 DeclaredType intermediateDeclaredType;
1117 if (enclosingType.getKind() == TypeKind.DECLARED) {
1118 intermediateDeclaredType = getDeclaredType((DeclaredType) enclosingType, typeDeclaration, newArguments);
1119 } else {
1120 intermediateDeclaredType = getDeclaredType(typeDeclaration, newArguments);
1121 }
1122
1123 return substitute(intermediateDeclaredType, substitutions);
1124 }
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153 protected TypeVariable getTypeVariable(TypeParameterElement typeParameter, TypeMirror upperBound,
1154 TypeMirror lowerBound, @Nullable WildcardType capturedTypeArgument) {
1155 Objects.requireNonNull(typeParameter);
1156 Objects.requireNonNull(upperBound);
1157 Objects.requireNonNull(lowerBound);
1158 requireValidType(upperBound);
1159 requireValidType(lowerBound);
1160 requireValidType(capturedTypeArgument);
1161
1162 TypeVariable typeVariable = createTypeVariable(typeParameter, capturedTypeArgument);
1163 setTypeVariableBounds(typeVariable, upperBound, lowerBound);
1164 return typeVariable;
1165 }
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198 protected abstract TypeVariable createTypeVariable(TypeParameterElement typeParameter,
1199 @Nullable WildcardType capturedTypeArgument);
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220 protected abstract void setTypeVariableBounds(TypeVariable typeVariable, TypeMirror upperBound,
1221 TypeMirror lowerBound);
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233 @Nullable
1234 protected abstract WildcardType capturedTypeArgument(TypeVariable typeVariable);
1235
1236
1237
1238
1239
1240
1241
1242
1243 public abstract IntersectionType getIntersectionType(TypeMirror... bounds);
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254 private final class ToStringVisitor extends ExtendedTypeKindVisitor7<Void, StringBuilder> {
1255 @Override
1256 public Void visitPrimitive(PrimitiveType primitiveType, @Nullable StringBuilder stringBuilder) {
1257 assert stringBuilder != null;
1258 stringBuilder.append(primitiveType.getKind().toString().toLowerCase());
1259 return null;
1260 }
1261
1262 @Override
1263 public Void visitNull(NullType nullType, @Nullable StringBuilder stringBuilder) {
1264 assert stringBuilder != null;
1265 stringBuilder.append("null");
1266 return null;
1267 }
1268
1269 @Override
1270 public Void visitNoType(NoType noType, @Nullable StringBuilder stringBuilder) {
1271 assert stringBuilder != null;
1272 stringBuilder.append(noType.getKind().toString().toLowerCase());
1273 return null;
1274 }
1275
1276 @Override
1277 public Void visitDeclared(DeclaredType declaredType, @Nullable StringBuilder stringBuilder) {
1278 assert stringBuilder != null;
1279 TypeMirror enclosingType = declaredType.getEnclosingType();
1280 TypeElement typeElement = (TypeElement) declaredType.asElement();
1281 if (enclosingType.getKind() == TypeKind.DECLARED) {
1282 visitDeclared((DeclaredType) enclosingType, stringBuilder);
1283 stringBuilder.append('.').append(typeElement.getSimpleName());
1284 } else {
1285 stringBuilder.append(typeElement.getQualifiedName());
1286 }
1287
1288 List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
1289 if (!typeArguments.isEmpty()) {
1290 stringBuilder.append('<');
1291 appendList(stringBuilder, typeArguments, ", ");
1292 stringBuilder.append('>');
1293 }
1294 return null;
1295 }
1296
1297 @Override
1298 public Void visitArray(ArrayType arrayType, @Nullable StringBuilder stringBuilder) {
1299 assert stringBuilder != null;
1300 arrayType.getComponentType().accept(this, stringBuilder);
1301 stringBuilder.append("[]");
1302 return null;
1303 }
1304
1305 @Override
1306 public Void visitTypeVariable(TypeVariable typeVariable, @Nullable StringBuilder stringBuilder) {
1307 assert stringBuilder != null;
1308 @Nullable WildcardType capturedTypeArgument = capturedTypeArgument(typeVariable);
1309 if (capturedTypeArgument != null) {
1310 stringBuilder.append("capture<");
1311 capturedTypeArgument.accept(this, stringBuilder);
1312 stringBuilder.append('>');
1313 } else {
1314 stringBuilder.append(typeVariable.asElement().getSimpleName());
1315 }
1316 return null;
1317 }
1318
1319 @Override
1320 public Void visitWildcard(WildcardType wildcardTypeArgument, @Nullable StringBuilder stringBuilder) {
1321 assert stringBuilder != null;
1322 stringBuilder.append('?');
1323 @Nullable TypeMirror extendsBound = wildcardTypeArgument.getExtendsBound();
1324 if (extendsBound != null) {
1325 stringBuilder.append(" extends ");
1326 extendsBound.accept(this, stringBuilder);
1327 }
1328 @Nullable TypeMirror superBound = wildcardTypeArgument.getSuperBound();
1329 if (superBound != null) {
1330 stringBuilder.append(" super ");
1331 superBound.accept(this, stringBuilder);
1332 }
1333 return null;
1334 }
1335
1336 @Override
1337 public Void visitIntersection(IntersectionType intersectionType, @Nullable StringBuilder stringBuilder) {
1338 assert stringBuilder != null;
1339 appendList(stringBuilder, intersectionType.getBounds(), " & ");
1340 return null;
1341 }
1342
1343 private void appendList(StringBuilder stringBuilder, List<? extends TypeMirror> types, String glue) {
1344 assert !types.isEmpty();
1345
1346 boolean first = true;
1347 for (TypeMirror type: types) {
1348 if (first) {
1349 first = false;
1350 } else {
1351 stringBuilder.append(glue);
1352 }
1353 type.accept(this, stringBuilder);
1354 }
1355 }
1356 }
1357
1358
1359
1360
1361
1362
1363
1364 public final String toString(TypeMirror type) {
1365 requireValidType(Objects.requireNonNull(type));
1366
1367 StringBuilder stringBuilder = new StringBuilder(DEFAULT_STRING_BUILDER_SIZE);
1368 type.accept(toStringVisitor, stringBuilder);
1369 return stringBuilder.toString();
1370 }
1371 }