/*
 * Copyright (C) 2006 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.common.reflect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A {@link Type} with generics.
 *
 *
Operations that are otherwise only available in {@link Class} are implemented to support
 * {@code Type}, for example {@link #isSubtypeOf}, {@link #isArray} and {@link #getComponentType}.
 * It also provides additional utilities such as {@link #getTypes}, {@link #resolveType}, etc.
 *
 *
There are three ways to get a {@code TypeToken} instance:
 *
 *

 *
Wrap a {@code Type} obtained via reflection. For example: {@code
 *       TypeToken.of(method.getGenericReturnType())}.
 *
Capture a generic type with a (usually anonymous) subclass. For example:
 *
{@code
 * new TypeToken<List<String>>() {}
 * }

 *
Note that it's critical that the actual type argument is carried by a subclass. The
 *       following code is wrong because it only captures the {@code <T>} type variable of the
 *       {@code listType()} method signature; while {@code <String>} is lost in erasure:
 *
{@code
 * class Util {
 *   static <T> TypeToken<List<T>> listType() {
 *     return new TypeToken<List<T>>() {};
 *   }
 * }
 *
 * TypeToken<List<String>> stringListType = Util.<String>listType();
 * }

 *
Capture a generic type with a (usually anonymous) subclass and resolve it against a context
 *       class that knows what the type parameters are. For example:
 *
{@code
 * abstract class IKnowMyType<T> {
 *   TypeToken<T> type = new TypeToken<T>(getClass()) {};
 * }
 * new IKnowMyType<String>() {}.type => String
 * }

 *

 *
 *
{@code TypeToken} is serializable when no type variable is contained in the type.
 *
 *
Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
 * that it is serializable and offers numerous additional utility methods.
 *
 * @author Bob Lee
 * @author Sven Mawson
 * @author Ben Yu
 * @since 12.0
 */
