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