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