@Beta
@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {

  private final Type runtimeType;

  /** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
  private transient @MonotonicNonNull TypeResolver invariantTypeResolver;

  /** Resolver for resolving covariant types with {@link #runtimeType} as context. */
  private transient @MonotonicNonNull TypeResolver covariantTypeResolver;

  /**
   * Constructs a new type token of {@code T}.
   *
   *
Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
   * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
   *
   *
For example:
   *
   *
{@code
   * TypeToken<List<String>> t = new TypeToken<List<String>>() {};
   * }

   */
  protected TypeToken() {
    this.runtimeType = capture();
    checkState(
        !(runtimeType instanceof TypeVariable),
        "Cannot construct a TypeToken for a type variable.\n"
            + "You probably meant to call new TypeToken<%s>(getClass()) "
            + "that can resolve the type variable for you.\n"
            + "If you do need to create a TypeToken of a type variable, "
            + "please use TypeToken.of() instead.",
        runtimeType);
  }

  /**
   * Constructs a new type token of {@code T} while resolving free type variables in the context of
   * {@code declaringClass}.
   *
   *
Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
   * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
   *
   *
For example:
   *
   *
{@code
   * abstract class IKnowMyType<T> {
   *   TypeToken<T> getMyType() {
   *     return new TypeToken<T>(getClass()) {};
   *   }
   * }
   *
   * new IKnowMyType<String>() {}.getMyType() => String
   * }

   */
  protected TypeToken(Class<?> declaringClass) {
    Type captured = super.capture();
    if (captured instanceof Class) {
      this.runtimeType = captured;
    } else {
      this.runtimeType = TypeResolver.covariantly(declaringClass).resolveType(captured);
    }
  }

  private TypeToken(Type type) {
    this.runtimeType = checkNotNull(type);
  }

  /** Returns an instance of type token that wraps {@code type}. */
  public static <T> TypeToken<T> of(Class<T> type) {
    return new SimpleTypeToken<T>(type);
  }

  /** Returns an instance of type token that wraps {@code type}. */
  public static TypeToken<?> of(Type type) {
    return new SimpleTypeToken<>(type);
  }

  /**
   * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by {@link
   * java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by {@link
   * java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
   *
   *

   *
If {@code T} is a {@code Class} itself, {@code T} itself is returned.
   *
If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
   *       returned.
   *
If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
   *       class. For example: {@code List<Integer>[] => List[]}.
   *
If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
   *       is returned. For example: {@code <X extends Foo> => Foo}.
   *

   */
  public final Class<? super T> getRawType() {
    // For wildcard or type variable, the first bound determines the runtime type.
    Class<?> rawType = getRawTypes().iterator().next();
    @SuppressWarnings("unchecked") // raw type is |T|
    Class<? super T> result = (Class<? super T>) rawType;
    return result;
  }

  /** Returns the represented type. */
  public final Type getType() {
    return runtimeType;
  }

  /**
   * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
   * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
   * any {@code K} and {@code V} type:
   *
   *
{@code
   * static <K, V> TypeToken<Map<K, V>> mapOf(
   *     TypeToken<K> keyType, TypeToken<V> valueType) {
   *   return new TypeToken<Map<K, V>>() {}
   *       .where(new TypeParameter<K>() {}, keyType)
   *       .where(new TypeParameter<V>() {}, valueType);
   * }
   * }

   *
   * @param <X> The parameter type
   * @param typeParam the parameter type variable
   * @param typeArg the actual type to substitute
   */
  public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
    TypeResolver resolver =
        new TypeResolver()
            .where(
                ImmutableMap.of(
                    new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType));
    // If there's any type error, we'd report now rather than later.
    return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
  }

  /**
   * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
   * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
   * any {@code K} and {@code V} type:
   *
   *
{@code
   * static <K, V> TypeToken<Map<K, V>> mapOf(
   *     Class<K> keyType, Class<V> valueType) {
   *   return new TypeToken<Map<K, V>>() {}
   *       .where(new TypeParameter<K>() {}, keyType)
   *       .where(new TypeParameter<V>() {}, valueType);
   * }
   * }

   *
   * @param <X> The parameter type
   * @param typeParam the parameter type variable
   * @param typeArg the actual type to substitute
   */
  public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
    return where(typeParam, of(typeArg));
  }

  /**
   * Resolves the given {@code type} against the type context represented by this type. For example:
   *
   *
{@code
   * new TypeToken<List<String>>() {}.resolveType(
   *     List.class.getMethod("get", int.class).getGenericReturnType())
   * => String.class
   * }

   */
  public final TypeToken<?> resolveType(Type type) {
    checkNotNull(type);
    // Being conservative here because the user could use resolveType() to resolve a type in an
    // invariant context.
    return of(getInvariantTypeResolver().resolveType(type));
  }

  private TypeToken<?> resolveSupertype(Type type) {
    TypeToken<?> supertype = of(getCovariantTypeResolver().resolveType(type));
    // super types' type mapping is a subset of type mapping of this type.
    supertype.covariantTypeResolver = covariantTypeResolver;
    supertype.invariantTypeResolver = invariantTypeResolver;
    return supertype;
  }

  /**
   * Returns the generic superclass of this type or {@code null} if the type represents {@link
   * Object} or an interface. This method is similar but different from {@link
   * Class#getGenericSuperclass}. For example, {@code new TypeToken<StringArrayList>()
   * {}.getGenericSuperclass()} will return {@code new TypeToken<ArrayList<String>>() {}}; while
   * {@code StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where
   * {@code E} is the type variable declared by class {@code ArrayList}.
   *
   *
If this type is a type variable or wildcard, its first upper bound is examined and returned
   * if the bound is a class or extends from a class. This means that the returned type could be a
   * type variable too.
   */
  final @Nullable TypeToken<? super T> getGenericSuperclass() {
    if (runtimeType instanceof TypeVariable) {
      // First bound is always the super class, if one exists.
      return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
    }
    if (runtimeType instanceof WildcardType) {
      // wildcard has one and only one upper bound.
      return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
    }
    Type superclass = getRawType().getGenericSuperclass();
    if (superclass == null) {
      return null;
    }
    @SuppressWarnings("unchecked") // super class of T
    TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
    return superToken;
  }

  private @Nullable TypeToken<? super T> boundAsSuperclass(Type bound) {
    TypeToken<?> token = of(bound);
    if (token.getRawType().isInterface()) {
      return null;
    }
    @SuppressWarnings("unchecked") // only upper bound of T is passed in.
    TypeToken<? super T> superclass = (TypeToken<? super T>) token;
    return superclass;
  }

  /**
   * Returns the generic interfaces that this type directly {@code implements}. This method is
   * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new
   * TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code
   * new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will
   * return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable
   * declared by interface {@code Iterable}.
   *
   *
If this type is a type variable or wildcard, its upper bounds are examined and those that
   * are either an interface or upper-bounded only by interfaces are returned. This means that the
   * returned types could include type variables too.
   */
  final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
    if (runtimeType instanceof TypeVariable) {
      return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
    }
    if (runtimeType instanceof WildcardType) {
      return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
    }
    ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
    for (Type interfaceType : getRawType().getGenericInterfaces()) {
      @SuppressWarnings("unchecked") // interface of T
      TypeToken<? super T> resolvedInterface =
          (TypeToken<? super T>) resolveSupertype(interfaceType);
      builder.add(resolvedInterface);
    }
    return builder.build();
  }

  private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
    ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
    for (Type bound : bounds) {
      @SuppressWarnings("unchecked") // upper bound of T
      TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
      if (boundType.getRawType().isInterface()) {
        builder.add(boundType);
      }
    }
    return builder.build();
  }

  /**
   * Returns the set of interfaces and classes that this type is or is a subtype of. The returned
   * types are parameterized with proper type arguments.
   *
   *
Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
   * necessarily a subtype of all the types following. Order between types without subtype
   * relationship is arbitrary and not guaranteed.
   *
   *
If this type is a type variable or wildcard, upper bounds that are themselves type variables
   * aren't included (their super interfaces and superclasses are).
   */
  public final TypeSet getTypes() {
    return new TypeSet();
  }

  /**
   * Returns the generic form of {@code superclass}. For example, if this is {@code
   * ArrayList<String>}, {@code Iterable<String>} is returned given the input {@code
   * Iterable.class}.
   */
  public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
    checkArgument(
        this.someRawTypeIsSubclassOf(superclass),
        "%s is not a super class of %s",
        superclass,
        this);
    if (runtimeType instanceof TypeVariable) {
      return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
    }
    if (runtimeType instanceof WildcardType) {
      return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
    }
    if (superclass.isArray()) {
      return getArraySupertype(superclass);
    }
    @SuppressWarnings("unchecked") // resolved supertype
    TypeToken<? super T> supertype =
        (TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType);
    return supertype;
  }

  /**
   * Returns subtype of {@code this} with {@code subclass} as the raw class. For example, if this is
   * {@code Iterable<String>} and {@code subclass} is {@code List}, {@code List<String>} is
   * returned.
   */
  public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
    checkArgument(
        !(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this);
    if (runtimeType instanceof WildcardType) {
      return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
    }
    // unwrap array type if necessary
    if (isArray()) {
      return getArraySubtype(subclass);
    }
    // At this point, it's either a raw class or parameterized type.
    checkArgument(
        getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this);
    Type resolvedTypeArgs = resolveTypeArgsForSubclass(subclass);
    @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
    TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolvedTypeArgs);
    checkArgument(
        subtype.isSubtypeOf(this), "%s does not appear to be a subtype of %s", subtype, this);
    return subtype;
  }

  /**
   * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
   * according to the rules for type
   * arguments introduced with Java generics.
   *
   * @since 19.0
   */
  public final boolean isSupertypeOf(TypeToken<?> type) {
    return type.isSubtypeOf(getType());
  }

  /**
   * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
   * according to the rules for type
   * arguments introduced with Java generics.
   *
   * @since 19.0
   */
  public final boolean isSupertypeOf(Type type) {
    return of(type).isSubtypeOf(getType());
  }

  /**
   * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
   * according to the rules for type
   * arguments introduced with Java generics.
   *
   * @since 19.0
   */
  public final boolean isSubtypeOf(TypeToken<?> type) {
    return isSubtypeOf(type.getType());
  }

  /**
   * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
   * according to the rules for type
   * arguments introduced with Java generics.
   *
   * @since 19.0
   */
  public final boolean isSubtypeOf(Type supertype) {
    checkNotNull(supertype);
    if (supertype instanceof WildcardType) {
      // if 'supertype' is <? super Foo>, 'this' can be:
      // Foo, SubFoo, <? extends Foo>.
      // if 'supertype' is <? extends Foo>, nothing is a subtype.
      return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType);
    }
    // if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends"
    // bounds is a subtype of 'supertype'.
    if (runtimeType instanceof WildcardType) {
      // <? super Base> is of no use in checking 'from' being a subtype of 'to'.
      return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype);
    }
    // if 'this' is type variable, it's a subtype if any of its "extends"
    // bounds is a subtype of 'supertype'.
    if (runtimeType instanceof TypeVariable) {
      return runtimeType.equals(supertype)
          || any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype);
    }
    if (runtimeType instanceof GenericArrayType) {
      return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType);
    }
    // Proceed to regular Type subtype check
    if (supertype instanceof Class) {
      return this.someRawTypeIsSubclassOf((Class<?>) supertype);
    } else if (supertype instanceof ParameterizedType) {
      return this.isSubtypeOfParameterizedType((ParameterizedType) supertype);
    } else if (supertype instanceof GenericArrayType) {
      return this.isSubtypeOfArrayType((GenericArrayType) supertype);
    } else { // to instanceof TypeVariable
      return false;
    }
  }

  /**
   * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
   * {@code <? extends Map<String, Integer>[]>} etc.
   */
  public final boolean isArray() {
    return getComponentType() != null;
  }

  /**
   * Returns true if this type is one of the nine primitive types (including {@code void}).
   *
   * @since 15.0
   */
  public final boolean isPrimitive() {
    return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive();
  }

  /**
   * Returns the corresponding wrapper type if this is a primitive type; otherwise returns {@code
   * this} itself. Idempotent.
   *
   * @since 15.0
   */
  public final TypeToken<T> wrap() {
    if (isPrimitive()) {
      @SuppressWarnings("unchecked") // this is a primitive class
      Class<T> type = (Class<T>) runtimeType;
      return of(Primitives.wrap(type));
    }
    return this;
  }

  private boolean isWrapper() {
    return Primitives.allWrapperTypes().contains(runtimeType);
  }

  /**
   * Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code
   * this} itself. Idempotent.
   *
   * @since 15.0
   */
  public final TypeToken<T> unwrap() {
    if (isWrapper()) {
      @SuppressWarnings("unchecked") // this is a wrapper class
      Class<T> type = (Class<T>) runtimeType;
      return of(Primitives.unwrap(type));
    }
    return this;
  }

  /**
   * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
   * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
   */
  public final @Nullable TypeToken<?> getComponentType() {
    Type componentType = Types.getComponentType(runtimeType);
    if (componentType == null) {
      return null;
    }
    return of(componentType);
  }

  /**
   * Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
   *
   * @since 14.0
   */
  public final Invokable<T, Object> method(Method method) {
    checkArgument(
        this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
        "%s not declared by %s",
        method,
        this);
    return new Invokable.MethodInvokable<T>(method) {
      @Override
      Type getGenericReturnType() {
        return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
      }

      @Override
      Type[] getGenericParameterTypes() {
        return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
      }

      @Override
      Type[] getGenericExceptionTypes() {
        return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
      }

      @Override
      public TypeToken<T> getOwnerType() {
        return TypeToken.this;
      }

      @Override
      public String toString() {
        return getOwnerType() + "." + super.toString();
      }
    };
  }

  /**
   * Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
   *
   * @since 14.0
   */
  public final Invokable<T, T> constructor(Constructor<?> constructor) {
    checkArgument(
        constructor.getDeclaringClass() == getRawType(),
        "%s not declared by %s",
        constructor,
        getRawType());
    return new Invokable.ConstructorInvokable<T>(constructor) {
      @Override
      Type getGenericReturnType() {
        return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
      }

      @Override
      Type[] getGenericParameterTypes() {
        return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
      }

      @Override
      Type[] getGenericExceptionTypes() {
        return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
      }

      @Override
      public TypeToken<T> getOwnerType() {
        return TypeToken.this;
      }

      @Override
      public String toString() {
        return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")";
      }
    };
  }

  /**
   * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
   * included in the set if this type is an interface.
   *
   * @since 13.0
   */
  public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {

    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> types;

    TypeSet() {}

    /** Returns the types that are interfaces implemented by this type. */
    public TypeSet interfaces() {
      return new InterfaceSet(this);
    }

    /** Returns the types that are classes. */
    public TypeSet classes() {
      return new ClassSet();
    }

    @Override
    protected Set<TypeToken<? super T>> delegate() {
      ImmutableSet<TypeToken<? super T>> filteredTypes = types;
      if (filteredTypes == null) {
        // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
        @SuppressWarnings({"unchecked", "rawtypes"})
        ImmutableList<TypeToken<? super T>> collectedTypes =
            (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
        return (types =
            FluentIterable.from(collectedTypes)
                .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
                .toSet());
      } else {
        return filteredTypes;
      }
    }

    /** Returns the raw types of the types in this set, in the same order. */
    public Set<Class<? super T>> rawTypes() {
      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
      @SuppressWarnings({"unchecked", "rawtypes"})
      ImmutableList<Class<? super T>> collectedTypes =
          (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
      return ImmutableSet.copyOf(collectedTypes);
    }

    private static final long serialVersionUID = 0;
  }

  private final class InterfaceSet extends TypeSet {

    private final transient TypeSet allTypes;
    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> interfaces;

    InterfaceSet(TypeSet allTypes) {
      this.allTypes = allTypes;
    }

    @Override
    protected Set<TypeToken<? super T>> delegate() {
      ImmutableSet<TypeToken<? super T>> result = interfaces;
      if (result == null) {
        return (interfaces =
            FluentIterable.from(allTypes).filter(TypeFilter.INTERFACE_ONLY).toSet());
      } else {
        return result;
      }
    }

    @Override
    public TypeSet interfaces() {
      return this;
    }

    @Override
    public Set<Class<? super T>> rawTypes() {
      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
      @SuppressWarnings({"unchecked", "rawtypes"})
      ImmutableList<Class<? super T>> collectedTypes =
          (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
      return FluentIterable.from(collectedTypes)
          .filter(
              new Predicate<Class<?>>() {
                @Override
                public boolean apply(Class<?> type) {
                  return type.isInterface();
                }
              })
          .toSet();
    }

    @Override
    public TypeSet classes() {
      throw new UnsupportedOperationException("interfaces().classes() not supported.");
    }

    private Object readResolve() {
      return getTypes().interfaces();
    }

    private static final long serialVersionUID = 0;
  }

  private final class ClassSet extends TypeSet {

    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> classes;

    @Override
    protected Set<TypeToken<? super T>> delegate() {
      ImmutableSet<TypeToken<? super T>> result = classes;
      if (result == null) {
        @SuppressWarnings({"unchecked", "rawtypes"})
        ImmutableList<TypeToken<? super T>> collectedTypes =
            (ImmutableList)
                TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
        return (classes =
            FluentIterable.from(collectedTypes)
                .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
                .toSet());
      } else {
        return result;
      }
    }

    @Override
    public TypeSet classes() {
      return this;
    }

    @Override
    public Set<Class<? super T>> rawTypes() {
      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
      @SuppressWarnings({"unchecked", "rawtypes"})
      ImmutableList<Class<? super T>> collectedTypes =
          (ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getRawTypes());
      return ImmutableSet.copyOf(collectedTypes);
    }

    @Override
    public TypeSet interfaces() {
      throw new UnsupportedOperationException("classes().interfaces() not supported.");
    }

    private Object readResolve() {
      return getTypes().classes();
    }

    private static final long serialVersionUID = 0;
  }

  private enum TypeFilter implements Predicate<TypeToken<?>> {
    IGNORE_TYPE_VARIABLE_OR_WILDCARD {
      @Override
      public boolean apply(TypeToken<?> type) {
        return !(type.runtimeType instanceof TypeVariable
            || type.runtimeType instanceof WildcardType);
      }
    },
    INTERFACE_ONLY {
      @Override
      public boolean apply(TypeToken<?> type) {
        return type.getRawType().isInterface();
      }
    }
  }

  /**
   * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
   */
  @Override
  public boolean equals(@Nullable Object o) {
    if (o instanceof TypeToken) {
      TypeToken<?> that = (TypeToken<?>) o;
      return runtimeType.equals(that.runtimeType);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return runtimeType.hashCode();
  }

  @Override
  public String toString() {
    return Types.toString(runtimeType);
  }

  /** Implemented to support serialization of subclasses. */
  protected Object writeReplace() {
    // TypeResolver just transforms the type to our own impls that are Serializable
    // except TypeVariable.
    return of(new TypeResolver().resolveType(runtimeType));
  }

  /**
   * Ensures that this type token doesn't contain type variables, which can cause unchecked type
   * errors for callers like {@link TypeToInstanceMap}.
   */
  @CanIgnoreReturnValue
  final TypeToken<T> rejectTypeVariables() {
    new TypeVisitor() {
      @Override
      void visitTypeVariable(TypeVariable<?> type) {
        throw new IllegalArgumentException(
            runtimeType + "contains a type variable and is not safe for the operation");
      }

      @Override
      void visitWildcardType(WildcardType type) {
        visit(type.getLowerBounds());
        visit(type.getUpperBounds());
      }

      @Override
      void visitParameterizedType(ParameterizedType type) {
        visit(type.getActualTypeArguments());
        visit(type.getOwnerType());
      }

      @Override
      void visitGenericArrayType(GenericArrayType type) {
        visit(type.getGenericComponentType());
      }
    }.visit(runtimeType);
    return this;
  }

  private boolean someRawTypeIsSubclassOf(Class<?> superclass) {
    for (Class<?> rawType : getRawTypes()) {
      if (superclass.isAssignableFrom(rawType)) {
        return true;
      }
    }
    return false;
  }

  private boolean isSubtypeOfParameterizedType(ParameterizedType supertype) {
    Class<?> matchedClass = of(supertype).getRawType();
    if (!someRawTypeIsSubclassOf(matchedClass)) {
      return false;
    }
    TypeVariable<?>[] typeVars = matchedClass.getTypeParameters();
    Type[] supertypeArgs = supertype.getActualTypeArguments();
    for (int i = 0; i < typeVars.length; i++) {
      Type subtypeParam = getCovariantTypeResolver().resolveType(typeVars[i]);
      // If 'supertype' is "List<? extends CharSequence>"
      // and 'this' is StringArrayList,
      // First step is to figure out StringArrayList "is-a" List<E> where <E> = String.
      // String is then matched against <? extends CharSequence>, the supertypeArgs[0].
      if (!of(subtypeParam).is(supertypeArgs[i], typeVars[i])) {
        return false;
      }
    }
    // We only care about the case when the supertype is a non-static inner class
    // in which case we need to make sure the subclass's owner type is a subtype of the
    // supertype's owner.
    return Modifier.isStatic(((Class<?>) supertype.getRawType()).getModifiers())
        || supertype.getOwnerType() == null
        || isOwnedBySubtypeOf(supertype.getOwnerType());
  }

  private boolean isSubtypeOfArrayType(GenericArrayType supertype) {
    if (runtimeType instanceof Class) {
      Class<?> fromClass = (Class<?>) runtimeType;
      if (!fromClass.isArray()) {
        return false;
      }
      return of(fromClass.getComponentType()).isSubtypeOf(supertype.getGenericComponentType());
    } else if (runtimeType instanceof GenericArrayType) {
      GenericArrayType fromArrayType = (GenericArrayType) runtimeType;
      return of(fromArrayType.getGenericComponentType())
          .isSubtypeOf(supertype.getGenericComponentType());
    } else {
      return false;
    }
  }

  private boolean isSupertypeOfArray(GenericArrayType subtype) {
    if (runtimeType instanceof Class) {
      Class<?> thisClass = (Class<?>) runtimeType;
      if (!thisClass.isArray()) {
        return thisClass.isAssignableFrom(Object[].class);
      }
      return of(subtype.getGenericComponentType()).isSubtypeOf(thisClass.getComponentType());
    } else if (runtimeType instanceof GenericArrayType) {
      return of(subtype.getGenericComponentType())
          .isSubtypeOf(((GenericArrayType) runtimeType).getGenericComponentType());
    } else {
      return false;
    }
  }

  /**
   * {@code A.is(B)} is defined as {@code Foo.isSubtypeOf(Foo)}.
   *
   *
Specifically, returns true if any of the following conditions is met:
   *
   *

   *
'this' and {@code formalType} are equal.
   *
'this' and {@code formalType} have equal canonical form.
   *
{@code formalType} is {@code <? extends Foo>} and 'this' is a subtype of {@code Foo}.
   *
{@code formalType} is {@code <? super Foo>} and 'this' is a supertype of {@code Foo}.
   *

   *
   * Note that condition 2 isn't technically accurate under the context of a recursively bounded
   * type variables. For example, {@code Enum<? extends Enum<E>>} canonicalizes to {@code Enum<?>}
   * where {@code E} is the type variable declared on the {@code Enum} class declaration. It's
   * technically not true that {@code Foo<Enum<? extends Enum<E>>>} is a subtype of {@code
   * Foo<Enum<?>>} according to JLS. See testRecursiveWildcardSubtypeBug() for a real example.
   *
   *
It appears that properly handling recursive type bounds in the presence of implicit type
   * bounds is not easy. For now we punt, hoping that this defect should rarely cause issues in real
   * code.
   *
   * @param formalType is {@code Foo<formalType>} a supertype of {@code Foo<T>}?
   * @param declaration The type variable in the context of a parameterized type. Used to infer type
   *     bound when {@code formalType} is a wildcard with implicit upper bound.
   */
  private boolean is(Type formalType, TypeVariable<?> declaration) {
    if (runtimeType.equals(formalType)) {
      return true;
    }
    if (formalType instanceof WildcardType) {
      WildcardType your = canonicalizeWildcardType(declaration, (WildcardType) formalType);
      // if "formalType" is <? extends Foo>, "this" can be:
      // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
      // <T extends SubFoo>.
      // if "formalType" is <? super Foo>, "this" can be:
      // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
      return every(your.getUpperBounds()).isSupertypeOf(runtimeType)
          && every(your.getLowerBounds()).isSubtypeOf(runtimeType);
    }
    return canonicalizeWildcardsInType(runtimeType).equals(canonicalizeWildcardsInType(formalType));
  }

  /**
   * In reflection, {@code Foo<?>.getUpperBounds()[0]} is always {@code Object.class}, even when Foo
   * is defined as {@code Foo<T extends String>}. Thus directly calling {@code <?>.is(String.class)}
   * will return false. To mitigate, we canonicalize wildcards by enforcing the following
   * invariants:
   *
   *

   *
{@code canonicalize(t)} always produces the equal result for equivalent types. For
   *       example both {@code Enum<?>} and {@code Enum<? extends Enum<?>>} canonicalize to {@code
   *       Enum<? extends Enum<E>}.
   *
{@code canonicalize(t)} produces a "literal" supertype of t. For example: {@code Enum<?
   *       extends Enum<?>>} canonicalizes to {@code Enum<?>}, which is a supertype (if we disregard
   *       the upper bound is implicitly an Enum too).
   *
If {@code canonicalize(A) == canonicalize(B)}, then {@code Foo.isSubtypeOf(Foo)}
   *       and vice versa. i.e. {@code A.is(B)} and {@code B.is(A)}.
   *
{@code canonicalize(canonicalize(A)) == canonicalize(A)}.
   *

   */
  private static Type canonicalizeTypeArg(TypeVariable<?> declaration, Type typeArg) {
    return typeArg instanceof WildcardType
        ? canonicalizeWildcardType(declaration, ((WildcardType) typeArg))
        : canonicalizeWildcardsInType(typeArg);
  }

  private static Type canonicalizeWildcardsInType(Type type) {
    if (type instanceof ParameterizedType) {
      return canonicalizeWildcardsInParameterizedType((ParameterizedType) type);
    }
    if (type instanceof GenericArrayType) {
      return Types.newArrayType(
          canonicalizeWildcardsInType(((GenericArrayType) type).getGenericComponentType()));
    }
    return type;
  }

  // WARNING: the returned type may have empty upper bounds, which may violate common expectations
  // by user code or even some of our own code. It's fine for the purpose of checking subtypes.
  // Just don't ever let the user access it.
  private static WildcardType canonicalizeWildcardType(
      TypeVariable<?> declaration, WildcardType type) {
    Type[] declared = declaration.getBounds();
    List<Type> upperBounds = new ArrayList<>();
    for (Type bound : type.getUpperBounds()) {
      if (!any(declared).isSubtypeOf(bound)) {
        upperBounds.add(canonicalizeWildcardsInType(bound));
      }
    }
    return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0]));
  }

  private static ParameterizedType canonicalizeWildcardsInParameterizedType(
      ParameterizedType type) {
    Class<?> rawType = (Class<?>) type.getRawType();
    TypeVariable<?>[] typeVars = rawType.getTypeParameters();
    Type[] typeArgs = type.getActualTypeArguments();
    for (int i = 0; i < typeArgs.length; i++) {
      typeArgs[i] = canonicalizeTypeArg(typeVars[i], typeArgs[i]);
    }
    return Types.newParameterizedTypeWithOwner(type.getOwnerType(), rawType, typeArgs);
  }

  private static Bounds every(Type[] bounds) {
    // Every bound must match. On any false, result is false.
    return new Bounds(bounds, false);
  }

  private static Bounds any(Type[] bounds) {
    // Any bound matches. On any true, result is true.
    return new Bounds(bounds, true);
  }

  private static class Bounds {
    private final Type[] bounds;
    private final boolean target;

    Bounds(Type[] bounds, boolean target) {
      this.bounds = bounds;
      this.target = target;
    }

    boolean isSubtypeOf(Type supertype) {
      for (Type bound : bounds) {
        if (of(bound).isSubtypeOf(supertype) == target) {
          return target;
        }
      }
      return !target;
    }

    boolean isSupertypeOf(Type subtype) {
      TypeToken<?> type = of(subtype);
      for (Type bound : bounds) {
        if (type.isSubtypeOf(bound) == target) {
          return target;
        }
      }
      return !target;
    }
  }

  private ImmutableSet<Class<? super T>> getRawTypes() {
    final ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder();
    new TypeVisitor() {
      @Override
      void visitTypeVariable(TypeVariable<?> t) {
        visit(t.getBounds());
      }

      @Override
      void visitWildcardType(WildcardType t) {
        visit(t.getUpperBounds());
      }

      @Override
      void visitParameterizedType(ParameterizedType t) {
        builder.add((Class<?>) t.getRawType());
      }

      @Override
      void visitClass(Class<?> t) {
        builder.add(t);
      }

      @Override
      void visitGenericArrayType(GenericArrayType t) {
        builder.add(Types.getArrayClass(of(t.getGenericComponentType()).getRawType()));
      }
    }.visit(runtimeType);
    // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>>
    @SuppressWarnings({"unchecked", "rawtypes"})
    ImmutableSet<Class<? super T>> result = (ImmutableSet) builder.build();
    return result;
  }

  private boolean isOwnedBySubtypeOf(Type supertype) {
    for (TypeToken<?> type : getTypes()) {
      Type ownerType = type.getOwnerTypeIfPresent();
      if (ownerType != null && of(ownerType).isSubtypeOf(supertype)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns the owner type of a {@link ParameterizedType} or enclosing class of a {@link Class}, or
   * null otherwise.
   */
  private @Nullable Type getOwnerTypeIfPresent() {
    if (runtimeType instanceof ParameterizedType) {
      return ((ParameterizedType) runtimeType).getOwnerType();
    } else if (runtimeType instanceof Class<?>) {
      return ((Class<?>) runtimeType).getEnclosingClass();
    } else {
      return null;
    }
  }

  /**
   * Returns the type token representing the generic type declaration of {@code cls}. For example:
   * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
   *
   *
If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
   * returned.
   */
  @VisibleForTesting
  static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
    if (cls.isArray()) {
      Type arrayOfGenericType =
          Types.newArrayType(
              // If we are passed with int[].class, don't turn it to GenericArrayType
              toGenericType(cls.getComponentType()).runtimeType);
      @SuppressWarnings("unchecked") // array is covariant
      TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
      return result;
    }
    TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
    Type ownerType =
        cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())
            ? toGenericType(cls.getEnclosingClass()).runtimeType
            : null;

    if ((typeParams.length > 0) || ((ownerType != null) && ownerType != cls.getEnclosingClass())) {
      @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
      TypeToken<? extends T> type =
          (TypeToken<? extends T>)
              of(Types.newParameterizedTypeWithOwner(ownerType, cls, typeParams));
      return type;
    } else {
      return of(cls);
    }
  }

  private TypeResolver getCovariantTypeResolver() {
    TypeResolver resolver = covariantTypeResolver;
    if (resolver == null) {
      resolver = (covariantTypeResolver = TypeResolver.covariantly(runtimeType));
    }
    return resolver;
  }

  private TypeResolver getInvariantTypeResolver() {
    TypeResolver resolver = invariantTypeResolver;
    if (resolver == null) {
      resolver = (invariantTypeResolver = TypeResolver.invariantly(runtimeType));
    }
    return resolver;
  }

  private TypeToken<? super T> getSupertypeFromUpperBounds(
      Class<? super T> supertype, Type[] upperBounds) {
    for (Type upperBound : upperBounds) {
      @SuppressWarnings("unchecked") // T's upperbound is <? super T>.
      TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
      if (bound.isSubtypeOf(supertype)) {
        @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isSubtypeOf check.
        TypeToken<? super T> result = bound.getSupertype((Class) supertype);
        return result;
      }
    }
    throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
  }

  private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
    for (Type lowerBound : lowerBounds) {
      @SuppressWarnings("unchecked") // T's lower bound is <? extends T>
      TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound);
      // Java supports only one lowerbound anyway.
      return bound.getSubtype(subclass);
    }
    throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
  }

  private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
    // with component type, we have lost generic type information
    // Use raw type so that compiler allows us to call getSupertype()
    @SuppressWarnings("rawtypes")
    TypeToken componentType =
        checkNotNull(getComponentType(), "%s isn't a super type of %s", supertype, this);
    // array is covariant. component type is super type, so is the array type.
    @SuppressWarnings("unchecked") // going from raw type back to generics
    TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
    @SuppressWarnings("unchecked") // component type is super type, so is array type.
    TypeToken<? super T> result =
        (TypeToken<? super T>)
            // If we are passed with int[].class, don't turn it to GenericArrayType
            of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
    return result;
  }

  private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
    // array is covariant. component type is subtype, so is the array type.
    TypeToken<?> componentSubtype = getComponentType().getSubtype(subclass.getComponentType());
    @SuppressWarnings("unchecked") // component type is subtype, so is array type.
    TypeToken<? extends T> result =
        (TypeToken<? extends T>)
            // If we are passed with int[].class, don't turn it to GenericArrayType
            of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
    return result;
  }

  private Type resolveTypeArgsForSubclass(Class<?> subclass) {
    // If both runtimeType and subclass are not parameterized, return subclass
    // If runtimeType is not parameterized but subclass is, process subclass as a parameterized type
    // If runtimeType is a raw type (i.e. is a parameterized type specified as a Class<?>), we
    // return subclass as a raw type
    if (runtimeType instanceof Class
        && ((subclass.getTypeParameters().length == 0)
            || (getRawType().getTypeParameters().length != 0))) {
      // no resolution needed
      return subclass;
    }
    // class Base {}
    // class Sub<X, Y> extends Base<X, Y> {}
    // Base<String, Integer>.subtype(Sub.class):

    // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
    // => X=String, Y=Integer
    // => Sub<X, Y>=Sub<String, Integer>
    TypeToken<?> genericSubtype = toGenericType(subclass);
    @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
    Type supertypeWithArgsFromSubtype =
        genericSubtype.getSupertype((Class) getRawType()).runtimeType;
    return new TypeResolver()
        .where(supertypeWithArgsFromSubtype, runtimeType)
        .resolveType(genericSubtype.runtimeType);
  }

  /**
   * Creates an array class if {@code componentType} is a class, or else, a {@link
   * GenericArrayType}. This is what Java7 does for generic array type parameters.
   */
  private static Type newArrayClassOrGenericArrayType(Type componentType) {
    return Types.JavaVersion.JAVA7.newArrayType(componentType);
  }

  private static final class SimpleTypeToken<T> extends TypeToken<T> {

    SimpleTypeToken(Type type) {
      super(type);
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Collects parent types from a sub type.
   *
   * @param <K> The type "kind". Either a TypeToken, or Class.
   */
  private abstract static class TypeCollector<K> {

    static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE =
        new TypeCollector<TypeToken<?>>() {
          @Override
          Class<?> getRawType(TypeToken<?> type) {
            return type.getRawType();
          }

          @Override
          Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) {
            return type.getGenericInterfaces();
          }

          @Override
          @Nullable
          TypeToken<?> getSuperclass(TypeToken<?> type) {
            return type.getGenericSuperclass();
          }
        };

    static final TypeCollector<Class<?>> FOR_RAW_TYPE =
        new TypeCollector<Class<?>>() {
          @Override
          Class<?> getRawType(Class<?> type) {
            return type;
          }

          @Override
          Iterable<? extends Class<?>> getInterfaces(Class<?> type) {
            return Arrays.asList(type.getInterfaces());
          }

          @Override
          @Nullable
          Class<?> getSuperclass(Class<?> type) {
            return type.getSuperclass();
          }
        };

    /** For just classes, we don't have to traverse interfaces. */
    final TypeCollector<K> classesOnly() {
      return new ForwardingTypeCollector<K>(this) {
        @Override
        Iterable<? extends K> getInterfaces(K type) {
          return ImmutableSet.of();
        }

        @Override
        ImmutableList<K> collectTypes(Iterable<? extends K> types) {
          ImmutableList.Builder<K> builder = ImmutableList.builder();
          for (K type : types) {
            if (!getRawType(type).isInterface()) {
              builder.add(type);
            }
          }
          return super.collectTypes(builder.build());
        }
      };
    }

    final ImmutableList<K> collectTypes(K type) {
      return collectTypes(ImmutableList.of(type));
    }

    ImmutableList<K> collectTypes(Iterable<? extends K> types) {
      // type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
      Map<K, Integer> map = Maps.newHashMap();
      for (K type : types) {
        collectTypes(type, map);
      }
      return sortKeysByValue(map, Ordering.natural().reverse());
    }

    /** Collects all types to map, and returns the total depth from T up to Object. */
    @CanIgnoreReturnValue
    private int collectTypes(K type, Map<? super K, Integer> map) {
      Integer existing = map.get(type);
      if (existing != null) {
        // short circuit: if set contains type it already contains its supertypes
        return existing;
      }
      // Interfaces should be listed before Object.
      int aboveMe = getRawType(type).isInterface() ? 1 : 0;
      for (K interfaceType : getInterfaces(type)) {
        aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
      }
      K superclass = getSuperclass(type);
      if (superclass != null) {
        aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
      }
      /*
       * TODO(benyu): should we include Object for interface? Also, CharSequence[] and Object[] for
       * String[]?
       *
       */
      map.put(type, aboveMe + 1);
      return aboveMe + 1;
    }

    private static <K, V> ImmutableList<K> sortKeysByValue(
        final Map<K, V> map, final Comparator<? super V> valueComparator) {
      Ordering<K> keyOrdering =
          new Ordering<K>() {
            @Override
            public int compare(K left, K right) {
              return valueComparator.compare(map.get(left), map.get(right));
            }
          };
      return keyOrdering.immutableSortedCopy(map.keySet());
    }

    abstract Class<?> getRawType(K type);

    abstract Iterable<? extends K> getInterfaces(K type);

    abstract @Nullable K getSuperclass(K type);

    private static class ForwardingTypeCollector<K> extends TypeCollector<K> {

      private final TypeCollector<K> delegate;

      ForwardingTypeCollector(TypeCollector<K> delegate) {
        this.delegate = delegate;
      }

      @Override
      Class<?> getRawType(K type) {
        return delegate.getRawType(type);
      }

      @Override
      Iterable<? extends K> getInterfaces(K type) {
        return delegate.getInterfaces(type);
      }

      @Override
      K getSuperclass(K type) {
        return delegate.getSuperclass(type);
      }
    }
  }

  // This happens to be the hash of the class as of now. So setting it makes a backward compatible
  // change. Going forward, if any incompatible change is added, we can change the UID back to 1.
  private static final long serialVersionUID = 3637540370352322684L;
}


