001/*
002 * Copyright (C) 2014 Square, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *    https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.avaje.jsonb.core;
017
018import io.avaje.jsonb.Types;
019
020import java.lang.annotation.Annotation;
021import java.lang.reflect.*;
022import java.util.*;
023
024/**
025 * Utility methods for defining Types.
026 */
027public final class Util {
028
029  static final Type[] EMPTY_TYPE_ARRAY = new Type[]{};
030
031  private Util() {
032  }
033
034  /**
035   * Returns an array type whose elements are all instances of {@code componentType}.
036   */
037  public static GenericArrayType arrayOf(Type elementType) {
038    return new Util.GenericArrayTypeImpl(elementType);
039  }
040
041  /**
042   * Returns a new parameterized type, applying {@code typeArguments} to {@code rawType}. Use this
043   * method if {@code rawType} is not enclosed in another type.
044   */
045  public static ParameterizedType newParameterizedType(Type rawType, Type... typeArguments) {
046    if (typeArguments.length == 0) {
047      throw new IllegalArgumentException("Missing type arguments for " + rawType);
048    }
049    return new Util.ParameterizedTypeImpl(null, rawType, typeArguments);
050  }
051
052  static boolean typesMatch(Type pattern, Type candidate) {
053    return Util.equals(pattern, candidate);
054  }
055
056  static boolean isAnnotationPresent(Set<? extends Annotation> annotations, Class<? extends Annotation> annotationClass) {
057    if (annotations.isEmpty()) return false; // Save an iterator in the common case.
058    for (Annotation annotation : annotations) {
059      if (annotation.annotationType() == annotationClass) return true;
060    }
061    return false;
062  }
063
064  static Type canonicalizeClass(Class<?> cls) {
065    return cls.isArray() ? new GenericArrayTypeImpl(canonicalize(cls.getComponentType())) : cls;
066  }
067
068  /**
069   * Returns a type that is functionally equal but not necessarily equal according to {@link
070   * Object#equals(Object) Object.equals()}.
071   */
072  static Type canonicalize(Type type) {
073    if (type instanceof Class) {
074      Class<?> c = (Class<?>) type;
075      return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;
076
077    } else if (type instanceof ParameterizedType) {
078      if (type instanceof ParameterizedTypeImpl) return type;
079      ParameterizedType p = (ParameterizedType) type;
080      return new ParameterizedTypeImpl(
081        p.getOwnerType(), p.getRawType(), p.getActualTypeArguments());
082
083    } else if (type instanceof GenericArrayType) {
084      if (type instanceof GenericArrayTypeImpl) return type;
085      GenericArrayType g = (GenericArrayType) type;
086      return new GenericArrayTypeImpl(g.getGenericComponentType());
087
088    } else if (type instanceof WildcardType) {
089      if (type instanceof WildcardTypeImpl) return type;
090      WildcardType w = (WildcardType) type;
091      return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
092
093    } else {
094      return type; // This type is unsupported!
095    }
096  }
097
098  /**
099   * If type is a "? extends X" wildcard, returns X; otherwise returns type unchanged.
100   */
101  static Type removeSubtypeWildcard(Type type) {
102    if (!(type instanceof WildcardType)) return type;
103
104    Type[] lowerBounds = ((WildcardType) type).getLowerBounds();
105    if (lowerBounds.length != 0) return type;
106
107    Type[] upperBounds = ((WildcardType) type).getUpperBounds();
108    if (upperBounds.length != 1) throw new IllegalArgumentException();
109
110    return upperBounds[0];
111  }
112
113  static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
114    return resolve(context, contextRawType, toResolve, new LinkedHashSet<TypeVariable<?>>());
115  }
116
117  private static Type resolve(
118    Type context,
119    Class<?> contextRawType,
120    Type toResolve,
121    Collection<TypeVariable<?>> visitedTypeVariables) {
122    // This implementation is made a little more complicated in an attempt to avoid object-creation.
123    while (true) {
124      if (toResolve instanceof TypeVariable) {
125        TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
126        if (visitedTypeVariables.contains(typeVariable)) {
127          // cannot reduce due to infinite recursion
128          return toResolve;
129        } else {
130          visitedTypeVariables.add(typeVariable);
131        }
132        toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
133        if (toResolve == typeVariable) return toResolve;
134
135      } else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
136        Class<?> original = (Class<?>) toResolve;
137        Type componentType = original.getComponentType();
138        Type newComponentType =
139          resolve(context, contextRawType, componentType, visitedTypeVariables);
140        return componentType == newComponentType ? original : arrayOf(newComponentType);
141
142      } else if (toResolve instanceof GenericArrayType) {
143        GenericArrayType original = (GenericArrayType) toResolve;
144        Type componentType = original.getGenericComponentType();
145        Type newComponentType =
146          resolve(context, contextRawType, componentType, visitedTypeVariables);
147        return componentType == newComponentType ? original : arrayOf(newComponentType);
148
149      } else if (toResolve instanceof ParameterizedType) {
150        ParameterizedType original = (ParameterizedType) toResolve;
151        Type ownerType = original.getOwnerType();
152        Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
153        boolean changed = newOwnerType != ownerType;
154
155        Type[] args = original.getActualTypeArguments();
156        for (int t = 0, length = args.length; t < length; t++) {
157          Type resolvedTypeArgument =
158            resolve(context, contextRawType, args[t], visitedTypeVariables);
159          if (resolvedTypeArgument != args[t]) {
160            if (!changed) {
161              args = args.clone();
162              changed = true;
163            }
164            args[t] = resolvedTypeArgument;
165          }
166        }
167
168        return changed
169          ? new ParameterizedTypeImpl(newOwnerType, original.getRawType(), args)
170          : original;
171
172      } else if (toResolve instanceof WildcardType) {
173        WildcardType original = (WildcardType) toResolve;
174        Type[] originalLowerBound = original.getLowerBounds();
175        Type[] originalUpperBound = original.getUpperBounds();
176
177        if (originalLowerBound.length == 1) {
178          Type lowerBound =
179            resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
180          if (lowerBound != originalLowerBound[0]) {
181            return supertypeOf(lowerBound);
182          }
183        } else if (originalUpperBound.length == 1) {
184          Type upperBound =
185            resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
186          if (upperBound != originalUpperBound[0]) {
187            return subtypeOf(upperBound);
188          }
189        }
190        return original;
191
192      } else {
193        return toResolve;
194      }
195    }
196  }
197
198  static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
199    Class<?> declaredByRaw = declaringClassOf(unknown);
200
201    // We can't reduce this further.
202    if (declaredByRaw == null) return unknown;
203
204    Type declaredBy = genericSupertype(context, contextRawType, declaredByRaw);
205    if (declaredBy instanceof ParameterizedType) {
206      int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
207      return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
208    }
209
210    return unknown;
211  }
212
213  /**
214   * Returns the generic supertype for {@code supertype}. For example, given a class {@code
215   * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
216   * result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
217   */
218  static Type genericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
219    if (toResolve == rawType) {
220      return context;
221    }
222
223    // we skip searching through interfaces if unknown is an interface
224    if (toResolve.isInterface()) {
225      Class<?>[] interfaces = rawType.getInterfaces();
226      for (int i = 0, length = interfaces.length; i < length; i++) {
227        if (interfaces[i] == toResolve) {
228          return rawType.getGenericInterfaces()[i];
229        } else if (toResolve.isAssignableFrom(interfaces[i])) {
230          return genericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
231        }
232      }
233    }
234
235    // check our supertypes
236    if (!rawType.isInterface()) {
237      while (rawType != Object.class) {
238        Class<?> rawSupertype = rawType.getSuperclass();
239        if (rawSupertype == toResolve) {
240          return rawType.getGenericSuperclass();
241        } else if (toResolve.isAssignableFrom(rawSupertype)) {
242          return genericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
243        }
244        rawType = rawSupertype;
245      }
246    }
247
248    // we can't resolve this further
249    return toResolve;
250  }
251
252  static int hashCodeOrZero(Object o) {
253    return o != null ? o.hashCode() : 0;
254  }
255
256  static String typeToString(Type type) {
257    return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
258  }
259
260  static int indexOf(Object[] array, Object toFind) {
261    for (int i = 0; i < array.length; i++) {
262      if (toFind.equals(array[i])) return i;
263    }
264    throw new NoSuchElementException();
265  }
266
267  /**
268   * Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
269   * a class.
270   */
271  static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
272    GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
273    return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null;
274  }
275
276  static void checkNotPrimitive(Type type) {
277    if ((type instanceof Class<?>) && ((Class<?>) type).isPrimitive()) {
278      throw new IllegalArgumentException("Unexpected primitive " + type + ". Use the boxed type.");
279    }
280  }
281
282  static final class ParameterizedTypeImpl implements ParameterizedType {
283    private final Type ownerType;
284    private final Type rawType;
285    public final Type[] typeArguments;
286
287    public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
288      // Require an owner type if the raw type needs it.
289      if (ownerType != null && rawType instanceof Class<?>) {
290        Class<?> enclosingClass = ((Class<?>) rawType).getEnclosingClass();
291        if (enclosingClass == null || Util.rawType(ownerType) != enclosingClass) {
292          throw new IllegalArgumentException("unexpected owner type for " + rawType + ": " + ownerType);
293
294        } else if (enclosingClass != null) {
295          throw new IllegalArgumentException("unexpected owner type for " + rawType + ": null");
296        }
297      }
298
299      this.ownerType = ownerType == null ? null : canonicalize(ownerType);
300      this.rawType = canonicalize(rawType);
301      this.typeArguments = typeArguments.clone();
302      for (int t = 0; t < this.typeArguments.length; t++) {
303        if (this.typeArguments[t] == null) throw new NullPointerException();
304        checkNotPrimitive(this.typeArguments[t]);
305        this.typeArguments[t] = canonicalize(this.typeArguments[t]);
306      }
307    }
308
309    @Override
310    public Type[] getActualTypeArguments() {
311      return typeArguments.clone();
312    }
313
314    @Override
315    public Type getRawType() {
316      return rawType;
317    }
318
319    @Override
320    public Type getOwnerType() {
321      return ownerType;
322    }
323
324    @Override
325    public boolean equals(Object other) {
326      return other instanceof ParameterizedType && Util.equals(this, (ParameterizedType) other);
327    }
328
329    @Override
330    public int hashCode() {
331      return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType);
332    }
333
334    @Override
335    public String toString() {
336      StringBuilder result = new StringBuilder(30 * (typeArguments.length + 1));
337      result.append(typeToString(rawType));
338
339      if (typeArguments.length == 0) {
340        return result.toString();
341      }
342
343      result.append("<").append(typeToString(typeArguments[0]));
344      for (int i = 1; i < typeArguments.length; i++) {
345        result.append(", ").append(typeToString(typeArguments[i]));
346      }
347      return result.append(">").toString();
348    }
349  }
350
351  static final class GenericArrayTypeImpl implements GenericArrayType {
352    private final Type componentType;
353
354    GenericArrayTypeImpl(Type componentType) {
355      this.componentType = canonicalize(componentType);
356    }
357
358    @Override
359    public Type getGenericComponentType() {
360      return componentType;
361    }
362
363    @Override
364    public boolean equals(Object o) {
365      return o instanceof GenericArrayType && Util.equals(this, (GenericArrayType) o);
366    }
367
368    @Override
369    public int hashCode() {
370      return componentType.hashCode();
371    }
372
373    @Override
374    public String toString() {
375      return typeToString(componentType) + "[]";
376    }
377  }
378
379  /**
380   * The WildcardType interface supports multiple upper bounds and multiple lower bounds. We only
381   * support what the Java 6 language needs - at most one bound. If a lower bound is set, the upper
382   * bound must be Object.class.
383   */
384  static final class WildcardTypeImpl implements WildcardType {
385    private final Type upperBound;
386    private final Type lowerBound;
387
388    WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
389      if (lowerBounds.length > 1) throw new IllegalArgumentException();
390      if (upperBounds.length != 1) throw new IllegalArgumentException();
391
392      if (lowerBounds.length == 1) {
393        if (lowerBounds[0] == null) throw new NullPointerException();
394        checkNotPrimitive(lowerBounds[0]);
395        if (upperBounds[0] != Object.class) throw new IllegalArgumentException();
396        this.lowerBound = canonicalize(lowerBounds[0]);
397        this.upperBound = Object.class;
398
399      } else {
400        if (upperBounds[0] == null) throw new NullPointerException();
401        checkNotPrimitive(upperBounds[0]);
402        this.lowerBound = null;
403        this.upperBound = canonicalize(upperBounds[0]);
404      }
405    }
406
407    @Override
408    public Type[] getUpperBounds() {
409      return new Type[]{upperBound};
410    }
411
412    @Override
413    public Type[] getLowerBounds() {
414      return lowerBound != null ? new Type[]{lowerBound} : EMPTY_TYPE_ARRAY;
415    }
416
417    @Override
418    public boolean equals(Object other) {
419      return other instanceof WildcardType && Util.equals(this, (WildcardType) other);
420    }
421
422    @Override
423    public int hashCode() {
424      // This equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds()).
425      return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode());
426    }
427
428    @Override
429    public String toString() {
430      if (lowerBound != null) {
431        return "? super " + typeToString(lowerBound);
432      } else if (upperBound == Object.class) {
433        return "?";
434      } else {
435        return "? extends " + typeToString(upperBound);
436      }
437    }
438  }
439
440  static String typeAnnotatedWithAnnotations(Type type, Set<? extends Annotation> annotations) {
441    return type + (annotations.isEmpty() ? " (with no annotations)" : " annotated " + annotations);
442  }
443
444  /**
445   * Returns a type that represents an unknown type that extends {@code bound}. For example, if
446   * {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
447   * {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code ?
448   * extends Object}.
449   */
450  static WildcardType subtypeOf(Type bound) {
451    Type[] upperBounds;
452    if (bound instanceof WildcardType) {
453      upperBounds = ((WildcardType) bound).getUpperBounds();
454    } else {
455      upperBounds = new Type[]{bound};
456    }
457    return new Util.WildcardTypeImpl(upperBounds, EMPTY_TYPE_ARRAY);
458  }
459
460  /**
461   * Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code
462   * bound} is {@code String.class}, this returns {@code ? super String}.
463   */
464  static WildcardType supertypeOf(Type bound) {
465    Type[] lowerBounds;
466    if (bound instanceof WildcardType) {
467      lowerBounds = ((WildcardType) bound).getLowerBounds();
468    } else {
469      lowerBounds = new Type[]{bound};
470    }
471    return new Util.WildcardTypeImpl(new Type[]{Object.class}, lowerBounds);
472  }
473
474
475  static Class<?> rawType(Type type) {
476    return Types.rawType(type);
477  }
478
479  /**
480   * Returns the element type of this collection type.
481   *
482   * @throws IllegalArgumentException if this type is not a collection.
483   */
484  static Type collectionElementType(Type context) {
485    Type collectionType = supertype(context, Collection.class, Collection.class);
486    if (collectionType instanceof WildcardType) {
487      collectionType = ((WildcardType) collectionType).getUpperBounds()[0];
488    }
489    if (collectionType instanceof ParameterizedType) {
490      return ((ParameterizedType) collectionType).getActualTypeArguments()[0];
491    }
492    return Object.class;
493  }
494
495  /**
496   * Returns true if {@code a} and {@code b} are equal.
497   */
498  static boolean equals(Type a, Type b) {
499    if (a == b) {
500      return true; // Also handles (a == null && b == null).
501
502    } else if (a instanceof Class) {
503      if (b instanceof GenericArrayType) {
504        return equals(((Class<?>) a).getComponentType(), ((GenericArrayType) b).getGenericComponentType());
505      }
506      return a.equals(b); // Class already specifies equals().
507
508    } else if (a instanceof ParameterizedType) {
509      if (!(b instanceof ParameterizedType)) return false;
510      ParameterizedType pa = (ParameterizedType) a;
511      ParameterizedType pb = (ParameterizedType) b;
512      Type[] aTypeArguments =
513        pa instanceof Util.ParameterizedTypeImpl
514          ? ((Util.ParameterizedTypeImpl) pa).typeArguments
515          : pa.getActualTypeArguments();
516      Type[] bTypeArguments =
517        pb instanceof Util.ParameterizedTypeImpl
518          ? ((Util.ParameterizedTypeImpl) pb).typeArguments
519          : pb.getActualTypeArguments();
520      return equals(pa.getOwnerType(), pb.getOwnerType())
521        && pa.getRawType().equals(pb.getRawType())
522        && Arrays.equals(aTypeArguments, bTypeArguments);
523
524    } else if (a instanceof GenericArrayType) {
525      if (b instanceof Class) {
526        return equals(((Class<?>) b).getComponentType(), ((GenericArrayType) a).getGenericComponentType());
527      }
528      if (!(b instanceof GenericArrayType)) return false;
529      GenericArrayType ga = (GenericArrayType) a;
530      GenericArrayType gb = (GenericArrayType) b;
531      return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
532
533    } else if (a instanceof WildcardType) {
534      if (!(b instanceof WildcardType)) return false;
535      WildcardType wa = (WildcardType) a;
536      WildcardType wb = (WildcardType) b;
537      return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
538        && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
539
540    } else if (a instanceof TypeVariable) {
541      if (!(b instanceof TypeVariable)) return false;
542      TypeVariable<?> va = (TypeVariable<?>) a;
543      TypeVariable<?> vb = (TypeVariable<?>) b;
544      return va.getGenericDeclaration() == vb.getGenericDeclaration()
545        && va.getName().equals(vb.getName());
546
547    } else {
548      // This isn't a supported type.
549      return false;
550    }
551  }
552
553  /**
554   * Returns a two element array containing this map's key and value types in positions 0 and 1
555   * respectively.
556   */
557  static Type mapValueType(Type context, Class<?> contextRawType) {
558    // Work around a problem with the declaration of java.util.Properties. That class should extend
559    // Hashtable<String, String>, but it's declared to extend Hashtable<Object, Object>.
560    if (context == Properties.class) {
561      return String.class;
562    }
563    Type mapType = supertype(context, contextRawType, Map.class);
564    if (mapType instanceof ParameterizedType) {
565      ParameterizedType mapParameterizedType = (ParameterizedType) mapType;
566      return mapParameterizedType.getActualTypeArguments()[1];
567    }
568    return Object.class;
569  }
570
571  /**
572   * Returns the generic form of {@code supertype}. For example, if this is {@code
573   * ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
574   * Iterable.class}.
575   *
576   * @param supertype a superclass of, or interface implemented by, this.
577   */
578  static Type supertype(Type context, Class<?> contextRawType, Class<?> supertype) {
579    if (!supertype.isAssignableFrom(contextRawType)) throw new IllegalArgumentException();
580    return resolve(context, contextRawType, genericSupertype(context, contextRawType, supertype));
581  }
582
583  /**
584   * Returns the element type of {@code type} if it is an array type, or null if it is not an array
585   * type.
586   */
587  static Type arrayComponentType(Type type) {
588    if (type instanceof GenericArrayType) {
589      return ((GenericArrayType) type).getGenericComponentType();
590    } else if (type instanceof Class) {
591      return ((Class<?>) type).getComponentType();
592    } else {
593      return null;
594    }
595  }
596}