/*
 * Copyright (C) 2009 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.escape;

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

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Static utility methods pertaining to {@link Escaper} instances.
 *
 * @author Sven Mawson
 * @author David Beaumont
 * @since 15.0
 */
@Beta
@GwtCompatible
public final class Escapers {
  private Escapers() {}

  /**
   * Returns an {@link Escaper} that does no escaping, passing all character data through unchanged.
   */
  public static Escaper nullEscaper() {
    return NULL_ESCAPER;
  }

  // An Escaper that efficiently performs no escaping.
  // Extending CharEscaper (instead of Escaper) makes Escapers.compose() easier.
  private static final Escaper NULL_ESCAPER =
      new CharEscaper() {
        @Override
        public String escape(String string) {
          return checkNotNull(string);
        }

        @Override
        protected char[] escape(char c) {
          // TODO: Fix tests not to call this directly and make it throw an error.
          return null;
        }
      };

  /**
   * Returns a builder for creating simple, fast escapers. A builder instance can be reused and each
   * escaper that is created will be a snapshot of the current builder state. Builders are not
   * thread safe.
   *
   *
The initial state of the builder is such that:
   *
   *

   *
There are no replacement mappings
   *
{@code safeMin == Character.MIN_VALUE}
   *
{@code safeMax == Character.MAX_VALUE}
   *
{@code unsafeReplacement == null}
   *

   *
   *
For performance reasons escapers created by this builder are not Unicode aware and will not
   * validate the well-formedness of their input.
   */
  public static Builder builder() {
    return new Builder();
  }

  /**
   * A builder for simple, fast escapers.
   *
   *
Typically an escaper needs to deal with the escaping of high valued characters or code
   * points. In these cases it is necessary to extend either {@link ArrayBasedCharEscaper} or {@link
   * ArrayBasedUnicodeEscaper} to provide the desired behavior. However this builder is suitable for
   * creating escapers that replace a relative small set of characters.
   *
   * @author David Beaumont
   * @since 15.0
   */
  @Beta
  public static final class Builder {
    private final Map<Character, String> replacementMap = new HashMap<>();
    private char safeMin = Character.MIN_VALUE;
    private char safeMax = Character.MAX_VALUE;
    private String unsafeReplacement = null;

    // The constructor is exposed via the builder() method above.
    private Builder() {}

    /**
     * Sets the safe range of characters for the escaper. Characters in this range that have no
     * explicit replacement are considered 'safe' and remain unescaped in the output. If {@code
     * safeMax < safeMin} then the safe range is empty.
     *
     * @param safeMin the lowest 'safe' character
     * @param safeMax the highest 'safe' character
     * @return the builder instance
     */
    @CanIgnoreReturnValue
    public Builder setSafeRange(char safeMin, char safeMax) {
      this.safeMin = safeMin;
      this.safeMax = safeMax;
      return this;
    }

    /**
     * Sets the replacement string for any characters outside the 'safe' range that have no explicit
     * replacement. If {@code unsafeReplacement} is {@code null} then no replacement will occur, if
     * it is {@code ""} then the unsafe characters are removed from the output.
     *
     * @param unsafeReplacement the string to replace unsafe characters
     * @return the builder instance
     */
    @CanIgnoreReturnValue
    public Builder setUnsafeReplacement(@Nullable String unsafeReplacement) {
      this.unsafeReplacement = unsafeReplacement;
      return this;
    }

    /**
     * Adds a replacement string for the given input character. The specified character will be
     * replaced by the given string whenever it occurs in the input, irrespective of whether it lies
     * inside or outside the 'safe' range.
     *
     * @param c the character to be replaced
     * @param replacement the string to replace the given character
     * @return the builder instance
     * @throws NullPointerException if {@code replacement} is null
     */
    @CanIgnoreReturnValue
    public Builder addEscape(char c, String replacement) {
      checkNotNull(replacement);
      // This can replace an existing character (the builder is re-usable).
      replacementMap.put(c, replacement);
      return this;
    }