/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.common.io;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Provides utility methods for working with character streams.
 *
 *
All method parameters must be non-null unless documented otherwise.
 *
 *
Some of the methods in this class take arguments with a generic type of {@code Readable &
 * Closeable}. A {@link java.io.Reader} implements both of those interfaces. Similarly for {@code
 * Appendable & Closeable} and {@link java.io.Writer}.
 *
 * @author Chris Nokleberg
 * @author Bin Zhu
 * @author Colin Decker
 * @since 1.0
 */
@GwtIncompatible
public final class CharStreams {

  // 2K chars (4K bytes)
  private static final int DEFAULT_BUF_SIZE = 0x800;

  /** Creates a new {@code CharBuffer} for buffering reads or writes. */
  static CharBuffer createBuffer() {
    return CharBuffer.allocate(DEFAULT_BUF_SIZE);
  }

  private CharStreams() {}

  /**
   * Copies all characters between the {@link Readable} and {@link Appendable} objects. Does not
   * close or flush either object.
   *
   * @param from the object to read from
   * @param to the object to write to
   * @return the number of characters copied
   * @throws IOException if an I/O error occurs
   */
  @CanIgnoreReturnValue
  public static long copy(Readable from, Appendable to) throws IOException {
    // The most common case is that from is a Reader (like InputStreamReader or StringReader) so
    // take advantage of that.
    if (from instanceof Reader) {
      // optimize for common output types which are optimized to deal with char[]
      if (to instanceof StringBuilder) {
        return copyReaderToBuilder((Reader) from, (StringBuilder) to);
      } else {
        return copyReaderToWriter((Reader) from, asWriter(to));
      }
    } else {
      checkNotNull(from);
      checkNotNull(to);
      long total = 0;
      CharBuffer buf = createBuffer();
      while (from.read(buf) != -1) {
        buf.flip();
        to.append(buf);
        total += buf.remaining();
        buf.clear();
      }
      return total;
    }
  }

