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