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