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