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 staticwhile 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(intboolean)
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 voidreturn 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 trueif 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     @Override
790     public boolean equals(Object x) {
791         return this == x || x instanceof MethodType && equals((MethodType)x);
792     }
793
794     private boolean equals(MethodType that) {
795         return this.rtype == that.rtype
796             && Arrays.equals(this.ptypes, that.ptypes);
797     }
798
799     /**
800      * Returns the hash code value for this method type.
801      * It is defined to be the same as the hashcode of a List
802      * whose elements are the return type followed by the
803      * parameter types.
804      * @return the hash code value for this method type
805      * @see Object#hashCode()
806      * @see #equals(Object)
807      * @see List#hashCode()
808      */

809     @Override
810     public int hashCode() {
811       int hashCode = 31 + rtype.hashCode();
812       for (Class<?> ptype : ptypes)
813           hashCode = 31*hashCode + ptype.hashCode();
814       return hashCode;
815     }
816
817     /**
818      * Returns a string representation of the method type,
819      * of the form {@code "(PT0,PT1...)RT"}.
820      * The string representation of a method type is a
821      * parenthesis enclosed, comma separated list of type names,
822      * followed immediately by the return type.
823      * <p>
824      * Each type is represented by its
825      * {@link java.lang.Class#getSimpleName simple name}.
826      */

827     @Override
828     public String toString() {
829         StringJoiner sj = new StringJoiner(",""(",
830                 ")" + rtype.getSimpleName());
831         for (int i = 0; i < ptypes.length; i++) {
832             sj.add(ptypes[i].getSimpleName());
833         }
834         return sj.toString();
835     }
836
837     /** True if my parameter list is effectively identical to the given full list,
838      *  after skipping the given number of my own initial parameters.
839      *  In other words, after disregarding {@code skipPos} parameters,
840      *  my remaining parameter list is no longer than the {@code fullList}, and
841      *  is equal to the same-length initial sublist of {@code fullList}.
842      */

843     /*non-public*/
844     boolean effectivelyIdenticalParameters(int skipPos, List<Class<?>> fullList) {
845         int myLen = ptypes.length, fullLen = fullList.size();
846         if (skipPos > myLen || myLen - skipPos > fullLen)
847             return false;
848         List<Class<?>> myList = Arrays.asList(ptypes);
849         if (skipPos != 0) {
850             myList = myList.subList(skipPos, myLen);
851             myLen -= skipPos;
852         }
853         if (fullLen == myLen)
854             return myList.equals(fullList);
855         else
856             return myList.equals(fullList.subList(0, myLen));
857     }
858
859     /** True if the old return type can always be viewed (w/o casting) under new return type,
860      *  and the new parameters can be viewed (w/o casting) under the old parameter types.
861      */

862     /*non-public*/
863     boolean isViewableAs(MethodType newType, boolean keepInterfaces) {
864         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), keepInterfaces))
865             return false;
866         if (form == newType.form && form.erasedType == this)
867             return true;  // my reference parameters are all Object
868         if (ptypes == newType.ptypes)
869             return true;
870         int argc = parameterCount();
871         if (argc != newType.parameterCount())
872             return false;
873         for (int i = 0; i < argc; i++) {
874             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), keepInterfaces))
875                 return false;
876         }
877         return true;
878     }
879     /*non-public*/
880     boolean isConvertibleTo(MethodType newType) {
881         MethodTypeForm oldForm = this.form();
882         MethodTypeForm newForm = newType.form();
883         if (oldForm == newForm)
884             // same parameter count, same primitive/object mix
885             return true;
886         if (!canConvert(returnType(), newType.returnType()))
887             return false;
888         Class<?>[] srcTypes = newType.ptypes;
889         Class<?>[] dstTypes = ptypes;
890         if (srcTypes == dstTypes)
891             return true;
892         int argc;
893         if ((argc = srcTypes.length) != dstTypes.length)
894             return false;
895         if (argc <= 1) {
896             if (argc == 1 && !canConvert(srcTypes[0], dstTypes[0]))
897                 return false;
898             return true;
899         }
900         if ((oldForm.primitiveParameterCount() == 0 && oldForm.erasedType == this) ||
901             (newForm.primitiveParameterCount() == 0 && newForm.erasedType == newType)) {
902             // Somewhat complicated test to avoid a loop of 2 or more trips.
903             // If either type has only Object parameters, we know we can convert.
904             assert(canConvertParameters(srcTypes, dstTypes));
905             return true;
906         }
907         return canConvertParameters(srcTypes, dstTypes);
908     }
909
910     /** Returns true if MHs.explicitCastArguments produces the same result as MH.asType.
911      *  If the type conversion is impossible for either, the result should be false.
912      */

