AbstractTypes.java

  1. package net.florianschoppmann.java.type;

  2. import javax.annotation.Nullable;
  3. import javax.lang.model.element.Element;
  4. import javax.lang.model.element.ElementKind;
  5. import javax.lang.model.element.TypeElement;
  6. import javax.lang.model.element.TypeParameterElement;
  7. import javax.lang.model.type.ArrayType;
  8. import javax.lang.model.type.DeclaredType;
  9. import javax.lang.model.type.NoType;
  10. import javax.lang.model.type.NullType;
  11. import javax.lang.model.type.PrimitiveType;
  12. import javax.lang.model.type.TypeKind;
  13. import javax.lang.model.type.TypeMirror;
  14. import javax.lang.model.type.TypeVariable;
  15. import javax.lang.model.type.WildcardType;
  16. import javax.lang.model.util.Types;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Type;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashMap;
  25. import java.util.LinkedHashSet;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Objects;
  29. import java.util.Set;

  30. /**
  31.  * Abstract skeletal implementation of {@link Types}.
  32.  *
  33.  * <p>This class provides a skeletal implementation of the {@link Types} interface. Specifically, it implements all
  34.  * methods pertaining to §4.10 (subtyping) in the Java Language Specification (JLS). Concrete subclasses are expected to
  35.  * implement the abstract methods in this class, which are responsible for creating appropriate type-mirror instances.
  36.  * This class does not place any additional constraints on the concrete {@link TypeMirror} and {@link Element}
  37.  * implementations, so mutability and thread-safety are implementation-defined. However, this class crucially relies on
  38.  * the {@code equals} method being well-defined. That is, {@link Element} objects that have equal names and equal
  39.  * enclosing elements must compare equal. Likewise, {@link TypeMirror} objects that contain equal values must compare
  40.  * equal. In particular, multiple instances created by one of the {@code get}-methods must compare equal when the given
  41.  * arguments compare equal.
  42.  *
  43.  * <p>Besides subtype-related methods, this class also provides method
  44.  * {@link #resolveActualTypeArguments(TypeElement, TypeMirror)} for resolving formal type parameters to actual type
  45.  * arguments. For instance, given type {@code List<String>}, this method determines the actual type argument for the
  46.  * formal type parameter of {@code Collection<E>} (that is, {@code String} in this simple example).
  47.  *
  48.  * <p>Unless explicitly stated otherwise, all methods in this class expect non-null arguments. Passing null where not
  49.  * expected will cause a {@link NullPointerException} to be thrown. Implementations typically place additional
  50.  * restrictions on method arguments not captured by the types of the formal parameters (which stem from
  51.  * {@link javax.lang.model} and its subpackages). While the details are implementation-defined, typically this means
  52.  * that arguments must have been crated by the same implementation, or otherwise an {@link IllegalArgumentException}
  53.  * will be thrown. Implementations must override {@link #requireValidType(TypeMirror)} and
  54.  * {@link #requireValidElement(Element)}, as these methods are expected to perform any necessary validation.
  55.  */
  56. public abstract class AbstractTypes implements Types {
  57.     private static final List<TypeKind> REFERENCE_TYPES = Collections.unmodifiableList(Arrays.asList(
  58.         TypeKind.ARRAY, TypeKind.DECLARED, TypeKind.NULL, TypeKind.TYPEVAR
  59.     ));
  60.     private static final int DEFAULT_STRING_BUILDER_SIZE = 256;

  61.     private final SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor();
  62.     private final ErasureVisitor erasureVisitor = new ErasureVisitor();
  63.     private final ToStringVisitor toStringVisitor = new ToStringVisitor();
  64.     private final SubtypeVisitor subtypeVisitor = new SubtypeVisitor();
  65.     private final DeclaredTypeSubtypeVisitor declaredTypeSubtypeVisitor = new DeclaredTypeSubtypeVisitor();

  66.     /**
  67.      * Verifies that the given {@link Element} is valid for use with this class.
  68.      *
  69.      * <p>The meaning of valid is implementation-defined, but typically a valid {@link Element} must have been created
  70.      * by the implementation that belongs to the current {@code AbstractTypes} instance.
  71.      *
  72.      * @param element element
  73.      * @throws NullPointerException if the argument is null
  74.      * @throws IllegalArgumentException if the given {@link Element} cannot be used with this class
  75.      */
  76.     protected abstract void requireValidElement(Element element);

  77.     /**
  78.      * Verifies that the given {@link TypeMirror} is valid for use with this class, or that it is {@code null}.
  79.      *
  80.      * <p>The meaning of valid is implementation-defined, but typically a valid {@link TypeMirror} must have been
  81.      * created by the implementation that belongs to the current {@code AbstractTypes} instance. A {@code null} argument
  82.      * is always valid. The rationale is that {@code null} {@link TypeMirror} arguments have a special meaning for some
  83.      * methods such as {@link #getWildcardType(TypeMirror, TypeMirror)} or
  84.      * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
  85.      *
  86.      * @param type type mirror, may be {@code null}
  87.      * @throws IllegalArgumentException if the given {@link TypeMirror} instance is non-null and it cannot be used with
  88.      *     this class
  89.      */
  90.     protected abstract void requireValidType(@Nullable TypeMirror type);

  91.     /**
  92.      * Verifies that the given array is non-null and contains valid types that are not null.
  93.      *
  94.      * @param types array of types
  95.      * @throws NullPointerException if the given array or any of its elements are null
  96.      * @throws IllegalArgumentException if {@link #requireValidType(TypeMirror)} throws an exception for one of the
  97.      *     array elements
  98.      */
  99.     protected final void requireValidTypes(TypeMirror[] types) {
  100.         for (TypeMirror typeArg: types) {
  101.             Objects.requireNonNull(typeArg, "TypeMirror array must not contain null elements.");
  102.             requireValidType(typeArg);
  103.         }
  104.     }

  105.     /**
  106.      * Returns a type mirror corresponding to the given Java reflection type.
  107.      *
  108.      * <p>Subclasses are required to return the appropriate {@link DeclaredType} instances for the following
  109.      * {@link Class} instances:
  110.      * <ul><li>
  111.      *     {@link Object}
  112.      * </li><li>
  113.      *     {@link Serializable}
  114.      * </li><li>
  115.      *     {@link Cloneable}
  116.      * </li></ul>
  117.      *
  118.      * <p>Support for other types is not required and implementation-defined.
  119.      *
  120.      * @param type type as represented by Java Reflection API
  121.      * @throws UnsupportedOperationException If the given type is not one of the above {@link Class} objects and
  122.      *     this type-utilities implementation does not support mirroring arbitrary Java reflection types.
  123.      * @return the type mirror corresponding to the given reflection type
  124.      */
  125.     protected abstract TypeMirror typeMirror(Type type);

  126.     /**
  127.      * Internal class that contains both the substitution map passed to {@link #substitute(TypeMirror, Map)} and the
  128.      * set of fresh type variables created at the beginning of that method.
  129.      */
  130.     private static final class Substitutions {
  131.         private final Map<TypeParameterElement, ? extends TypeMirror> map;
  132.         private final Map<TypeParameterElement, TypeVariable> freshTypeVariables;

  133.         private Substitutions(Map<TypeParameterElement, ? extends TypeMirror> map,
  134.                 Map<TypeParameterElement, TypeVariable> freshTypeVariables) {
  135.             this.map = map;
  136.             this.freshTypeVariables = freshTypeVariables;
  137.         }
  138.     }

  139.     /**
  140.      * Visitor of a type mirror. Returns a new type mirror after performing the substitutions passed as visitor
  141.      * argument.
  142.      *
  143.      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
  144.      * can be asserted that the visitor parameter is always non-null.
  145.      *
  146.      * @see #substitutionVisitor
  147.      * @see #requireValidType(TypeMirror)
  148.      */
  149.     private final class SubstitutionVisitor extends ExtendedTypeKindVisitor7<TypeMirror, Substitutions> {
  150.         private TypeMirror[] substituteInList(List<? extends TypeMirror> types, Substitutions substitutions) {
  151.             TypeMirror[] substituted = new TypeMirror[types.size()];
  152.             int i = 0;
  153.             for (TypeMirror type: types) {
  154.                 substituted[i] = type.accept(this, substitutions);
  155.                 ++i;
  156.             }
  157.             return substituted;
  158.         }

  159.         @Override
  160.         public TypeMirror visitDeclared(DeclaredType declaredType, @Nullable Substitutions substitutions) {
  161.             assert substitutions != null;
  162.             TypeMirror enclosingType = declaredType.getEnclosingType();
  163.             TypeElement typeDeclaration = (TypeElement) declaredType.asElement();
  164.             TypeMirror[] substitutedArguments = substituteInList(declaredType.getTypeArguments(), substitutions);
  165.             if (enclosingType.getKind() == TypeKind.DECLARED) {
  166.                 return getDeclaredType((DeclaredType) enclosingType, typeDeclaration, substitutedArguments);
  167.             } else {
  168.                 return getDeclaredType(typeDeclaration, substitutedArguments);
  169.             }
  170.         }

  171.         @Override
  172.         public TypeMirror visitArray(ArrayType arrayType, @Nullable Substitutions substitutions) {
  173.             assert substitutions != null;
  174.             return getArrayType(arrayType.getComponentType().accept(this, substitutions));
  175.         }

  176.         @Override
  177.         public TypeMirror visitTypeVariable(TypeVariable typeVariable, @Nullable Substitutions substitutions) {
  178.             assert substitutions != null;
  179.             TypeParameterElement formalTypeParameter = (TypeParameterElement) typeVariable.asElement();
  180.             @Nullable TypeVariable freshTypeVariable = substitutions.freshTypeVariables.get(formalTypeParameter);
  181.             if (freshTypeVariable != null && formalTypeParameter.asType().equals(typeVariable)) {
  182.                 return freshTypeVariable;
  183.             }

  184.             @Nullable TypeMirror substitution = substitutions.map.get(formalTypeParameter);
  185.             if (substitution != null) {
  186.                 return substitution;
  187.             }

  188.             return getTypeVariable(
  189.                 formalTypeParameter,
  190.                 typeVariable.getUpperBound().accept(this, substitutions),
  191.                 typeVariable.getLowerBound().accept(this, substitutions),
  192.                 capturedTypeArgument(typeVariable)
  193.             );
  194.         }

  195.         @Override
  196.         public TypeMirror visitWildcard(WildcardType wildcardType, @Nullable Substitutions substitutions) {
  197.             assert substitutions != null;
  198.             @Nullable TypeMirror extendsBounds = wildcardType.getExtendsBound();
  199.             @Nullable TypeMirror superBound = wildcardType.getSuperBound();

  200.             return getWildcardType(
  201.                 extendsBounds != null
  202.                     ? extendsBounds.accept(this, substitutions)
  203.                     : null,
  204.                 superBound != null
  205.                     ? superBound.accept(this, substitutions)
  206.                     : null
  207.             );
  208.         }

  209.         @Override
  210.         public TypeMirror visitIntersection(IntersectionType intersectionType, @Nullable Substitutions substitutions) {
  211.             assert substitutions != null;
  212.             return getIntersectionType(substituteInList(intersectionType.getBounds(), substitutions));
  213.         }

  214.         @Override
  215.         protected TypeMirror defaultAction(TypeMirror type, Substitutions substitutions) {
  216.             return type;
  217.         }
  218.     }

  219.     /**
  220.      * Replaces formal type parameters in the given type.
  221.      *
  222.      * <p>This method requires that {@code type} does not contain transitive references to itself, unless through
  223.      * {@link DeclaredType#asElement()} → {@link TypeElement#asType()} or {@link TypeVariable#asElement()} →
  224.      * {@link TypeParameterElement#asType()}. Otherwise, this method might run into an infinite recursion, resulting in
  225.      * a {@link StackOverflowError}.
  226.      *
  227.      * <p>Moreover, this method requires that any type variable transitively referenced by {@code substitutionMap} must
  228.      * not contain a transitive reference (through {@link TypeVariable#getUpperBound()} or
  229.      * {@link TypeVariable#getLowerBound()}) to itself. Instead, any instance of {@link TypeVariable} (transitively)
  230.      * referenced by a value in {@code substitutionMap} must be the result of {@link TypeParameterElement#asType()}.
  231.      *
  232.      * <p>This method creates a fresh type variable for each formal type parameter that is to be substituted by a type
  233.      * variable for the same formal type parameter. For instance, suppose {@code T extends Object} is a formal type
  234.      * parameter, and {@code substitutionMap} specifies to replace it with the type variable {@code T extends U<T>}. In
  235.      * this case, {@link #createTypeVariable(TypeParameterElement, WildcardType)} will be called with the formal type
  236.      * parameter {@code T extends Object} as (first) argument. Once all fresh types have been created,
  237.      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} will then be called with {@code U<T>} as
  238.      * upper bound, where {@code T} is the fresh type variable {@code T extends U<T>}.
  239.      *
  240.      * @param type type in which the type parameters will be replaced recursively, guaranteed non-null
  241.      * @param substitutionMap mapping from formal type parameters to substituted type, guaranteed non-null
  242.      * @return new port type, guaranteed non-null
  243.      */
  244.     protected TypeMirror substitute(TypeMirror type, Map<TypeParameterElement, ? extends TypeMirror> substitutionMap) {
  245.         Objects.requireNonNull(type);
  246.         Objects.requireNonNull(substitutionMap);
  247.         requireValidType(type);
  248.         for (TypeMirror substitutionType: substitutionMap.values()) {
  249.             Objects.requireNonNull(substitutionType, "Substitution type cannot be null.");
  250.             requireValidType(substitutionType);
  251.         }

  252.         Map<TypeParameterElement, TypeVariable> freshTypeVariables = new LinkedHashMap<>();
  253.         for (Map.Entry<TypeParameterElement, ? extends TypeMirror> entry: substitutionMap.entrySet()) {
  254.             TypeMirror value = entry.getValue();
  255.             if (value.getKind() == TypeKind.TYPEVAR) {
  256.                 TypeParameterElement formalTypeParameter = entry.getKey();
  257.                 TypeVariable typeVariable = (TypeVariable) value;
  258.                 if (entry.getKey().equals(typeVariable.asElement())) {
  259.                     assert !freshTypeVariables.containsKey(formalTypeParameter);

  260.                     freshTypeVariables.put(
  261.                         formalTypeParameter,
  262.                         createTypeVariable(formalTypeParameter, capturedTypeArgument(typeVariable))
  263.                     );
  264.                 }
  265.             }
  266.         }

  267.         Substitutions substitutions = new Substitutions(substitutionMap, freshTypeVariables);
  268.         for (Map.Entry<TypeParameterElement, TypeVariable> entry: freshTypeVariables.entrySet()) {
  269.             TypeVariable substitution = (TypeVariable) substitutionMap.get(entry.getKey());
  270.             setTypeVariableBounds(
  271.                 entry.getValue(),
  272.                 substitution.getUpperBound().accept(substitutionVisitor, substitutions),
  273.                 substitution.getLowerBound().accept(substitutionVisitor, substitutions)
  274.             );
  275.         }

  276.         return type.accept(substitutionVisitor, substitutions);
  277.     }

  278.     /**
  279.      * Returns the actual type arguments of a type declaration given a subtype (typically with its own actual type
  280.      * arguments).
  281.      *
  282.      * <p>This method "projects" the actual type arguments of {@code subtype}, as well as all actual type arguments of
  283.      * super types in the type hierarchy between {@code typeElement} and {@code subType}, onto the type declaration
  284.      * represented by {@code typeElement}.
  285.      *
  286.      * <p>For example, {@code typeElement} may be the (generic) type declaration {@code Comparable<T>}, and
  287.      * {@code subType} may be the (non-generic) type {@link Integer}. The result in this case would be a singleton list
  288.      * containing the type {@link Integer}.
  289.      *
  290.      * <p>More generally, resolution works as follows: First, the shortest inheritance path from {@code subType} to
  291.      * {@code typeElement} is found. Note that while Java allows multiple inheritance for interfaces, JLS §8.1.5
  292.      * disallows inheriting from the same interface with different type parameters (both directly and transitively).
  293.      * Hence, the shortest path contains all information that is necessary to resolve formal type parameters to actual
  294.      * parameters. This method then propagates the actual type arguments bottom-up along the inheritance path.
  295.      * Note that the inheritance path consists of {@link DeclaredType} instances, and it may consist of generic types,
  296.      * non-generic types, and raw types.
  297.      *
  298.      * <p>If the inheritance path contains a raw type <em>before</em> the last path element, this method proceeds
  299.      * by using the "prototypical" type returned by {@link Element#asType()} instead. Correspondingly, it is possible
  300.      * that the returned list may contain type variables from a type declaration along the inheritance path. However, if
  301.      * the <em>last</em> inheritance path element is a raw type, the returned list will be empty. Otherwise, if a
  302.      * non-null non-empty {@link List} is returned, it is guaranteed to have the same number of elements as
  303.      * {@code typeElement.getTypeParameters()}.
  304.      *
  305.      * @param typeElement type declaration
  306.      * @param subType potential subtype of {@code typeElement}, must be a non-generic type declaration, raw type,
  307.      *     generic type declaration, or parameterized type
  308.      * @return actual type arguments for the formal parameters of {@code typeElement} (empty list if the <em>last</em>
  309.      *     path element in the inheritance path from {@code subType} to {@code typeElement} is a raw type), or
  310.      *     {@code null} if {@code subType} is not a subtype of {@code typeElement}
  311.      * @throws IllegalArgumentException if the arguments do not satisfy the constraints mentioned above
  312.      */
  313.     @Nullable
  314.     public final List<? extends TypeMirror> resolveActualTypeArguments(TypeElement typeElement, TypeMirror subType) {
  315.         requireValidElement(Objects.requireNonNull(typeElement));
  316.         requireValidType(Objects.requireNonNull(subType));

  317.         if (subType.getKind() != TypeKind.DECLARED) {
  318.             return null;
  319.         }

  320.         DeclaredType declaredSubType = (DeclaredType) subType;

  321.         // getShortestPathToSuperType() will throw an exception if subType does not satisfy the constraints mentioned
  322.         // above.
  323.         @Nullable List<DeclaredType> path = getShortestPathToSuperType(typeElement, declaredSubType);
  324.         if (path == null) {
  325.             return null;
  326.         }

  327.         // Early exit if there is nothing to resolve. However, we must not move this early exit any earlier, because
  328.         // we do want to return null if subType is not a subtype of typeElement.
  329.         if (typeElement.getTypeParameters().isEmpty()) {
  330.             return Collections.emptyList();
  331.         }

  332.         Iterator<DeclaredType> pathIterator = path.iterator();
  333.         DeclaredType current = pathIterator.next();
  334.         while (pathIterator.hasNext()) {
  335.             TypeElement currentTypeElement = (TypeElement) current.asElement();

  336.             // Check whether "current" is a raw type. This may happen in the first loop iteration if subType is a raw
  337.             // type, or in subsequent iterations if the type that was previously "current" (during the last iteration
  338.             // of the for-loop) derived from a raw type. If yes, use instead the "prototypical" type returned by
  339.             // Element#asType().
  340.             if (current.getTypeArguments().isEmpty() && !currentTypeElement.getTypeParameters().isEmpty()) {
  341.                 current = (DeclaredType) currentTypeElement.asType();
  342.             }

  343.             List<? extends TypeParameterElement> currentFormalParameters = currentTypeElement.getTypeParameters();
  344.             List<? extends TypeMirror> currentActualParameters = current.getTypeArguments();

  345.             Map<TypeParameterElement, TypeMirror> currentFormalToActual = new LinkedHashMap<>();
  346.             for (int index = 0; index < currentFormalParameters.size(); ++index) {
  347.                 currentFormalToActual.put(currentFormalParameters.get(index), currentActualParameters.get(index));
  348.             }

  349.             current = (DeclaredType) substitute(pathIterator.next(), currentFormalToActual);
  350.         }
  351.         return current.getTypeArguments();
  352.     }

  353.     /**
  354.      * Visitor of a type mirror. Returns whether the visited type mirror is a subtype of the visitor argument (of type
  355.      * {@link DeclaredType}).
  356.      *
  357.      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
  358.      * can be asserted that the visitor parameter is always non-null.
  359.      *
  360.      * @see #declaredTypeSubtypeVisitor
  361.      * @see #requireValidType(TypeMirror)
  362.      */
  363.     private final class DeclaredTypeSubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, DeclaredType> {
  364.         private DeclaredTypeSubtypeVisitor() {
  365.             super(false);
  366.         }

  367.         /**
  368.          * Returns whether the first declared type is a subtype of the second declared type.
  369.          *
  370.          * <p>This method proceeds by computing the actual type arguments when {@code subType} is projected onto the
  371.          * type declaration corresponding to {@code superType}. It then tests if all actual type arguments of
  372.          * {@code subType} are <em>contained</em> in those of {@code superType}.
  373.          */
  374.         @Override
  375.         public Boolean visitDeclared(DeclaredType subType, @Nullable DeclaredType superType) {
  376.             assert superType != null;
  377.             DeclaredType actualSubType = subType;

  378.             // First test if there subType has at least one wildcard type argument. In that case, we need to perform a
  379.             // capture conversion first.
  380.             // Note that this is the right place to do capture conversion: JLS §8.1.4 and §9.1.3 state about class types
  381.             // and interfaces type listed in the extends or implements clause of a class/interface declaration:
  382.             // - "If the ClassType has type arguments, it must denote a well-formed parameterized type (§4.5), and none
  383.             // of the type arguments may be wildcard type arguments, or a compile-time error occurs."
  384.             // - "If an InterfaceType has type arguments, it must denote a well-formed parameterized type (§4.5), and
  385.             // none of the type arguments may be wildcard type arguments, or a compile-time error occurs."
  386.             // Hence, wildcards do not appear on the "inheritance path" between subType and superType.
  387.             for (TypeMirror subTypeArgument: subType.getTypeArguments()) {
  388.                 if (subTypeArgument.getKind() == TypeKind.WILDCARD) {
  389.                     actualSubType = (DeclaredType) capture(subType);
  390.                     break;
  391.                 }
  392.             }

  393.             // Resolve the actual type parameters of subType when projected onto the superType
  394.             TypeElement superTypeDeclaration = (TypeElement) superType.asElement();
  395.             @Nullable List<? extends TypeMirror> projectedTypeArguments
  396.                 = resolveActualTypeArguments(superTypeDeclaration, actualSubType);

  397.             if (projectedTypeArguments == null) {
  398.                 // subType is not a subtype of the type declaration
  399.                 return false;
  400.             }

  401.             List<? extends TypeMirror> superTypeArguments = superType.getTypeArguments();
  402.             if (projectedTypeArguments.isEmpty() && !superTypeArguments.isEmpty()) {
  403.                 // the projection of subType onto superType resulted in a raw type, which is neither a subtype of any
  404.                 // parametrized type of the generic type declaration of superType, nor the generic type declaration
  405.                 // itself
  406.                 return false;
  407.             }

  408.             // Note that superType could be a raw type, in which case superTypeArguments is empty. In that case, the
  409.             // loop would not be executed at all.
  410.             Iterator<? extends TypeMirror> projectedTypeArgumentsIterator = projectedTypeArguments.iterator();
  411.             for (TypeMirror to: superTypeArguments) {
  412.                 TypeMirror from = projectedTypeArgumentsIterator.next();
  413.                 if (!contains(to, from)) {
  414.                     return false;
  415.                 }
  416.             }
  417.             return true;
  418.         }

  419.         /**
  420.          * Returns whether the array type is a subtype of the declared type.
  421.          *
  422.          * <p>According to JLS §4.10.3, an array type can only be a subtype of a declared type if the latter represents
  423.          * one of {@link Object}, {@link Cloneable}, or {@link Serializable}.
  424.          */
  425.         @Override
  426.         public Boolean visitArray(ArrayType subType, @Nullable DeclaredType superType) {
  427.             assert superType != null;
  428.             return typeMirror(Object.class).equals(superType)
  429.                 || typeMirror(Cloneable.class).equals(superType)
  430.                 || typeMirror(Serializable.class).equals(superType);
  431.         }

  432.         /**
  433.          * Returns whether the type variable is a subtype of the declared type.
  434.          *
  435.          * <p>According to JLS §4.10.2, the direct supertypes of a type variable are the types listed in its bound.
  436.          * Hence, this method returns true if {@link TypeVariable#getUpperBound()} is a subtype of {@code superType}.
  437.          */
  438.         @Override
  439.         public Boolean visitTypeVariable(TypeVariable subType, @Nullable DeclaredType superType) {
  440.             assert superType != null;
  441.             return isSubtype(subType.getUpperBound(), superType);
  442.         }

  443.         /**
  444.          * Returns whether the intersection type is a subtype of the declared type.
  445.          *
  446.          * <p>According to JLS §4.10.2, the direct supertypes of an intersection type {@code T_1 & ... T_n} are
  447.          * {@code T_1}, ..., {@code T_n}. Hence, this method returns true if at least one of
  448.          * {@link IntersectionType#getBounds()} is a subtype of {@code superType}.
  449.          */
  450.         @Override
  451.         public Boolean visitIntersection(IntersectionType subType, @Nullable DeclaredType superType) {
  452.             assert superType != null;
  453.             for (TypeMirror bound: subType.getBounds()) {
  454.                 if (isSubtype(bound, superType)) {
  455.                     return true;
  456.                 }
  457.             }
  458.             return false;
  459.         }
  460.     }

  461.     /**
  462.      * Visitor of a type mirror. Returns whether the visited type mirror is a supertype of the visitor argument.
  463.      *
  464.      * <p>This visitor does not have to deal with the null-type, which has been dealt with before. It has to make a
  465.      * decision for {@link ArrayType}, {@link DeclaredType}, {@link PrimitiveType}, and {@link TypeVariable}.
  466.      *
  467.      * <p>Java 8 introduces {@code IntersectionType}, but this code currently uses Java 7. Moreover, there are other
  468.      * types that are currently not supported, such as {@link javax.lang.model.type.UnionType}. Finally,
  469.      * {@link WildcardType} is not a type, but only a type argument, so it is not necessary to be dealt with here.
  470.      * Likewise, {@link NoType} is not used to model proper types, but only empty bounds, non-existence of interface
  471.      * super classes, etc.
  472.      *
  473.      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
  474.      * can be asserted that the visitor parameter is always non-null.
  475.      *
  476.      * @see #subtypeVisitor
  477.      * @see #requireValidType(TypeMirror)
  478.      */
  479.     private final class SubtypeVisitor extends ExtendedTypeKindVisitor7<Boolean, TypeMirror> {
  480.         private SubtypeVisitor() {
  481.             super(false);
  482.         }

  483.         /**
  484.          * Returns whether the array type is a super type of the type given as second argument.
  485.          *
  486.          * <p>According to JLS §4.10.3, array component types are covariant; for instance, {@code Integer[]} is a proper
  487.          * subtype of {@code Number[]}. Moreover, all subtypes of an array type are again array types. Hence, this
  488.          * method simply reduces the problem to testing if {@code subType} is also an array type and then applying
  489.          * {@link AbstractTypes#isSubtype(TypeMirror, TypeMirror)} to the component types.
  490.          */
  491.         @Override
  492.         public Boolean visitArray(ArrayType superType, @Nullable TypeMirror subType) {
  493.             assert subType != null;
  494.             return subType.getKind() == TypeKind.ARRAY
  495.                 && isSubtype(((ArrayType) subType).getComponentType(), superType.getComponentType());
  496.         }

  497.         /**
  498.          * Returns whether the declared type is a super type of the type given as second argument.
  499.          *
  500.          * <p>This method has {@link DeclaredTypeSubtypeVisitor} visit {@code subType}.
  501.          */
  502.         @Override
  503.         public Boolean visitDeclared(DeclaredType superType, @Nullable TypeMirror subType) {
  504.             assert subType != null;
  505.             return subType.accept(declaredTypeSubtypeVisitor, superType);
  506.         }

  507.         private final List<TypeKind> numericKindEnumValues = Collections.unmodifiableList(Arrays.asList(
  508.             TypeKind.DOUBLE, TypeKind.FLOAT, TypeKind.LONG, TypeKind.INT, TypeKind.SHORT, TypeKind.BYTE
  509.         ));
  510.         private final int intIndex = numericKindEnumValues.indexOf(TypeKind.INT);

  511.         /**
  512.          * Returns whether the primitive type is a supertype of the given type.
  513.          */
  514.         @Override
  515.         public Boolean visitPrimitive(PrimitiveType superType, @Nullable TypeMirror subType) {
  516.             assert subType != null;
  517.             if (!subType.getKind().isPrimitive()) {
  518.                 return false;
  519.             }

  520.             int superTypeIndex = numericKindEnumValues.indexOf(superType.getKind());
  521.             int subTypeIndex = numericKindEnumValues.indexOf(subType.getKind());
  522.             return (subType.getKind() == TypeKind.CHAR && 0 <= superTypeIndex && superTypeIndex <= intIndex)
  523.                 || (0 <= superTypeIndex && superTypeIndex <= subTypeIndex);
  524.         }

  525.         /**
  526.          * Returns whether the type variable is a super type of the given type.
  527.          *
  528.          * <p>A type variable is only a supertype of its lower bound.
  529.          */
  530.         @Override
  531.         public Boolean visitTypeVariable(TypeVariable superType, @Nullable TypeMirror subType) {
  532.             assert subType != null;
  533.             return isSameType(superType.getLowerBound(), subType);
  534.         }

  535.         /**
  536.          * Returns whether the given intersection type is a super type of the given type.
  537.          *
  538.          * <p>While one might expect that the set of supertypes of an intersection type {@code T_1 & ... & T_n} includes
  539.          * the intersection of any (non-empty) subset of {@code T_1}, ..., {@code T_n}, this seems is not specified by
  540.          * JLS §4.10 (which only says that "the direct supertypes of an intersection type {@code T_1 & ... & T_n} are
  541.          * {@code T_i} (1 ≤ i ≤ n)"). See also issue
  542.          * <a href="https://bugs.openjdk.java.net/browse/JDK-6718388">JDK-6718388</a>.
  543.          *
  544.          * <p>Therefore, an intersection type is only a supertype of itself.
  545.          */
  546.         @Override
  547.         public Boolean visitIntersection(IntersectionType superType, @Nullable TypeMirror subType) {
  548.             assert subType != null;
  549.             return isSameType(superType, subType);
  550.         }
  551.     }

  552.     /**
  553.      * Returns whether the first type is a subtype of the second type, as specified by JLS §4.10.
  554.      *
  555.      * <p>The subtype relationship is transitive and reflexive.
  556.      *
  557.      * @param t1 the first type
  558.      * @param t2 the second type
  559.      * @return {@code true} if and only if the first type is a subtype of the second
  560.      * @throws NullPointerException if an argument is null
  561.      * @throws IllegalArgumentException if given an executable or package type
  562.      */
  563.     @Override
  564.     public final boolean isSubtype(TypeMirror t1, TypeMirror t2) {
  565.         requireValidType(Objects.requireNonNull(t1));
  566.         requireValidType(Objects.requireNonNull(t2));

  567.         // §4.10.2: The direct supertypes of the null type are all reference types other than the null type itself.
  568.         if (t1.getKind() == TypeKind.NULL && REFERENCE_TYPES.contains(t2.getKind())) {
  569.             return true;
  570.         }

  571.         return t2.accept(subtypeVisitor, t1);
  572.     }

  573.     /**
  574.      * Returns whether the first type argument <em>contains</em> the second type argument, as specified by JLS §4.5.1.
  575.      *
  576.      * <p>Using the JLS notation, this method returns true if {@code t2 <= t1}. As JLS §4.10 states, "subtyping does not
  577.      * extend through parameterized types." Hence, this method is necessarily different from
  578.      * {@link #isSubtype(TypeMirror, TypeMirror)}. In particular, the super-type relationship does not include types
  579.      * with covariant type arguments.
  580.      *
  581.      * @param t1 the first type
  582.      * @param t2 the second type
  583.      * @return {@code true} if and only if the first type contains the second
  584.      * @throws IllegalArgumentException if given an executable or package type
  585.      */
  586.     @Override
  587.     public final boolean contains(TypeMirror t1, TypeMirror t2) {
  588.         Objects.requireNonNull(t1);
  589.         Objects.requireNonNull(t2);
  590.         requireValidType(t1);
  591.         requireValidType(t2);

  592.         // We need to cover these cases (JLS §4.5.1):
  593.         //
  594.         // (a) wildcard t2 <= wildcard t1
  595.         // 1. ? extends T <= ? extends S if T <: S
  596.         // 2. ? extends T <= ?
  597.         // 3. ? super T <= ? super S if S <: T
  598.         // 4. ? super T <= ?
  599.         // 5. ? super T <= ? extends Object
  600.         //
  601.         // (b) other type t2 <= other type t1
  602.         // 1. T <= T
  603.         //
  604.         // (c) other type t2 <= wildcard t1
  605.         // 1. T <= ? extends T
  606.         // 2. T <= ? super T

  607.         if (t1.getKind() == TypeKind.WILDCARD) {
  608.             @Nullable TypeMirror t1ExtendsBound = ((WildcardType) t1).getExtendsBound();
  609.             @Nullable TypeMirror t1SuperBound = ((WildcardType) t1).getSuperBound();
  610.             boolean t1HasExtendsBound = t1ExtendsBound != null;
  611.             boolean t1HasSuperBound = t1SuperBound != null;

  612.             if (t2.getKind() == TypeKind.WILDCARD) {
  613.                 // Handle (a).
  614.                 @Nullable TypeMirror t2ExtendsBound = ((WildcardType) t2).getExtendsBound();
  615.                 @Nullable TypeMirror t2SuperBound = ((WildcardType) t2).getSuperBound();

  616.                 if (t2ExtendsBound != null) {
  617.                     if (t1ExtendsBound != null) {
  618.                         // (a) 1.
  619.                         return isSubtype(t2ExtendsBound, t1ExtendsBound);
  620.                     } else if (t1SuperBound == null) {
  621.                         // (a) 2.
  622.                         return true;
  623.                     }
  624.                     // Note that "? super S" never contains a type argument of form "? extends T"
  625.                     return false;
  626.                 } else if (t2SuperBound != null) {
  627.                     if (t1SuperBound != null) {
  628.                         // (a) 3.
  629.                         return isSubtype(t1SuperBound, t2SuperBound);
  630.                     } else {
  631.                         // (a) 4. and 5.: Handle case "? super T <= ?" (always true) or "? super S <= ? extends T" (only
  632.                         // if T is Object)
  633.                         return t1ExtendsBound == null
  634.                             || isSameType(t1ExtendsBound, typeMirror(Object.class));
  635.                     }
  636.                 } else {
  637.                     // Handle special case of (a), namely "? <= ? extends T" (only if T is Object), "? <= ? super T"
  638.                     // (always false), or "? <= ?" (which is equivalent to "? extends Object <= ? extends Object" and
  639.                     // therefore true).
  640.                     return t1SuperBound == null && (
  641.                         t1ExtendsBound == null || isSameType(t1ExtendsBound, typeMirror(Object.class))
  642.                     );
  643.                 }
  644.             } else {
  645.                 // Handle (c). Reduce to case (a).
  646.                 if (t1HasExtendsBound) {
  647.                     // (c) 1.
  648.                     return contains(t1, getWildcardType(t2, null));
  649.                 } else if (t1HasSuperBound) {
  650.                     // (c) 2.
  651.                     return contains(t1, getWildcardType(null, t2));
  652.                 }
  653.                 // Combining (c) 1. with (a) 2. or (c) 2. with (a) 4., we immediately have "T <= ?"
  654.                 return true;
  655.             }
  656.         } else {
  657.             // Handle (b).
  658.             return isSameType(t1, t2);
  659.         }
  660.     }

  661.     /**
  662.      * Returns the direct super types of the given type declaration, as defined by JLS §4.10.2.
  663.      */
  664.     private List<DeclaredType> directSupertypesOfTypeDeclaration(TypeElement typeElement) {
  665.         TypeMirror superClass = typeElement.getSuperclass();
  666.         List<? extends TypeMirror> interfaces = typeElement.getInterfaces();
  667.         List<DeclaredType> newSuperTypes = new ArrayList<>(1 + interfaces.size());
  668.         if (superClass.getKind() == TypeKind.DECLARED) {
  669.             newSuperTypes.add((DeclaredType) superClass);
  670.         }
  671.         for (TypeMirror superInterface: interfaces) {
  672.             newSuperTypes.add((DeclaredType) superInterface);
  673.         }
  674.         if (typeElement.getKind() == ElementKind.INTERFACE && interfaces.isEmpty()) {
  675.             newSuperTypes.add((DeclaredType) typeMirror(Object.class));
  676.         }
  677.         return newSuperTypes;
  678.     }

  679.     /**
  680.      * Internal class to keep state for the Dijkstra shortest-path algorithm in
  681.      * {@link #getShortestPathToSuperType(TypeElement, DeclaredType)}.
  682.      */
  683.     private static final class TypeDeclarationVertexState {
  684.         private int distance;
  685.         private boolean visited;
  686.         private final TypeElement typeElement;

  687.         /**
  688.          * The type as contained in {@code previous.typeDeclaration.getSuperTypes()}.
  689.          */
  690.         private final DeclaredType declaredType;

  691.         @Nullable private TypeDeclarationVertexState previous;

  692.         private TypeDeclarationVertexState(int distance, boolean visited, TypeElement typeElement,
  693.                 DeclaredType declaredType) {
  694.             this.distance = distance;
  695.             this.visited = visited;
  696.             this.typeElement = typeElement;
  697.             this.declaredType = declaredType;
  698.         }

  699.         /**
  700.          * Returns the path induced by this node, starting with {@code derived} and ending with {@link #declaredType}.
  701.          *
  702.          * <p>The path is obtained by following {@link #previous} until {@code null}. Each element in the path (except
  703.          * for the first) is the {@link #declaredType} of the current instance.
  704.          *
  705.          * @param derived the first element in the path
  706.          * @return the path induced by this node
  707.          */
  708.         private List<DeclaredType> toPath(DeclaredType derived) {
  709.             DeclaredType[] path = new DeclaredType[distance + 1];
  710.             int count = path.length;
  711.             TypeDeclarationVertexState pathElement = this;
  712.             while (pathElement.previous != null) {
  713.                 --count;
  714.                 path[count] = pathElement.declaredType;
  715.                 pathElement = pathElement.previous;
  716.             }
  717.             path[0] = derived;
  718.             return Arrays.asList(path);
  719.         }
  720.     }

  721.     /**
  722.      * Returns the shortest inheritance path between a type declaration and a subtype (starting with
  723.      * {@code derived} and ending with {@code base}).
  724.      *
  725.      * <p>Each element in the returned path is a non-generic type, a raw type, or a parameterized type. The
  726.      * {@link DeclaredType} at position {@code i} is always contained in the result of
  727.      * {@link #directSupertypesOfTypeDeclaration(TypeElement)} applied to the type declaration of the type at position
  728.      * {@code (i - 1)}.
  729.      *
  730.      * <p>This methods runs a Dijkstra shortest-path algorithm. It relies on {@link TypeElement#equals(Object)}
  731.      * being well-defined (two object representing the same type declaration must compare equal). Consequently, if
  732.      * {@link DeclaredType} instances have an identity, it must be guaranteed that there are no two instances
  733.      * representing the same type declaration.
  734.      *
  735.      * @param base base type declaration
  736.      * @param derived derived type
  737.      * @return If there is an inheritance path from {@code derived} to {@code base}, then a {@code List<DeclaredType>}
  738.      *     {@code p} such that {@code p.get(0).equals(toGenericType(derived))} and
  739.      *     {@code toRawTypeDeclaration(p.get(p.size() - 1)).equals(base)} are {@code true}. Otherwise, {@code null} to
  740.      *     indicate that there is no such path.
  741.      */
  742.     @Nullable
  743.     private List<DeclaredType> getShortestPathToSuperType(TypeElement base, DeclaredType derived) {
  744.         TypeElement typeElement = (TypeElement) derived.asElement();

  745.         Set<TypeElement> boundary = new LinkedHashSet<>();
  746.         Map<TypeElement, TypeDeclarationVertexState> dijkstraState = new HashMap<>();

  747.         // Distance from derived to itself is 0
  748.         dijkstraState.put(typeElement, new TypeDeclarationVertexState(0, false, typeElement, derived));
  749.         // Start off with derived
  750.         boundary.add(typeElement);

  751.         // Invariants:
  752.         // - boundary only contains nodes that have *not* been visited
  753.         // - For all visited nodes, the shortest path is known
  754.         while (!boundary.isEmpty()) {
  755.             // shortest := vertex in boundary with smallest distance from typeElement
  756.             @Nullable TypeDeclarationVertexState shortest = null;
  757.             for (TypeElement currentDeclaration: boundary) {
  758.                 TypeDeclarationVertexState current = dijkstraState.get(currentDeclaration);
  759.                 if (shortest == null || current.distance < shortest.distance) {
  760.                     shortest = current;
  761.                 }
  762.             }
  763.             // Since boundary is non-empty, shortest was assigned in the previous loop. Also note that due to the above
  764.             // invariant, shortest has not been visited.
  765.             assert shortest != null && !shortest.visited;

  766.             // Terminate if we found base. Since shortest.distance is non-decreasing over the loop iterations, it is
  767.             // impossible to find a shorter path in future iterations.
  768.             if (shortest.typeElement.equals(base)) {
  769.                 return shortest.toPath(derived);
  770.             }

  771.             // Remove shortest from boundary.
  772.             boundary.remove(shortest.typeElement);
  773.             shortest.visited = true;

  774.             for (DeclaredType superType: directSupertypesOfTypeDeclaration(shortest.typeElement)) {
  775.                 // A direct super type of a type declaration is either a non-generic type declaration or a raw type (in
  776.                 // both cases represented as DeclaredType with no actual type parameters) or a parameterized type
  777.                 TypeElement superDeclaration = (TypeElement) superType.asElement();
  778.                 @Nullable TypeDeclarationVertexState stats = dijkstraState.get(superDeclaration);

  779.                 if (stats == null) {
  780.                     stats = new TypeDeclarationVertexState(Integer.MAX_VALUE, false, superDeclaration, superType);
  781.                     dijkstraState.put(superDeclaration, stats);
  782.                 }

  783.                 int alt = shortest.distance + 1;
  784.                 if (!stats.visited && alt < stats.distance) {
  785.                     stats.distance = alt;
  786.                     stats.previous = shortest;
  787.                     boundary.add(superDeclaration);
  788.                 }
  789.             }
  790.         }
  791.         return null;
  792.     }

  793.     /**
  794.      * Visitor of a type mirror. Returns the erasure of the visited type mirror.
  795.      *
  796.      * @see #erasureVisitor
  797.      */
  798.     private final class ErasureVisitor extends ExtendedTypeKindVisitor7<TypeMirror, Void> {
  799.         @Override
  800.         public TypeMirror visitDeclared(DeclaredType declaredType, @Nullable Void ignored) {
  801.             TypeMirror originalEnclosingType = declaredType.getEnclosingType();
  802.             @Nullable DeclaredType newEnclosingType = originalEnclosingType.getKind() == TypeKind.NONE
  803.                 ? null
  804.                 : (DeclaredType) erasure(declaredType.getEnclosingType());
  805.             return getDeclaredType(newEnclosingType, (TypeElement) declaredType.asElement());
  806.         }

  807.         /**
  808.          * Returns the array type corresponding to the erasure of the component type.
  809.          */
  810.         @Override
  811.         public TypeMirror visitArray(ArrayType arrayType, @Nullable Void ignored) {
  812.             return getArrayType(erasure(arrayType.getComponentType()));
  813.         }

  814.         /**
  815.          * Returns the erasure of the leftmost bound of the given type variable.
  816.          *
  817.          * <p>The erasure of a type variable is the erasure of its leftmost bound (JLS §4.6). If multiple bounds are
  818.          * present, the upper bound is modelled as an intersection type. The erasure of an intersection type is
  819.          * guaranteed to have see right form (see {@link #visitIntersection(IntersectionType, Void)}).
  820.          */
  821.         @Override
  822.         public TypeMirror visitTypeVariable(TypeVariable typeVariable, @Nullable Void ignored) {
  823.             return erasure(typeVariable.getUpperBound());
  824.         }

  825.         /**
  826.          * Returns the erasure of the leftmost member of the given intersection type.
  827.          *
  828.          * <p>While JLS §4.6 does not mention intersection types (and thus, strictly speaking, the erasure of an
  829.          * intersection type should be the unmodified intersection type itself), this implementation computes the
  830.          * erasure of an intersection type as the erasure of its left-most type.
  831.          */
  832.         @Override
  833.         public TypeMirror visitIntersection(IntersectionType intersectionType, @Nullable Void ignored) {
  834.             return erasure(intersectionType.getBounds().get(0));
  835.         }

  836.         /**
  837.          * Returns the given type itself.
  838.          *
  839.          * <p>JLS §4.6 specifies: "The erasure of every other type is the type itself."
  840.          */
  841.         @Override
  842.         protected TypeMirror defaultAction(TypeMirror type, Void ignored) {
  843.             return type;
  844.         }
  845.     }

  846.     /**
  847.      * Returns the erasure of a type, as specified by JLS §4.6.
  848.      *
  849.      * @param type the type to be erased
  850.      * @return the erasure of the given type
  851.      * @throws IllegalArgumentException if given a package type
  852.      */
  853.     @Override
  854.     public final TypeMirror erasure(TypeMirror type) {
  855.         Objects.requireNonNull(type);
  856.         requireValidType(type);

  857.         return type.accept(erasureVisitor, null);
  858.     }

  859.     /**
  860.      * Returns the element corresponding to a type.
  861.      *
  862.      * <p>The type may be a {@code DeclaredType} or {@code TypeVariable}. Returns {@code null} if the type is not one
  863.      * with a corresponding element.
  864.      *
  865.      * @param type the type
  866.      * @return the element corresponding to the given type
  867.      */
  868.     @Override
  869.     public final Element asElement(TypeMirror type) {
  870.         Objects.requireNonNull(type);
  871.         requireValidType(type);

  872.         if (type.getKind() == TypeKind.DECLARED) {
  873.             return ((DeclaredType) type).asElement();
  874.         } else if (type.getKind() == TypeKind.TYPEVAR) {
  875.             return ((TypeVariable) type).asElement();
  876.         } else {
  877.             return null;
  878.         }
  879.     }

  880.     /**
  881.      * Returns whether the two given type arguments represent the same type.
  882.      *
  883.      * <p>If either of the arguments to this method represents a wildcard, this method will return false. As a
  884.      * consequence, a wildcard is not the same type as itself.
  885.      *
  886.      * @param t1 the first type
  887.      * @param t2 the second type
  888.      * @return {@code true} if and only if the two types are the same
  889.      */
  890.     @Override
  891.     public final boolean isSameType(TypeMirror t1, TypeMirror t2) {
  892.         requireValidType(Objects.requireNonNull(t1));
  893.         requireValidType(Objects.requireNonNull(t2));

  894.         return t1.getKind() != TypeKind.WILDCARD && t1.equals(t2);
  895.     }

  896.     /**
  897.      * Returns the greatest lower bound (glb) of a wildcard extends bound and an upper bound of a type parameter.
  898.      *
  899.      * <p>This method is only called from {@link #capture(TypeMirror)}. JLS §5.1.10 defines the greatest lower bound
  900.      * {@code glb(V_1, ..., V_m)} as {@code V_1 & ... & V_m}. Unfortunately, the specification provides no clarity
  901.      * whether intersection types are allowed to be nested. This implementation takes the interpretation that
  902.      * intersection types should not be nested. Therefore, the bounds contained in {@code originalUpperBound} are
  903.      * unwrapped.
  904.      *
  905.      * @param wildcardExtendsBound extends bound of the wildcard type argument
  906.      * @param originalUpperBound original upper bound of the type parameter
  907.      * @return the greatest lower bound
  908.      */
  909.     private static TypeMirror[] greatestLowerBound(TypeMirror wildcardExtendsBound, TypeMirror originalUpperBound) {
  910.         @Nullable TypeMirror[] result = null;
  911.         if (originalUpperBound instanceof IntersectionType) {
  912.             IntersectionType originalIntersectionBound = (IntersectionType) originalUpperBound;
  913.             if (originalIntersectionBound.isIntersectionType()) {
  914.                 List<? extends TypeMirror> originalBounds = originalIntersectionBound.getBounds();
  915.                 result = new TypeMirror[1 + originalBounds.size()];
  916.                 int i = 0;
  917.                 for (TypeMirror originalBound: originalBounds) {
  918.                     ++i;
  919.                     result[i] = originalBound;
  920.                 }
  921.             }
  922.         }

  923.         if (result == null) {
  924.             result = new TypeMirror[2];
  925.             result[1] = originalUpperBound;
  926.         }

  927.         result[0] = wildcardExtendsBound;
  928.         return result;
  929.     }

  930.     /**
  931.      * Returns the caputure conversion of (just) the given wildcard argument.
  932.      *
  933.      * <p>This method is only called by {@link #capture(TypeMirror)}.
  934.      */
  935.     private TypeVariable captureWildcardArgument(WildcardType wildcardArgument, TypeParameterElement typeParameter) {
  936.         TypeVariable originalTypeVariable = (TypeVariable) typeParameter.asType();

  937.         // Denoted U_i in JLS 5.1.10
  938.         TypeMirror originalUpperBound = originalTypeVariable.getUpperBound();

  939.         // Both of the following are denoted B_i in JLS 5.1.10 (in "? extends B_i" and "? super B_i", respectively)
  940.         @Nullable TypeMirror wildcardExtendsBound = wildcardArgument.getExtendsBound();
  941.         @Nullable TypeMirror wildcardSuperBound = wildcardArgument.getSuperBound();

  942.         TypeMirror newUpperBound;
  943.         TypeMirror newLowerBound;

  944.         // There exists a capture conversion from a parameterized type G<T_1,...,T_n> (§4.5) to a parameterized type
  945.         // G<S_1, ..., S_n>, where, for 1 <= i <= n:
  946.         if (wildcardExtendsBound == null && wildcardSuperBound == null) {
  947.             // If T_i is a wildcard type argument (§4.5.1) of the form ?, then S_i is a fresh type variable whose
  948.             // upper bound is U_i[A_1 := S_1, ..., A_n := S_n] and whose lower bound is the null type (§4.1).
  949.             newUpperBound = originalUpperBound;
  950.             newLowerBound = getNullType();
  951.         } else if (wildcardSuperBound == null) {
  952.             // If T_i is a wildcard type argument of the form ? extends B_i, then S_i is a fresh type variable whose
  953.             // upper bound is glb(B_i, U_i[A_1 := S_1, ..., A_n := S_n]) and whose lower bound is the null type.
  954.             //
  955.             // glb(V_1, ..., V_m) is defined as V_1 & ... & V_m.
  956.             // It is a compile-time error if, for any two classes (not interfaces) V_i and V_j, V_i is not a
  957.             // subclass of V_j or vice versa.
  958.             newUpperBound = getIntersectionType(greatestLowerBound(wildcardExtendsBound, originalUpperBound));
  959.             newLowerBound = getNullType();
  960.         } else {
  961.             // If T_i is a wildcard type argument of the form ? super B_i, then S_i is a fresh type variable whose
  962.             // upper bound is U_i[A_1 := S1, ..., A_n := S_n] and whose lower bound is B_i.
  963.             assert wildcardExtendsBound == null;

  964.             newUpperBound = originalUpperBound;
  965.             newLowerBound = wildcardSuperBound;
  966.         }

  967.         return getTypeVariable(typeParameter, newUpperBound, newLowerBound, wildcardArgument);
  968.     }

  969.     /**
  970.      * Returns the capture conversion of the given type, as specified by JLS §5.1.10.
  971.      *
  972.      * @param type the type to be converted
  973.      * @return the result of applying capture conversion
  974.      * @throws IllegalArgumentException if given an executable or package type
  975.      */
  976.     @Override
  977.     public final TypeMirror capture(TypeMirror type) {
  978.         Objects.requireNonNull(type);
  979.         requireValidType(type);

  980.         // JLS §5.1.10 states: "Capture conversion on any type other than a parameterized type (§4.5) acts as an
  981.         // identity conversion (§5.1.1)."
  982.         if (type.getKind() != TypeKind.DECLARED) {
  983.             return type;
  984.         }

  985.         DeclaredType declaredType = (DeclaredType) type;
  986.         List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
  987.         if (typeArguments.isEmpty()) {
  988.             return declaredType;
  989.         }

  990.         TypeElement typeDeclaration = (TypeElement) declaredType.asElement();
  991.         Iterator<? extends TypeMirror> typeArgumentIterator = typeArguments.iterator();
  992.         Iterator<? extends TypeParameterElement> typeParameterIterator = typeDeclaration.getTypeParameters().iterator();
  993.         TypeMirror[] newArguments = new TypeMirror[typeArguments.size()];
  994.         Map<TypeParameterElement, TypeMirror> substitutions = new LinkedHashMap<>();
  995.         for (int index = 0; index < newArguments.length; ++index) {
  996.             TypeMirror typeArgument = typeArgumentIterator.next();
  997.             TypeParameterElement typeParameter = typeParameterIterator.next();
  998.             TypeMirror substitution;

  999.             if (typeArgument.getKind() != TypeKind.WILDCARD) {
  1000.                 newArguments[index] = typeArgument;
  1001.                 substitution = typeArgument;
  1002.             } else {
  1003.                 // For the intermediate declared type (see below), we need the original type variable corresponding to
  1004.                 // the formal type parameter. Only original type variables will be replaced by the substitutionVisitor.
  1005.                 newArguments[index] = typeParameter.asType();
  1006.                 substitution = captureWildcardArgument((WildcardType) typeArgument, typeParameter);
  1007.             }
  1008.             substitutions.put(typeParameter, substitution);
  1009.         }

  1010.         TypeMirror enclosingType = declaredType.getEnclosingType();

  1011.         // Construct intermediateDeclaredType that already has type variables in its argument list instead of wildcard
  1012.         // arguments.
  1013.         DeclaredType intermediateDeclaredType;
  1014.         if (enclosingType.getKind() == TypeKind.DECLARED) {
  1015.             intermediateDeclaredType = getDeclaredType((DeclaredType) enclosingType, typeDeclaration, newArguments);
  1016.         } else {
  1017.             intermediateDeclaredType = getDeclaredType(typeDeclaration, newArguments);
  1018.         }

  1019.         return substitute(intermediateDeclaredType, substitutions);
  1020.     }

  1021.     /**
  1022.      * Returns a new type variable that corresponds to the given formal type parameter and that has the given actual
  1023.      * upper and lower bounds.
  1024.      *
  1025.      * <p>This method is primarily needed during capture conversion, in order to create a fresh type variable that
  1026.      * overrides the bounds of the formal type parameter it represents. This method is also called during substitution.
  1027.      * As an example, given a formal type parameter {@code T extends Object} and an upper bound {@code Number}, this
  1028.      * method returns the type variable {@code T} with upper bound {@code Number}.
  1029.      *
  1030.      * <p>This method is not suited for creating type variables with recursive type bounds if these bounds override the
  1031.      * bounds of the formal type parameter (as only happens during capture conversion). In order to create such a type
  1032.      * variable, this method may be used to create an interim type variable, where the (overridden) upper and lower
  1033.      * bounds should only reference the type variable returned by {@link TypeParameterElement#asType()}. As a second
  1034.      * step, {@link #substitute(TypeMirror, Map)} may then be used to substitute the original type variable with the
  1035.      * interim type variable. The result will be a fresh type variable with the overridden bounds, and these bounds
  1036.      * will reference the fresh type variable instead of the original type variable.
  1037.      *
  1038.      * @param typeParameter the formal type parameter
  1039.      * @param upperBound the upper bound for the new type variable, may contain recursive references to
  1040.      *     {@code typeParameter.asType()}
  1041.      * @param lowerBound the lower bound for the new type variable, may contain recursive references to
  1042.      *     {@code typeParameter.asType()}
  1043.      * @param capturedTypeArgument the wildcard type argument that new type variable captures as part of a capture
  1044.      *     conversion (§5.1.10 JLS), or {@code null} if the new type variable is not the result of a capture conversion
  1045.      * @return the new type variable
  1046.      * @throws NullPointerException if any of the first three arguments is null
  1047.      */
  1048.     protected TypeVariable getTypeVariable(TypeParameterElement typeParameter, TypeMirror upperBound,
  1049.             TypeMirror lowerBound, @Nullable WildcardType capturedTypeArgument) {
  1050.         Objects.requireNonNull(typeParameter);
  1051.         Objects.requireNonNull(upperBound);
  1052.         Objects.requireNonNull(lowerBound);
  1053.         requireValidType(upperBound);
  1054.         requireValidType(lowerBound);
  1055.         requireValidType(capturedTypeArgument);

  1056.         TypeVariable typeVariable = createTypeVariable(typeParameter, capturedTypeArgument);
  1057.         setTypeVariableBounds(typeVariable, upperBound, lowerBound);
  1058.         return typeVariable;
  1059.     }

  1060.     /**
  1061.      * Creates a new <em>unfinished</em> type variable for the given formal parameter.
  1062.      *
  1063.      * <p>Whenever this method is called within this class, the returned type variable is guaranteed to be passed to
  1064.      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} before being used as a {@link TypeVariable}
  1065.      * instance. That is, the returned type variable is considered to be under construction until being passed to
  1066.      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)}, and only after that method call, the type
  1067.      * variable will have to satisfy the contract specified by interface {@link TypeVariable} and its super-interfaces.
  1068.      *
  1069.      * <p>Before {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} is called on the returned
  1070.      * {@link TypeVariable}, calling either {@link TypeVariable#getUpperBound()} or {@link TypeVariable#getLowerBound()}
  1071.      * must trigger an {@link IllegalStateException}.
  1072.      *
  1073.      * <p>Note that the previous paragraph does not guarantee that
  1074.      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} is always called on the newly returned
  1075.      * type-variable instance. If any exception occurs before the new type-variable could be used, then
  1076.      * {@link #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)} may not be called (even if the exception is
  1077.      * unrelated to the construction of the new type-variable instance).
  1078.      *
  1079.      * <p>The {@link TypeVariable} interface does not provide access to captured wildcard type arguments. It can be
  1080.      * retrieved by calling {@link #capturedTypeArgument(TypeVariable)} instead.
  1081.      *
  1082.      * @param typeParameter the formal type parameter
  1083.      * @param capturedTypeArgument the wildcard type argument that new type variable captures as part of a capture
  1084.      *     conversion (§5.1.10 JLS), or {@code null} if the new type variable is not the result of a capture conversion
  1085.      * @return new unfinished type variable for the given formal parameter, which may not yet satisfy the contracts
  1086.      *     of {@link TypeVariable}
  1087.      * @see #setTypeVariableBounds(TypeVariable, TypeMirror, TypeMirror)
  1088.      * @see #capturedTypeArgument(TypeVariable)
  1089.      * @throws NullPointerException if {@code typeParameter} is null
  1090.      */
  1091.     protected abstract TypeVariable createTypeVariable(TypeParameterElement typeParameter,
  1092.         @Nullable WildcardType capturedTypeArgument);

  1093.     /**
  1094.      * Sets the bounds of a type variable previously returned by
  1095.      * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
  1096.      *
  1097.      * <p>Before an (unfinished) type-variable instance returned by
  1098.      * {@link #createTypeVariable(TypeParameterElement, WildcardType)} is used by this class, this method is guaranteed
  1099.      * to be called exactly once.
  1100.      *
  1101.      * <p>Implementations that create effectively immutable {@link TypeMirror} instances may use this method to "freeze"
  1102.      * the given type-variable instance.
  1103.      *
  1104.      * @param typeVariable type variable previously returned by
  1105.      *     {@link #createTypeVariable(TypeParameterElement, WildcardType)}
  1106.      * @param upperBound Upper bound for the given type variable. If no explicit upper bound is used, a
  1107.      *     {@link DeclaredType} representing {@link Object} will be passed.
  1108.      * @param lowerBound Lower bound for the given type variable. This may a {@link NullType} instance, unless capture
  1109.      *     conversion produced a type variable with a non-trivial lower bound.
  1110.      * @see #createTypeVariable(TypeParameterElement, WildcardType)
  1111.      */
  1112.     protected abstract void setTypeVariableBounds(TypeVariable typeVariable, TypeMirror upperBound,
  1113.         TypeMirror lowerBound);

  1114.     /**
  1115.      * Returns the captured wildcard type argument of the given type variable, or null if the given type variable is not
  1116.      * the result of a capture conversion.
  1117.      *
  1118.      * <p>This method returns the wildcard type argument that was previously passed to
  1119.      * {@link #createTypeVariable(TypeParameterElement, WildcardType)}.
  1120.      *
  1121.      * @param typeVariable the type variable that may be the result of a capture conversion
  1122.      * @return the captured wildcard type argument, or null if not applicable
  1123.      */
  1124.     @Nullable
  1125.     protected abstract WildcardType capturedTypeArgument(TypeVariable typeVariable);

  1126.     /**
  1127.      * Returns a new intersection type. At least one bounds needs to be given.
  1128.      *
  1129.      * @param bounds the bounds of the new intersection type
  1130.      * @return the new intersection type
  1131.      * @throws IllegalArgumentException if the given array is empty
  1132.      */
  1133.     public abstract IntersectionType getIntersectionType(TypeMirror... bounds);

  1134.     /**
  1135.      * Visitor of {@link TypeMirror} instances that appends the {@link String} representation to the
  1136.      * {@link StringBuilder} instance passed as visitor argument.
  1137.      *
  1138.      * <p>This visitor is only used within this class and only on <em>valid</em> {@link TypeMirror} instances. Hence, it
  1139.      * can be asserted that the visitor parameter is always non-null.
  1140.      *
  1141.      * @see #requireValidType(TypeMirror)
  1142.      */
  1143.     private final class ToStringVisitor extends ExtendedTypeKindVisitor7<Void, StringBuilder> {
  1144.         @Override
  1145.         public Void visitPrimitive(PrimitiveType primitiveType, @Nullable StringBuilder stringBuilder) {
  1146.             assert stringBuilder != null;
  1147.             stringBuilder.append(primitiveType.getKind().toString().toLowerCase());
  1148.             return null;
  1149.         }

  1150.         @Override
  1151.         public Void visitNull(NullType nullType, @Nullable StringBuilder stringBuilder) {
  1152.             assert stringBuilder != null;
  1153.             stringBuilder.append("null");
  1154.             return null;
  1155.         }

  1156.         @Override
  1157.         public Void visitNoType(NoType noType, @Nullable StringBuilder stringBuilder) {
  1158.             assert stringBuilder != null;
  1159.             stringBuilder.append(noType.getKind().toString().toLowerCase());
  1160.             return null;
  1161.         }

  1162.         @Override
  1163.         public Void visitDeclared(DeclaredType declaredType, @Nullable StringBuilder stringBuilder) {
  1164.             assert stringBuilder != null;
  1165.             TypeMirror enclosingType = declaredType.getEnclosingType();
  1166.             TypeElement typeElement = (TypeElement) declaredType.asElement();
  1167.             if (enclosingType.getKind() == TypeKind.DECLARED) {
  1168.                 visitDeclared((DeclaredType) enclosingType, stringBuilder);
  1169.                 stringBuilder.append('.').append(typeElement.getSimpleName());
  1170.             } else {
  1171.                 stringBuilder.append(typeElement.getQualifiedName());
  1172.             }

  1173.             List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
  1174.             if (!typeArguments.isEmpty()) {
  1175.                 stringBuilder.append('<');
  1176.                 appendList(stringBuilder, typeArguments, ", ");
  1177.                 stringBuilder.append('>');
  1178.             }
  1179.             return null;
  1180.         }

  1181.         @Override
  1182.         public Void visitArray(ArrayType arrayType, @Nullable StringBuilder stringBuilder) {
  1183.             assert stringBuilder != null;
  1184.             arrayType.getComponentType().accept(this, stringBuilder);
  1185.             stringBuilder.append("[]");
  1186.             return null;
  1187.         }

  1188.         @Override
  1189.         public Void visitTypeVariable(TypeVariable typeVariable, @Nullable StringBuilder stringBuilder) {
  1190.             assert stringBuilder != null;
  1191.             @Nullable WildcardType capturedTypeArgument = capturedTypeArgument(typeVariable);
  1192.             if (capturedTypeArgument != null) {
  1193.                 stringBuilder.append("capture<");
  1194.                 capturedTypeArgument.accept(this, stringBuilder);
  1195.                 stringBuilder.append('>');
  1196.             } else {
  1197.                 stringBuilder.append(typeVariable.asElement().getSimpleName());
  1198.             }
  1199.             return null;
  1200.         }

  1201.         @Override
  1202.         public Void visitWildcard(WildcardType wildcardTypeArgument, @Nullable StringBuilder stringBuilder) {
  1203.             assert stringBuilder != null;
  1204.             stringBuilder.append('?');
  1205.             @Nullable TypeMirror extendsBound = wildcardTypeArgument.getExtendsBound();
  1206.             if (extendsBound != null) {
  1207.                 stringBuilder.append(" extends ");
  1208.                 extendsBound.accept(this, stringBuilder);
  1209.             }
  1210.             @Nullable TypeMirror superBound = wildcardTypeArgument.getSuperBound();
  1211.             if (superBound != null) {
  1212.                 stringBuilder.append(" super ");
  1213.                 superBound.accept(this, stringBuilder);
  1214.             }
  1215.             return null;
  1216.         }

  1217.         @Override
  1218.         public Void visitIntersection(IntersectionType intersectionType, @Nullable StringBuilder stringBuilder) {
  1219.             assert stringBuilder != null;
  1220.             appendList(stringBuilder, intersectionType.getBounds(), " & ");
  1221.             return null;
  1222.         }

  1223.         private void appendList(StringBuilder stringBuilder, List<? extends TypeMirror> types, String glue) {
  1224.             assert !types.isEmpty();

  1225.             boolean first = true;
  1226.             for (TypeMirror type: types) {
  1227.                 if (first) {
  1228.                     first = false;
  1229.                 } else {
  1230.                     stringBuilder.append(glue);
  1231.                 }
  1232.                 type.accept(this, stringBuilder);
  1233.             }
  1234.         }
  1235.     }

  1236.     /**
  1237.      * Returns the canonical string representation of the given type.
  1238.      *
  1239.      * @param type type
  1240.      * @return canonical string representation of the given type
  1241.      */
  1242.     public final String toString(TypeMirror type) {
  1243.         requireValidType(Objects.requireNonNull(type));

  1244.         StringBuilder stringBuilder = new StringBuilder(DEFAULT_STRING_BUILDER_SIZE);
  1245.         type.accept(toStringVisitor, stringBuilder);
  1246.         return stringBuilder.toString();
  1247.     }
  1248. }