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