  // TODO(lukes): consider allowing callers to pass in a buffer to use, some callers would be able
  // to reuse buffers, others would be able to size them more appropriately than the constant
  // defaults

  /**
   * Copies all characters between the {@link Reader} and {@link StringBuilder} objects. Does not
   * close or flush the reader.
   *
   *
This is identical to {@link #copy(Readable, Appendable)} but optimized for these specific
   * types. CharBuffer has poor performance when being written into or read out of so round tripping
   * all the bytes through the buffer takes a long time. With these specialized types we can just
   * use a char array.
   *
   * @param from the object to read from
   * @param to the object to write to
   * @return the number of characters copied
   * @throws IOException if an I/O error occurs
   */
  @CanIgnoreReturnValue
  static long copyReaderToBuilder(Reader from, StringBuilder to) throws IOException {
    checkNotNull(from);
    checkNotNull(to);
    char[] buf = new char[DEFAULT_BUF_SIZE];
    int nRead;
    long total = 0;
    while ((nRead = from.read(buf)) != -1) {
      to.append(buf, 0, nRead);
      total += nRead;
    }
    return total;
  }

  /**
   * Copies all characters between the {@link Reader} and {@link Writer} objects. Does not close or
   * flush the reader or writer.
   *
   *
This is identical to {@link #copy(Readable, Appendable)} but optimized for these specific
   * types. CharBuffer has poor performance when being written into or read out of so round tripping
   * all the bytes through the buffer takes a long time. With these specialized types we can just
   * use a char array.
   *
   * @param from the object to read from
   * @param to the object to write to
   * @return the number of characters copied
   * @throws IOException if an I/O error occurs
   */
  @CanIgnoreReturnValue
  static long copyReaderToWriter(Reader from, Writer to) throws IOException {
    checkNotNull(from);
    checkNotNull(to);
    char[] buf = new char[DEFAULT_BUF_SIZE];
    int nRead;
    long total = 0;
    while ((nRead = from.read(buf)) != -1) {
      to.write(buf, 0, nRead);
      total += nRead;
    }
    return total;
  }