913     /*non-public*/
914     boolean explicitCastEquivalentToAsType(MethodType newType) {
915         if (this == newType)  return true;
916         if (!explicitCastEquivalentToAsType(rtype, newType.rtype)) {
917             return false;
918         }
919         Class<?>[] srcTypes = newType.ptypes;
920         Class<?>[] dstTypes = ptypes;
921         if (dstTypes == srcTypes) {
922             return true;
923         }
924         assert(dstTypes.length == srcTypes.length);
925         for (int i = 0; i < dstTypes.length; i++) {
926             if (!explicitCastEquivalentToAsType(srcTypes[i], dstTypes[i])) {
927                 return false;
928             }
929         }
930         return true;
931     }
932
933     /** Reports true if the src can be converted to the dst, by both asType and MHs.eCE,
934      *  and with the same effect.
935      *  MHs.eCA has the following "upgrades" to MH.asType:
936      *  1. interfaces are unchecked (that is, treated as if aliased to Object)
937      *     Therefore, {@code Object->CharSequence} is possible in both cases but has different semantics
938      *  2. the full matrix of primitive-to-primitive conversions is supported
939      *     Narrowing like {@code long->byte} and basic-typing like {@code boolean->int}
940      *     are not supported by asType, but anything supported by asType is equivalent
941      *     with MHs.eCE.
942      *  3a. unboxing conversions can be followed by the full matrix of primitive conversions
943      *  3b. unboxing of null is permitted (creates a zero primitive value)
944      * Other than interfaces, reference-to-reference conversions are the same.
945      * Boxing primitives to references is the same for both operators.
946      */

947     private static boolean explicitCastEquivalentToAsType(Class<?> src, Class<?> dst) {
948         if (src == dst || dst == Object.class || dst == void.class)  return true;
949         if (src.isPrimitive()) {
950             // Could be a prim/prim conversion, where casting is a strict superset.
951             // Or a boxing conversion, which is always to an exact wrapper class.
952             return canConvert(src, dst);
953         } else if (dst.isPrimitive()) {
954             // Unboxing behavior is different between MHs.eCA & MH.asType (see 3b).
955             return false;
956         } else {
957             // R->R always works, but we have to avoid a check-cast to an interface.
958             return !dst.isInterface() || dst.isAssignableFrom(src);
959         }
960     }
961
962     private boolean canConvertParameters(Class<?>[] srcTypes, Class<?>[] dstTypes) {
963         for (int i = 0; i < srcTypes.length; i++) {
964             if (!canConvert(srcTypes[i], dstTypes[i])) {
965                 return false;
966             }
967         }
968         return true;
969     }
970
971     /*non-public*/
972     static boolean canConvert(Class<?> src, Class<?> dst) {
973         // short-circuit a few cases:
974         if (src == dst || src == Object.class || dst == Object.class)  return true;
975         // the remainder of this logic is documented in MethodHandle.asType
976         if (src.isPrimitive()) {
977             // can force void to an explicit null, a la reflect.Method.invoke
978             // can also force void to a primitive zero, by analogy
979             if (src == void.class)  return true;  //or !dst.isPrimitive()?
980             Wrapper sw = Wrapper.forPrimitiveType(src);
981             if (dst.isPrimitive()) {
982                 // P->P must widen
983                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
984             } else {
985                 // P->R must box and widen
986                 return dst.isAssignableFrom(sw.wrapperType());
987             }
988         } else if (dst.isPrimitive()) {
989             // any value can be dropped
990             if (dst == void.class)  return true;
991             Wrapper dw = Wrapper.forPrimitiveType(dst);
992             // R->P must be able to unbox (from a dynamically chosen type) and widen
993             // For example:
994             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
995             //   Character/Comparable/Object -> dw:Character -> char
996             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
997             // This means that dw must be cast-compatible with src.
998             if (src.isAssignableFrom(dw.wrapperType())) {
999                 return true;
1000             }
1001             // The above does not work if the source reference is strongly typed
1002             // to a wrapper whose primitive must be widened.  For example:
1003             //   Byte -> unbox:byte -> short/int/long/float/double
1004             //   Character -> unbox:char -> int/long/float/double
1005             if (Wrapper.isWrapperType(src) &&
1006                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
1007                 // can unbox from src and then widen to dst
1008                 return true;
1009             }
1010             // We have already covered cases which arise due to runtime unboxing
1011             // of a reference type which covers several wrapper types:
1012             //   Object -> cast:Integer -> unbox:int -> long/float/double
1013             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
1014             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
1015             // subclass of Number which wraps a value that can convert to char.
1016             // Since there is none, we don't need an extra check here to cover char or boolean.
1017             return false;
1018         } else {
1019             // R->R always works, since null is always valid dynamically
1020             return true;
1021         }
1022     }
1023
1024     /// Queries which have to do with the bytecode architecture
1025
1026     /** Reports the number of JVM stack slots required to invoke a method
1027      * of this type.  Note that (for historical reasons) the JVM requires
1028      * a second stack slot to pass long and double arguments.
1029      * So this method returns {@link #parameterCount() parameterCount} plus the
1030      * number of long and double parameters (if any).
1031      * <p>
1032      * This method is included for the benefit of applications that must
1033      * generate bytecodes that process method handles and invokedynamic.
1034      * @return the number of JVM stack slots for this type's parameters
1035      */

