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