    /** Returns a new escaper based on the current state of the builder. */
    public Escaper build() {
      return new ArrayBasedCharEscaper(replacementMap, safeMin, safeMax) {
        private final char[] replacementChars =
            unsafeReplacement != null ? unsafeReplacement.toCharArray() : null;

        @Override
        protected char[] escapeUnsafe(char c) {
          return replacementChars;
        }
      };
    }
  }

  /**
   * Returns a {@link UnicodeEscaper} equivalent to the given escaper instance. If the escaper is
   * already a UnicodeEscaper then it is simply returned, otherwise it is wrapped in a
   * UnicodeEscaper.
   *
   *
When a {@link CharEscaper} escaper is wrapped by this method it acquires extra behavior with
   * respect to the well-formedness of Unicode character sequences and will throw {@link
   * IllegalArgumentException} when given bad input.
   *
   * @param escaper the instance to be wrapped
   * @return a UnicodeEscaper with the same behavior as the given instance
   * @throws NullPointerException if escaper is null
   * @throws IllegalArgumentException if escaper is not a UnicodeEscaper or a CharEscaper
   */
  static UnicodeEscaper asUnicodeEscaper(Escaper escaper) {
    checkNotNull(escaper);
    if (escaper instanceof UnicodeEscaper) {
      return (UnicodeEscaper) escaper;
    } else if (escaper instanceof CharEscaper) {
      return wrap((CharEscaper) escaper);
    }
    // In practice this shouldn't happen because it would be very odd not to
    // extend either CharEscaper or UnicodeEscaper for non trivial cases.
    throw new IllegalArgumentException(
        "Cannot create a UnicodeEscaper from: " + escaper.getClass().getName());
  }

  /**
   * Returns a string that would replace the given character in the specified escaper, or {@code
   * null} if no replacement should be made. This method is intended for use in tests through the
   * {@code EscaperAsserts} class; production users of {@link CharEscaper} should limit themselves
   * to its public interface.
   *
   * @param c the character to escape if necessary
   * @return the replacement string, or {@code null} if no escaping was needed
   */
  public static String computeReplacement(CharEscaper escaper, char c) {
    return stringOrNull(escaper.escape(c));
  }

  /**
   * Returns a string that would replace the given character in the specified escaper, or {@code
   * null} if no replacement should be made. This method is intended for use in tests through the
   * {@code EscaperAsserts} class; production users of {@link UnicodeEscaper} should limit
   * themselves to its public interface.
   *
   * @param cp the Unicode code point to escape if necessary
   * @return the replacement string, or {@code null} if no escaping was needed
   */
  public static String computeReplacement(UnicodeEscaper escaper, int cp) {
    return stringOrNull(escaper.escape(cp));
  }

  private static String stringOrNull(char[] in) {
    return (in == null) ? null : new String(in);
  }

