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