  /**
   * Reads all characters from a {@link Readable} object into a {@link String}. Does not close the
   * {@code Readable}.
   *
   * @param r the object to read from
   * @return a string containing all the characters
   * @throws IOException if an I/O error occurs
   */
  public static String toString(Readable r) throws IOException {
    return toStringBuilder(r).toString();
  }

  /**
   * Reads all characters from a {@link Readable} object into a new {@link StringBuilder} instance.
   * Does not close the {@code Readable}.
   *
   * @param r the object to read from
   * @return a {@link StringBuilder} containing all the characters
   * @throws IOException if an I/O error occurs
   */
  private static StringBuilder toStringBuilder(Readable r) throws IOException {
    StringBuilder sb = new StringBuilder();
    if (r instanceof Reader) {
      copyReaderToBuilder((Reader) r, sb);
    } else {
      copy(r, sb);
    }
    return sb;
  }

  /**
   * Reads all of the lines from a {@link Readable} object. The lines do not include
   * line-termination characters, but do include other leading and trailing whitespace.
   *
   *
Does not close the {@code Readable}. If reading files or resources you should use the {@link
   * Files#readLines} and {@link Resources#readLines} methods.
   *
   * @param r the object to read from
   * @return a mutable {@link List} containing all the lines
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static List<String> readLines(Readable r) throws IOException {
    List<String> result = new ArrayList<>();
    LineReader lineReader = new LineReader(r);
    String line;
    while ((line = lineReader.readLine()) != null) {
      result.add(line);
    }
    return result;
  }

  /**
   * Streams lines from a {@link Readable} object, stopping when the processor returns {@code false}
   * or all lines have been read and returning the result produced by the processor. Does not close
   * {@code readable}. Note that this method may not fully consume the contents of {@code readable}
   * if the processor stops processing early.
   *
   * @throws IOException if an I/O error occurs
   * @since 14.0
   */
  @Beta
  @CanIgnoreReturnValue // some processors won't return a useful result
  public static <T> T readLines(Readable readable, LineProcessor<T> processor) throws IOException {
    checkNotNull(readable);
    checkNotNull(processor);

    LineReader lineReader = new LineReader(readable);
    String line;
    while ((line = lineReader.readLine()) != null) {
      if (!processor.processLine(line)) {
        break;
      }
    }
    return processor.getResult();
  }