1036     /*non-public*/ int parameterSlotCount() {
1037         return form.parameterSlotCount();
1038     }
1039
1040     /*non-public*/ Invokers invokers() {
1041         Invokers inv = invokers;
1042         if (inv != null)  return inv;
1043         invokers = inv = new Invokers(this);
1044         return inv;
1045     }
1046
1047     /** Reports the number of JVM stack slots which carry all parameters including and after
1048      * the given position, which must be in the range of 0 to
1049      * {@code parameterCount} inclusive.  Successive parameters are
1050      * more shallowly stacked, and parameters are indexed in the bytecodes
1051      * according to their trailing edge.  Thus, to obtain the depth
1052      * in the outgoing call stack of parameter {@code N}, obtain
1053      * the {@code parameterSlotDepth} of its trailing edge
1054      * at position {@code N+1}.
1055      * <p>
1056      * Parameters of type {@code long} and {@code double} occupy
1057      * two stack slots (for historical reasons) and all others occupy one.
1058      * Therefore, the number returned is the number of arguments
1059      * <em>including</em> and <em>after</em> the given parameter,
1060      * <em>plus</em> the number of long or double arguments
1061      * at or after the argument for the given parameter.
1062      * <p>
1063      * This method is included for the benefit of applications that must
1064      * generate bytecodes that process method handles and invokedynamic.
1065      * @param num an index (zero-based, inclusive) within the parameter types
1066      * @return the index of the (shallowest) JVM stack slot transmitting the
1067      *         given parameter
1068      * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
1069      */

1070     /*non-public*/ int parameterSlotDepth(int num) {
1071         if (num < 0 || num > ptypes.length)
1072             parameterType(num);  // force a range check
1073         return form.parameterToArgSlot(num-1);
1074     }
1075
1076     /** Reports the number of JVM stack slots required to receive a return value
1077      * from a method of this type.
1078      * If the {@link #returnType() return type} is void, it will be zero,
1079      * else if the return type is long or double, it will be two, else one.
1080      * <p>
1081      * This method is included for the benefit of applications that must
1082      * generate bytecodes that process method handles and invokedynamic.
1083      * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
1084      * Will be removed for PFD.
1085      */

1086     /*non-public*/ int returnSlotCount() {
1087         return form.returnSlotCount();
1088     }
1089
1090     /**
1091      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
1092      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
1093      * Any class or interface name embedded in the descriptor string
1094      * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
1095      * on the given loader (or if it is null, on the system class loader).
1096      * <p>
1097      * Note that it is possible to encounter method types which cannot be
1098      * constructed by this method, because their component types are
1099      * not all reachable from a common class loader.
1100      * <p>
1101      * This method is included for the benefit of applications that must
1102      * generate bytecodes that process method handles and {@code invokedynamic}.
1103      * @param descriptor a bytecode-level type descriptor string "(T...)T"
1104      * @param loader the class loader in which to look up the types
1105      * @return a method type matching the bytecode-level type descriptor
1106      * @throws NullPointerException if the string is null
1107      * @throws IllegalArgumentException if the string is not well-formed
1108      * @throws TypeNotPresentException if a named type cannot be found
1109      */

