001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.reflect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020import static java.util.Arrays.asList;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.Joiner;
024import com.google.common.base.Objects;
025import com.google.common.collect.ImmutableMap;
026import com.google.common.collect.Maps;
027import java.lang.reflect.GenericArrayType;
028import java.lang.reflect.ParameterizedType;
029import java.lang.reflect.Type;
030import java.lang.reflect.TypeVariable;
031import java.lang.reflect.WildcardType;
032import java.util.Arrays;
033import java.util.LinkedHashSet;
034import java.util.Map;
035import java.util.Map.Entry;
036import java.util.Set;
037import java.util.concurrent.atomic.AtomicInteger;
038import org.checkerframework.checker.nullness.compatqual.NullableDecl;
039
040/**
041 * An object of this class encapsulates type mappings from type variables. Mappings are established
042 * with {@link #where} and types are resolved using {@link #resolveType}.
043 *
044 * <p>Note that usually type mappings are already implied by the static type hierarchy (for example,
045 * the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in
046 * the context of {@code class MyStringList implements List<String>}. In such case, prefer to use
047 * {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be
048 * used when the type mapping isn't implied by the static type hierarchy, but provided through other
049 * means such as an annotation or external configuration file.
050 *
051 * @author Ben Yu
052 * @since 15.0
053 */
054@Beta
055public final class TypeResolver {
056
057  private final TypeTable typeTable;
058
059  public TypeResolver() {
060    this.typeTable = new TypeTable();
061  }
062
063  private TypeResolver(TypeTable typeTable) {
064    this.typeTable = typeTable;
065  }
066
067  static TypeResolver accordingTo(Type type) {
068    return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(type));
069  }
070
071  /**
072   * Returns a new {@code TypeResolver} with type variables in {@code formal} mapping to types in
073   * {@code actual}.
074   *
075   * <p>For example, if {@code formal} is a {@code TypeVariable T}, and {@code actual} is {@code
076   * String.class}, then {@code new TypeResolver().where(formal, actual)} will {@linkplain
077   * #resolveType resolve} {@code ParameterizedType List<T>} to {@code List<String>}, and resolve
078   * {@code Map<T, Something>} to {@code Map<String, Something>} etc. Similarly, {@code formal} and
079   * {@code actual} can be {@code Map<K, V>} and {@code Map<String, Integer>} respectively, or they
080   * can be {@code E[]} and {@code String[]} respectively, or even any arbitrary combination
081   * thereof.
082   *
083   * @param formal The type whose type variables or itself is mapped to other type(s). It's almost
084   *     always a bug if {@code formal} isn't a type variable and contains no type variable. Make
085   *     sure you are passing the two parameters in the right order.
086   * @param actual The type that the formal type variable(s) are mapped to. It can be or contain yet
087   *     other type variables, in which case these type variables will be further resolved if
088   *     corresponding mappings exist in the current {@code TypeResolver} instance.
089   */
090  public TypeResolver where(Type formal, Type actual) {
091    Map<TypeVariableKey, Type> mappings = Maps.newHashMap();
092    populateTypeMappings(mappings, checkNotNull(formal), checkNotNull(actual));
093    return where(mappings);
094  }
095
096  /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */
097  TypeResolver where(Map<TypeVariableKey, ? extends Type> mappings) {
098    return new TypeResolver(typeTable.where(mappings));
099  }
100
101  private static void populateTypeMappings(
102      final Map<TypeVariableKey, Type> mappings, Type from, final Type to) {
103    if (from.equals(to)) {
104      return;
105    }
106    new TypeVisitor() {
107      @Override
108      void visitTypeVariable(TypeVariable<?> typeVariable) {
109        mappings.put(new TypeVariableKey(typeVariable), to);
110      }
111
112      @Override
113      void visitWildcardType(WildcardType fromWildcardType) {
114        if (!(to instanceof WildcardType)) {
115          return; // okay to say <?> is anything
116        }
117        WildcardType toWildcardType = (WildcardType) to;
118        Type[] fromUpperBounds = fromWildcardType.getUpperBounds();
119        Type[] toUpperBounds = toWildcardType.getUpperBounds();
120        Type[] fromLowerBounds = fromWildcardType.getLowerBounds();
121        Type[] toLowerBounds = toWildcardType.getLowerBounds();
122        checkArgument(
123            fromUpperBounds.length == toUpperBounds.length
124                && fromLowerBounds.length == toLowerBounds.length,
125            "Incompatible type: %s vs. %s",
126            fromWildcardType,
127            to);
128        for (int i = 0; i < fromUpperBounds.length; i++) {
129          populateTypeMappings(mappings, fromUpperBounds[i], toUpperBounds[i]);
130        }
131        for (int i = 0; i < fromLowerBounds.length; i++) {
132          populateTypeMappings(mappings, fromLowerBounds[i], toLowerBounds[i]);
133        }
134      }
135
136      @Override
137      void visitParameterizedType(ParameterizedType fromParameterizedType) {
138        if (to instanceof WildcardType) {
139          return; // Okay to say Foo<A> is <?>
140        }
141        ParameterizedType toParameterizedType = expectArgument(ParameterizedType.class, to);
142        if (fromParameterizedType.getOwnerType() != null
143            && toParameterizedType.getOwnerType() != null) {
144          populateTypeMappings(
145              mappings, fromParameterizedType.getOwnerType(), toParameterizedType.getOwnerType());
146        }
147        checkArgument(
148            fromParameterizedType.getRawType().equals(toParameterizedType.getRawType()),
149            "Inconsistent raw type: %s vs. %s",
150            fromParameterizedType,
151            to);
152        Type[] fromArgs = fromParameterizedType.getActualTypeArguments();
153        Type[] toArgs = toParameterizedType.getActualTypeArguments();
154        checkArgument(
155            fromArgs.length == toArgs.length,
156            "%s not compatible with %s",
157            fromParameterizedType,
158            toParameterizedType);
159        for (int i = 0; i < fromArgs.length; i++) {
160          populateTypeMappings(mappings, fromArgs[i], toArgs[i]);
161        }
162      }
163
164      @Override
165      void visitGenericArrayType(GenericArrayType fromArrayType) {
166        if (to instanceof WildcardType) {
167          return; // Okay to say A[] is <?>
168        }
169        Type componentType = Types.getComponentType(to);
170        checkArgument(componentType != null, "%s is not an array type.", to);
171        populateTypeMappings(mappings, fromArrayType.getGenericComponentType(), componentType);
172      }
173
174      @Override
175      void visitClass(Class<?> fromClass) {
176        if (to instanceof WildcardType) {
177          return; // Okay to say Foo is <?>
178        }
179        // Can't map from a raw class to anything other than itself or a wildcard.
180        // You can't say "assuming String is Integer".
181        // And we don't support "assuming String is T"; user has to say "assuming T is String".
182        throw new IllegalArgumentException("No type mapping from " + fromClass + " to " + to);
183      }
184    }.visit(from);
185  }
186
187  /**
188   * Resolves all type variables in {@code type} and all downstream types and returns a
189   * corresponding type with type variables resolved.
190   */
191  public Type resolveType(Type type) {
192    checkNotNull(type);
193    if (type instanceof TypeVariable) {
194      return typeTable.resolve((TypeVariable<?>) type);
195    } else if (type instanceof ParameterizedType) {
196      return resolveParameterizedType((ParameterizedType) type);
197    } else if (type instanceof GenericArrayType) {
198      return resolveGenericArrayType((GenericArrayType) type);
199    } else if (type instanceof WildcardType) {
200      return resolveWildcardType((WildcardType) type);
201    } else {
202      // if Class<?>, no resolution needed, we are done.
203      return type;
204    }
205  }
206
207  private Type[] resolveTypes(Type[] types) {
208    Type[] result = new Type[types.length];
209    for (int i = 0; i < types.length; i++) {
210      result[i] = resolveType(types[i]);
211    }
212    return result;
213  }
214
215  private WildcardType resolveWildcardType(WildcardType type) {
216    Type[] lowerBounds = type.getLowerBounds();
217    Type[] upperBounds = type.getUpperBounds();
218    return new Types.WildcardTypeImpl(resolveTypes(lowerBounds), resolveTypes(upperBounds));
219  }
220
221  private Type resolveGenericArrayType(GenericArrayType type) {
222    Type componentType = type.getGenericComponentType();
223    Type resolvedComponentType = resolveType(componentType);
224    return Types.newArrayType(resolvedComponentType);
225  }
226
227  private ParameterizedType resolveParameterizedType(ParameterizedType type) {
228    Type owner = type.getOwnerType();
229    Type resolvedOwner = (owner == null) ? null : resolveType(owner);
230    Type resolvedRawType = resolveType(type.getRawType());
231
232    Type[] args = type.getActualTypeArguments();
233    Type[] resolvedArgs = resolveTypes(args);
234    return Types.newParameterizedTypeWithOwner(
235        resolvedOwner, (Class<?>) resolvedRawType, resolvedArgs);
236  }
237
238  private static <T> T expectArgument(Class<T> type, Object arg) {
239    try {
240      return type.cast(arg);
241    } catch (ClassCastException e) {
242      throw new IllegalArgumentException(arg + " is not a " + type.getSimpleName());
243    }
244  }
245
246  /** A TypeTable maintains mapping from {@link TypeVariable} to types. */
247  private static class TypeTable {
248    private final ImmutableMap<TypeVariableKey, Type> map;
249
250    TypeTable() {
251      this.map = ImmutableMap.of();
252    }
253
254    private TypeTable(ImmutableMap<TypeVariableKey, Type> map) {
255      this.map = map;
256    }
257
258    /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */
259    final TypeTable where(Map<TypeVariableKey, ? extends Type> mappings) {
260      ImmutableMap.Builder<TypeVariableKey, Type> builder = ImmutableMap.builder();
261      builder.putAll(map);
262      for (Entry<TypeVariableKey, ? extends Type> mapping : mappings.entrySet()) {
263        TypeVariableKey variable = mapping.getKey();
264        Type type = mapping.getValue();
265        checkArgument(!variable.equalsType(type), "Type variable %s bound to itself", variable);
266        builder.put(variable, type);
267      }
268      return new TypeTable(builder.build());
269    }
270
271    final Type resolve(final TypeVariable<?> var) {
272      final TypeTable unguarded = this;
273      TypeTable guarded =
274          new TypeTable() {
275            @Override
276            public Type resolveInternal(TypeVariable<?> intermediateVar, TypeTable forDependent) {
277              if (intermediateVar.getGenericDeclaration().equals(var.getGenericDeclaration())) {
278                return intermediateVar;
279              }
280              return unguarded.resolveInternal(intermediateVar, forDependent);
281            }
282          };
283      return resolveInternal(var, guarded);
284    }
285
286    /**
287     * Resolves {@code var} using the encapsulated type mapping. If it maps to yet another
288     * non-reified type or has bounds, {@code forDependants} is used to do further resolution, which
289     * doesn't try to resolve any type variable on generic declarations that are already being
290     * resolved.
291     *
292     * <p>Should only be called and overridden by {@link #resolve(TypeVariable)}.
293     */
294    Type resolveInternal(TypeVariable<?> var, TypeTable forDependants) {
295      Type type = map.get(new TypeVariableKey(var));
296      if (type == null) {
297        Type[] bounds = var.getBounds();
298        if (bounds.length == 0) {
299          return var;
300        }
301        Type[] resolvedBounds = new TypeResolver(forDependants).resolveTypes(bounds);
302        /*
303         * We'd like to simply create our own TypeVariable with the newly resolved bounds. There's
304         * just one problem: Starting with JDK 7u51, the JDK TypeVariable's equals() method doesn't
305         * recognize instances of our TypeVariable implementation. This is a problem because users
306         * compare TypeVariables from the JDK against TypeVariables returned by TypeResolver. To
307         * work with all JDK versions, TypeResolver must return the appropriate TypeVariable
308         * implementation in each of the three possible cases:
309         *
310         * 1. Prior to JDK 7u51, the JDK TypeVariable implementation interoperates with ours.
311         * Therefore, we can always create our own TypeVariable.
312         *
313         * 2. Starting with JDK 7u51, the JDK TypeVariable implementations does not interoperate
314         * with ours. Therefore, we have to be careful about whether we create our own TypeVariable:
315         *
316         * 2a. If the resolved types are identical to the original types, then we can return the
317         * original, identical JDK TypeVariable. By doing so, we sidestep the problem entirely.
318         *
319         * 2b. If the resolved types are different from the original types, things are trickier. The
320         * only way to get a TypeVariable instance for the resolved types is to create our own. The
321         * created TypeVariable will not interoperate with any JDK TypeVariable. But this is OK: We
322         * don't _want_ our new TypeVariable to be equal to the JDK TypeVariable because it has
323         * _different bounds_ than the JDK TypeVariable. And it wouldn't make sense for our new
324         * TypeVariable to be equal to any _other_ JDK TypeVariable, either, because any other JDK
325         * TypeVariable must have a different declaration or name. The only TypeVariable that our
326         * new TypeVariable _will_ be equal to is an equivalent TypeVariable that was also created
327         * by us. And that equality is guaranteed to hold because it doesn't involve the JDK
328         * TypeVariable implementation at all.
329         */
330        if (Types.NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY
331            && Arrays.equals(bounds, resolvedBounds)) {
332          return var;
333        }
334        return Types.newArtificialTypeVariable(
335            var.getGenericDeclaration(), var.getName(), resolvedBounds);
336      }
337      // in case the type is yet another type variable.
338      return new TypeResolver(forDependants).resolveType(type);
339    }
340  }
341
342  private static final class TypeMappingIntrospector extends TypeVisitor {
343
344    private static final WildcardCapturer wildcardCapturer = new WildcardCapturer();
345
346    private final Map<TypeVariableKey, Type> mappings = Maps.newHashMap();
347
348    /**
349     * Returns type mappings using type parameters and type arguments found in the generic
350     * superclass and the super interfaces of {@code contextClass}.
351     */
352    static ImmutableMap<TypeVariableKey, Type> getTypeMappings(Type contextType) {
353      TypeMappingIntrospector introspector = new TypeMappingIntrospector();
354      introspector.visit(wildcardCapturer.capture(contextType));
355      return ImmutableMap.copyOf(introspector.mappings);
356    }
357
358    @Override
359    void visitClass(Class<?> clazz) {
360      visit(clazz.getGenericSuperclass());
361      visit(clazz.getGenericInterfaces());
362    }
363
364    @Override
365    void visitParameterizedType(ParameterizedType parameterizedType) {
366      Class<?> rawClass = (Class<?>) parameterizedType.getRawType();
367      TypeVariable<?>[] vars = rawClass.getTypeParameters();
368      Type[] typeArgs = parameterizedType.getActualTypeArguments();
369      checkState(vars.length == typeArgs.length);
370      for (int i = 0; i < vars.length; i++) {
371        map(new TypeVariableKey(vars[i]), typeArgs[i]);
372      }
373      visit(rawClass);
374      visit(parameterizedType.getOwnerType());
375    }
376
377    @Override
378    void visitTypeVariable(TypeVariable<?> t) {
379      visit(t.getBounds());
380    }
381
382    @Override
383    void visitWildcardType(WildcardType t) {
384      visit(t.getUpperBounds());
385    }
386
387    private void map(final TypeVariableKey var, final Type arg) {
388      if (mappings.containsKey(var)) {
389        // Mapping already established
390        // This is possible when following both superClass -> enclosingClass
391        // and enclosingclass -> superClass paths.
392        // Since we follow the path of superclass first, enclosing second,
393        // superclass mapping should take precedence.
394        return;
395      }
396      // First, check whether var -> arg forms a cycle
397      for (Type t = arg; t != null; t = mappings.get(TypeVariableKey.forLookup(t))) {
398        if (var.equalsType(t)) {
399          // cycle detected, remove the entire cycle from the mapping so that
400          // each type variable resolves deterministically to itself.
401          // Otherwise, a F -> T cycle will end up resolving both F and T
402          // nondeterministically to either F or T.
403          for (Type x = arg; x != null; x = mappings.remove(TypeVariableKey.forLookup(x))) {}
404          return;
405        }
406      }
407      mappings.put(var, arg);
408    }
409  }
410
411  // This is needed when resolving types against a context with wildcards
412  // For example:
413  // class Holder<T> {
414  //   void set(T data) {...}
415  // }
416  // Holder<List<?>> should *not* resolve the set() method to set(List<?> data).
417  // Instead, it should create a capture of the wildcard so that set() rejects any List<T>.
418  private static class WildcardCapturer {
419
420    private final AtomicInteger id;
421
422    WildcardCapturer() {
423      this(new AtomicInteger());
424    }
425
426    private WildcardCapturer(AtomicInteger id) {
427      this.id = id;
428    }
429
430    final Type capture(Type type) {
431      checkNotNull(type);
432      if (type instanceof Class) {
433        return type;
434      }
435      if (type instanceof TypeVariable) {
436        return type;
437      }
438      if (type instanceof GenericArrayType) {
439        GenericArrayType arrayType = (GenericArrayType) type;
440        return Types.newArrayType(
441            notForTypeVariable().capture(arrayType.getGenericComponentType()));
442      }
443      if (type instanceof ParameterizedType) {
444        ParameterizedType parameterizedType = (ParameterizedType) type;
445        Class<?> rawType = (Class<?>) parameterizedType.getRawType();
446        TypeVariable<?>[] typeVars = rawType.getTypeParameters();
447        Type[] typeArgs = parameterizedType.getActualTypeArguments();
448        for (int i = 0; i < typeArgs.length; i++) {
449          typeArgs[i] = forTypeVariable(typeVars[i]).capture(typeArgs[i]);
450        }
451        return Types.newParameterizedTypeWithOwner(
452            notForTypeVariable().captureNullable(parameterizedType.getOwnerType()),
453            rawType,
454            typeArgs);
455      }
456      if (type instanceof WildcardType) {
457        WildcardType wildcardType = (WildcardType) type;
458        Type[] lowerBounds = wildcardType.getLowerBounds();
459        if (lowerBounds.length == 0) { // ? extends something changes to capture-of
460          return captureAsTypeVariable(wildcardType.getUpperBounds());
461        } else {
462          // TODO(benyu): handle ? super T somehow.
463          return type;
464        }
465      }
466      throw new AssertionError("must have been one of the known types");
467    }
468
469    TypeVariable<?> captureAsTypeVariable(Type[] upperBounds) {
470      String name =
471          "capture#" + id.incrementAndGet() + "-of ? extends " + Joiner.on('&').join(upperBounds);
472      return Types.newArtificialTypeVariable(WildcardCapturer.class, name, upperBounds);
473    }
474
475    private WildcardCapturer forTypeVariable(final TypeVariable<?> typeParam) {
476      return new WildcardCapturer(id) {
477        @Override
478        TypeVariable<?> captureAsTypeVariable(Type[] upperBounds) {
479          Set<Type> combined = new LinkedHashSet<>(asList(upperBounds));
480          // Since this is an artifically generated type variable, we don't bother checking
481          // subtyping between declared type bound and actual type bound. So it's possible that we
482          // may generate something like <capture#1-of ? extends Foo&SubFoo>.
483          // Checking subtype between declared and actual type bounds
484          // adds recursive isSubtypeOf() call and feels complicated.
485          // There is no contract one way or another as long as isSubtypeOf() works as expected.
486          combined.addAll(asList(typeParam.getBounds()));
487          if (combined.size() > 1) { // Object is implicit and only useful if it's the only bound.
488            combined.remove(Object.class);
489          }
490          return super.captureAsTypeVariable(combined.toArray(new Type[0]));
491        }
492      };
493    }
494
495    private WildcardCapturer notForTypeVariable() {
496      return new WildcardCapturer(id);
497    }
498
499    private Type captureNullable(@NullableDecl Type type) {
500      if (type == null) {
501        return null;
502      }
503      return capture(type);
504    }
505  }
506
507  /**
508   * Wraps around {@code TypeVariable<?>} to ensure that any two type variables are equal as long as
509   * they are declared by the same {@link java.lang.reflect.GenericDeclaration} and have the same
510   * name, even if their bounds differ.
511   *
512   * <p>While resolving a type variable from a {@code var -> type} map, we don't care whether the
513   * type variable's bound has been partially resolved. As long as the type variable "identity"
514   * matches.
515   *
516   * <p>On the other hand, if for example we are resolving {@code List<A extends B>} to {@code
517   * List<A extends String>}, we need to compare that {@code <A extends B>} is unequal to {@code <A
518   * extends String>} in order to decide to use the transformed type instead of the original type.
519   */
520  static final class TypeVariableKey {
521    private final TypeVariable<?> var;
522
523    TypeVariableKey(TypeVariable<?> var) {
524      this.var = checkNotNull(var);
525    }
526
527    @Override
528    public int hashCode() {
529      return Objects.hashCode(var.getGenericDeclaration(), var.getName());
530    }
531
532    @Override
533    public boolean equals(Object obj) {
534      if (obj instanceof TypeVariableKey) {
535        TypeVariableKey that = (TypeVariableKey) obj;
536        return equalsTypeVariable(that.var);
537      } else {
538        return false;
539      }
540    }
541
542    @Override
543    public String toString() {
544      return var.toString();
545    }
546
547    /** Wraps {@code t} in a {@code TypeVariableKey} if it's a type variable. */
548    static TypeVariableKey forLookup(Type t) {
549      if (t instanceof TypeVariable) {
550        return new TypeVariableKey((TypeVariable<?>) t);
551      } else {
552        return null;
553      }
554    }
555
556    /**
557     * Returns true if {@code type} is a {@code TypeVariable} with the same name and declared by the
558     * same {@code GenericDeclaration}.
559     */
560    boolean equalsType(Type type) {
561      if (type instanceof TypeVariable) {
562        return equalsTypeVariable((TypeVariable<?>) type);
563      } else {
564        return false;
565      }
566    }
567
568    private boolean equalsTypeVariable(TypeVariable<?> that) {
569      return var.getGenericDeclaration().equals(that.getGenericDeclaration())
570          && var.getName().equals(that.getName());
571    }
572  }
573}