1 /*
   2  * Copyright (c) 2008, 2012, 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 sun.invoke.util.Wrapper;
  29 import java.lang.ref.WeakReference;
  30 import java.lang.ref.Reference;
  31 import java.lang.ref.ReferenceQueue;
  32 import java.util.Arrays;
  33 import java.util.Collections;
  34 import java.util.List;
  35 import java.util.concurrent.ConcurrentMap;
  36 import java.util.concurrent.ConcurrentHashMap;
  37 import sun.invoke.util.BytecodeDescriptor;
  38 import static java.lang.invoke.MethodHandleStatics.*;
  39 import sun.invoke.util.VerifyType;
  40 
  41 /**
  42  * A method type represents the arguments and return type accepted and
  43  * returned by a method handle, or the arguments and return type passed
  44  * and expected  by a method handle caller.  Method types must be properly
  45  * matched between a method handle and all its callers,
  46  * and the JVM's operations enforce this matching at, specifically
  47  * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
  48  * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
  49  * of {@code invokedynamic} instructions.
  50  * <p>
  51  * The structure is a return type accompanied by any number of parameter types.
  52  * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
  53  * (For ease of exposition, we treat {@code void} as if it were a type.
  54  * In fact, it denotes the absence of a return type.)
  55  * <p>
  56  * All instances of {@code MethodType} are immutable.
  57  * Two instances are completely interchangeable if they compare equal.
  58  * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
  59  * <p>
  60  * This type can be created only by factory methods.
  61  * All factory methods may cache values, though caching is not guaranteed.
  62  * Some factory methods are static, while others are virtual methods which
  63  * modify precursor method types, e.g., by changing a selected parameter.
  64  * <p>
  65  * Factory methods which operate on groups of parameter types
  66  * are systematically presented in two versions, so that both Java arrays and
  67  * Java lists can be used to work with groups of parameter types.
  68  * The query methods {@code parameterArray} and {@code parameterList}
  69  * also provide a choice between arrays and lists.
  70  * <p>
  71  * {@code MethodType} objects are sometimes derived from bytecode instructions
  72  * such as {@code invokedynamic}, specifically from the type descriptor strings associated
  73  * with the instructions in a class file's constant pool.
  74  * <p>
  75  * Like classes and strings, method types can also be represented directly
  76  * in a class file's constant pool as constants.
  77  * A method type may be loaded by an {@code ldc} instruction which refers
  78  * to a suitable {@code CONSTANT_MethodType} constant pool entry.
  79  * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
  80  * For more details, see the <a href="package-summary.html#mtcon">package summary</a>.
  81  * <p>
  82  * When the JVM materializes a {@code MethodType} from a descriptor string,
  83  * all classes named in the descriptor must be accessible, and will be loaded.
  84  * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
  85  * This loading may occur at any time before the {@code MethodType} object is first derived.
  86  * @author John Rose, JSR 292 EG
  87  */
  88 public final
  89 class MethodType implements java.io.Serializable {
  90     private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
  91 
  92     // The rtype and ptypes fields define the structural identity of the method type:
  93     private final Class<?>   rtype;
  94     private final Class<?>[] ptypes;
  95 
  96     // The remaining fields are caches of various sorts:
  97     private MethodTypeForm form; // erased form, plus cached data about primitives
  98     private MethodType wrapAlt;  // alternative wrapped/unwrapped version
  99     private Invokers invokers;   // cache of handy higher-order adapters
 100 
 101     /**
 102      * Check the given parameters for validity and store them into the final fields.
 103      */
 104     private MethodType(Class<?> rtype, Class<?>[] ptypes) {
 105         checkRtype(rtype);
 106         checkPtypes(ptypes);
 107         this.rtype = rtype;
 108         this.ptypes = ptypes;
 109     }
 110 
 111     /*trusted*/ MethodTypeForm form() { return form; }
 112     /*trusted*/ Class<?> rtype() { return rtype; }
 113     /*trusted*/ Class<?>[] ptypes() { return ptypes; }
 114 
 115     void setForm(MethodTypeForm f) { form = f; }
 116 
 117     /** This number, mandated by the JVM spec as 255,
 118      *  is the maximum number of <em>slots</em>
 119      *  that any Java method can receive in its argument list.
 120      *  It limits both JVM signatures and method type objects.
 121      *  The longest possible invocation will look like
 122      *  {@code staticMethod(arg1, arg2, ..., arg255)} or
 123      *  {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
 124      */
 125     /*non-public*/ static final int MAX_JVM_ARITY = 255;  // this is mandated by the JVM spec.
 126 
 127     /** This number is the maximum arity of a method handle, 254.
 128      *  It is derived from the absolute JVM-imposed arity by subtracting one,
 129      *  which is the slot occupied by the method handle itself at the
 130      *  beginning of the argument list used to invoke the method handle.
 131      *  The longest possible invocation will look like
 132      *  {@code mh.invoke(arg1, arg2, ..., arg254)}.
 133      */
 134     // Issue:  Should we allow MH.invokeWithArguments to go to the full 255?
 135     /*non-public*/ static final int MAX_MH_ARITY = MAX_JVM_ARITY-1;  // deduct one for mh receiver
 136 
 137     /** This number is the maximum arity of a method handle invoker, 253.
 138      *  It is derived from the absolute JVM-imposed arity by subtracting two,
 139      *  which are the slots occupied by invoke method handle, and the the
 140      *  target method handle, which are both at the beginning of the argument
 141      *  list used to invoke the target method handle.
 142      *  The longest possible invocation will look like
 143      *  {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
 144      */
 145     /*non-public*/ static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1;  // deduct one more for invoker
 146 
 147     private static void checkRtype(Class<?> rtype) {
 148         rtype.equals(rtype);  // null check
 149     }
 150     private static int checkPtype(Class<?> ptype) {
 151         ptype.getClass();  //NPE
 152         if (ptype == void.class)
 153             throw newIllegalArgumentException("parameter type cannot be void");
 154         if (ptype == double.class || ptype == long.class)  return 1;
 155         return 0;
 156     }
 157     /** Return number of extra slots (count of long/double args). */
 158     private static int checkPtypes(Class<?>[] ptypes) {
 159         int slots = 0;
 160         for (Class<?> ptype : ptypes) {
 161             slots += checkPtype(ptype);
 162         }
 163         checkSlotCount(ptypes.length + slots);
 164         return slots;
 165     }
 166     static void checkSlotCount(int count) {
 167         assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
 168         // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
 169         if ((count & MAX_JVM_ARITY) != count)
 170             throw newIllegalArgumentException("bad parameter count "+count);
 171     }
 172     private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
 173         if (num instanceof Integer)  num = "bad index: "+num;
 174         return new IndexOutOfBoundsException(num.toString());
 175     }
 176 
 177     static final ConcurrentWeakInternSet<MethodType> internTable = new ConcurrentWeakInternSet<>();
 178 
 179     static final Class<?>[] NO_PTYPES = {};
 180 
 181     /**
 182      * Finds or creates an instance of the given method type.
 183      * @param rtype  the return type
 184      * @param ptypes the parameter types
 185      * @return a method type with the given components
 186      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 187      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 188      */
 189     public static
 190     MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
 191         return makeImpl(rtype, ptypes, false);
 192     }
 193 
 194     /**
 195      * Finds or creates a method type with the given components.
 196      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 197      * @return a method type with the given components
 198      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 199      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 200      */
 201     public static
 202     MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
 203         boolean notrust = false;  // random List impl. could return evil ptypes array
 204         return makeImpl(rtype, listToArray(ptypes), notrust);
 205     }
 206 
 207     private static Class<?>[] listToArray(List<Class<?>> ptypes) {
 208         // sanity check the size before the toArray call, since size might be huge
 209         checkSlotCount(ptypes.size());
 210         return ptypes.toArray(NO_PTYPES);
 211     }
 212 
 213     /**
 214      * Finds or creates a method type with the given components.
 215      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 216      * The leading parameter type is prepended to the remaining array.
 217      * @return a method type with the given components
 218      * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
 219      * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
 220      */
 221     public static
 222     MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
 223         Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
 224         ptypes1[0] = ptype0;
 225         System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
 226         return makeImpl(rtype, ptypes1, true);
 227     }
 228 
 229     /**
 230      * Finds or creates a method type with the given components.
 231      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 232      * The resulting method has no parameter types.
 233      * @return a method type with the given return value
 234      * @throws NullPointerException if {@code rtype} is null
 235      */
 236     public static
 237     MethodType methodType(Class<?> rtype) {
 238         return makeImpl(rtype, NO_PTYPES, true);
 239     }
 240 
 241     /**
 242      * Finds or creates a method type with the given components.
 243      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 244      * The resulting method has the single given parameter type.
 245      * @return a method type with the given return value and parameter type
 246      * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
 247      * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
 248      */
 249     public static
 250     MethodType methodType(Class<?> rtype, Class<?> ptype0) {
 251         return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
 252     }
 253 
 254     /**
 255      * Finds or creates a method type with the given components.
 256      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 257      * The resulting method has the same parameter types as {@code ptypes},
 258      * and the specified return type.
 259      * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
 260      */
 261     public static
 262     MethodType methodType(Class<?> rtype, MethodType ptypes) {
 263         return makeImpl(rtype, ptypes.ptypes, true);
 264     }
 265 
 266     /**
 267      * Sole factory method to find or create an interned method type.
 268      * @param rtype desired return type
 269      * @param ptypes desired parameter types
 270      * @param trusted whether the ptypes can be used without cloning
 271      * @return the unique method type of the desired structure
 272      */
 273     /*trusted*/ static
 274     MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 275         if (ptypes.length == 0) {
 276             ptypes = NO_PTYPES; trusted = true;
 277         }
 278         MethodType mt1 = new MethodType(rtype, ptypes);
 279         MethodType mt0 = internTable.get(mt1);
 280         if (mt0 != null)
 281             return mt0;
 282         if (!trusted)
 283             // defensively copy the array passed in by the user
 284             mt1 = new MethodType(rtype, ptypes.clone());
 285         // promote the object to the Real Thing, and reprobe
 286         MethodTypeForm form = MethodTypeForm.findForm(mt1);
 287         mt1.form = form;
 288         return internTable.add(mt1);
 289     }
 290     private static final MethodType[] objectOnlyTypes = new MethodType[20];
 291 
 292     /**
 293      * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
 294      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 295      * All parameters and the return type will be {@code Object},
 296      * except the final array parameter if any, which will be {@code Object[]}.
 297      * @param objectArgCount number of parameters (excluding the final array parameter if any)
 298      * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
 299      * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
 300      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
 301      * @see #genericMethodType(int)
 302      */
 303     public static
 304     MethodType genericMethodType(int objectArgCount, boolean finalArray) {
 305         MethodType mt;
 306         checkSlotCount(objectArgCount);
 307         int ivarargs = (!finalArray ? 0 : 1);
 308         int ootIndex = objectArgCount*2 + ivarargs;
 309         if (ootIndex < objectOnlyTypes.length) {
 310             mt = objectOnlyTypes[ootIndex];
 311             if (mt != null)  return mt;
 312         }
 313         Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
 314         Arrays.fill(ptypes, Object.class);
 315         if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
 316         mt = makeImpl(Object.class, ptypes, true);
 317         if (ootIndex < objectOnlyTypes.length) {
 318             objectOnlyTypes[ootIndex] = mt;     // cache it here also!
 319         }
 320         return mt;
 321     }
 322 
 323     /**
 324      * Finds or creates a method type whose components are all {@code Object}.
 325      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 326      * All parameters and the return type will be Object.
 327      * @param objectArgCount number of parameters
 328      * @return a generally applicable method type, for all calls of the given argument count
 329      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
 330      * @see #genericMethodType(int, boolean)
 331      */
 332     public static
 333     MethodType genericMethodType(int objectArgCount) {
 334         return genericMethodType(objectArgCount, false);
 335     }
 336 
 337     /**
 338      * Finds or creates a method type with a single different parameter type.
 339      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 340      * @param num    the index (zero-based) of the parameter type to change
 341      * @param nptype a new parameter type to replace the old one with
 342      * @return the same type, except with the selected parameter changed
 343      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 344      * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
 345      * @throws NullPointerException if {@code nptype} is null
 346      */
 347     public MethodType changeParameterType(int num, Class<?> nptype) {
 348         if (parameterType(num) == nptype)  return this;
 349         checkPtype(nptype);
 350         Class<?>[] nptypes = ptypes.clone();
 351         nptypes[num] = nptype;
 352         return makeImpl(rtype, nptypes, true);
 353     }
 354 
 355     /**
 356      * Finds or creates a method type with additional parameter types.
 357      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 358      * @param num    the position (zero-based) of the inserted parameter type(s)
 359      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 360      * @return the same type, except with the selected parameter(s) inserted
 361      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 362      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 363      *                                  or if the resulting method type would have more than 255 parameter slots
 364      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 365      */
 366     public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
 367         int len = ptypes.length;
 368         if (num < 0 || num > len)
 369             throw newIndexOutOfBoundsException(num);
 370         int ins = checkPtypes(ptypesToInsert);
 371         checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
 372         int ilen = ptypesToInsert.length;
 373         if (ilen == 0)  return this;
 374         Class<?>[] nptypes = Arrays.copyOfRange(ptypes, 0, len+ilen);
 375         System.arraycopy(nptypes, num, nptypes, num+ilen, len-num);
 376         System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
 377         return makeImpl(rtype, nptypes, true);
 378     }
 379 
 380     /**
 381      * Finds or creates a method type with additional parameter types.
 382      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 383      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 384      * @return the same type, except with the selected parameter(s) appended
 385      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 386      *                                  or if the resulting method type would have more than 255 parameter slots
 387      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 388      */
 389     public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
 390         return insertParameterTypes(parameterCount(), ptypesToInsert);
 391     }
 392 
 393     /**
 394      * Finds or creates a method type with additional parameter types.
 395      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 396      * @param num    the position (zero-based) of the inserted parameter type(s)
 397      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 398      * @return the same type, except with the selected parameter(s) inserted
 399      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 400      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 401      *                                  or if the resulting method type would have more than 255 parameter slots
 402      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 403      */
 404     public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
 405         return insertParameterTypes(num, listToArray(ptypesToInsert));
 406     }
 407 
 408     /**
 409      * Finds or creates a method type with additional parameter types.
 410      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 411      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 412      * @return the same type, except with the selected parameter(s) appended
 413      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 414      *                                  or if the resulting method type would have more than 255 parameter slots
 415      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 416      */
 417     public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
 418         return insertParameterTypes(parameterCount(), ptypesToInsert);
 419     }
 420 
 421      /**
 422      * Finds or creates a method type with modified parameter types.
 423      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 424      * @param start  the position (zero-based) of the first replaced parameter type(s)
 425      * @param end    the position (zero-based) after the last replaced parameter type(s)
 426      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 427      * @return the same type, except with the selected parameter(s) replaced
 428      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 429      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 430      *                                  or if {@code start} is greater than {@code end}
 431      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 432      *                                  or if the resulting method type would have more than 255 parameter slots
 433      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 434      */
 435     /*non-public*/ MethodType replaceParameterTypes(int start, int end, Class<?>... ptypesToInsert) {
 436         if (start == end)
 437             return insertParameterTypes(start, ptypesToInsert);
 438         int len = ptypes.length;
 439         if (!(0 <= start && start <= end && end <= len))
 440             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 441         int ilen = ptypesToInsert.length;
 442         if (ilen == 0)
 443             return dropParameterTypes(start, end);
 444         return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert);
 445     }
 446 
 447     /**
 448      * Finds or creates a method type with some parameter types omitted.
 449      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 450      * @param start  the index (zero-based) of the first parameter type to remove
 451      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
 452      * @return the same type, except with the selected parameter(s) removed
 453      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 454      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 455      *                                  or if {@code start} is greater than {@code end}
 456      */
 457     public MethodType dropParameterTypes(int start, int end) {
 458         int len = ptypes.length;
 459         if (!(0 <= start && start <= end && end <= len))
 460             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 461         if (start == end)  return this;
 462         Class<?>[] nptypes;
 463         if (start == 0) {
 464             if (end == len) {
 465                 // drop all parameters
 466                 nptypes = NO_PTYPES;
 467             } else {
 468                 // drop initial parameter(s)
 469                 nptypes = Arrays.copyOfRange(ptypes, end, len);
 470             }
 471         } else {
 472             if (end == len) {
 473                 // drop trailing parameter(s)
 474                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
 475             } else {
 476                 int tail = len - end;
 477                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
 478                 System.arraycopy(ptypes, end, nptypes, start, tail);
 479             }
 480         }
 481         return makeImpl(rtype, nptypes, true);
 482     }
 483 
 484     /**
 485      * Finds or creates a method type with a different return type.
 486      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 487      * @param nrtype a return parameter type to replace the old one with
 488      * @return the same type, except with the return type change
 489      * @throws NullPointerException if {@code nrtype} is null
 490      */
 491     public MethodType changeReturnType(Class<?> nrtype) {
 492         if (returnType() == nrtype)  return this;
 493         return makeImpl(nrtype, ptypes, true);
 494     }
 495 
 496     /**
 497      * Reports if this type contains a primitive argument or return value.
 498      * The return type {@code void} counts as a primitive.
 499      * @return true if any of the types are primitives
 500      */
 501     public boolean hasPrimitives() {
 502         return form.hasPrimitives();
 503     }
 504 
 505     /**
 506      * Reports if this type contains a wrapper argument or return value.
 507      * Wrappers are types which box primitive values, such as {@link Integer}.
 508      * The reference type {@code java.lang.Void} counts as a wrapper,
 509      * if it occurs as a return type.
 510      * @return true if any of the types are wrappers
 511      */
 512     public boolean hasWrappers() {
 513         return unwrap() != this;
 514     }
 515 
 516     /**
 517      * Erases all reference types to {@code Object}.
 518      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 519      * All primitive types (including {@code void}) will remain unchanged.
 520      * @return a version of the original type with all reference types replaced
 521      */
 522     public MethodType erase() {
 523         return form.erasedType();
 524     }
 525 
 526     /**
 527      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
 528      * This is the reduced type polymorphism used by private methods
 529      * such as {@link MethodHandle#invokeBasic invokeBasic}.
 530      * @return a version of the original type with all reference and subword types replaced
 531      */
 532     /*non-public*/ MethodType basicType() {
 533         return form.basicType();
 534     }
 535 
 536     /**
 537      * @return a version of the original type with MethodHandle prepended as the first argument
 538      */
 539     /*non-public*/ MethodType invokerType() {
 540         return insertParameterTypes(0, MethodHandle.class);
 541     }
 542 
 543     /**
 544      * Converts all types, both reference and primitive, to {@code Object}.
 545      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
 546      * The expression {@code type.wrap().erase()} produces the same value
 547      * as {@code type.generic()}.
 548      * @return a version of the original type with all types replaced
 549      */
 550     public MethodType generic() {
 551         return genericMethodType(parameterCount());
 552     }
 553 
 554     /**
 555      * Converts all primitive types to their corresponding wrapper types.
 556      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 557      * All reference types (including wrapper types) will remain unchanged.
 558      * A {@code void} return type is changed to the type {@code java.lang.Void}.
 559      * The expression {@code type.wrap().erase()} produces the same value
 560      * as {@code type.generic()}.
 561      * @return a version of the original type with all primitive types replaced
 562      */
 563     public MethodType wrap() {
 564         return hasPrimitives() ? wrapWithPrims(this) : this;
 565     }
 566 
 567     /**
 568      * Converts all wrapper types to their corresponding primitive types.
 569      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 570      * All primitive types (including {@code void}) will remain unchanged.
 571      * A return type of {@code java.lang.Void} is changed to {@code void}.
 572      * @return a version of the original type with all wrapper types replaced
 573      */
 574     public MethodType unwrap() {
 575         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
 576         return unwrapWithNoPrims(noprims);
 577     }
 578 
 579     private static MethodType wrapWithPrims(MethodType pt) {
 580         assert(pt.hasPrimitives());
 581         MethodType wt = pt.wrapAlt;
 582         if (wt == null) {
 583             // fill in lazily
 584             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
 585             assert(wt != null);
 586             pt.wrapAlt = wt;
 587         }
 588         return wt;
 589     }
 590 
 591     private static MethodType unwrapWithNoPrims(MethodType wt) {
 592         assert(!wt.hasPrimitives());
 593         MethodType uwt = wt.wrapAlt;
 594         if (uwt == null) {
 595             // fill in lazily
 596             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
 597             if (uwt == null)
 598                 uwt = wt;    // type has no wrappers or prims at all
 599             wt.wrapAlt = uwt;
 600         }
 601         return uwt;
 602     }
 603 
 604     /**
 605      * Returns the parameter type at the specified index, within this method type.
 606      * @param num the index (zero-based) of the desired parameter type
 607      * @return the selected parameter type
 608      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 609      */
 610     public Class<?> parameterType(int num) {
 611         return ptypes[num];
 612     }
 613     /**
 614      * Returns the number of parameter types in this method type.
 615      * @return the number of parameter types
 616      */
 617     public int parameterCount() {
 618         return ptypes.length;
 619     }
 620     /**
 621      * Returns the return type of this method type.
 622      * @return the return type
 623      */
 624     public Class<?> returnType() {
 625         return rtype;
 626     }
 627 
 628     /**
 629      * Presents the parameter types as a list (a convenience method).
 630      * The list will be immutable.
 631      * @return the parameter types (as an immutable list)
 632      */
 633     public List<Class<?>> parameterList() {
 634         return Collections.unmodifiableList(Arrays.asList(ptypes));
 635     }
 636 
 637     /*non-public*/ Class<?> lastParameterType() {
 638         int len = ptypes.length;
 639         return len == 0 ? void.class : ptypes[len-1];
 640     }
 641 
 642     /**
 643      * Presents the parameter types as an array (a convenience method).
 644      * Changes to the array will not result in changes to the type.
 645      * @return the parameter types (as a fresh copy if necessary)
 646      */
 647     public Class<?>[] parameterArray() {
 648         return ptypes.clone();
 649     }
 650 
 651     /**
 652      * Compares the specified object with this type for equality.
 653      * That is, it returns <tt>true</tt> if and only if the specified object
 654      * is also a method type with exactly the same parameters and return type.
 655      * @param x object to compare
 656      * @see Object#equals(Object)
 657      */
 658     @Override
 659     public boolean equals(Object x) {
 660         return this == x || x instanceof MethodType && equals((MethodType)x);
 661     }
 662 
 663     private boolean equals(MethodType that) {
 664         return this.rtype == that.rtype
 665             && Arrays.equals(this.ptypes, that.ptypes);
 666     }
 667 
 668     /**
 669      * Returns the hash code value for this method type.
 670      * It is defined to be the same as the hashcode of a List
 671      * whose elements are the return type followed by the
 672      * parameter types.
 673      * @return the hash code value for this method type
 674      * @see Object#hashCode()
 675      * @see #equals(Object)
 676      * @see List#hashCode()
 677      */
 678     @Override
 679     public int hashCode() {
 680       int hashCode = 31 + rtype.hashCode();
 681       for (Class<?> ptype : ptypes)
 682           hashCode = 31*hashCode + ptype.hashCode();
 683       return hashCode;
 684     }
 685 
 686     /**
 687      * Returns a string representation of the method type,
 688      * of the form {@code "(PT0,PT1...)RT"}.
 689      * The string representation of a method type is a
 690      * parenthesis enclosed, comma separated list of type names,
 691      * followed immediately by the return type.
 692      * <p>
 693      * Each type is represented by its
 694      * {@link java.lang.Class#getSimpleName simple name}.
 695      */
 696     @Override
 697     public String toString() {
 698         StringBuilder sb = new StringBuilder();
 699         sb.append("(");
 700         for (int i = 0; i < ptypes.length; i++) {
 701             if (i > 0)  sb.append(",");
 702             sb.append(ptypes[i].getSimpleName());
 703         }
 704         sb.append(")");
 705         sb.append(rtype.getSimpleName());
 706         return sb.toString();
 707     }
 708 
 709 
 710     /*non-public*/
 711     boolean isViewableAs(MethodType newType) {
 712         if (!VerifyType.isNullConversion(returnType(), newType.returnType()))
 713             return false;
 714         int argc = parameterCount();
 715         if (argc != newType.parameterCount())
 716             return false;
 717         for (int i = 0; i < argc; i++) {
 718             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i)))
 719                 return false;
 720         }
 721         return true;
 722     }
 723     /*non-public*/
 724     boolean isCastableTo(MethodType newType) {
 725         int argc = parameterCount();
 726         if (argc != newType.parameterCount())
 727             return false;
 728         return true;
 729     }
 730     /*non-public*/
 731     boolean isConvertibleTo(MethodType newType) {
 732         if (!canConvert(returnType(), newType.returnType()))
 733             return false;
 734         int argc = parameterCount();
 735         if (argc != newType.parameterCount())
 736             return false;
 737         for (int i = 0; i < argc; i++) {
 738             if (!canConvert(newType.parameterType(i), parameterType(i)))
 739                 return false;
 740         }
 741         return true;
 742     }
 743     /*non-public*/
 744     static boolean canConvert(Class<?> src, Class<?> dst) {
 745         // short-circuit a few cases:
 746         if (src == dst || dst == Object.class)  return true;
 747         // the remainder of this logic is documented in MethodHandle.asType
 748         if (src.isPrimitive()) {
 749             // can force void to an explicit null, a la reflect.Method.invoke
 750             // can also force void to a primitive zero, by analogy
 751             if (src == void.class)  return true;  //or !dst.isPrimitive()?
 752             Wrapper sw = Wrapper.forPrimitiveType(src);
 753             if (dst.isPrimitive()) {
 754                 // P->P must widen
 755                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
 756             } else {
 757                 // P->R must box and widen
 758                 return dst.isAssignableFrom(sw.wrapperType());
 759             }
 760         } else if (dst.isPrimitive()) {
 761             // any value can be dropped
 762             if (dst == void.class)  return true;
 763             Wrapper dw = Wrapper.forPrimitiveType(dst);
 764             // R->P must be able to unbox (from a dynamically chosen type) and widen
 765             // For example:
 766             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
 767             //   Character/Comparable/Object -> dw:Character -> char
 768             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
 769             // This means that dw must be cast-compatible with src.
 770             if (src.isAssignableFrom(dw.wrapperType())) {
 771                 return true;
 772             }
 773             // The above does not work if the source reference is strongly typed
 774             // to a wrapper whose primitive must be widened.  For example:
 775             //   Byte -> unbox:byte -> short/int/long/float/double
 776             //   Character -> unbox:char -> int/long/float/double
 777             if (Wrapper.isWrapperType(src) &&
 778                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
 779                 // can unbox from src and then widen to dst
 780                 return true;
 781             }
 782             // We have already covered cases which arise due to runtime unboxing
 783             // of a reference type which covers several wrapper types:
 784             //   Object -> cast:Integer -> unbox:int -> long/float/double
 785             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
 786             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
 787             // subclass of Number which wraps a value that can convert to char.
 788             // Since there is none, we don't need an extra check here to cover char or boolean.
 789             return false;
 790         } else {
 791             // R->R always works, since null is always valid dynamically
 792             return true;
 793         }
 794     }
 795 
 796     /// Queries which have to do with the bytecode architecture
 797 
 798     /** Reports the number of JVM stack slots required to invoke a method
 799      * of this type.  Note that (for historical reasons) the JVM requires
 800      * a second stack slot to pass long and double arguments.
 801      * So this method returns {@link #parameterCount() parameterCount} plus the
 802      * number of long and double parameters (if any).
 803      * <p>
 804      * This method is included for the benfit of applications that must
 805      * generate bytecodes that process method handles and invokedynamic.
 806      * @return the number of JVM stack slots for this type's parameters
 807      */
 808     /*non-public*/ int parameterSlotCount() {
 809         return form.parameterSlotCount();
 810     }
 811 
 812     /*non-public*/ Invokers invokers() {
 813         Invokers inv = invokers;
 814         if (inv != null)  return inv;
 815         invokers = inv = new Invokers(this);
 816         return inv;
 817     }
 818 
 819     /** Reports the number of JVM stack slots which carry all parameters including and after
 820      * the given position, which must be in the range of 0 to
 821      * {@code parameterCount} inclusive.  Successive parameters are
 822      * more shallowly stacked, and parameters are indexed in the bytecodes
 823      * according to their trailing edge.  Thus, to obtain the depth
 824      * in the outgoing call stack of parameter {@code N}, obtain
 825      * the {@code parameterSlotDepth} of its trailing edge
 826      * at position {@code N+1}.
 827      * <p>
 828      * Parameters of type {@code long} and {@code double} occupy
 829      * two stack slots (for historical reasons) and all others occupy one.
 830      * Therefore, the number returned is the number of arguments
 831      * <em>including</em> and <em>after</em> the given parameter,
 832      * <em>plus</em> the number of long or double arguments
 833      * at or after after the argument for the given parameter.
 834      * <p>
 835      * This method is included for the benfit of applications that must
 836      * generate bytecodes that process method handles and invokedynamic.
 837      * @param num an index (zero-based, inclusive) within the parameter types
 838      * @return the index of the (shallowest) JVM stack slot transmitting the
 839      *         given parameter
 840      * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
 841      */
 842     /*non-public*/ int parameterSlotDepth(int num) {
 843         if (num < 0 || num > ptypes.length)
 844             parameterType(num);  // force a range check
 845         return form.parameterToArgSlot(num-1);
 846     }
 847 
 848     /** Reports the number of JVM stack slots required to receive a return value
 849      * from a method of this type.
 850      * If the {@link #returnType() return type} is void, it will be zero,
 851      * else if the return type is long or double, it will be two, else one.
 852      * <p>
 853      * This method is included for the benfit of applications that must
 854      * generate bytecodes that process method handles and invokedynamic.
 855      * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
 856      * Will be removed for PFD.
 857      */
 858     /*non-public*/ int returnSlotCount() {
 859         return form.returnSlotCount();
 860     }
 861 
 862     /**
 863      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
 864      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 865      * Any class or interface name embedded in the descriptor string
 866      * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
 867      * on the given loader (or if it is null, on the system class loader).
 868      * <p>
 869      * Note that it is possible to encounter method types which cannot be
 870      * constructed by this method, because their component types are
 871      * not all reachable from a common class loader.
 872      * <p>
 873      * This method is included for the benfit of applications that must
 874      * generate bytecodes that process method handles and {@code invokedynamic}.
 875      * @param descriptor a bytecode-level type descriptor string "(T...)T"
 876      * @param loader the class loader in which to look up the types
 877      * @return a method type matching the bytecode-level type descriptor
 878      * @throws NullPointerException if the string is null
 879      * @throws IllegalArgumentException if the string is not well-formed
 880      * @throws TypeNotPresentException if a named type cannot be found
 881      */
 882     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
 883         throws IllegalArgumentException, TypeNotPresentException
 884     {
 885         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
 886             descriptor.indexOf(')') < 0 ||
 887             descriptor.indexOf('.') >= 0)
 888             throw new IllegalArgumentException("not a method descriptor: "+descriptor);
 889         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
 890         Class<?> rtype = types.remove(types.size() - 1);
 891         checkSlotCount(types.size());
 892         Class<?>[] ptypes = listToArray(types);
 893         return makeImpl(rtype, ptypes, true);
 894     }
 895 
 896     /**
 897      * Produces a bytecode descriptor representation of the method type.
 898      * <p>
 899      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
 900      * Two distinct classes which share a common name but have different class loaders
 901      * will appear identical when viewed within descriptor strings.
 902      * <p>
 903      * This method is included for the benfit of applications that must
 904      * generate bytecodes that process method handles and {@code invokedynamic}.
 905      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
 906      * because the latter requires a suitable class loader argument.
 907      * @return the bytecode type descriptor representation
 908      */
 909     public String toMethodDescriptorString() {
 910         return BytecodeDescriptor.unparse(this);
 911     }
 912 
 913     /*non-public*/ static String toFieldDescriptorString(Class<?> cls) {
 914         return BytecodeDescriptor.unparse(cls);
 915     }
 916 
 917     /// Serialization.
 918 
 919     /**
 920      * There are no serializable fields for {@code MethodType}.
 921      */
 922     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
 923 
 924     /**
 925      * Save the {@code MethodType} instance to a stream.
 926      *
 927      * @serialData
 928      * For portability, the serialized format does not refer to named fields.
 929      * Instead, the return type and parameter type arrays are written directly
 930      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
 931      * as follows:
 932      * <blockquote><pre>
 933 s.writeObject(this.returnType());
 934 s.writeObject(this.parameterArray());
 935      * </pre></blockquote>
 936      * <p>
 937      * The deserialized field values are checked as if they were
 938      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
 939      * For example, null values, or {@code void} parameter types,
 940      * will lead to exceptions during deserialization.
 941      * @param the stream to write the object to
 942      */
 943     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
 944         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
 945         s.writeObject(returnType());
 946         s.writeObject(parameterArray());
 947     }
 948 
 949     /**
 950      * Reconstitute the {@code MethodType} instance from a stream (that is,
 951      * deserialize it).
 952      * This instance is a scratch object with bogus final fields.
 953      * It provides the parameters to the factory method called by
 954      * {@link #readResolve readResolve}.
 955      * After that call it is discarded.
 956      * @param the stream to read the object from
 957      * @see #MethodType()
 958      * @see #readResolve
 959      * @see #writeObject
 960      */
 961     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
 962         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
 963 
 964         Class<?>   returnType     = (Class<?>)   s.readObject();
 965         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
 966 
 967         // Probably this object will never escape, but let's check
 968         // the field values now, just to be sure.
 969         checkRtype(returnType);
 970         checkPtypes(parameterArray);
 971 
 972         parameterArray = parameterArray.clone();  // make sure it is unshared
 973         MethodType_init(returnType, parameterArray);
 974     }
 975 
 976     /**
 977      * For serialization only.
 978      * Sets the final fields to null, pending {@code Unsafe.putObject}.
 979      */
 980     private MethodType() {
 981         this.rtype = null;
 982         this.ptypes = null;
 983     }
 984     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
 985         // In order to communicate these values to readResolve, we must
 986         // store them into the implementation-specific final fields.
 987         checkRtype(rtype);
 988         checkPtypes(ptypes);
 989         UNSAFE.putObject(this, rtypeOffset, rtype);
 990         UNSAFE.putObject(this, ptypesOffset, ptypes);
 991     }
 992 
 993     // Support for resetting final fields while deserializing
 994     private static final long rtypeOffset, ptypesOffset;
 995     static {
 996         try {
 997             rtypeOffset = UNSAFE.objectFieldOffset
 998                 (MethodType.class.getDeclaredField("rtype"));
 999             ptypesOffset = UNSAFE.objectFieldOffset
1000                 (MethodType.class.getDeclaredField("ptypes"));
1001         } catch (Exception ex) {
1002             throw new Error(ex);
1003         }
1004     }
1005 
1006     /**
1007      * Resolves and initializes a {@code MethodType} object
1008      * after serialization.
1009      * @return the fully initialized {@code MethodType} object
1010      */
1011     private Object readResolve() {
1012         // Do not use a trusted path for deserialization:
1013         //return makeImpl(rtype, ptypes, true);
1014         // Verify all operands, and make sure ptypes is unshared:
1015         return methodType(rtype, ptypes);
1016     }
1017 
1018     /**
1019      * Simple implementation of weak concurrent intern set.
1020      *
1021      * @param <T> interned type
1022      */
1023     private static class ConcurrentWeakInternSet<T> {
1024 
1025         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1026         private final ReferenceQueue<T> stale;
1027 
1028         public ConcurrentWeakInternSet() {
1029             this.map = new ConcurrentHashMap<>();
1030             this.stale = new ReferenceQueue<>();
1031         }
1032 
1033         /**
1034          * Get the existing interned element.
1035          * This method returns null if no element is interned.
1036          *
1037          * @param elem element to look up
1038          * @return the interned element
1039          */
1040         public T get(T elem) {
1041             if (elem == null) throw new NullPointerException();
1042             expungeStaleElements();
1043 
1044             WeakEntry<T> value = map.get(new WeakEntry<>(elem));
1045             if (value != null) {
1046                 T res = value.get();
1047                 if (res != null) {
1048                     return res;
1049                 }
1050             }
1051             return null;
1052         }
1053 
1054         /**
1055          * Interns the element.
1056          * Always returns non-null element, matching the one in the intern set.
1057          * Under the race against another add(), it can return <i>different</i>
1058          * element, if another thread beats us to interning it.
1059          *
1060          * @param elem element to add
1061          * @return element that was actually added
1062          */
1063         public T add(T elem) {
1064             if (elem == null) throw new NullPointerException();
1065 
1066             // Playing double race here, and so spinloop is required.
1067             // First race is with two concurrent updaters.
1068             // Second race is with GC purging weak ref under our feet.
1069             // Hopefully, we almost always end up with a single pass.
1070             T interned;
1071             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1072             do {
1073                 expungeStaleElements();
1074                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1075                 interned = (exist == null) ? elem : exist.get();
1076             } while (interned == null);
1077             return interned;
1078         }
1079 
1080         private void expungeStaleElements() {
1081             Reference<? extends T> reference;
1082             while ((reference = stale.poll()) != null) {
1083                 map.remove(reference);
1084             }
1085         }
1086 
1087         private static class WeakEntry<T> extends WeakReference<T> {
1088 
1089             public final int hashcode;
1090 
1091             public WeakEntry(T key, ReferenceQueue<T> queue) {
1092                 super(key, queue);
1093                 hashcode = key.hashCode();
1094             }
1095 
1096             public WeakEntry(T key) {
1097                 super(key);
1098                 hashcode = key.hashCode();
1099             }
1100 
1101             @Override
1102             public boolean equals(Object obj) {
1103                 if (obj instanceof WeakEntry) {
1104                     Object that = ((WeakEntry) obj).get();
1105                     Object mine = get();
1106                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1107                 }
1108                 return false;
1109             }
1110 
1111             @Override
1112             public int hashCode() {
1113                 return hashcode;
1114             }
1115 
1116         }
1117     }
1118 
1119 }