1110     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
1111         throws IllegalArgumentException, TypeNotPresentException
1112     {
1113         return fromDescriptor(descriptor,
1114                               (loader == null) ? ClassLoader.getSystemClassLoader() : loader);
1115     }
1116
1117     /**
1118      * Same as {@link #fromMethodDescriptorString(String, ClassLoader)}, but
1119      * {@code null} ClassLoader means the bootstrap loader is used here.
1120      * <p>
1121      * IMPORTANT: This method is preferable for JDK internal use as it more
1122      * correctly interprets {@code null} ClassLoader than
1123      * {@link #fromMethodDescriptorString(String, ClassLoader)}.
1124      * Use of this method also avoids early initialization issues when system
1125      * ClassLoader is not initialized yet.
1126      */

1127     static MethodType fromDescriptor(String descriptor, ClassLoader loader)
1128         throws IllegalArgumentException, TypeNotPresentException
1129     {
1130         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
1131             descriptor.indexOf(')') < 0 ||
1132             descriptor.indexOf('.') >= 0)
1133             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
1134         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
1135         Class<?> rtype = types.remove(types.size() - 1);
1136         Class<?>[] ptypes = listToArray(types);
1137         return makeImpl(rtype, ptypes, true);
1138     }
1139
1140     /**
1141      * Produces a bytecode descriptor representation of the method type.
1142      * <p>
1143      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
1144      * Two distinct classes which share a common name but have different class loaders
1145      * will appear identical when viewed within descriptor strings.
1146      * <p>
1147      * This method is included for the benefit of applications that must
1148      * generate bytecodes that process method handles and {@code invokedynamic}.
1149      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
1150      * because the latter requires a suitable class loader argument.
1151      * @return the bytecode type descriptor representation
1152      */

1153     public String toMethodDescriptorString() {
1154         String desc = methodDescriptor;
1155         if (desc == null) {
1156             desc = BytecodeDescriptor.unparseMethod(this.rtype, this.ptypes);
1157             methodDescriptor = desc;
1158         }
1159         return desc;
1160     }
1161
1162     /*non-public*/ static String toFieldDescriptorString(Class<?> cls) {
1163         return BytecodeDescriptor.unparse(cls);
1164     }
1165
1166     /// Serialization.
1167
1168     /**
1169      * There are no serializable fields for {@code MethodType}.
1170      */

1171     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
1172
1173     /**
1174      * Save the {@code MethodType} instance to a stream.
1175      *
1176      * @serialData
1177      * For portability, the serialized format does not refer to named fields.
1178      * Instead, the return type and parameter type arrays are written directly
1179      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1180      * as follows:
1181      * <blockquote><pre>{@code
1182 s.writeObject(this.returnType());
1183 s.writeObject(this.parameterArray());
1184      * }</pre></blockquote>
1185      * <p>
1186      * The deserialized field values are checked as if they were
1187      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1188      * For example, null values, or {@code void} parameter types,
1189      * will lead to exceptions during deserialization.
1190      * @param s the stream to write the object to
1191      * @throws java.io.IOException if there is a problem writing the object
1192      */

1193     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1194         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1195         s.writeObject(returnType());
1196         s.writeObject(parameterArray());
1197     }
1198
1199     /**
1200      * Reconstitute the {@code MethodType} instance from a stream (that is,
1201      * deserialize it).
1202      * This instance is a scratch object with bogus final fields.
1203      * It provides the parameters to the factory method called by
1204      * {@link #readResolve readResolve}.
1205      * After that call it is discarded.
1206      * @param s the stream to read the object from
1207      * @throws java.io.IOException if there is a problem reading the object
1208      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1209      * @see #readResolve
1210      * @see #writeObject
1211      */

