View Javadoc
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   * Abstract skeletal implementation of {@link Types}.
34   *
35   * <p>This class provides a skeletal implementation of the {@link Types} interface. Specifically, it implements all
36   * methods pertaining to §4.10 (subtyping) in the Java Language Specification (JLS). Concrete subclasses are expected to
37   * implement the abstract methods in this class, which are responsible for creating appropriate type-mirror instances.
38   * This class does not place any additional constraints on the concrete {@link TypeMirror} and {@link Element}
39   * implementations, so mutability and thread-safety are implementation-defined. However, this class crucially relies on
40   * the {@code equals} method being well-defined. That is, {@link Element} objects that have equal names and equal
41   * enclosing elements must compare equal. Likewise, {@link TypeMirror} objects that contain equal values must compare
42   * equal. In particular, multiple instances created by one of the {@code get}-methods must compare equal when the given
43   * arguments compare equal.
44   *
45   * <p>Besides subtype-related methods, this class also provides method
46   * {@link #resolveActualTypeArguments(TypeElement, TypeMirror)} for resolving formal type parameters to actual type
47   * arguments. For instance, given type {@code List<String>}, this method determines the actual type argument for the
48   * formal type parameter of {@code Collection<E>} (that is, {@code String} in this simple example).
49   *
50   * <p>Unless explicitly stated otherwise, all methods in this class expect non-null arguments. Passing null where not
51   * expected will cause a {@link NullPointerException} to be thrown. Implementations typically place additional
52   * restrictions on method arguments not captured by the types of the formal parameters (which stem from
53   * {@link javax.lang.model} and its subpackages). While the details are implementation-defined, typically this means
54   * that arguments must have been crated by the same implementation, or otherwise an {@link IllegalArgumentException}
55   * will be thrown. Implementations must override {@link #requireValidType(TypeMirror)} and
56   * {@link #requireValidElement(Element)}, as these methods are expected to perform any necessary validation.
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       * Verifies that the given {@link Element} is valid for use with this class.
72       *
73       * <p>The meaning of valid is implementation-defined, but typically a valid {@link Element} must have been created
74       * by the implementation that belongs to the current {@code AbstractTypes} instance.
75       *
76       * @param element element
77       * @throws NullPointerException if the argument is null
78       * @throws IllegalArgumentException if the given {@link Element} cannot be used with this class
79       */
80      protected abstract void requireValidElement(Element element);
81  
82      /**
83       * Verifies that the given {@link TypeMirror} is valid for use with this class, or that it is {@code null}.
84       *
85       * <p>The meaning of valid is implementation-defined, but typically a valid {@link TypeMirror} must have been
86       * created by the implementation that belongs to the current {@code AbstractTypes} instance. A {@code null} argument
87       * is always valid. The rationale is that {@code null} {@link TypeMirror} arguments have a special meaning for some
88       * methods such as {@link #getWildcardType(TypeMirror, TypeMirror)} or
89       * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
90       *
91       * @param type type mirror, may be {@code null}
92       * @throws IllegalArgumentException if the given {@link TypeMirror} instance is non-null and it cannot be used with
93       *     this class
94       */
95      protected abstract void requireValidType(@Nullable TypeMirror type);
96  
97      /**
98       * Verifies that the given array is non-null and contains valid types that are not null.
99       *
100      * @param types array of types
101      * @throws NullPointerException if the given array or any of its elements are null
102      * @throws IllegalArgumentException if {@link #requireValidType(TypeMirror)} throws an exception for one of the
103      *     array elements
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      * Returns a type mirror corresponding to the given Java reflection type.
114      *
115      * <p>Subclasses are required to return the appropriate {@link DeclaredType} instances for the following
116      * {@link Class} instances:
117      * <ul><li>
118      *     {@link Object}
119      * </li><li>
120      *     {@link Serializable}
121      * </li><li>
122      *     {@link Cloneable}
123      * </li></ul>
124      *
125      * <p>Support for other types is not required and implementation-defined.
126      *
127      * @param type type as represented by Java Reflection API
128      * @throws UnsupportedOperationException If the given type is not one of the above {@link Class} objects and
129      *     this type-utilities implementation does not support mirroring arbitrary Java reflection types.
130      * @return the type mirror corresponding to the given reflection type
131      */
132     protected abstract TypeMirror typeMirror(Type type);
133 
134     /**
135      * Internal class that contains both the substitution map passed to {@link #substitute(TypeMirror, Map)} and the
136      * set of fresh type variables created at the beginning of that method.
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      * Visitor of a type mirror. Returns a new type mirror after performing the substitutions passed as visitor
151      * argument.
152      *
153      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
154      * can be asserted that the visitor parameter is always non-null.
155      *
156      * @see #substitutionVisitor
157      * @see #requireValidType(TypeMirror)
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      * Replaces formal type parameters in the given type.
241      *
242      * <p>This method requires that {@code type} does not contain transitive references to itself, unless through
243      * {@link DeclaredType#asElement()} → {@link TypeElement#asType()} or {@link TypeVariable#asElement()} →
244      * {@link TypeParameterElement#asType()}. Otherwise, this method might run into an infinite recursion, resulting in
245      * a {@link StackOverflowError}.
246      *
247      * <p>Moreover, this method requires that any type variable transitively referenced by {@code substitutionMap} must
248      * not contain a transitive reference (through {@link TypeVariable#getUpperBound()} or
249      * {@link TypeVariable#getLowerBound()}) to itself. Instead, any instance of {@link TypeVariable} (transitively)
250      * referenced by a value in {@code substitutionMap} must be the result of {@link TypeParameterElement#asType()}.
251      *
252      * <p>This method creates a fresh type variable for each formal type parameter that is to be substituted by a type
253      * variable for the same formal type parameter. For instance, suppose {@code T extends Object} is a formal type
254      * parameter, and {@code substitutionMap} specifies to replace it with the type variable {@code T extends U<T>}. In
255      * this case, {@link #createTypeVariable(TypeParameterElement, WildcardType)} will be called with the formal type
256      * parameter {@code T extends Object} as (first) argument. Once all fresh types have been created,
257      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} will then be called with {@code U<T>} as
258      * upper bound, where {@code T} is the fresh type variable {@code T extends U<T>}.
259      *
260      * @param type type in which the type parameters will be replaced recursively, guaranteed non-null
261      * @param substitutionMap mapping from formal type parameters to substituted type, guaranteed non-null
262      * @return new port type, guaranteed non-null
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      * Returns the actual type arguments of a type declaration given a subtype (typically with its own actual type
305      * arguments).
306      *
307      * <p>This method "projects" the actual type arguments of {@code subtype}, as well as all actual type arguments of
308      * super types in the type hierarchy between {@code typeElement} and {@code subType}, onto the type declaration
309      * represented by {@code typeElement}.
310      *
311      * <p>For example, {@code typeElement} may be the (generic) type declaration {@code Comparable<T>}, and
312      * {@code subType} may be the (non-generic) type {@link Integer}. The result in this case would be a singleton list
313      * containing the type {@link Integer}.
314      *
315      * <p>More generally, resolution works as follows: First, the shortest inheritance path from {@code subType} to
316      * {@code typeElement} is found. Note that while Java allows multiple inheritance for interfaces, JLS §8.1.5
317      * disallows inheriting from the same interface with different type parameters (both directly and transitively).
318      * Hence, the shortest path contains all information that is necessary to resolve formal type parameters to actual
319      * parameters. This method then propagates the actual type arguments bottom-up along the inheritance path.
320      * Note that the inheritance path consists of {@link DeclaredType} instances, and it may consist of generic types,
321      * non-generic types, and raw types.
322      *
323      * <p>If the inheritance path contains a raw type <em>before</em> the last path element, this method proceeds
324      * by using the "prototypical" type returned by {@link Element#asType()} instead. Correspondingly, it is possible
325      * that the returned list may contain type variables from a type declaration along the inheritance path. However, if
326      * the <em>last</em> inheritance path element is a raw type, the returned list will be empty. Otherwise, if a
327      * non-null non-empty {@link List} is returned, it is guaranteed to have the same number of elements as
328      * {@code typeElement.getTypeParameters()}.
329      *
330      * @param typeElement type declaration
331      * @param subType potential subtype of {@code typeElement}, must be a non-generic type declaration, raw type,
332      *     generic type declaration, or parameterized type
333      * @return actual type arguments for the formal parameters of {@code typeElement} (empty list if the <em>last</em>
334      *     path element in the inheritance path from {@code subType} to {@code typeElement} is a raw type), or
335      *     {@code null} if {@code subType} is not a subtype of {@code typeElement}
336      * @throws IllegalArgumentException if the arguments do not satisfy the constraints mentioned above
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         // getShortestPathToSuperType() will throw an exception if subType does not satisfy the constraints mentioned
350         // above.
351         @Nullable List<DeclaredType> path = getShortestPathToSuperType(typeElement, declaredSubType);
352         if (path == null) {
353             return null;
354         }
355 
356         // Early exit if there is nothing to resolve. However, we must not move this early exit any earlier, because
357         // we do want to return null if subType is not a subtype of typeElement.
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             // Check whether "current" is a raw type. This may happen in the first loop iteration if subType is a raw
368             // type, or in subsequent iterations if the type that was previously "current" (during the last iteration
369             // of the for-loop) derived from a raw type. If yes, use instead the "prototypical" type returned by
370             // Element#asType().
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      * Visitor of a type mirror. Returns whether the visited type mirror is a subtype of the visitor argument (of type
390      * {@link DeclaredType}).
391      *
392      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
393      * can be asserted that the visitor parameter is always non-null.
394      *
395      * @see #declaredTypeSubtypeVisitor
396      * @see #requireValidType(TypeMirror)
397      */
398     private final class DeclaredTypeSubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, DeclaredType> {
399         private DeclaredTypeSubtypeVisitor() {
400             super(false);
401         }
402 
403         /**
404          * Returns whether the first declared type is a subtype of the second declared type.
405          *
406          * <p>This method proceeds by computing the actual type arguments when {@code subType} is projected onto the
407          * type declaration corresponding to {@code superType}. It then tests if all actual type arguments of
408          * {@code subType} are <em>contained</em> in those of {@code superType}.
409          */
410         @Override
411         public Boolean visitDeclared(DeclaredType subType, @Nullable DeclaredType superType) {
412             assert superType != null;
413             DeclaredType actualSubType = subType;
414 
415             // First test if there subType has at least one wildcard type argument. In that case, we need to perform a
416             // capture conversion first.
417             // Note that this is the right place to do capture conversion: JLS §8.1.4 and §9.1.3 state about class types
418             // and interfaces type listed in the extends or implements clause of a class/interface declaration:
419             // - "If the ClassType has type arguments, it must denote a well-formed parameterized type (§4.5), and none
420             // of the type arguments may be wildcard type arguments, or a compile-time error occurs."
421             // - "If an InterfaceType has type arguments, it must denote a well-formed parameterized type (§4.5), and
422             // none of the type arguments may be wildcard type arguments, or a compile-time error occurs."
423             // Hence, wildcards do not appear on the "inheritance path" between subType and superType.
424             for (TypeMirror subTypeArgument: subType.getTypeArguments()) {
425                 if (subTypeArgument.getKind() == TypeKind.WILDCARD) {
426                     actualSubType = (DeclaredType) capture(subType);
427                     break;
428                 }
429             }
430 
431             // Resolve the actual type parameters of subType when projected onto the superType
432             TypeElement superTypeDeclaration = (TypeElement) superType.asElement();
433             @Nullable List<? extends TypeMirror> projectedTypeArguments
434                 = resolveActualTypeArguments(superTypeDeclaration, actualSubType);
435 
436             if (projectedTypeArguments == null) {
437                 // subType is not a subtype of the type declaration
438                 return false;
439             }
440 
441             List<? extends TypeMirror> superTypeArguments = superType.getTypeArguments();
442             if (projectedTypeArguments.isEmpty() && !superTypeArguments.isEmpty()) {
443                 // the projection of subType onto superType resulted in a raw type, which is neither a subtype of any
444                 // parametrized type of the generic type declaration of superType, nor the generic type declaration
445                 // itself
446                 return false;
447             }
448 
449             // Note that superType could be a raw type, in which case superTypeArguments is empty. In that case, the
450             // loop would not be executed at all.
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          * Returns whether the array type is a subtype of the declared type.
463          *
464          * <p>According to JLS §4.10.3, an array type can only be a subtype of a declared type if the latter represents
465          * one of {@link Object}, {@link Cloneable}, or {@link Serializable}.
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          * Returns whether the type variable is a subtype of the declared type.
477          *
478          * <p>According to JLS §4.10.2, the direct supertypes of a type variable are the types listed in its bound.
479          * Hence, this method returns true if {@link TypeVariable#getUpperBound()} is a subtype of {@code superType}.
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          * Returns whether the intersection type is a subtype of the declared type.
489          *
490          * <p>According to JLS §4.10.2, the direct supertypes of an intersection type {@code T_1 & ... T_n} are
491          * {@code T_1}, ..., {@code T_n}. Hence, this method returns true if at least one of
492          * {@link IntersectionType#getBounds()} is a subtype of {@code superType}.
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      * Visitor of a type mirror. Returns whether the visited type mirror is a supertype of the visitor argument.
508      *
509      * <p>This visitor does not have to deal with the null-type, which has been dealt with before. It has to make a
510      * decision for {@link ArrayType}, {@link DeclaredType}, {@link PrimitiveType}, and {@link TypeVariable}.
511      *
512      * <p>Java 8 introduces {@code IntersectionType}, but this code currently uses Java 7. Moreover, there are other
513      * types that are currently not supported, such as {@link javax.lang.model.type.UnionType}. Finally,
514      * {@link WildcardType} is not a type, but only a type argument, so it is not necessary to be dealt with here.
515      * Likewise, {@link NoType} is not used to model proper types, but only empty bounds, non-existence of interface
516      * super classes, etc.
517      *
518      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
519      * can be asserted that the visitor parameter is always non-null.
520      *
521      * @see #subtypeVisitor
522      * @see #requireValidType(TypeMirror)
523      */
524     private final class SubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, TypeMirror> {
525         private SubtypeVisitor() {
526             super(false);
527         }
528 
529         /**
530          * Returns whether the array type is a super type of the type given as second argument.
531          *
532          * <p>According to JLS §4.10.3, array component types are covariant; for instance, {@code Integer[]} is a proper
533          * subtype of {@code Number[]}. Moreover, all subtypes of an array type are again array types. Hence, this
534          * method simply reduces the problem to testing if {@code subType} is also an array type and then applying
535          * {@link AbstractTypes#isSubtype(TypeMirror, TypeMirror)} to the component types.
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          * Returns whether the declared type is a super type of the type given as second argument.
546          *
547          * <p>This method has {@link DeclaredTypeSubtypeVisitor} visit {@code subType}.
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          * Returns whether the primitive type is a supertype of the given type.
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          * Returns whether the type variable is a super type of the given type.
578          *
579          * <p>A type variable is only a supertype of its lower bound.
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          * Returns whether the given intersection type is a super type of the given type.
589          *
590          * <p>While one might expect that the set of supertypes of an intersection type {@code T_1 & ... & T_n} includes
591          * the intersection of any (non-empty) subset of {@code T_1}, ..., {@code T_n}, this seems is not specified by
592          * JLS §4.10 (which only says that "the direct supertypes of an intersection type {@code T_1 & ... & T_n} are
593          * {@code T_i} (1 ≤ i ≤ n)"). See also issue
594          * <a href="https://bugs.openjdk.java.net/browse/JDK-6718388">JDK-6718388</a>.
595          *
596          * <p>Therefore, an intersection type is only a supertype of itself.
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      * Returns whether the first type is a subtype of the second type, as specified by JLS §4.10.
607      *
608      * <p>The subtype relationship is transitive and reflexive.
609      *
610      * @param t1 the first type
611      * @param t2 the second type
612      * @return {@code true} if and only if the first type is a subtype of the second
613      * @throws NullPointerException if an argument is null
614      * @throws IllegalArgumentException if given an executable or package type
615      */
616     @Override
617     public final boolean isSubtype(TypeMirror t1, TypeMirror t2) {
618         requireValidType(Objects.requireNonNull(t1));
619         requireValidType(Objects.requireNonNull(t2));
620 
621         // §4.10.2: The direct supertypes of the null type are all reference types other than the null type itself.
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      * Returns whether the first type argument <em>contains</em> the second type argument, as specified by JLS §4.5.1.
631      *
632      * <p>Using the JLS notation, this method returns true if {@code t2 <= t1}. As JLS §4.10 states, "subtyping does not
633      * extend through parameterized types." Hence, this method is necessarily different from
634      * {@link #isSubtype(TypeMirror, TypeMirror)}. In particular, the super-type relationship does not include types
635      * with covariant type arguments.
636      *
637      * @param t1 the first type
638      * @param t2 the second type
639      * @return {@code true} if and only if the first type contains the second
640      * @throws IllegalArgumentException if given an executable or package type
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         // We need to cover these cases (JLS §4.5.1):
650         //
651         // (a) wildcard t2 <= wildcard t1
652         // 1. ? extends T <= ? extends S if T <: S
653         // 2. ? extends T <= ?
654         // 3. ? super T <= ? super S if S <: T
655         // 4. ? super T <= ?
656         // 5. ? super T <= ? extends Object
657         //
658         // (b) other type t2 <= other type t1
659         // 1. T <= T
660         //
661         // (c) other type t2 <= wildcard t1
662         // 1. T <= ? extends T
663         // 2. T <= ? super T
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                 // Handle (a).
673                 @Nullable TypeMirror t2ExtendsBound = ((WildcardType) t2).getExtendsBound();
674                 @Nullable TypeMirror t2SuperBound = ((WildcardType) t2).getSuperBound();
675 
676                 if (t2ExtendsBound != null) {
677                     if (t1ExtendsBound != null) {
678                         // (a) 1.
679                         return isSubtype(t2ExtendsBound, t1ExtendsBound);
680                     } else if (t1SuperBound == null) {
681                         // (a) 2.
682                         return true;
683                     }
684                     // Note that "? super S" never contains a type argument of form "? extends T"
685                     return false;
686                 } else if (t2SuperBound != null) {
687                     if (t1SuperBound != null) {
688                         // (a) 3.
689                         return isSubtype(t1SuperBound, t2SuperBound);
690                     } else {
691                         // (a) 4. and 5.: Handle case "? super T <= ?" (always true) or "? super S <= ? extends T" (only
692                         // if T is Object)
693                         return t1ExtendsBound == null
694                             || isSameType(t1ExtendsBound, typeMirror(Object.class));
695                     }
696                 } else {
697                     // Handle special case of (a), namely "? <= ? extends T" (only if T is Object), "? <= ? super T"
698                     // (always false), or "? <= ?" (which is equivalent to "? extends Object <= ? extends Object" and
699                     // therefore true).
700                     return t1SuperBound == null && (
701                         t1ExtendsBound == null || isSameType(t1ExtendsBound, typeMirror(Object.class))
702                     );
703                 }
704             } else {
705                 // Handle (c). Reduce to case (a).
706                 if (t1HasExtendsBound) {
707                     // (c) 1.
708                     return contains(t1, getWildcardType(t2, null));
709                 } else if (t1HasSuperBound) {
710                     // (c) 2.
711                     return contains(t1, getWildcardType(null, t2));
712                 }
713                 // Combining (c) 1. with (a) 2. or (c) 2. with (a) 4., we immediately have "T <= ?"
714                 return true;
715             }
716         } else {
717             // Handle (b).
718             return isSameType(t1, t2);
719         }
720     }
721 
722     /**
723      * Returns the direct super types of the given type declaration, as defined by JLS §4.10.2.
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      * Internal class to keep state for the Dijkstra shortest-path algorithm in
743      * {@link #getShortestPathToSuperType(TypeElement, DeclaredType)}.
744      */
745     private static final class TypeDeclarationVertexState {
746         private int distance;
747         private boolean visited;
748         private final TypeElement typeElement;
749 
750         /**
751          * The type as contained in {@code previous.typeDeclaration.getSuperTypes()}.
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          * Returns the path induced by this node, starting with {@code derived} and ending with {@link #declaredType}.
767          *
768          * <p>The path is obtained by following {@link #previous} until {@code null}. Each element in the path (except
769          * for the first) is the {@link #declaredType} of the current instance.
770          *
771          * @param derived the first element in the path
772          * @return the path induced by this node
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      * Returns the shortest inheritance path between a type declaration and a subtype (starting with
790      * {@code derived} and ending with {@code base}).
791      *
792      * <p>Each element in the returned path is a non-generic type, a raw type, or a parameterized type. The
793      * {@link DeclaredType} at position {@code i} is always contained in the result of
794      * {@link #directSupertypesOfTypeDeclaration(TypeElement)} applied to the type declaration of the type at position
795      * {@code (i - 1)}.
796      *
797      * <p>This methods runs a Dijkstra shortest-path algorithm. It relies on {@link TypeElement#equals(Object)}
798      * being well-defined (two object representing the same type declaration must compare equal). Consequently, if
799      * {@link DeclaredType} instances have an identity, it must be guaranteed that there are no two instances
800      * representing the same type declaration.
801      *
802      * @param base base type declaration
803      * @param derived derived type
804      * @return If there is an inheritance path from {@code derived} to {@code base}, then a {@code List<DeclaredType>}
805      *     {@code p} such that {@code p.get(0).equals(toGenericType(derived))} and
806      *     {@code toRawTypeDeclaration(p.get(p.size() - 1)).equals(base)} are {@code true}. Otherwise, {@code null} to
807      *     indicate that there is no such path.
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         // Distance from derived to itself is 0
817         dijkstraState.put(typeElement, new TypeDeclarationVertexState(0, false, typeElement, derived));
818         // Start off with derived
819         boundary.add(typeElement);
820 
821         // Invariants:
822         // - boundary only contains nodes that have *not* been visited
823         // - For all visited nodes, the shortest path is known
824         while (!boundary.isEmpty()) {
825             // shortest := vertex in boundary with smallest distance from typeElement
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             // Since boundary is non-empty, shortest was assigned in the previous loop. Also note that due to the above
834             // invariant, shortest has not been visited.
835             assert shortest != null && !shortest.visited;
836 
837             // Terminate if we found base. Since shortest.distance is non-decreasing over the loop iterations, it is
838             // impossible to find a shorter path in future iterations.
839             if (shortest.typeElement.equals(base)) {
840                 return shortest.toPath(derived);
841             }
842 
843             // Remove shortest from boundary.
844             boundary.remove(shortest.typeElement);
845             shortest.visited = true;
846 
847             for (DeclaredType superType: directSupertypesOfTypeDeclaration(shortest.typeElement)) {
848                 // A direct super type of a type declaration is either a non-generic type declaration or a raw type (in
849                 // both cases represented as DeclaredType with no actual type parameters) or a parameterized type
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      * Visitor of a type mirror. Returns the erasure of the visited type mirror.
871      *
872      * @see #erasureVisitor
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          * Returns the array type corresponding to the erasure of the component type.
886          */
887         @Override
888         public TypeMirror visitArray(ArrayType arrayType, @Nullable Void ignored) {
889             return getArrayType(erasure(arrayType.getComponentType()));
890         }
891 
892         /**
893          * Returns the erasure of the leftmost bound of the given type variable.
894          *
895          * <p>The erasure of a type variable is the erasure of its leftmost bound (JLS §4.6). If multiple bounds are
896          * present, the upper bound is modelled as an intersection type. The erasure of an intersection type is
897          * guaranteed to have see right form (see {@link #visitIntersection(IntersectionType, Void)}).
898          */
899         @Override
900         public TypeMirror visitTypeVariable(TypeVariable typeVariable, @Nullable Void ignored) {
901             return erasure(typeVariable.getUpperBound());
902         }
903 
904         /**
905          * Returns the erasure of the leftmost member of the given intersection type.
906          *
907          * <p>While JLS §4.6 does not mention intersection types (and thus, strictly speaking, the erasure of an
908          * intersection type should be the unmodified intersection type itself), this implementation computes the
909          * erasure of an intersection type as the erasure of its left-most type.
910          */
911         @Override
912         public TypeMirror visitIntersection(IntersectionType intersectionType, @Nullable Void ignored) {
913             return erasure(intersectionType.getBounds().get(0));
914         }
915 
916         /**
917          * Returns the given type itself.
918          *
919          * <p>JLS §4.6 specifies: "The erasure of every other type is the type itself."
920          */
921         @Override
922         protected TypeMirror defaultAction(TypeMirror type, Void ignored) {
923             return type;
924         }
925     }
926 
927     /**
928      * Returns the erasure of a type, as specified by JLS §4.6.
929      *
930      * @param type the type to be erased
931      * @return the erasure of the given type
932      * @throws IllegalArgumentException if given a package type
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      * Returns the element corresponding to a type.
944      *
945      * <p>The type may be a {@code DeclaredType} or {@code TypeVariable}. Returns {@code null} if the type is not one
946      * with a corresponding element.
947      *
948      * @param type the type
949      * @return the element corresponding to the given type
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      * Returns whether the two given type arguments represent the same type.
967      *
968      * <p>If either of the arguments to this method represents a wildcard, this method will return false. As a
969      * consequence, a wildcard is not the same type as itself.
970      *
971      * @param t1 the first type
972      * @param t2 the second type
973      * @return {@code true} if and only if the two types are the same
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      * Returns the greatest lower bound (glb) of a wildcard extends bound and an upper bound of a type parameter.
985      *
986      * <p>This method is only called from {@link #capture(TypeMirror)}. JLS §5.1.10 defines the greatest lower bound
987      * {@code glb(V_1, ..., V_m)} as {@code V_1 & ... & V_m}. Unfortunately, the specification provides no clarity
988      * whether intersection types are allowed to be nested. This implementation takes the interpretation that
989      * intersection types should not be nested. Therefore, the bounds contained in {@code originalUpperBound} are
990      * unwrapped.
991      *
992      * @param wildcardExtendsBound extends bound of the wildcard type argument
993      * @param originalUpperBound original upper bound of the type parameter
994      * @return the greatest lower bound
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      * Returns the caputure conversion of (just) the given wildcard argument.
1022      *
1023      * <p>This method is only called by {@link #capture(TypeMirror)}.
1024      */
1025     private TypeVariable captureWildcardArgument(WildcardType wildcardArgument, TypeParameterElement typeParameter) {
1026         TypeVariable originalTypeVariable = (TypeVariable) typeParameter.asType();
1027 
1028         // Denoted U_i in JLS 5.1.10
1029         TypeMirror originalUpperBound = originalTypeVariable.getUpperBound();
1030 
1031         // Both of the following are denoted B_i in JLS 5.1.10 (in "? extends B_i" and "? super B_i", respectively)
1032         @Nullable TypeMirror wildcardExtendsBound = wildcardArgument.getExtendsBound();
1033         @Nullable TypeMirror wildcardSuperBound = wildcardArgument.getSuperBound();
1034 
1035         TypeMirror newUpperBound;
1036         TypeMirror newLowerBound;
1037 
1038         // There exists a capture conversion from a parameterized type G<T_1,...,T_n> (§4.5) to a parameterized type
1039         // G<S_1, ..., S_n>, where, for 1 <= i <= n:
1040         if (wildcardExtendsBound == null && wildcardSuperBound == null) {
1041             // If T_i is a wildcard type argument (§4.5.1) of the form ?, then S_i is a fresh type variable whose
1042             // upper bound is U_i[A_1 := S_1, ..., A_n := S_n] and whose lower bound is the null type (§4.1).
1043             newUpperBound = originalUpperBound;
1044             newLowerBound = getNullType();
1045         } else if (wildcardSuperBound == null) {
1046             // If T_i is a wildcard type argument of the form ? extends B_i, then S_i is a fresh type variable whose
1047             // upper bound is glb(B_i, U_i[A_1 := S_1, ..., A_n := S_n]) and whose lower bound is the null type.
1048             //
1049             // glb(V_1, ..., V_m) is defined as V_1 & ... & V_m.
1050             // It is a compile-time error if, for any two classes (not interfaces) V_i and V_j, V_i is not a
1051             // subclass of V_j or vice versa.
1052             newUpperBound = getIntersectionType(greatestLowerBound(wildcardExtendsBound, originalUpperBound));
1053             newLowerBound = getNullType();
1054         } else {
1055             // If T_i is a wildcard type argument of the form ? super B_i, then S_i is a fresh type variable whose
1056             // upper bound is U_i[A_1 := S1, ..., A_n := S_n] and whose lower bound is B_i.
1057             assert wildcardExtendsBound == null;
1058 
1059             newUpperBound = originalUpperBound;
1060             newLowerBound = wildcardSuperBound;
1061         }
1062 
1063         return getTypeVariable(typeParameter, newUpperBound, newLowerBound, wildcardArgument);
1064     }
1065 
1066     /**
1067      * Returns the capture conversion of the given type, as specified by JLS §5.1.10.
1068      *
1069      * @param type the type to be converted
1070      * @return the result of applying capture conversion
1071      * @throws IllegalArgumentException if given an executable or package type
1072      */
1073     @Override
1074     public final TypeMirror capture(TypeMirror type) {
1075         Objects.requireNonNull(type);
1076         requireValidType(type);
1077 
1078         // JLS §5.1.10 states: "Capture conversion on any type other than a parameterized type (§4.5) acts as an
1079         // identity conversion (§5.1.1)."
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                 // For the intermediate declared type (see below), we need the original type variable corresponding to
1105                 // the formal type parameter. Only original type variables will be replaced by the substitutionVisitor.
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         // Construct intermediateDeclaredType that already has type variables in its argument list instead of wildcard
1115         // arguments.
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      * Returns a new type variable that corresponds to the given formal type parameter and that has the given actual
1128      * upper and lower bounds.
1129      *
1130      * <p>This method is primarily needed during capture conversion, in order to create a fresh type variable that
1131      * overrides the bounds of the formal type parameter it represents. This method is also called during substitution.
1132      * As an example, given a formal type parameter {@code T extends Object} and an upper bound {@code Number}, this
1133      * method returns the type variable {@code T} with upper bound {@code Number}.
1134      *
1135      * <p>This method is not suited for creating type variables with recursive type bounds if these bounds override the
1136      * bounds of the formal type parameter (as only happens during capture conversion). In order to create such a type
1137      * variable, this method may be used to create an interim type variable, where the (overridden) upper and lower
1138      * bounds should only reference the type variable returned by {@link TypeParameterElement#asType()}. As a second
1139      * step, {@link #substitute(TypeMirror, Map)} may then be used to substitute the original type variable with the
1140      * interim type variable. The result will be a fresh type variable with the overridden bounds, and these bounds
1141      * will reference the fresh type variable instead of the original type variable.
1142      *
1143      * @param typeParameter the formal type parameter
1144      * @param upperBound the upper bound for the new type variable, may contain recursive references to
1145      *     {@code typeParameter.asType()}
1146      * @param lowerBound the lower bound for the new type variable, may contain recursive references to
1147      *     {@code typeParameter.asType()}
1148      * @param capturedTypeArgument the wildcard type argument that new type variable captures as part of a capture
1149      *     conversion (§5.1.10 JLS), or {@code null} if the new type variable is not the result of a capture conversion
1150      * @return the new type variable
1151      * @throws NullPointerException if any of the first three arguments is null
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      * Creates a new <em>unfinished</em> type variable for the given formal parameter.
1169      *
1170      * <p>Whenever this method is called within this class, the returned type variable is guaranteed to be passed to
1171      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} before being used as a {@link TypeVariable}
1172      * instance. That is, the returned type variable is considered to be under construction until being passed to
1173      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)}, and only after that method call, the type
1174      * variable will have to satisfy the contract specified by interface {@link TypeVariable} and its super-interfaces.
1175      *
1176      * <p>Before {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} is called on the returned
1177      * {@link TypeVariable}, calling either {@link TypeVariable#getUpperBound()} or {@link TypeVariable#getLowerBound()}
1178      * must trigger an {@link IllegalStateException}.
1179      *
1180      * <p>Note that the previous paragraph does not guarantee that
1181      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} is always called on the newly returned
1182      * type-variable instance. If any exception occurs before the new type-variable could be used, then
1183      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} may not be called (even if the exception is
1184      * unrelated to the construction of the new type-variable instance).
1185      *
1186      * <p>The {@link TypeVariable} interface does not provide access to captured wildcard type arguments. It can be
1187      * retrieved by calling {@link #capturedTypeArgument(TypeVariable)} instead.
1188      *
1189      * @param typeParameter the formal type parameter
1190      * @param capturedTypeArgument the wildcard type argument that new type variable captures as part of a capture
1191      *     conversion (§5.1.10 JLS), or {@code null} if the new type variable is not the result of a capture conversion
1192      * @return new unfinished type variable for the given formal parameter, which may not yet satisfy the contracts
1193      *     of {@link TypeVariable}
1194      * @see #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)
1195      * @see #capturedTypeArgument(TypeVariable)
1196      * @throws NullPointerException if {@code typeParameter} is null
1197      */
1198     protected abstract TypeVariable createTypeVariable(TypeParameterElement typeParameter,
1199         @Nullable WildcardType capturedTypeArgument);
1200 
1201     /**
1202      * Sets the bounds of a type variable previously returned by
1203      * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
1204      *
1205      * <p>Before an (unfinished) type-variable instance returned by
1206      * {@link #createTypeVariable(TypeParameterElement, WildcardType)} is used by this class, this method is guaranteed
1207      * to be called exactly once.
1208      *
1209      * <p>Implementations that create effectively immutable {@link TypeMirror} instances may use this method to "freeze"
1210      * the given type-variable instance.
1211      *
1212      * @param typeVariable type variable previously returned by
1213      *     {@link #createTypeVariable(TypeParameterElement, WildcardType)}
1214      * @param upperBound Upper bound for the given type variable. If no explicit upper bound is used, a
1215      *     {@link DeclaredType} representing {@link Object} will be passed.
1216      * @param lowerBound Lower bound for the given type variable. This may a {@link NullType} instance, unless capture
1217      *     conversion produced a type variable with a non-trivial lower bound.
1218      * @see #createTypeVariable(TypeParameterElement, WildcardType)
1219      */
1220     protected abstract void setTypeVariableBounds(TypeVariable typeVariable, TypeMirror upperBound,
1221         TypeMirror lowerBound);
1222 
1223     /**
1224      * Returns the captured wildcard type argument of the given type variable, or null if the given type variable is not
1225      * the result of a capture conversion.
1226      *
1227      * <p>This method returns the wildcard type argument that was previously passed to
1228      * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
1229      *
1230      * @param typeVariable the type variable that may be the result of a capture conversion
1231      * @return the captured wildcard type argument, or null if not applicable
1232      */
1233     @Nullable
1234     protected abstract WildcardType capturedTypeArgument(TypeVariable typeVariable);
1235 
1236     /**
1237      * Returns a new intersection type. At least one bounds needs to be given.
1238      *
1239      * @param bounds the bounds of the new intersection type
1240      * @return the new intersection type
1241      * @throws IllegalArgumentException if the given array is empty
1242      */
1243     public abstract IntersectionType getIntersectionType(TypeMirror... bounds);
1244 
1245     /**
1246      * Visitor of {@link TypeMirror} instances that appends the {@link String} representation to the
1247      * {@link StringBuilder} instance passed as visitor argument.
1248      *
1249      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
1250      * can be asserted that the visitor parameter is always non-null.
1251      *
1252      * @see #requireValidType(TypeMirror)
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      * Returns the canonical string representation of the given type.
1360      *
1361      * @param type type
1362      * @return canonical string representation of the given type
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 }