  /**
   * Reads and discards data from the given {@code Readable} until the end of the stream is reached.
   * Returns the total number of chars read. Does not close the stream.
   *
   * @since 20.0
   */
  @Beta
  @CanIgnoreReturnValue
  public static long exhaust(Readable readable) throws IOException {
    long total = 0;
    long read;
    CharBuffer buf = createBuffer();
    while ((read = readable.read(buf)) != -1) {
      total += read;
      buf.clear();
    }
    return total;
  }

  /**
   * Discards {@code n} characters of data from the reader. This method will block until the full
   * amount has been skipped. Does not close the reader.
   *
   * @param reader the reader to read from
   * @param n the number of characters to skip
   * @throws EOFException if this stream reaches the end before skipping all the characters
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void skipFully(Reader reader, long n) throws IOException {
    checkNotNull(reader);
    while (n > 0) {
      long amt = reader.skip(n);
      if (amt == 0) {
        throw new EOFException();
      }
      n -= amt;
    }
  }

  /**
   * Returns a {@link Writer} that simply discards written chars.
   *
   * @since 15.0
   */
  @Beta
  public static Writer nullWriter() {
    return NullWriter.INSTANCE;
  }

  private static final class NullWriter extends Writer {

    private static final NullWriter INSTANCE = new NullWriter();

    @Override
    public void write(int c) {}

    @Override
    public void write(char[] cbuf) {
      checkNotNull(cbuf);
    }

    @Override
    public void write(char[] cbuf, int off, int len) {
      checkPositionIndexes(off, off + len, cbuf.length);
    }

    @Override
    public void write(String str) {
      checkNotNull(str);
    }

    @Override
    public void write(String str, int off, int len) {
      checkPositionIndexes(off, off + len, str.length());
    }

    @Override
    public Writer append(CharSequence csq) {
      checkNotNull(csq);
      return this;
    }

    @Override
    public Writer append(CharSequence csq, int start, int end) {
      checkPositionIndexes(start, end, csq.length());
      return this;
    }

    @Override
    public Writer append(char c) {
      return this;
    }

    @Override
    public void flush() {}

    @Override
    public void close() {}

    @Override
    public String toString() {
      return "CharStreams.nullWriter()";
    }
  }

  /**
   * Returns a Writer that sends all output to the given {@link Appendable} target. Closing the
   * writer will close the target if it is {@link Closeable}, and flushing the writer will flush the
   * target if it is {@link java.io.Flushable}.
   *
   * @param target the object to which output will be sent
   * @return a new Writer object, unless target is a Writer, in which case the target is returned
   */
  @Beta
  public static Writer asWriter(Appendable target) {
    if (target instanceof Writer) {
      return (Writer) target;
    }
    return new AppendableWriter(target);
  }
}


/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
import static com.google.common.collect.RegularImmutableList.EMPTY;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A {@link List} whose contents will never change, with many other important properties detailed at
 * {@link ImmutableCollection}.
 *
 *
