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