  /** Private helper to wrap a CharEscaper as a UnicodeEscaper. */
  private static UnicodeEscaper wrap(final CharEscaper escaper) {
    return new UnicodeEscaper() {
      @Override
      protected char[] escape(int cp) {
        // If a code point maps to a single character, just escape that.
        if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
          return escaper.escape((char) cp);
        }
        // Convert the code point to a surrogate pair and escape them both.
        // Note: This code path is horribly slow and typically allocates 4 new
        // char[] each time it is invoked. However this avoids any
        // synchronization issues and makes the escaper thread safe.
        char[] surrogateChars = new char[2];
        Character.toChars(cp, surrogateChars, 0);
        char[] hiChars = escaper.escape(surrogateChars[0]);
        char[] loChars = escaper.escape(surrogateChars[1]);

        // If either hiChars or lowChars are non-null, the CharEscaper is trying
        // to escape the characters of a surrogate pair separately. This is
        // uncommon and applies only to escapers that assume UCS-2 rather than
        // UTF-16. See: http://en.wikipedia.org/wiki/UTF-16/UCS-2
        if (hiChars == null && loChars == null) {
          // We expect this to be the common code path for most escapers.
          return null;
        }
        // Combine the characters and/or escaped sequences into a single array.
        int hiCount = hiChars != null ? hiChars.length : 1;
        int loCount = loChars != null ? loChars.length : 1;
        char[] output = new char[hiCount + loCount];
        if (hiChars != null) {
          // TODO: Is this faster than System.arraycopy() for small arrays?
          for (int n = 0; n < hiChars.length; ++n) {
            output[n] = hiChars[n];
          }
        } else {
          output[0] = surrogateChars[0];
        }
        if (loChars != null) {
          for (int n = 0; n < loChars.length; ++n) {
            output[hiCount + n] = loChars[n];
          }
        } else {
          output[hiCount] = surrogateChars[1];
        }
        return output;
      }
    };
  }
}


