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