1212     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1213         // Assign temporary defaults in case this object escapes
1214         MethodType_init(void.class, NO_PTYPES);
1215
1216         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1217
1218         Class<?>   returnType     = (Class<?>)   s.readObject();
1219         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1220         parameterArray = parameterArray.clone();  // make sure it is unshared
1221
1222         // Assign deserialized values
1223         MethodType_init(returnType, parameterArray);
1224     }
1225
1226     // Initialization of state for deserialization only
1227     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
1228         // In order to communicate these values to readResolve, we must
1229         // store them into the implementation-specific final fields.
1230         checkRtype(rtype);
1231         checkPtypes(ptypes);
1232         UNSAFE.putObject(this, OffsetHolder.rtypeOffset, rtype);
1233         UNSAFE.putObject(this, OffsetHolder.ptypesOffset, ptypes);
1234     }
1235
1236     // Support for resetting final fields while deserializing. Implement Holder
1237     // pattern to make the rarely needed offset calculation lazy.
1238     private static class OffsetHolder {
1239         static final long rtypeOffset
1240                 = UNSAFE.objectFieldOffset(MethodType.class"rtype");
1241
1242         static final long ptypesOffset
1243                 = UNSAFE.objectFieldOffset(MethodType.class"ptypes");
1244     }
1245
1246     /**
1247      * Resolves and initializes a {@code MethodType} object
1248      * after serialization.
1249      * @return the fully initialized {@code MethodType} object
1250      */

1251     private Object readResolve() {
1252         // Do not use a trusted path for deserialization:
1253         //    return makeImpl(rtype, ptypes, true);
1254         // Verify all operands, and make sure ptypes is unshared:
1255         try {
1256             return methodType(rtype, ptypes);
1257         } finally {
1258             // Re-assign defaults in case this object escapes
1259             MethodType_init(void.class, NO_PTYPES);
1260         }
1261     }
1262
1263     /**
1264      * Simple implementation of weak concurrent intern set.
1265      *
1266      * @param <T> interned type
1267      */

1268     private static class ConcurrentWeakInternSet<T> {
1269
1270         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1271         private final ReferenceQueue<T> stale;
1272
1273         public ConcurrentWeakInternSet() {
1274             this.map = new ConcurrentHashMap<>(512);
1275             this.stale = new ReferenceQueue<>();
1276         }
1277
1278         /**
1279          * Get the existing interned element.
1280          * This method returns null if no element is interned.
1281          *
1282          * @param elem element to look up
1283          * @return the interned element
1284          */

1285         public T get(T elem) {
1286             if (elem == nullthrow new NullPointerException();
1287             expungeStaleElements();
1288
1289             WeakEntry<T> value = map.get(new WeakEntry<>(elem));
1290             if (value != null) {
1291                 T res = value.get();
1292                 if (res != null) {
1293                     return res;
1294                 }
1295             }
1296             return null;
1297         }
1298
1299         /**
1300          * Interns the element.
1301          * Always returns non-null element, matching the one in the intern set.
1302          * Under the race against another add(), it can return <i>different</i>
1303          * element, if another thread beats us to interning it.
1304          *
1305          * @param elem element to add
1306          * @return element that was actually added
1307          */

1308         public T add(T elem) {
1309             if (elem == nullthrow new NullPointerException();
1310
1311             // Playing double race here, and so spinloop is required.
1312             // First race is with two concurrent updaters.
1313             // Second race is with GC purging weak ref under our feet.
1314             // Hopefully, we almost always end up with a single pass.
1315             T interned;
1316             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1317             do {
1318                 expungeStaleElements();
1319                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1320                 interned = (exist == null) ? elem : exist.get();
1321             } while (interned == null);
1322             return interned;
1323         }
1324
1325         private void expungeStaleElements() {
1326             Reference<? extends T> reference;
1327             while ((reference = stale.poll()) != null) {
1328                 map.remove(reference);
1329             }
1330         }
1331
1332         private static class WeakEntry<T> extends WeakReference<T> {
1333
1334             public final int hashcode;
1335
1336             public WeakEntry(T key, ReferenceQueue<T> queue) {
1337                 super(key, queue);
1338                 hashcode = key.hashCode();
1339             }
1340
1341             public WeakEntry(T key) {
1342                 super(key);
1343                 hashcode = key.hashCode();
1344             }
1345
1346             @Override
1347             public boolean equals(Object obj) {
1348                 if (obj instanceof WeakEntry) {
1349                     Object that = ((WeakEntry) obj).get();
1350                     Object mine = get();
1351                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1352                 }
1353                 return false;
1354             }
1355
1356             @Override
1357             public int hashCode() {
1358                 return hashcode;
1359             }
1360
1361         }
1362     }
1363
1364 }
1365