/*
 * 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.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Basic implementation of {@code Multiset<E>} backed by an instance of {@code
 * AbstractObjectCountMap<E>}.
 *
 * <p>For serialization to work, the subclass must specify explicit {@code readObject} and {@code
 * writeObject} methods.
 *
 * @author Kevin Bourrillion
 */
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E> implements Serializable {

  transient ObjectCountHashMap<E> backingMap;
  transient long size;

  AbstractMapBasedMultiset(int distinctElements) {
    init(distinctElements);
  }

  abstract void init(int distinctElements);

  @Override
  public final int count(@NullableDecl Object element) {
    return backingMap.get(element);
  }

  // Optional Operations - Modification Operations

  /**
   * {@inheritDoc}
   *
   * @throws IllegalArgumentException if the call would result in more than {@link
   *     Integer#MAX_VALUE} occurrences of {@code element} in this multiset.
   */
  @CanIgnoreReturnValue
  @Override
  public final int add(@NullableDecl E element, int occurrences) {
    if (occurrences == 0) {
      return count(element);
    }
    checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
    int entryIndex = backingMap.indexOf(element);
    if (entryIndex == -1) {
      backingMap.put(element, occurrences);
      size += occurrences;
      return 0;
    }
    int oldCount = backingMap.getValue(entryIndex);
    long newCount = (long) oldCount + (long) occurrences;
    checkArgument(newCount <= Integer.MAX_VALUE, "too many occurrences: %s", newCount);
    backingMap.setValue(entryIndex, (int) newCount);
    size += occurrences;
    return oldCount;
  }

  @CanIgnoreReturnValue
  @Override
  public final int remove(@NullableDecl Object element, int occurrences) {
    if (occurrences == 0) {
      return count(element);
    }
    checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
    int entryIndex = backingMap.indexOf(element);
    if (entryIndex == -1) {
      return 0;
    }
    int oldCount = backingMap.getValue(entryIndex);
    int numberRemoved;
    if (oldCount > occurrences) {
      numberRemoved = occurrences;
      backingMap.setValue(entryIndex, oldCount - occurrences);
    } else {
      numberRemoved = oldCount;
      backingMap.removeEntry(entryIndex);
    }
    size -= numberRemoved;
    return oldCount;
  }

  @CanIgnoreReturnValue
  @Override
  public final int setCount(@NullableDecl E element, int count) {
    checkNonnegative(count, "count");
    int oldCount = (count == 0) ? backingMap.remove(element) : backingMap.put(element, count);
    size += (count - oldCount);
    return oldCount;
  }

  @Override
  public final boolean setCount(@NullableDecl E element, int oldCount, int newCount) {
    checkNonnegative(oldCount, "oldCount");
    checkNonnegative(newCount, "newCount");
    int entryIndex = backingMap.indexOf(element);
    if (entryIndex == -1) {
      if (oldCount != 0) {
        return false;
      }
      if (newCount > 0) {
        backingMap.put(element, newCount);
        size += newCount;
      }
      return true;
    }
    int actualOldCount = backingMap.getValue(entryIndex);
    if (actualOldCount != oldCount) {
      return false;
    }
    if (newCount == 0) {
      backingMap.removeEntry(entryIndex);
      size -= oldCount;
    } else {
      backingMap.setValue(entryIndex, newCount);
      size += newCount - oldCount;
    }
    return true;
  }

  @Override
  public final void clear() {
    backingMap.clear();
    size = 0;
  }

  /**
   * Skeleton of per-entry iterators. We could push this down and win a few bytes, but it's complex
   * enough it's not especially worth it.
   */
  abstract class Itr<T> implements Iterator<T> {
    int entryIndex = backingMap.firstIndex();
    int toRemove = -1;
    int expectedModCount = backingMap.modCount;

    abstract T result(int entryIndex);

    private void checkForConcurrentModification() {
      if (backingMap.modCount != expectedModCount) {
        throw new ConcurrentModificationException();
      }
    }

    @Override
    public boolean hasNext() {
      checkForConcurrentModification();
      return entryIndex >= 0;
    }

    @Override
    public T next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      T result = result(entryIndex);
      toRemove = entryIndex;
      entryIndex = backingMap.nextIndex(entryIndex);
      return result;
    }

    @Override
    public void remove() {
      checkForConcurrentModification();
      CollectPreconditions.checkRemove(toRemove != -1);
      size -= backingMap.removeEntry(toRemove);
      entryIndex = backingMap.nextIndexAfterRemove(entryIndex, toRemove);
      toRemove = -1;
      expectedModCount = backingMap.modCount;
    }
  }

  @Override
  final Iterator<E> elementIterator() {
    return new Itr<E>() {
      @Override
      E result(int entryIndex) {
        return backingMap.getKey(entryIndex);
      }
    };
  }

  @Override
  final Iterator<Entry<E>> entryIterator() {
    return new Itr<Entry<E>>() {
      @Override
      Entry<E> result(int entryIndex) {
        return backingMap.getEntry(entryIndex);
      }
    };
  }

  /** Allocation-free implementation of {@code target.addAll(this)}. */
  void addTo(Multiset<? super E> target) {
    checkNotNull(target);
    for (int i = backingMap.firstIndex(); i >= 0; i = backingMap.nextIndex(i)) {
      target.add(backingMap.getKey(i), backingMap.getValue(i));
    }
  }

  @Override
  final int distinctElements() {
    return backingMap.size();
  }

  @Override
  public final Iterator<E> iterator() {
    return Multisets.iteratorImpl(this);
  }

  @Override
  public final int size() {
    return Ints.saturatedCast(size);
  }

  /**
   * @serialData the number of distinct elements, the first element, its count, the second element,
   *     its count, and so on
   */
  @GwtIncompatible // java.io.ObjectOutputStream
  private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    Serialization.writeMultiset(this, stream);
  }

  @GwtIncompatible // java.io.ObjectInputStream
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    int distinctElements = Serialization.readCount(stream);
    init(ObjectCountHashMap.DEFAULT_SIZE);
    Serialization.populateMultiset(this, stream, distinctElements);
  }

  @GwtIncompatible // Not needed in emulated source.
  private static final long serialVersionUID = 0;
}