See the Guava User Guide article on  immutable collections.
 *
 * @see ImmutableMap
 * @see ImmutableSet
 * @author Kevin Bourrillion
 * @since 2.0
 */
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableList<E> extends ImmutableCollection<E>
    implements List<E>, RandomAccess {

  /**
   * Returns a {@code Collector} that accumulates the input elements into a new {@code
   * ImmutableList}, in encounter order.
   *
   * @since 21.0
   */
  public static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
    return CollectCollectors.toImmutableList();
  }

  /**
   * Returns the empty immutable list. This list behaves and performs comparably to {@link
   * Collections#emptyList}, and is preferable mainly for consistency and maintainability of your
   * code.
   */
  // Casting to any type is safe because the list will never hold any elements.
  @SuppressWarnings("unchecked")
  public static <E> ImmutableList<E> of() {
    return (ImmutableList<E>) EMPTY;
  }

  /**
   * Returns an immutable list containing a single element. This list behaves and performs
   * comparably to {@link Collections#singleton}, but will not accept a null element. It is
   * preferable mainly for consistency and maintainability of your code.
   *
   * @throws NullPointerException if {@code element} is null
   */
  public static <E> ImmutableList<E> of(E element) {
    return new SingletonImmutableList<E>(element);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2) {
    return construct(e1, e2);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
    return construct(e1, e2, e3);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
    return construct(e1, e2, e3, e4);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
    return construct(e1, e2, e3, e4, e5);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
    return construct(e1, e2, e3, e4, e5, e6);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
    return construct(e1, e2, e3, e4, e5, e6, e7);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
    return construct(e1, e2, e3, e4, e5, e6, e7, e8);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   */
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
    return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
  }

  // These go up to eleven. After that, you just get the varargs form, and
  // whatever warnings might come along with it. :(

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   *
The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 12}.
   *
   * @throws NullPointerException if any element is null
   * @since 3.0 (source-compatible since 2.0)
   */
  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
  public static <E> ImmutableList<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
    checkArgument(
        others.length <= Integer.MAX_VALUE - 12, "the total number of elements must fit in an int");
    Object[] array = new Object[12 + others.length];
    array[0] = e1;
    array[1] = e2;
    array[2] = e3;
    array[3] = e4;
    array[4] = e5;
    array[5] = e6;
    array[6] = e7;
    array[7] = e8;
    array[8] = e9;
    array[9] = e10;
    array[10] = e11;
    array[11] = e12;
    System.arraycopy(others, 0, array, 12, others.length);
    return construct(array);
  }

  /**
   * Returns an immutable list containing the given elements, in order. If {@code elements} is a
   * {@link Collection}, this method behaves exactly as {@link #copyOf(Collection)}; otherwise, it
   * behaves exactly as {@code copyOf(elements.iterator()}.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
    checkNotNull(elements); // TODO(kevinb): is this here only for GWT?
    return (elements instanceof Collection)
        ? copyOf((Collection<? extends E>) elements)
        : copyOf(elements.iterator());
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   *
Despite the method name, this method attempts to avoid actually copying the data when it is
   * safe to do so. The exact circumstances under which a copy will or will not be performed are
   * undocumented and subject to change.
   *
   *
Note that if {@code list} is a {@code List<String>}, then {@code ImmutableList.copyOf(list)}
   * returns an {@code ImmutableList<String>} containing each of the strings in {@code list}, while
   * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} containing one element
   * (the given list itself).
   *
   *
This method is safe to use even when {@code elements} is a synchronized or concurrent
   * collection that is currently being modified by another thread.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
    if (elements instanceof ImmutableCollection) {
      @SuppressWarnings("unchecked") // all supported methods are covariant
      ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
      return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list;
    }
    return construct(elements.toArray());
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
    // We special-case for 0 or 1 elements, but going further is madness.
    if (!elements.hasNext()) {
      return of();
    }
    E first = elements.next();
    if (!elements.hasNext()) {
      return of(first);
    } else {
      return new ImmutableList.Builder<E>().add(first).addAll(elements).build();
    }
  }

  /**
   * Returns an immutable list containing the given elements, in order.
   *
   * @throws NullPointerException if any of {@code elements} is null
   * @since 3.0
   */
  public static <E> ImmutableList<E> copyOf(E[] elements) {
    switch (elements.length) {
      case 0:
        return of();
      case 1:
        return of(elements[0]);
      default:
        return construct(elements.clone());
    }
  }

  /**
   * Returns an immutable list containing the given elements, sorted according to their natural
   * order. The sorting algorithm used is stable, so elements that compare as equal will stay in the
   * order in which they appear in the input.
   *
   *
If your data has no duplicates, or you wish to deduplicate elements, use {@code
   * ImmutableSortedSet.copyOf(elements)}; if you want a {@code List} you can use its {@code
   * asList()} view.
   *
   *
Java 8 users: If you want to convert a {@link java.util.stream.Stream} to a sorted
   * {@code ImmutableList}, use {@code stream.sorted().collect(toImmutableList())}.
   *
   * @throws NullPointerException if any element in the input is null
   * @since 21.0
   */
  public static <E extends Comparable<? super E>> ImmutableList<E> sortedCopyOf(
      Iterable<? extends E> elements) {
    Comparable<?>[] array = Iterables.toArray(elements, new Comparable<?>[0]);
    checkElementsNotNull((Object[]) array);
    Arrays.sort(array);
    return asImmutableList(array);
  }

  /**
   * Returns an immutable list containing the given elements, in sorted order relative to the
   * specified comparator. The sorting algorithm used is stable, so elements that compare as equal
   * will stay in the order in which they appear in the input.
   *
   *
If your data has no duplicates, or you wish to deduplicate elements, use {@code
   * ImmutableSortedSet.copyOf(comparator, elements)}; if you want a {@code List} you can use its
   * {@code asList()} view.
   *
   *
Java 8 users: If you want to convert a {@link java.util.stream.Stream} to a sorted
   * {@code ImmutableList}, use {@code stream.sorted(comparator).collect(toImmutableList())}.
   *
   * @throws NullPointerException if any element in the input is null
   * @since 21.0
   */
  public static <E> ImmutableList<E> sortedCopyOf(
      Comparator<? super E> comparator, Iterable<? extends E> elements) {
    checkNotNull(comparator);
    @SuppressWarnings("unchecked") // all supported methods are covariant
    E[] array = (E[]) Iterables.toArray(elements);
    checkElementsNotNull(array);
    Arrays.sort(array, comparator);
    return asImmutableList(array);
  }

  /** Views the array as an immutable list. Checks for nulls; does not copy. */
  private static <E> ImmutableList<E> construct(Object... elements) {
    return asImmutableList(checkElementsNotNull(elements));
  }

  /**
   * Views the array as an immutable list. Does not check for nulls; does not copy.
   *
   *
The array must be internally created.
   */
  static <E> ImmutableList<E> asImmutableList(Object[] elements) {
    return asImmutableList(elements, elements.length);
  }

  /**
   * Views the array as an immutable list. Copies if the specified range does not cover the complete
   * array. Does not check for nulls.
   */
  static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
    switch (length) {
      case 0:
        return of();
      case 1:
        return of((E) elements[0]);
      default:
        if (length < elements.length) {
          elements = Arrays.copyOf(elements, length);
        }
        return new RegularImmutableList<E>(elements);
    }
  }

  ImmutableList() {}

  // This declaration is needed to make List.iterator() and
  // ImmutableCollection.iterator() consistent.
  @Override
  public UnmodifiableIterator<E> iterator() {
    return listIterator();
  }

  @Override
  public UnmodifiableListIterator<E> listIterator() {
    return listIterator(0);
  }

  @Override
  public UnmodifiableListIterator<E> listIterator(int index) {
    return new AbstractIndexedListIterator<E>(size(), index) {
      @Override
      protected E get(int index) {
        return ImmutableList.this.get(index);
      }
    };
  }

  @Override
  public void forEach(Consumer<? super E> consumer) {
    checkNotNull(consumer);
    int n = size();
    for (int i = 0; i < n; i++) {
      consumer.accept(get(i));
    }
  }

  @Override
  public int indexOf(@Nullable Object object) {
    return (object == null) ? -1 : Lists.indexOfImpl(this, object);
  }

  @Override
  public int lastIndexOf(@Nullable Object object) {
    return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
  }

  @Override
  public boolean contains(@Nullable Object object) {
    return indexOf(object) >= 0;
  }

  // constrain the return type to ImmutableList<E>

  /**
   * Returns an immutable list of the elements between the specified {@code fromIndex}, inclusive,
   * and {@code toIndex}, exclusive. (If {@code fromIndex} and {@code toIndex} are equal, the empty
   * immutable list is returned.)
   */
  @Override
  public ImmutableList<E> subList(int fromIndex, int toIndex) {
    checkPositionIndexes(fromIndex, toIndex, size());
    int length = toIndex - fromIndex;
    if (length == size()) {
      return this;
    } else if (length == 0) {
      return of();
    } else if (length == 1) {
      return of(get(fromIndex));
    } else {
      return subListUnchecked(fromIndex, toIndex);
    }
  }

  /**
   * Called by the default implementation of {@link #subList} when {@code toIndex - fromIndex > 1},
   * after index validation has already been performed.
   */
  ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) {
    return new SubList(fromIndex, toIndex - fromIndex);
  }

  class SubList extends ImmutableList<E> {
    final transient int offset;
    final transient int length;

    SubList(int offset, int length) {
      this.offset = offset;
      this.length = length;
    }

    @Override
    public int size() {
      return length;
    }

    @Override
    public E get(int index) {
      checkElementIndex(index, length);
      return ImmutableList.this.get(index + offset);
    }

    @Override
    public ImmutableList<E> subList(int fromIndex, int toIndex) {
      checkPositionIndexes(fromIndex, toIndex, length);
      return ImmutableList.this.subList(fromIndex + offset, toIndex + offset);
    }

    @Override
    boolean isPartialView() {
      return true;
    }
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public final boolean addAll(int index, Collection<? extends E> newElements) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public final E set(int index, E element) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final void add(int index, E element) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public final E remove(int index) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final void replaceAll(UnaryOperator<E> operator) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the list unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final void sort(Comparator<? super E> c) {
    throw new UnsupportedOperationException();
  }

  /**
   * Returns this list instance.
   *
   * @since 2.0
   */
  @Override
  public final ImmutableList<E> asList() {
    return this;
  }

  @Override
  public Spliterator<E> spliterator() {
    return CollectSpliterators.indexed(size(), SPLITERATOR_CHARACTERISTICS, this::get);
  }

  @Override
  int copyIntoArray(Object[] dst, int offset) {
    // this loop is faster for RandomAccess instances, which ImmutableLists are
    int size = size();
    for (int i = 0; i < size; i++) {
      dst[offset + i] = get(i);
    }
    return offset + size;
  }

  /**
   * Returns a view of this immutable list in reverse order. For example, {@code ImmutableList.of(1,
   * 2, 3).reverse()} is equivalent to {@code ImmutableList.of(3, 2, 1)}.
   *
   * @return a view of this immutable list in reverse order
   * @since 7.0
   */
  public ImmutableList<E> reverse() {
    return (size() <= 1) ? this : new ReverseImmutableList<E>(this);
  }

  private static class ReverseImmutableList<E> extends ImmutableList<E> {
    private final transient ImmutableList<E> forwardList;

    ReverseImmutableList(ImmutableList<E> backingList) {
      this.forwardList = backingList;
    }

    private int reverseIndex(int index) {
      return (size() - 1) - index;
    }

    private int reversePosition(int index) {
      return size() - index;
    }

    @Override
    public ImmutableList<E> reverse() {
      return forwardList;
    }

    @Override
    public boolean contains(@Nullable Object object) {
      return forwardList.contains(object);
    }

    @Override
    public int indexOf(@Nullable Object object) {
      int index = forwardList.lastIndexOf(object);
      return (index >= 0) ? reverseIndex(index) : -1;
    }

    @Override
    public int lastIndexOf(@Nullable Object object) {
      int index = forwardList.indexOf(object);
      return (index >= 0) ? reverseIndex(index) : -1;
    }

    @Override
    public ImmutableList<E> subList(int fromIndex, int toIndex) {
      checkPositionIndexes(fromIndex, toIndex, size());
      return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse();
    }

    @Override
    public E get(int index) {
      checkElementIndex(index, size());
      return forwardList.get(reverseIndex(index));
    }

    @Override
    public int size() {
      return forwardList.size();
    }

    @Override
    boolean isPartialView() {
      return forwardList.isPartialView();
    }
  }

  @Override
  public boolean equals(@Nullable Object obj) {
    return Lists.equalsImpl(this, obj);
  }

  @Override
  public int hashCode() {
    int hashCode = 1;
    int n = size();
    for (int i = 0; i < n; i++) {
      hashCode = 31 * hashCode + get(i).hashCode();

      hashCode = ~~hashCode;
      // needed to deal with GWT integer overflow
    }
    return hashCode;
  }

  /*
   * Serializes ImmutableLists as their logical contents. This ensures that
   * implementation types do not leak into the serialized representation.
   */
  static class SerializedForm implements Serializable {
    final Object[] elements;

    SerializedForm(Object[] elements) {
      this.elements = elements;
    }

    Object readResolve() {
      return copyOf(elements);
    }

    private static final long serialVersionUID = 0;
  }

  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
    throw new InvalidObjectException("Use SerializedForm");
  }

  @Override
  Object writeReplace() {
    return new SerializedForm(toArray());
  }

  /**
   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
   * Builder} constructor.
   */
  public static <E> Builder<E> builder() {
    return new Builder<E>();
  }

  /**
   * Returns a new builder, expecting the specified number of elements to be added.
   *
   *
If {@code expectedSize} is exactly the number of elements added to the builder before {@link
   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
   * #builder()} would have.
   *
   *
It is not specified if any performance benefits apply if {@code expectedSize} is close to,
   * but not exactly, the number of elements added to the builder.
   *
   * @since 23.1
   */
  @Beta
  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
    checkNonnegative(expectedSize, "expectedSize");
    return new ImmutableList.Builder<E>(expectedSize);
  }

  /**
   * A builder for creating immutable list instances, especially {@code public static final} lists
   * ("constant lists"). Example:
   *
   *
{@code
   * public static final ImmutableList<Color> GOOGLE_COLORS
   *     = new ImmutableList.Builder<Color>()
   *         .addAll(WEBSAFE_COLORS)
   *         .add(new Color(0, 191, 255))
   *         .build();
   * }

   *
   *
Elements appear in the resulting list in the same order they were added to the builder.
   *
   *
Builder instances can be reused; it is safe to call {@link #build} multiple times to build
   * multiple lists in series. Each new list contains all the elements of the ones created before
   * it.
   *
   * @since 2.0
   */
  public static final class Builder<E> extends ImmutableCollection.Builder<E> {
    @VisibleForTesting Object[] contents;
    private int size;
    private boolean forceCopy;

    /**
     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
     * ImmutableList#builder}.
     */
    public Builder() {
      this(DEFAULT_INITIAL_CAPACITY);
    }

    Builder(int capacity) {
      this.contents = new Object[capacity];
      this.size = 0;
    }

    private void getReadyToExpandTo(int minCapacity) {
      if (contents.length < minCapacity) {
        this.contents = Arrays.copyOf(contents, expandedCapacity(contents.length, minCapacity));
        forceCopy = false;
      } else if (forceCopy) {
        contents = Arrays.copyOf(contents, contents.length);
        forceCopy = false;
      }
    }

    /**
     * Adds {@code element} to the {@code ImmutableList}.
     *
     * @param element the element to add
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code element} is null
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<E> add(E element) {
      checkNotNull(element);
      getReadyToExpandTo(size + 1);
      contents[size++] = element;
      return this;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableList}.
     *
     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a null element
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<E> add(E... elements) {
      checkElementsNotNull(elements);
      add(elements, elements.length);
      return this;
    }

    private void add(Object[] elements, int n) {
      getReadyToExpandTo(size + n);
      System.arraycopy(elements, 0, contents, size, n);
      size += n;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableList}.
     *
     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a null element
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<E> addAll(Iterable<? extends E> elements) {
      checkNotNull(elements);
      if (elements instanceof Collection) {
        Collection<?> collection = (Collection<?>) elements;
        getReadyToExpandTo(size + collection.size());
        if (collection instanceof ImmutableCollection) {
          ImmutableCollection<?> immutableCollection = (ImmutableCollection<?>) collection;
          size = immutableCollection.copyIntoArray(contents, size);
          return this;
        }
      }
      super.addAll(elements);
      return this;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableList}.
     *
     * @param elements the {@code Iterable} to add to the {@code ImmutableList}
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a null element
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    @CanIgnoreReturnValue
    Builder<E> combine(Builder<E> builder) {
      checkNotNull(builder);
      add(builder.contents, builder.size);
      return this;
    }

    /**
     * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}.
     */
    @Override
    public ImmutableList<E> build() {
      forceCopy = true;
      return asImmutableList(contents, size);
    }
  }
}