1 /*
   2  * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.vm.annotation.Stable;
  29 import sun.invoke.util.Wrapper;
  30 import java.lang.ref.WeakReference;
  31 import java.lang.ref.Reference;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.util.Arrays;
  34 import java.util.Collections;
  35 import java.util.List;
  36 import java.util.Objects;
  37 import java.util.StringJoiner;
  38 import java.util.concurrent.ConcurrentMap;
  39 import java.util.concurrent.ConcurrentHashMap;
  40 import sun.invoke.util.BytecodeDescriptor;
  41 import static java.lang.invoke.MethodHandleStatics.*;
  42 import sun.invoke.util.VerifyType;
  43 
  44 /**
  45  * A method type represents the arguments and return type accepted and
  46  * returned by a method handle, or the arguments and return type passed
  47  * and expected  by a method handle caller.  Method types must be properly
  48  * matched between a method handle and all its callers,
  49  * and the JVM's operations enforce this matching at, specifically
  50  * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
  51  * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
  52  * of {@code invokedynamic} instructions.
  53  * <p>
  54  * The structure is a return type accompanied by any number of parameter types.
  55  * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
  56  * (For ease of exposition, we treat {@code void} as if it were a type.
  57  * In fact, it denotes the absence of a return type.)
  58  * <p>
  59  * All instances of {@code MethodType} are immutable.
  60  * Two instances are completely interchangeable if they compare equal.
  61  * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
  62  * <p>
  63  * This type can be created only by factory methods.
  64  * All factory methods may cache values, though caching is not guaranteed.
  65  * Some factory methods are static, while others are virtual methods which
  66  * modify precursor method types, e.g., by changing a selected parameter.
  67  * <p>
  68  * Factory methods which operate on groups of parameter types
  69  * are systematically presented in two versions, so that both Java arrays and
  70  * Java lists can be used to work with groups of parameter types.
  71  * The query methods {@code parameterArray} and {@code parameterList}
  72  * also provide a choice between arrays and lists.
  73  * <p>
  74  * {@code MethodType} objects are sometimes derived from bytecode instructions
  75  * such as {@code invokedynamic}, specifically from the type descriptor strings associated
  76  * with the instructions in a class file's constant pool.
  77  * <p>
  78  * Like classes and strings, method types can also be represented directly
  79  * in a class file's constant pool as constants.
  80  * A method type may be loaded by an {@code ldc} instruction which refers
  81  * to a suitable {@code CONSTANT_MethodType} constant pool entry.
  82  * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
  83  * (For full details on method type constants,
  84  * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
  85  * <p>
  86  * When the JVM materializes a {@code MethodType} from a descriptor string,
  87  * all classes named in the descriptor must be accessible, and will be loaded.
  88  * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
  89  * This loading may occur at any time before the {@code MethodType} object is first derived.
  90  * @author John Rose, JSR 292 EG
  91  * @since 1.7
  92  */
  93 public final
  94 class MethodType implements java.io.Serializable {
  95     private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
  96 
  97     // The rtype and ptypes fields define the structural identity of the method type:
  98     private final @Stable Class<?>   rtype;
  99     private final @Stable Class<?>[] ptypes;
 100 
 101     // The remaining fields are caches of various sorts:
 102     private @Stable MethodTypeForm form; // erased form, plus cached data about primitives
 103     private @Stable MethodType wrapAlt;  // alternative wrapped/unwrapped version
 104     private @Stable Invokers invokers;   // cache of handy higher-order adapters
 105     private @Stable String methodDescriptor;  // cache for toMethodDescriptorString
 106 
 107     /**
 108      * Check the given parameters for validity and store them into the final fields.
 109      */
 110     private MethodType(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 111         checkRtype(rtype);
 112         checkPtypes(ptypes);
 113         this.rtype = rtype;
 114         // defensively copy the array passed in by the user
 115         this.ptypes = trusted ? ptypes : Arrays.copyOf(ptypes, ptypes.length);
 116     }
 117 
 118     /**
 119      * Construct a temporary unchecked instance of MethodType for use only as a key to the intern table.
 120      * Does not check the given parameters for validity, and must discarded (if untrusted) or checked
 121      * (if trusted) after it has been used as a searching key.
 122      * The parameters are reversed for this constructor, so that it is not accidentally used.
 123      */
 124     private MethodType(Class<?>[] ptypes, Class<?> rtype) {
 125         this.rtype = rtype;
 126         this.ptypes = ptypes;
 127     }
 128 
 129     /*trusted*/ MethodTypeForm form() { return form; }
 130     /*trusted*/ Class<?> rtype() { return rtype; }
 131     /*trusted*/ Class<?>[] ptypes() { return ptypes; }
 132 
 133     void setForm(MethodTypeForm f) { form = f; }
 134 
 135     /** This number, mandated by the JVM spec as 255,
 136      *  is the maximum number of <em>slots</em>
 137      *  that any Java method can receive in its argument list.
 138      *  It limits both JVM signatures and method type objects.
 139      *  The longest possible invocation will look like
 140      *  {@code staticMethod(arg1, arg2, ..., arg255)} or
 141      *  {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
 142      */
 143     /*non-public*/ static final int MAX_JVM_ARITY = 255;  // this is mandated by the JVM spec.
 144 
 145     /** This number is the maximum arity of a method handle, 254.
 146      *  It is derived from the absolute JVM-imposed arity by subtracting one,
 147      *  which is the slot occupied by the method handle itself at the
 148      *  beginning of the argument list used to invoke the method handle.
 149      *  The longest possible invocation will look like
 150      *  {@code mh.invoke(arg1, arg2, ..., arg254)}.
 151      */
 152     // Issue:  Should we allow MH.invokeWithArguments to go to the full 255?
 153     /*non-public*/ static final int MAX_MH_ARITY = MAX_JVM_ARITY-1;  // deduct one for mh receiver
 154 
 155     /** This number is the maximum arity of a method handle invoker, 253.
 156      *  It is derived from the absolute JVM-imposed arity by subtracting two,
 157      *  which are the slots occupied by invoke method handle, and the
 158      *  target method handle, which are both at the beginning of the argument
 159      *  list used to invoke the target method handle.
 160      *  The longest possible invocation will look like
 161      *  {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
 162      */
 163     /*non-public*/ static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1;  // deduct one more for invoker
 164 
 165     private static void checkRtype(Class<?> rtype) {
 166         Objects.requireNonNull(rtype);
 167     }
 168     private static void checkPtype(Class<?> ptype) {
 169         Objects.requireNonNull(ptype);
 170         if (ptype == void.class)
 171             throw newIllegalArgumentException("parameter type cannot be void");
 172     }
 173     /** Return number of extra slots (count of long/double args). */
 174     private static int checkPtypes(Class<?>[] ptypes) {
 175         int slots = 0;
 176         for (Class<?> ptype : ptypes) {
 177             checkPtype(ptype);
 178             if (ptype == double.class || ptype == long.class) {
 179                 slots++;
 180             }
 181         }
 182         checkSlotCount(ptypes.length + slots);
 183         return slots;
 184     }
 185 
 186     static {
 187         // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
 188         assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
 189     }
 190     static void checkSlotCount(int count) {
 191         if ((count & MAX_JVM_ARITY) != count)
 192             throw newIllegalArgumentException("bad parameter count "+count);
 193     }
 194     private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
 195         if (num instanceof Integer)  num = "bad index: "+num;
 196         return new IndexOutOfBoundsException(num.toString());
 197     }
 198 
 199     static final ConcurrentWeakInternSet<MethodType> internTable = new ConcurrentWeakInternSet<>();
 200 
 201     static final Class<?>[] NO_PTYPES = {};
 202 
 203     /**
 204      * Finds or creates an instance of the given method type.
 205      * @param rtype  the return type
 206      * @param ptypes the parameter types
 207      * @return a method type with the given components
 208      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 209      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 210      */
 211     public static
 212     MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
 213         return makeImpl(rtype, ptypes, false);
 214     }
 215 
 216     /**
 217      * Finds or creates a method type with the given components.
 218      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 219      * @param rtype  the return type
 220      * @param ptypes the parameter types
 221      * @return a method type with the given components
 222      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 223      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 224      */
 225     public static
 226     MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
 227         boolean notrust = false;  // random List impl. could return evil ptypes array
 228         return makeImpl(rtype, listToArray(ptypes), notrust);
 229     }
 230 
 231     private static Class<?>[] listToArray(List<Class<?>> ptypes) {
 232         // sanity check the size before the toArray call, since size might be huge
 233         checkSlotCount(ptypes.size());
 234         return ptypes.toArray(NO_PTYPES);
 235     }
 236 
 237     /**
 238      * Finds or creates a method type with the given components.
 239      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 240      * The leading parameter type is prepended to the remaining array.
 241      * @param rtype  the return type
 242      * @param ptype0 the first parameter type
 243      * @param ptypes the remaining parameter types
 244      * @return a method type with the given components
 245      * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
 246      * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
 247      */
 248     public static
 249     MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
 250         Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
 251         ptypes1[0] = ptype0;
 252         System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
 253         return makeImpl(rtype, ptypes1, true);
 254     }
 255 
 256     /**
 257      * Finds or creates a method type with the given components.
 258      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 259      * The resulting method has no parameter types.
 260      * @param rtype  the return type
 261      * @return a method type with the given return value
 262      * @throws NullPointerException if {@code rtype} is null
 263      */
 264     public static
 265     MethodType methodType(Class<?> rtype) {
 266         return makeImpl(rtype, NO_PTYPES, true);
 267     }
 268 
 269     /**
 270      * Finds or creates a method type with the given components.
 271      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 272      * The resulting method has the single given parameter type.
 273      * @param rtype  the return type
 274      * @param ptype0 the parameter type
 275      * @return a method type with the given return value and parameter type
 276      * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
 277      * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
 278      */
 279     public static
 280     MethodType methodType(Class<?> rtype, Class<?> ptype0) {
 281         return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
 282     }
 283 
 284     /**
 285      * Finds or creates a method type with the given components.
 286      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 287      * The resulting method has the same parameter types as {@code ptypes},
 288      * and the specified return type.
 289      * @param rtype  the return type
 290      * @param ptypes the method type which supplies the parameter types
 291      * @return a method type with the given components
 292      * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
 293      */
 294     public static
 295     MethodType methodType(Class<?> rtype, MethodType ptypes) {
 296         return makeImpl(rtype, ptypes.ptypes, true);
 297     }
 298 
 299     /**
 300      * Sole factory method to find or create an interned method type.
 301      * @param rtype desired return type
 302      * @param ptypes desired parameter types
 303      * @param trusted whether the ptypes can be used without cloning
 304      * @return the unique method type of the desired structure
 305      */
 306     /*trusted*/ static
 307     MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 308         if (ptypes.length == 0) {
 309             ptypes = NO_PTYPES; trusted = true;
 310         }
 311         MethodType primordialMT = new MethodType(ptypes, rtype);
 312         MethodType mt = internTable.get(primordialMT);
 313         if (mt != null)
 314             return mt;
 315 
 316         // promote the object to the Real Thing, and reprobe
 317         if (trusted) {
 318             MethodType.checkRtype(rtype);
 319             MethodType.checkPtypes(ptypes);
 320             mt = primordialMT;
 321         } else {
 322             mt = new MethodType(rtype, ptypes, false);
 323         }
 324         mt.form = MethodTypeForm.findForm(mt);
 325         return internTable.add(mt);
 326     }
 327     private static final @Stable MethodType[] objectOnlyTypes = new MethodType[20];
 328 
 329     /**
 330      * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
 331      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 332      * All parameters and the return type will be {@code Object},
 333      * except the final array parameter if any, which will be {@code Object[]}.
 334      * @param objectArgCount number of parameters (excluding the final array parameter if any)
 335      * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
 336      * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
 337      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
 338      * @see #genericMethodType(int)
 339      */
 340     public static
 341     MethodType genericMethodType(int objectArgCount, boolean finalArray) {
 342         MethodType mt;
 343         checkSlotCount(objectArgCount);
 344         int ivarargs = (!finalArray ? 0 : 1);
 345         int ootIndex = objectArgCount*2 + ivarargs;
 346         if (ootIndex < objectOnlyTypes.length) {
 347             mt = objectOnlyTypes[ootIndex];
 348             if (mt != null)  return mt;
 349         }
 350         Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
 351         Arrays.fill(ptypes, Object.class);
 352         if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
 353         mt = makeImpl(Object.class, ptypes, true);
 354         if (ootIndex < objectOnlyTypes.length) {
 355             objectOnlyTypes[ootIndex] = mt;     // cache it here also!
 356         }
 357         return mt;
 358     }
 359 
 360     /**
 361      * Finds or creates a method type whose components are all {@code Object}.
 362      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 363      * All parameters and the return type will be Object.
 364      * @param objectArgCount number of parameters
 365      * @return a generally applicable method type, for all calls of the given argument count
 366      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
 367      * @see #genericMethodType(int, boolean)
 368      */
 369     public static
 370     MethodType genericMethodType(int objectArgCount) {
 371         return genericMethodType(objectArgCount, false);
 372     }
 373 
 374     /**
 375      * Finds or creates a method type with a single different parameter type.
 376      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 377      * @param num    the index (zero-based) of the parameter type to change
 378      * @param nptype a new parameter type to replace the old one with
 379      * @return the same type, except with the selected parameter changed
 380      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 381      * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
 382      * @throws NullPointerException if {@code nptype} is null
 383      */
 384     public MethodType changeParameterType(int num, Class<?> nptype) {
 385         if (parameterType(num) == nptype)  return this;
 386         checkPtype(nptype);
 387         Class<?>[] nptypes = ptypes.clone();
 388         nptypes[num] = nptype;
 389         return makeImpl(rtype, nptypes, true);
 390     }
 391 
 392     /**
 393      * Finds or creates a method type with additional parameter types.
 394      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 395      * @param num    the position (zero-based) of the inserted parameter type(s)
 396      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 397      * @return the same type, except with the selected parameter(s) inserted
 398      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 399      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 400      *                                  or if the resulting method type would have more than 255 parameter slots
 401      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 402      */
 403     public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
 404         int len = ptypes.length;
 405         if (num < 0 || num > len)
 406             throw newIndexOutOfBoundsException(num);
 407         int ins = checkPtypes(ptypesToInsert);
 408         checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
 409         int ilen = ptypesToInsert.length;
 410         if (ilen == 0)  return this;
 411         Class<?>[] nptypes = new Class<?>[len + ilen];
 412         if (num > 0) {
 413             System.arraycopy(ptypes, 0, nptypes, 0, num);
 414         }
 415         System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
 416         if (num < len) {
 417             System.arraycopy(ptypes, num, nptypes, num+ilen, len-num);
 418         }
 419         return makeImpl(rtype, nptypes, true);
 420     }
 421 
 422     /**
 423      * Finds or creates a method type with additional parameter types.
 424      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 425      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 426      * @return the same type, except with the selected parameter(s) appended
 427      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 428      *                                  or if the resulting method type would have more than 255 parameter slots
 429      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 430      */
 431     public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
 432         return insertParameterTypes(parameterCount(), ptypesToInsert);
 433     }
 434 
 435     /**
 436      * Finds or creates a method type with additional parameter types.
 437      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 438      * @param num    the position (zero-based) of the inserted parameter type(s)
 439      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 440      * @return the same type, except with the selected parameter(s) inserted
 441      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 442      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 443      *                                  or if the resulting method type would have more than 255 parameter slots
 444      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 445      */
 446     public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
 447         return insertParameterTypes(num, listToArray(ptypesToInsert));
 448     }
 449 
 450     /**
 451      * Finds or creates a method type with additional parameter types.
 452      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 453      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 454      * @return the same type, except with the selected parameter(s) appended
 455      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 456      *                                  or if the resulting method type would have more than 255 parameter slots
 457      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 458      */
 459     public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
 460         return insertParameterTypes(parameterCount(), ptypesToInsert);
 461     }
 462 
 463      /**
 464      * Finds or creates a method type with modified parameter types.
 465      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 466      * @param start  the position (zero-based) of the first replaced parameter type(s)
 467      * @param end    the position (zero-based) after the last replaced parameter type(s)
 468      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 469      * @return the same type, except with the selected parameter(s) replaced
 470      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 471      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 472      *                                  or if {@code start} is greater than {@code end}
 473      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 474      *                                  or if the resulting method type would have more than 255 parameter slots
 475      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 476      */
 477     /*non-public*/ MethodType replaceParameterTypes(int start, int end, Class<?>... ptypesToInsert) {
 478         if (start == end)
 479             return insertParameterTypes(start, ptypesToInsert);
 480         int len = ptypes.length;
 481         if (!(0 <= start && start <= end && end <= len))
 482             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 483         int ilen = ptypesToInsert.length;
 484         if (ilen == 0)
 485             return dropParameterTypes(start, end);
 486         return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert);
 487     }
 488 
 489     /** Replace the last arrayLength parameter types with the component type of arrayType.
 490      * @param arrayType any array type
 491      * @param pos position at which to spread
 492      * @param arrayLength the number of parameter types to change
 493      * @return the resulting type
 494      */
 495     /*non-public*/ MethodType asSpreaderType(Class<?> arrayType, int pos, int arrayLength) {
 496         assert(parameterCount() >= arrayLength);
 497         int spreadPos = pos;
 498         if (arrayLength == 0)  return this;  // nothing to change
 499         if (arrayType == Object[].class) {
 500             if (isGeneric())  return this;  // nothing to change
 501             if (spreadPos == 0) {
 502                 // no leading arguments to preserve; go generic
 503                 MethodType res = genericMethodType(arrayLength);
 504                 if (rtype != Object.class) {
 505                     res = res.changeReturnType(rtype);
 506                 }
 507                 return res;
 508             }
 509         }
 510         Class<?> elemType = arrayType.getComponentType();
 511         assert(elemType != null);
 512         for (int i = spreadPos; i < spreadPos + arrayLength; i++) {
 513             if (ptypes[i] != elemType) {
 514                 Class<?>[] fixedPtypes = ptypes.clone();
 515                 Arrays.fill(fixedPtypes, i, spreadPos + arrayLength, elemType);
 516                 return methodType(rtype, fixedPtypes);
 517             }
 518         }
 519         return this;  // arguments check out; no change
 520     }
 521 
 522     /** Return the leading parameter type, which must exist and be a reference.
 523      *  @return the leading parameter type, after error checks
 524      */
 525     /*non-public*/ Class<?> leadingReferenceParameter() {
 526         Class<?> ptype;
 527         if (ptypes.length == 0 ||
 528             (ptype = ptypes[0]).isPrimitive())
 529             throw newIllegalArgumentException("no leading reference parameter");
 530         return ptype;
 531     }
 532 
 533     /** Delete the last parameter type and replace it with arrayLength copies of the component type of arrayType.
 534      * @param arrayType any array type
 535      * @param pos position at which to insert parameters
 536      * @param arrayLength the number of parameter types to insert
 537      * @return the resulting type
 538      */
 539     /*non-public*/ MethodType asCollectorType(Class<?> arrayType, int pos, int arrayLength) {
 540         assert(parameterCount() >= 1);
 541         assert(pos < ptypes.length);
 542         assert(ptypes[pos].isAssignableFrom(arrayType));
 543         MethodType res;
 544         if (arrayType == Object[].class) {
 545             res = genericMethodType(arrayLength);
 546             if (rtype != Object.class) {
 547                 res = res.changeReturnType(rtype);
 548             }
 549         } else {
 550             Class<?> elemType = arrayType.getComponentType();
 551             assert(elemType != null);
 552             res = methodType(rtype, Collections.nCopies(arrayLength, elemType));
 553         }
 554         if (ptypes.length == 1) {
 555             return res;
 556         } else {
 557             // insert after (if need be), then before
 558             if (pos < ptypes.length - 1) {
 559                 res = res.insertParameterTypes(arrayLength, Arrays.copyOfRange(ptypes, pos + 1, ptypes.length));
 560             }
 561             return res.insertParameterTypes(0, Arrays.copyOf(ptypes, pos));
 562         }
 563     }
 564 
 565     /**
 566      * Finds or creates a method type with some parameter types omitted.
 567      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 568      * @param start  the index (zero-based) of the first parameter type to remove
 569      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
 570      * @return the same type, except with the selected parameter(s) removed
 571      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 572      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 573      *                                  or if {@code start} is greater than {@code end}
 574      */
 575     public MethodType dropParameterTypes(int start, int end) {
 576         int len = ptypes.length;
 577         if (!(0 <= start && start <= end && end <= len))
 578             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 579         if (start == end)  return this;
 580         Class<?>[] nptypes;
 581         if (start == 0) {
 582             if (end == len) {
 583                 // drop all parameters
 584                 nptypes = NO_PTYPES;
 585             } else {
 586                 // drop initial parameter(s)
 587                 nptypes = Arrays.copyOfRange(ptypes, end, len);
 588             }
 589         } else {
 590             if (end == len) {
 591                 // drop trailing parameter(s)
 592                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
 593             } else {
 594                 int tail = len - end;
 595                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
 596                 System.arraycopy(ptypes, end, nptypes, start, tail);
 597             }
 598         }
 599         return makeImpl(rtype, nptypes, true);
 600     }
 601 
 602     /**
 603      * Finds or creates a method type with a different return type.
 604      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 605      * @param nrtype a return parameter type to replace the old one with
 606      * @return the same type, except with the return type change
 607      * @throws NullPointerException if {@code nrtype} is null
 608      */
 609     public MethodType changeReturnType(Class<?> nrtype) {
 610         if (returnType() == nrtype)  return this;
 611         return makeImpl(nrtype, ptypes, true);
 612     }
 613 
 614     /**
 615      * Reports if this type contains a primitive argument or return value.
 616      * The return type {@code void} counts as a primitive.
 617      * @return true if any of the types are primitives
 618      */
 619     public boolean hasPrimitives() {
 620         return form.hasPrimitives();
 621     }
 622 
 623     /**
 624      * Reports if this type contains a wrapper argument or return value.
 625      * Wrappers are types which box primitive values, such as {@link Integer}.
 626      * The reference type {@code java.lang.Void} counts as a wrapper,
 627      * if it occurs as a return type.
 628      * @return true if any of the types are wrappers
 629      */
 630     public boolean hasWrappers() {
 631         return unwrap() != this;
 632     }
 633 
 634     /**
 635      * Erases all reference types to {@code Object}.
 636      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 637      * All primitive types (including {@code void}) will remain unchanged.
 638      * @return a version of the original type with all reference types replaced
 639      */
 640     public MethodType erase() {
 641         return form.erasedType();
 642     }
 643 
 644     /**
 645      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
 646      * This is the reduced type polymorphism used by private methods
 647      * such as {@link MethodHandle#invokeBasic invokeBasic}.
 648      * @return a version of the original type with all reference and subword types replaced
 649      */
 650     /*non-public*/ MethodType basicType() {
 651         return form.basicType();
 652     }
 653 
 654     private static final @Stable Class<?>[] METHOD_HANDLE_ARRAY
 655             = new Class<?>[] { MethodHandle.class };
 656 
 657     /**
 658      * @return a version of the original type with MethodHandle prepended as the first argument
 659      */
 660     /*non-public*/ MethodType invokerType() {
 661         return insertParameterTypes(0, METHOD_HANDLE_ARRAY);
 662     }
 663 
 664     /**
 665      * Converts all types, both reference and primitive, to {@code Object}.
 666      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
 667      * The expression {@code type.wrap().erase()} produces the same value
 668      * as {@code type.generic()}.
 669      * @return a version of the original type with all types replaced
 670      */
 671     public MethodType generic() {
 672         return genericMethodType(parameterCount());
 673     }
 674 
 675     /*non-public*/ boolean isGeneric() {
 676         return this == erase() && !hasPrimitives();
 677     }
 678 
 679     /**
 680      * Converts all primitive types to their corresponding wrapper types.
 681      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 682      * All reference types (including wrapper types) will remain unchanged.
 683      * A {@code void} return type is changed to the type {@code java.lang.Void}.
 684      * The expression {@code type.wrap().erase()} produces the same value
 685      * as {@code type.generic()}.
 686      * @return a version of the original type with all primitive types replaced
 687      */
 688     public MethodType wrap() {
 689         return hasPrimitives() ? wrapWithPrims(this) : this;
 690     }
 691 
 692     /**
 693      * Converts all wrapper types to their corresponding primitive types.
 694      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 695      * All primitive types (including {@code void}) will remain unchanged.
 696      * A return type of {@code java.lang.Void} is changed to {@code void}.
 697      * @return a version of the original type with all wrapper types replaced
 698      */
 699     public MethodType unwrap() {
 700         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
 701         return unwrapWithNoPrims(noprims);
 702     }
 703 
 704     private static MethodType wrapWithPrims(MethodType pt) {
 705         assert(pt.hasPrimitives());
 706         MethodType wt = pt.wrapAlt;
 707         if (wt == null) {
 708             // fill in lazily
 709             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
 710             assert(wt != null);
 711             pt.wrapAlt = wt;
 712         }
 713         return wt;
 714     }
 715 
 716     private static MethodType unwrapWithNoPrims(MethodType wt) {
 717         assert(!wt.hasPrimitives());
 718         MethodType uwt = wt.wrapAlt;
 719         if (uwt == null) {
 720             // fill in lazily
 721             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
 722             if (uwt == null)
 723                 uwt = wt;    // type has no wrappers or prims at all
 724             wt.wrapAlt = uwt;
 725         }
 726         return uwt;
 727     }
 728 
 729     /**
 730      * Returns the parameter type at the specified index, within this method type.
 731      * @param num the index (zero-based) of the desired parameter type
 732      * @return the selected parameter type
 733      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 734      */
 735     public Class<?> parameterType(int num) {
 736         return ptypes[num];
 737     }
 738     /**
 739      * Returns the number of parameter types in this method type.
 740      * @return the number of parameter types
 741      */
 742     public int parameterCount() {
 743         return ptypes.length;
 744     }
 745     /**
 746      * Returns the return type of this method type.
 747      * @return the return type
 748      */
 749     public Class<?> returnType() {
 750         return rtype;
 751     }
 752 
 753     /**
 754      * Presents the parameter types as a list (a convenience method).
 755      * The list will be immutable.
 756      * @return the parameter types (as an immutable list)
 757      */
 758     public List<Class<?>> parameterList() {
 759         return Collections.unmodifiableList(Arrays.asList(ptypes.clone()));
 760     }
 761 
 762     /*non-public*/ Class<?> lastParameterType() {
 763         int len = ptypes.length;
 764         return len == 0 ? void.class : ptypes[len-1];
 765     }
 766 
 767     /**
 768      * Presents the parameter types as an array (a convenience method).
 769      * Changes to the array will not result in changes to the type.
 770      * @return the parameter types (as a fresh copy if necessary)
 771      */
 772     public Class<?>[] parameterArray() {
 773         return ptypes.clone();
 774     }
 775 
 776     /**
 777      * Compares the specified object with this type for equality.
 778      * That is, it returns {@code true} if and only if the specified object
 779      * is also a method type with exactly the same parameters and return type.
 780      * @param x object to compare
 781      * @see Object#equals(Object)
 782      */
 783     @Override
 784     public boolean equals(Object x) {
 785         return this == x || x instanceof MethodType && equals((MethodType)x);
 786     }
 787 
 788     private boolean equals(MethodType that) {
 789         return this.rtype == that.rtype
 790             && Arrays.equals(this.ptypes, that.ptypes);
 791     }
 792 
 793     /**
 794      * Returns the hash code value for this method type.
 795      * It is defined to be the same as the hashcode of a List
 796      * whose elements are the return type followed by the
 797      * parameter types.
 798      * @return the hash code value for this method type
 799      * @see Object#hashCode()
 800      * @see #equals(Object)
 801      * @see List#hashCode()
 802      */
 803     @Override
 804     public int hashCode() {
 805       int hashCode = 31 + rtype.hashCode();
 806       for (Class<?> ptype : ptypes)
 807           hashCode = 31*hashCode + ptype.hashCode();
 808       return hashCode;
 809     }
 810 
 811     /**
 812      * Returns a string representation of the method type,
 813      * of the form {@code "(PT0,PT1...)RT"}.
 814      * The string representation of a method type is a
 815      * parenthesis enclosed, comma separated list of type names,
 816      * followed immediately by the return type.
 817      * <p>
 818      * Each type is represented by its
 819      * {@link java.lang.Class#getSimpleName simple name}.
 820      */
 821     @Override
 822     public String toString() {
 823         StringJoiner sj = new StringJoiner(",", "(",
 824                 ")" + rtype.getSimpleName());
 825         for (int i = 0; i < ptypes.length; i++) {
 826             sj.add(ptypes[i].getSimpleName());
 827         }
 828         return sj.toString();
 829     }
 830 
 831     /** True if my parameter list is effectively identical to the given full list,
 832      *  after skipping the given number of my own initial parameters.
 833      *  In other words, after disregarding {@code skipPos} parameters,
 834      *  my remaining parameter list is no longer than the {@code fullList}, and
 835      *  is equal to the same-length initial sublist of {@code fullList}.
 836      */
 837     /*non-public*/
 838     boolean effectivelyIdenticalParameters(int skipPos, List<Class<?>> fullList) {
 839         int myLen = ptypes.length, fullLen = fullList.size();
 840         if (skipPos > myLen || myLen - skipPos > fullLen)
 841             return false;
 842         List<Class<?>> myList = Arrays.asList(ptypes);
 843         if (skipPos != 0) {
 844             myList = myList.subList(skipPos, myLen);
 845             myLen -= skipPos;
 846         }
 847         if (fullLen == myLen)
 848             return myList.equals(fullList);
 849         else
 850             return myList.equals(fullList.subList(0, myLen));
 851     }
 852 
 853     /** True if the old return type can always be viewed (w/o casting) under new return type,
 854      *  and the new parameters can be viewed (w/o casting) under the old parameter types.
 855      */
 856     /*non-public*/
 857     boolean isViewableAs(MethodType newType, boolean keepInterfaces) {
 858         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), keepInterfaces))
 859             return false;
 860         if (form == newType.form && form.erasedType == this)
 861             return true;  // my reference parameters are all Object
 862         if (ptypes == newType.ptypes)
 863             return true;
 864         int argc = parameterCount();
 865         if (argc != newType.parameterCount())
 866             return false;
 867         for (int i = 0; i < argc; i++) {
 868             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), keepInterfaces))
 869                 return false;
 870         }
 871         return true;
 872     }
 873     /*non-public*/
 874     boolean isConvertibleTo(MethodType newType) {
 875         MethodTypeForm oldForm = this.form();
 876         MethodTypeForm newForm = newType.form();
 877         if (oldForm == newForm)
 878             // same parameter count, same primitive/object mix
 879             return true;
 880         if (!canConvert(returnType(), newType.returnType()))
 881             return false;
 882         Class<?>[] srcTypes = newType.ptypes;
 883         Class<?>[] dstTypes = ptypes;
 884         if (srcTypes == dstTypes)
 885             return true;
 886         int argc;
 887         if ((argc = srcTypes.length) != dstTypes.length)
 888             return false;
 889         if (argc <= 1) {
 890             if (argc == 1 && !canConvert(srcTypes[0], dstTypes[0]))
 891                 return false;
 892             return true;
 893         }
 894         if ((oldForm.primitiveParameterCount() == 0 && oldForm.erasedType == this) ||
 895             (newForm.primitiveParameterCount() == 0 && newForm.erasedType == newType)) {
 896             // Somewhat complicated test to avoid a loop of 2 or more trips.
 897             // If either type has only Object parameters, we know we can convert.
 898             assert(canConvertParameters(srcTypes, dstTypes));
 899             return true;
 900         }
 901         return canConvertParameters(srcTypes, dstTypes);
 902     }
 903 
 904     /** Returns true if MHs.explicitCastArguments produces the same result as MH.asType.
 905      *  If the type conversion is impossible for either, the result should be false.
 906      */
 907     /*non-public*/
 908     boolean explicitCastEquivalentToAsType(MethodType newType) {
 909         if (this == newType)  return true;
 910         if (!explicitCastEquivalentToAsType(rtype, newType.rtype)) {
 911             return false;
 912         }
 913         Class<?>[] srcTypes = newType.ptypes;
 914         Class<?>[] dstTypes = ptypes;
 915         if (dstTypes == srcTypes) {
 916             return true;
 917         }
 918         assert(dstTypes.length == srcTypes.length);
 919         for (int i = 0; i < dstTypes.length; i++) {
 920             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
 921                 return false;
 922             }
 923         }
 924         return true;
 925     }
 926 
 927     /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE,
 928      *  and with the same effect.
 929      *  MHs.eCA has the following "upgrades" to MH.asType:
 930      *  1. interfaces are unchecked (that is, treated as if aliased to Object)
 931      *     Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics
 932      *  2. the full matrix of primitive-to-primitive conversions is supported
 933      *     Narrowing like {@code long->byte} and basic-typing like {@code boolean->int}
 934      *     are not supported by asType, but anything supported by asType is equivalent
 935      *     with MHs.eCE.
 936      *  3a. unboxing conversions can be followed by the full matrix of primitive conversions
 937      *  3b. unboxing of null is permitted (creates a zero primitive value)
 938      * Other than interfaces, reference-to-reference conversions are the same.
 939      * Boxing primitives to references is the same for both operators.
 940      */
 941     private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) {
 942         if (src == dst || dst == Object.class || dst == void.class)  return true;
 943         if (src.isPrimitive()) {
 944             // Could be a prim/prim conversion, where casting is a strict superset.
 945             // Or a boxing conversion, which is always to an exact wrapper class.
 946             return canConvert(src, dst);
 947         } else if (dst.isPrimitive()) {
 948             // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b).
 949             return false;
 950         } else {
 951             // R->R always works, but we have to avoid a check-cast to an interface.
 952             return !dst.isInterface() || dst.isAssignableFrom(src);
 953         }
 954     }
 955 
 956     private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) {
 957         for (int i = 0; i < srcTypes.length; i++) {
 958             if (!canConvert(srcTypes[i], dstTypes[i])) {
 959                 return false;
 960             }
 961         }
 962         return true;
 963     }
 964 
 965     /*non-public*/
 966     static boolean canConvert(Class<?> src, Class<?> dst) {
 967         // short-circuit a few cases:
 968         if (src == dst || src == Object.class || dst == Object.class)  return true;
 969         // the remainder of this logic is documented in MethodHandle.asType
 970         if (src.isPrimitive()) {
 971             // can force void to an explicit null, a la reflect.Method.invoke
 972             // can also force void to a primitive zero, by analogy
 973             if (src == void.class)  return true;  //or !dst.isPrimitive()?
 974             Wrapper sw = Wrapper.forPrimitiveType(src);
 975             if (dst.isPrimitive()) {
 976                 // P->P must widen
 977                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
 978             } else {
 979                 // P->R must box and widen
 980                 return dst.isAssignableFrom(sw.wrapperType());
 981             }
 982         } else if (dst.isPrimitive()) {
 983             // any value can be dropped
 984             if (dst == void.class)  return true;
 985             Wrapper dw = Wrapper.forPrimitiveType(dst);
 986             // R->P must be able to unbox (from a dynamically chosen type) and widen
 987             // For example:
 988             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
 989             //   Character/Comparable/Object -> dw:Character -> char
 990             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
 991             // This means that dw must be cast-compatible with src.
 992             if (src.isAssignableFrom(dw.wrapperType())) {
 993                 return true;
 994             }
 995             // The above does not work if the source reference is strongly typed
 996             // to a wrapper whose primitive must be widened.  For example:
 997             //   Byte -> unbox:byte -> short/int/long/float/double
 998             //   Character -> unbox:char -> int/long/float/double
 999             if (Wrapper.isWrapperType(src) &&
1000                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
1001                 // can unbox from src and then widen to dst
1002                 return true;
1003             }
1004             // We have already covered cases which arise due to runtime unboxing
1005             // of a reference type which covers several wrapper types:
1006             //   Object -> cast:Integer -> unbox:int -> long/float/double
1007             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
1008             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
1009             // subclass of Number which wraps a value that can convert to char.
1010             // Since there is none, we don't need an extra check here to cover char or boolean.
1011             return false;
1012         } else {
1013             // R->R always works, since null is always valid dynamically
1014             return true;
1015         }
1016     }
1017 
1018     /// Queries which have to do with the bytecode architecture
1019 
1020     /** Reports the number of JVM stack slots required to invoke a method
1021      * of this type.  Note that (for historical reasons) the JVM requires
1022      * a second stack slot to pass long and double arguments.
1023      * So this method returns {@link #parameterCount() parameterCount} plus the
1024      * number of long and double parameters (if any).
1025      * <p>
1026      * This method is included for the benefit of applications that must
1027      * generate bytecodes that process method handles and invokedynamic.
1028      * @return the number of JVM stack slots for this type's parameters
1029      */
1030     /*non-public*/ int parameterSlotCount() {
1031         return form.parameterSlotCount();
1032     }
1033 
1034     /*non-public*/ Invokers invokers() {
1035         Invokers inv = invokers;
1036         if (inv != null)  return inv;
1037         invokers = inv = new Invokers(this);
1038         return inv;
1039     }
1040 
1041     /** Reports the number of JVM stack slots which carry all parameters including and after
1042      * the given position, which must be in the range of 0 to
1043      * {@code parameterCount} inclusive.  Successive parameters are
1044      * more shallowly stacked, and parameters are indexed in the bytecodes
1045      * according to their trailing edge.  Thus, to obtain the depth
1046      * in the outgoing call stack of parameter {@code N}, obtain
1047      * the {@code parameterSlotDepth} of its trailing edge
1048      * at position {@code N+1}.
1049      * <p>
1050      * Parameters of type {@code long} and {@code double} occupy
1051      * two stack slots (for historical reasons) and all others occupy one.
1052      * Therefore, the number returned is the number of arguments
1053      * <em>including</em> and <em>after</em> the given parameter,
1054      * <em>plus</em> the number of long or double arguments
1055      * at or after the argument for the given parameter.
1056      * <p>
1057      * This method is included for the benefit of applications that must
1058      * generate bytecodes that process method handles and invokedynamic.
1059      * @param num an index (zero-based, inclusive) within the parameter types
1060      * @return the index of the (shallowest) JVM stack slot transmitting the
1061      *         given parameter
1062      * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
1063      */
1064     /*non-public*/ int parameterSlotDepth(int num) {
1065         if (num < 0 || num > ptypes.length)
1066             parameterType(num);  // force a range check
1067         return form.parameterToArgSlot(num-1);
1068     }
1069 
1070     /** Reports the number of JVM stack slots required to receive a return value
1071      * from a method of this type.
1072      * If the {@link #returnType() return type} is void, it will be zero,
1073      * else if the return type is long or double, it will be two, else one.
1074      * <p>
1075      * This method is included for the benefit of applications that must
1076      * generate bytecodes that process method handles and invokedynamic.
1077      * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
1078      * Will be removed for PFD.
1079      */
1080     /*non-public*/ int returnSlotCount() {
1081         return form.returnSlotCount();
1082     }
1083 
1084     /**
1085      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
1086      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
1087      * Any class or interface name embedded in the descriptor string
1088      * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
1089      * on the given loader (or if it is null, on the system class loader).
1090      * <p>
1091      * Note that it is possible to encounter method types which cannot be
1092      * constructed by this method, because their component types are
1093      * not all reachable from a common class loader.
1094      * <p>
1095      * This method is included for the benefit of applications that must
1096      * generate bytecodes that process method handles and {@code invokedynamic}.
1097      * @param descriptor a bytecode-level type descriptor string "(T...)T"
1098      * @param loader the class loader in which to look up the types
1099      * @return a method type matching the bytecode-level type descriptor
1100      * @throws NullPointerException if the string is null
1101      * @throws IllegalArgumentException if the string is not well-formed
1102      * @throws TypeNotPresentException if a named type cannot be found
1103      */
1104     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
1105         throws IllegalArgumentException, TypeNotPresentException
1106     {
1107         return fromDescriptor(descriptor,
1108                               (loader == null) ? ClassLoader.getSystemClassLoader() : loader);
1109     }
1110 
1111     /**
1112      * Same as {@link #fromMethodDescriptorString(String, ClassLoader)}, but
1113      * {@code null} ClassLoader means the bootstrap loader is used here.
1114      * <p>
1115      * IMPORTANT: This method is preferable for JDK internal use as it more
1116      * correctly interprets {@code null} ClassLoader than
1117      * {@link #fromMethodDescriptorString(String, ClassLoader)}.
1118      * Use of this method also avoids early initialization issues when system
1119      * ClassLoader is not initialized yet.
1120      */
1121     static MethodType fromDescriptor(String descriptor, ClassLoader loader)
1122         throws IllegalArgumentException, TypeNotPresentException
1123     {
1124         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
1125             descriptor.indexOf(')') < 0 ||
1126             descriptor.indexOf('.') >= 0)
1127             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
1128         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
1129         Class<?> rtype = types.remove(types.size() - 1);
1130         Class<?>[] ptypes = listToArray(types);
1131         return makeImpl(rtype, ptypes, true);
1132     }
1133 
1134     /**
1135      * Produces a bytecode descriptor representation of the method type.
1136      * <p>
1137      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
1138      * Two distinct classes which share a common name but have different class loaders
1139      * will appear identical when viewed within descriptor strings.
1140      * <p>
1141      * This method is included for the benefit of applications that must
1142      * generate bytecodes that process method handles and {@code invokedynamic}.
1143      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
1144      * because the latter requires a suitable class loader argument.
1145      * @return the bytecode type descriptor representation
1146      */
1147     public String toMethodDescriptorString() {
1148         String desc = methodDescriptor;
1149         if (desc == null) {
1150             desc = BytecodeDescriptor.unparseMethod(this.rtype, this.ptypes);
1151             methodDescriptor = desc;
1152         }
1153         return desc;
1154     }
1155 
1156     /*non-public*/ static String toFieldDescriptorString(Class<?> cls) {
1157         return BytecodeDescriptor.unparse(cls);
1158     }
1159 
1160     /// Serialization.
1161 
1162     /**
1163      * There are no serializable fields for {@code MethodType}.
1164      */
1165     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
1166 
1167     /**
1168      * Save the {@code MethodType} instance to a stream.
1169      *
1170      * @serialData
1171      * For portability, the serialized format does not refer to named fields.
1172      * Instead, the return type and parameter type arrays are written directly
1173      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1174      * as follows:
1175      * <blockquote><pre>{@code
1176 s.writeObject(this.returnType());
1177 s.writeObject(this.parameterArray());
1178      * }</pre></blockquote>
1179      * <p>
1180      * The deserialized field values are checked as if they were
1181      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1182      * For example, null values, or {@code void} parameter types,
1183      * will lead to exceptions during deserialization.
1184      * @param s the stream to write the object to
1185      * @throws java.io.IOException if there is a problem writing the object
1186      */
1187     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1188         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1189         s.writeObject(returnType());
1190         s.writeObject(parameterArray());
1191     }
1192 
1193     /**
1194      * Reconstitute the {@code MethodType} instance from a stream (that is,
1195      * deserialize it).
1196      * This instance is a scratch object with bogus final fields.
1197      * It provides the parameters to the factory method called by
1198      * {@link #readResolve readResolve}.
1199      * After that call it is discarded.
1200      * @param s the stream to read the object from
1201      * @throws java.io.IOException if there is a problem reading the object
1202      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1203      * @see #MethodType()
1204      * @see #readResolve
1205      * @see #writeObject
1206      */
1207     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1208         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1209 
1210         Class<?>   returnType     = (Class<?>)   s.readObject();
1211         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1212 
1213         // Probably this object will never escape, but let's check
1214         // the field values now, just to be sure.
1215         checkRtype(returnType);
1216         checkPtypes(parameterArray);
1217 
1218         parameterArray = parameterArray.clone();  // make sure it is unshared
1219         MethodType_init(returnType, parameterArray);
1220     }
1221 
1222     /**
1223      * For serialization only.
1224      * Sets the final fields to null, pending {@code Unsafe.putObject}.
1225      */
1226     private MethodType() {
1227         this.rtype = null;
1228         this.ptypes = null;
1229     }
1230     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
1231         // In order to communicate these values to readResolve, we must
1232         // store them into the implementation-specific final fields.
1233         checkRtype(rtype);
1234         checkPtypes(ptypes);
1235         UNSAFE.putObject(this, OffsetHolder.rtypeOffset, rtype);
1236         UNSAFE.putObject(this, OffsetHolder.ptypesOffset, ptypes);
1237     }
1238 
1239     // Support for resetting final fields while deserializing. Implement Holder
1240     // pattern to make the rarely needed offset calculation lazy.
1241     private static class OffsetHolder {
1242         private static final long rtypeOffset, ptypesOffset;
1243         static {
1244             try {
1245                 rtypeOffset = UNSAFE.objectFieldOffset
1246                     (MethodType.class.getDeclaredField("rtype"));
1247                 ptypesOffset = UNSAFE.objectFieldOffset
1248                     (MethodType.class.getDeclaredField("ptypes"));
1249             } catch (Exception ex) {
1250                 throw new Error(ex);
1251             }
1252         }
1253     }
1254 
1255     /**
1256      * Resolves and initializes a {@code MethodType} object
1257      * after serialization.
1258      * @return the fully initialized {@code MethodType} object
1259      */
1260     private Object readResolve() {
1261         // Do not use a trusted path for deserialization:
1262         //return makeImpl(rtype, ptypes, true);
1263         // Verify all operands, and make sure ptypes is unshared:
1264         return methodType(rtype, ptypes);
1265     }
1266 
1267     /**
1268      * Simple implementation of weak concurrent intern set.
1269      *
1270      * @param <T> interned type
1271      */
1272     private static class ConcurrentWeakInternSet<T> {
1273 
1274         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1275         private final ReferenceQueue<T> stale;
1276 
1277         public ConcurrentWeakInternSet() {
1278             this.map = new ConcurrentHashMap<>(512);
1279             this.stale = new ReferenceQueue<>();
1280         }
1281 
1282         /**
1283          * Get the existing interned element.
1284          * This method returns null if no element is interned.
1285          *
1286          * @param elem element to look up
1287          * @return the interned element
1288          */
1289         public T get(T elem) {
1290             if (elem == null) throw new NullPointerException();
1291             expungeStaleElements();
1292 
1293             WeakEntry<T> value = map.get(new WeakEntry<>(elem));
1294             if (value != null) {
1295                 T res = value.get();
1296                 if (res != null) {
1297                     return res;
1298                 }
1299             }
1300             return null;
1301         }
1302 
1303         /**
1304          * Interns the element.
1305          * Always returns non-null element, matching the one in the intern set.
1306          * Under the race against another add(), it can return <i>different</i>
1307          * element, if another thread beats us to interning it.
1308          *
1309          * @param elem element to add
1310          * @return element that was actually added
1311          */
1312         public T add(T elem) {
1313             if (elem == null) throw new NullPointerException();
1314 
1315             // Playing double race here, and so spinloop is required.
1316             // First race is with two concurrent updaters.
1317             // Second race is with GC purging weak ref under our feet.
1318             // Hopefully, we almost always end up with a single pass.
1319             T interned;
1320             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1321             do {
1322                 expungeStaleElements();
1323                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1324                 interned = (exist == null) ? elem : exist.get();
1325             } while (interned == null);
1326             return interned;
1327         }
1328 
1329         private void expungeStaleElements() {
1330             Reference<? extends T> reference;
1331             while ((reference = stale.poll()) != null) {
1332                 map.remove(reference);
1333             }
1334         }
1335 
1336         private static class WeakEntry<T> extends WeakReference<T> {
1337 
1338             public final int hashcode;
1339 
1340             public WeakEntry(T key, ReferenceQueue<T> queue) {
1341                 super(key, queue);
1342                 hashcode = key.hashCode();
1343             }
1344 
1345             public WeakEntry(T key) {
1346                 super(key);
1347                 hashcode = key.hashCode();
1348             }
1349 
1350             @Override
1351             public boolean equals(Object obj) {
1352                 if (obj instanceof WeakEntry) {
1353                     Object that = ((WeakEntry) obj).get();
1354                     Object mine = get();
1355                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1356                 }
1357                 return false;
1358             }
1359 
1360             @Override
1361             public int hashCode() {
1362                 return hashcode;
1363             }
1364 
1365         }
1366     }
1367 
1368 }