/*
 * 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.compatqual.MonotonicNonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * 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. */
  @MonotonicNonNullDecl private transient TypeResolver invariantTypeResolver;

  /** Resolver for resolving covariant types with {@link #runtimeType} as context. */
  @MonotonicNonNullDecl private transient 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.
   */
  @NullableDecl
  final 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;
  }

  @NullableDecl
  private 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.
   */
  @NullableDecl
  public final 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 {

    @MonotonicNonNullDecl private transient 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;
    @MonotonicNonNullDecl private transient 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 {

    @MonotonicNonNullDecl private transient 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(@NullableDecl 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.
   */
  @NullableDecl
  private 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
          @NullableDecl
          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
          @NullableDecl
          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);

    @NullableDecl
    abstract 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) 2012 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.math;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.primitives.Doubles.isFinite;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;

/**
 * A mutable object which accumulates paired double values (e.g. points on a plane) and tracks some
 * basic statistics over all the values added so far. This class is not thread safe.
 *
 * @author Pete Gillin
 * @since 20.0
 */
@Beta
@GwtIncompatible
public final class PairedStatsAccumulator {

  // These fields must satisfy the requirements of PairedStats' constructor as well as those of the
  // stat methods of this class.
  private final StatsAccumulator xStats = new StatsAccumulator();
  private final StatsAccumulator yStats = new StatsAccumulator();
  private double sumOfProductsOfDeltas = 0.0;

  /** Adds the given pair of values to the dataset. */
  public void add(double x, double y) {
    // We extend the recursive expression for the one-variable case at Art of Computer Programming
    // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i.
    // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i.
    // We also define the sum of the products of the differences from the means
    //           C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n
    // for all n >= 1. Then for all n > 1:
    //       C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1}
    // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1}
    //               = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1}
    //               = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1}
    //               = (x_n - X_n) (y_n - Y_{n-1})
    xStats.add(x);
    if (isFinite(x) && isFinite(y)) {
      if (xStats.count() > 1) {
        sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean());
      }
    } else {
      sumOfProductsOfDeltas = NaN;
    }
    yStats.add(y);
  }

  /**
   * Adds the given statistics to the dataset, as if the individual values used to compute the
   * statistics had been added directly.
   */
  public void addAll(PairedStats values) {
    if (values.count() == 0) {
      return;
    }

    xStats.addAll(values.xStats());
    if (yStats.count() == 0) {
      sumOfProductsOfDeltas = values.sumOfProductsOfDeltas();
    } else {
      // This is a generalized version of the calculation in add(double, double) above. Note that
      // non-finite inputs will have sumOfProductsOfDeltas = NaN, so non-finite values will result
      // in NaN naturally.
      sumOfProductsOfDeltas +=
          values.sumOfProductsOfDeltas()
              + (values.xStats().mean() - xStats.mean())
                  * (values.yStats().mean() - yStats.mean())
                  * values.count();
    }
    yStats.addAll(values.yStats());
  }

  /** Returns an immutable snapshot of the current statistics. */
  public PairedStats snapshot() {
    return new PairedStats(xStats.snapshot(), yStats.snapshot(), sumOfProductsOfDeltas);
  }

  /** Returns the number of pairs in the dataset. */
  public long count() {
    return xStats.count();
  }

  /** Returns an immutable snapshot of the statistics on the {@code x} values alone. */
  public Stats xStats() {
    return xStats.snapshot();
  }

  /** Returns an immutable snapshot of the statistics on the {@code y} values alone. */
  public Stats yStats() {
    return yStats.snapshot();
  }

  /**
   * Returns the population covariance of the values. The count must be non-zero.
   *
   *
This is guaranteed to return zero if the dataset contains a single pair of finite values. It
   * is not guaranteed to return zero when the dataset consists of the same pair of values multiple
   * times, due to numerical errors.
   *
   *
Non-finite values

   *
   *
If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
   *
   * @throws IllegalStateException if the dataset is empty
   */
  public double populationCovariance() {
    checkState(count() != 0);
    return sumOfProductsOfDeltas / count();
  }

  /**
   * Returns the sample covariance of the values. The count must be greater than one.
   *
   *
This is not guaranteed to return zero when the dataset consists of the same pair of values
   * multiple times, due to numerical errors.
   *
   *
Non-finite values

   *
   *
If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
   *
   * @throws IllegalStateException if the dataset is empty or contains a single pair of values
   */
  public final double sampleCovariance() {
    checkState(count() > 1);
    return sumOfProductsOfDeltas / (count() - 1);
  }

  /**
   * Returns the Pearson's or
   * product-moment correlation coefficient of the values. The count must greater than one, and
   * the {@code x} and {@code y} values must both have non-zero population variance (i.e. {@code
   * xStats().populationVariance() > 0.0 && yStats().populationVariance() > 0.0}). The result is not
   * guaranteed to be exactly +/-1 even when the data are perfectly (anti-)correlated, due to
   * numerical errors. However, it is guaranteed to be in the inclusive range [-1, +1].
   *
   *
Non-finite values

   *
   *
If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}.
   *
   * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or
   *     either the {@code x} and {@code y} dataset has zero population variance
   */
  public final double pearsonsCorrelationCoefficient() {
    checkState(count() > 1);
    if (isNaN(sumOfProductsOfDeltas)) {
      return NaN;
    }
    double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas();
    double ySumOfSquaresOfDeltas = yStats.sumOfSquaresOfDeltas();
    checkState(xSumOfSquaresOfDeltas > 0.0);
    checkState(ySumOfSquaresOfDeltas > 0.0);
    // The product of two positive numbers can be zero if the multiplication underflowed. We
    // force a positive value by effectively rounding up to MIN_VALUE.
    double productOfSumsOfSquaresOfDeltas =
        ensurePositive(xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas);
    return ensureInUnitRange(sumOfProductsOfDeltas / Math.sqrt(productOfSumsOfSquaresOfDeltas));
  }

  /**
   * Returns a linear transformation giving the best fit to the data according to Ordinary Least Squares linear
   * regression of {@code y} as a function of {@code x}. The count must be greater than one, and
   * either the {@code x} or {@code y} data must have a non-zero population variance (i.e. {@code
   * xStats().populationVariance() > 0.0 || yStats().populationVariance() > 0.0}). The result is
   * guaranteed to be horizontal if there is variance in the {@code x} data but not the {@code y}
   * data, and vertical if there is variance in the {@code y} data but not the {@code x} data.
   *
   *
This fit minimizes the root-mean-square error in {@code y} as a function of {@code x}. This
   * error is defined as the square root of the mean of the squares of the differences between the
   * actual {@code y} values of the data and the values predicted by the fit for the {@code x}
   * values (i.e. it is the square root of the mean of the squares of the vertical distances between
   * the data points and the best fit line). For this fit, this error is a fraction {@code sqrt(1 -
   * R*R)} of the population standard deviation of {@code y}, where {@code R} is the Pearson's
   * correlation coefficient (as given by {@link #pearsonsCorrelationCoefficient()}).
   *
   *
The corresponding root-mean-square error in {@code x} as a function of {@code y} is a
   * fraction {@code sqrt(1/(R*R) - 1)} of the population standard deviation of {@code x}. This fit
   * does not normally minimize that error: to do that, you should swap the roles of {@code x} and
   * {@code y}.
   *
   *
Non-finite values

   *
   *
If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link
   * Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link
   * LinearTransformation#forNaN()}.
   *
   * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or
   *     both the {@code x} and {@code y} dataset have zero population variance
   */
  public final LinearTransformation leastSquaresFit() {
    checkState(count() > 1);
    if (isNaN(sumOfProductsOfDeltas)) {
      return LinearTransformation.forNaN();
    }
    double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas();
    if (xSumOfSquaresOfDeltas > 0.0) {
      if (yStats.sumOfSquaresOfDeltas() > 0.0) {
        return LinearTransformation.mapping(xStats.mean(), yStats.mean())
            .withSlope(sumOfProductsOfDeltas / xSumOfSquaresOfDeltas);
      } else {
        return LinearTransformation.horizontal(yStats.mean());
      }
    } else {
      checkState(yStats.sumOfSquaresOfDeltas() > 0.0);
      return LinearTransformation.vertical(xStats.mean());
    }
  }

  private double ensurePositive(double value) {
    if (value > 0.0) {
      return value;
    } else {
      return Double.MIN_VALUE;
    }
  }

  private static double ensureInUnitRange(double value) {
    if (value >= 1.0) {
      return 1.0;
    }
    if (value <= -1.0) {
      return -1.0;
    }
    return value;
  }
}


/*
 * Copyright (C) 2009 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.checkNotNull;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.primitives.Primitives;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
import java.io.Serializable;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A {@link ClassToInstanceMap} whose contents will never change, with many other important
 * properties detailed at {@link ImmutableCollection}.
 *
 * @author Kevin Bourrillion
 * @since 2.0
 */
@Immutable(containerOf = "B")
@GwtIncompatible
public final class ImmutableClassToInstanceMap extends ForwardingMap<Class<? extends B>, B>
    implements ClassToInstanceMap, Serializable {

  private static final ImmutableClassToInstanceMap<Object> EMPTY =
      new ImmutableClassToInstanceMap<>(ImmutableMap.<Class<?>, Object>of());

  /**
   * Returns an empty {@code ImmutableClassToInstanceMap}.
   *
   * @since 19.0
   */
  @SuppressWarnings("unchecked")
  public static  ImmutableClassToInstanceMap of() {
    return (ImmutableClassToInstanceMap) EMPTY;
  }

  /**
   * Returns an {@code ImmutableClassToInstanceMap} containing a single entry.
   *
   * @since 19.0
   */
  public static  ImmutableClassToInstanceMap of(Class<T> type, T value) {
    ImmutableMap<Class<? extends B>, B> map = ImmutableMap.<Class<? extends B>, B>of(type, value);
    return new ImmutableClassToInstanceMap(map);
  }

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

  /**
   * A builder for creating immutable class-to-instance maps. Example:
   *
   *
{@code
   * static final ImmutableClassToInstanceMap<Handler> HANDLERS =
   *     new ImmutableClassToInstanceMap.Builder<Handler>()
   *         .put(FooHandler.class, new FooHandler())
   *         .put(BarHandler.class, new SubBarHandler())
   *         .put(Handler.class, new QuuxHandler())
   *         .build();
   * }

   *
   *
After invoking {@link #build()} it is still possible to add more entries and build again.
   * Thus each map generated by this builder will be a superset of any map generated before it.
   *
   * @since 2.0
   */
  public static final class Builder {
    private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder = ImmutableMap.builder();

    /**
     * Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
     * and will cause {@link #build} to fail.
     */
    @CanIgnoreReturnValue
    public <T extends B> Builder put(Class<T> key, T value) {
      mapBuilder.put(key, value);
      return this;
    }

    /**
     * Associates all of {@code map's} keys and values in the built map. Duplicate keys are not
     * allowed, and will cause {@link #build} to fail.
     *
     * @throws NullPointerException if any key or value in {@code map} is null
     * @throws ClassCastException if any value is not an instance of the type specified by its key
     */
    @CanIgnoreReturnValue
    public <T extends B> Builder putAll(Map<? extends Class<? extends T>, ? extends T> map) {
      for (Entry<? extends Class<? extends T>, ? extends T> entry : map.entrySet()) {
        Class<? extends T> type = entry.getKey();
        T value = entry.getValue();
        mapBuilder.put(type, cast(type, value));
      }
      return this;
    }

    private static  T cast(Class<T> type, B value) {
      return Primitives.wrap(type).cast(value);
    }

    /**
     * Returns a new immutable class-to-instance map containing the entries provided to this
     * builder.
     *
     * @throws IllegalArgumentException if duplicate keys were added
     */
    public ImmutableClassToInstanceMap build() {
      ImmutableMap<Class<? extends B>, B> map = mapBuilder.build();
      if (map.isEmpty()) {
        return of();
      } else {
        return new ImmutableClassToInstanceMap(map);
      }
    }
  }

  /**
   * Returns an immutable map containing the same entries as {@code map}. If {@code map} somehow
   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
   * comparator is not consistent with equals), the results of this method are undefined.
   *
   *
Note: Despite what the method name suggests, if {@code map} is an {@code
   * ImmutableClassToInstanceMap}, no copy will actually be performed.
   *
   * @throws NullPointerException if any key or value in {@code map} is null
   * @throws ClassCastException if any value is not an instance of the type specified by its key
   */
  public static  ImmutableClassToInstanceMap copyOf(
      Map<? extends Class<? extends S>, ? extends S> map) {
    if (map instanceof ImmutableClassToInstanceMap) {
      @SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
      // Eclipse won't compile if we cast to the parameterized type.
      ImmutableClassToInstanceMap cast = (ImmutableClassToInstanceMap) map;
      return cast;
    }
    return new Builder().putAll(map).build();
  }

  private final ImmutableMap<Class<? extends B>, B> delegate;

  private ImmutableClassToInstanceMap(ImmutableMap<Class<? extends B>, B> delegate) {
    this.delegate = delegate;
  }

  @Override
  protected Map<Class<? extends B>, B> delegate() {
    return delegate;
  }

  @Override
  @SuppressWarnings("unchecked") // value could not get in if not a T
  public <T extends B> @Nullable T getInstance(Class<T> type) {
    return (T) delegate.get(checkNotNull(type));
  }

  /**
   * Guaranteed to throw an exception and leave the map unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public <T extends B> T putInstance(Class<T> type, T value) {
    throw new UnsupportedOperationException();
  }

  Object readResolve() {
    return isEmpty() ? of() : this;
  }
}


/*
 * Copyright (C) 2008 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 java.util.Arrays;
import java.util.Map;
import java.util.Set;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

/**
 * Minimal GWT emulation of {@code com.google.common.collect.Platform}.
 *
 *
This .java file should never be consumed by javac.
 *
 * @author Hayward Chan
 */
final class Platform {
  static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
    return Maps.newHashMapWithExpectedSize(expectedSize);
  }

  static <K, V> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
    return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
  }

  static <E> Set<E> newHashSetWithExpectedSize(int expectedSize) {
    return Sets.newHashSetWithExpectedSize(expectedSize);
  }

  static <E> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
    return Sets.newLinkedHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred map implementation that preserves insertion order when used only
   * for insertions.
   */
  static <K, V> Map<K, V> preservesInsertionOrderOnPutsMap() {
    return Maps.newLinkedHashMap();
  }

  /**
   * Returns the platform preferred set implementation that preserves insertion order when used only
   * for insertions.
   */
  static <E> Set<E> preservesInsertionOrderOnAddsSet() {
    return Sets.newLinkedHashSet();
  }

  static <T> T[] newArray(T[] reference, int length) {
    T[] clone = Arrays.copyOf(reference, 0);
    resizeArray(clone, length);
    return clone;
  }

  private static void resizeArray(Object array, int newSize) {
    ((NativeArray) array).setLength(newSize);
  }

  /** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */
  static <T> T[] copy(Object[] source, int from, int to, T[] arrayOfType) {
    T[] result = newArray(arrayOfType, to - from);
    System.arraycopy(source, from, result, 0, to - from);
    return result;
  }

  // TODO(user): Move this logic to a utility class.
  @JsType(isNative = true, name = "Array", namespace = JsPackage.GLOBAL)
  private interface NativeArray {
    @JsProperty
    void setLength(int length);
  }

  static MapMaker tryWeakKeys(MapMaker mapMaker) {
    return mapMaker;
  }

  static int reduceIterationsIfGwt(int iterations) {
    return iterations / 10;
  }

  static int reduceExponentIfGwt(int exponent) {
    return exponent / 2;
  }

  private Platform() {}
}