jaroslav@1646: /* jaroslav@1646: * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. jaroslav@1646: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1646: * jaroslav@1646: * This code is free software; you can redistribute it and/or modify it jaroslav@1646: * under the terms of the GNU General Public License version 2 only, as jaroslav@1646: * published by the Free Software Foundation. Oracle designates this jaroslav@1646: * particular file as subject to the "Classpath" exception as provided jaroslav@1646: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1646: * jaroslav@1646: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1646: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1646: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1646: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1646: * accompanied this code). jaroslav@1646: * jaroslav@1646: * You should have received a copy of the GNU General Public License version jaroslav@1646: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1646: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1646: * jaroslav@1646: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1646: * or visit www.oracle.com if you need additional information or have any jaroslav@1646: * questions. jaroslav@1646: */ jaroslav@1646: jaroslav@1646: package java.lang.invoke; jaroslav@1646: jaroslav@1646: import sun.invoke.util.Wrapper; jaroslav@1646: import java.lang.ref.WeakReference; jaroslav@1646: import java.lang.ref.Reference; jaroslav@1646: import java.lang.ref.ReferenceQueue; jaroslav@1646: import java.util.Arrays; jaroslav@1646: import java.util.Collections; jaroslav@1646: import java.util.List; jaroslav@1646: import java.util.Objects; jaroslav@1646: import java.util.concurrent.ConcurrentMap; jaroslav@1646: import java.util.concurrent.ConcurrentHashMap; jaroslav@1646: import sun.invoke.util.BytecodeDescriptor; jaroslav@1646: import static java.lang.invoke.MethodHandleStatics.*; jaroslav@1646: import sun.invoke.util.VerifyType; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * A method type represents the arguments and return type accepted and jaroslav@1646: * returned by a method handle, or the arguments and return type passed jaroslav@1646: * and expected by a method handle caller. Method types must be properly jaroslav@1646: * matched between a method handle and all its callers, jaroslav@1646: * and the JVM's operations enforce this matching at, specifically jaroslav@1646: * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact} jaroslav@1646: * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution jaroslav@1646: * of {@code invokedynamic} instructions. jaroslav@1646: *

jaroslav@1646: * The structure is a return type accompanied by any number of parameter types. jaroslav@1646: * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects. jaroslav@1646: * (For ease of exposition, we treat {@code void} as if it were a type. jaroslav@1646: * In fact, it denotes the absence of a return type.) jaroslav@1646: *

jaroslav@1646: * All instances of {@code MethodType} are immutable. jaroslav@1646: * Two instances are completely interchangeable if they compare equal. jaroslav@1646: * Equality depends on pairwise correspondence of the return and parameter types and on nothing else. jaroslav@1646: *

jaroslav@1646: * This type can be created only by factory methods. jaroslav@1646: * All factory methods may cache values, though caching is not guaranteed. jaroslav@1646: * Some factory methods are static, while others are virtual methods which jaroslav@1646: * modify precursor method types, e.g., by changing a selected parameter. jaroslav@1646: *

jaroslav@1646: * Factory methods which operate on groups of parameter types jaroslav@1646: * are systematically presented in two versions, so that both Java arrays and jaroslav@1646: * Java lists can be used to work with groups of parameter types. jaroslav@1646: * The query methods {@code parameterArray} and {@code parameterList} jaroslav@1646: * also provide a choice between arrays and lists. jaroslav@1646: *

jaroslav@1646: * {@code MethodType} objects are sometimes derived from bytecode instructions jaroslav@1646: * such as {@code invokedynamic}, specifically from the type descriptor strings associated jaroslav@1646: * with the instructions in a class file's constant pool. jaroslav@1646: *

jaroslav@1646: * Like classes and strings, method types can also be represented directly jaroslav@1646: * in a class file's constant pool as constants. jaroslav@1646: * A method type may be loaded by an {@code ldc} instruction which refers jaroslav@1646: * to a suitable {@code CONSTANT_MethodType} constant pool entry. jaroslav@1646: * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string. jaroslav@1646: * (For full details on method type constants, jaroslav@1646: * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.) jaroslav@1646: *

jaroslav@1646: * When the JVM materializes a {@code MethodType} from a descriptor string, jaroslav@1646: * all classes named in the descriptor must be accessible, and will be loaded. jaroslav@1646: * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.) jaroslav@1646: * This loading may occur at any time before the {@code MethodType} object is first derived. jaroslav@1646: * @author John Rose, JSR 292 EG jaroslav@1646: */ jaroslav@1646: public final jaroslav@1646: class MethodType implements java.io.Serializable { jaroslav@1646: private static final long serialVersionUID = 292L; // {rtype, {ptype...}} jaroslav@1646: jaroslav@1646: // The rtype and ptypes fields define the structural identity of the method type: jaroslav@1646: private final Class rtype; jaroslav@1646: private final Class[] ptypes; jaroslav@1646: jaroslav@1646: // The remaining fields are caches of various sorts: jaroslav@1646: private @Stable MethodTypeForm form; // erased form, plus cached data about primitives jaroslav@1646: private @Stable MethodType wrapAlt; // alternative wrapped/unwrapped version jaroslav@1646: private @Stable Invokers invokers; // cache of handy higher-order adapters jaroslav@1646: private @Stable String methodDescriptor; // cache for toMethodDescriptorString jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Check the given parameters for validity and store them into the final fields. jaroslav@1646: */ jaroslav@1646: private MethodType(Class rtype, Class[] ptypes, boolean trusted) { jaroslav@1646: checkRtype(rtype); jaroslav@1646: checkPtypes(ptypes); jaroslav@1646: this.rtype = rtype; jaroslav@1646: // defensively copy the array passed in by the user jaroslav@1646: this.ptypes = trusted ? ptypes : Arrays.copyOf(ptypes, ptypes.length); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Construct a temporary unchecked instance of MethodType for use only as a key to the intern table. jaroslav@1646: * Does not check the given parameters for validity, and must be discarded after it is used as a searching key. jaroslav@1646: * The parameters are reversed for this constructor, so that is is not accidentally used. jaroslav@1646: */ jaroslav@1646: private MethodType(Class[] ptypes, Class rtype) { jaroslav@1646: this.rtype = rtype; jaroslav@1646: this.ptypes = ptypes; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*trusted*/ MethodTypeForm form() { return form; } jaroslav@1646: /*trusted*/ Class rtype() { return rtype; } jaroslav@1646: /*trusted*/ Class[] ptypes() { return ptypes; } jaroslav@1646: jaroslav@1646: void setForm(MethodTypeForm f) { form = f; } jaroslav@1646: jaroslav@1646: /** This number, mandated by the JVM spec as 255, jaroslav@1646: * is the maximum number of slots jaroslav@1646: * that any Java method can receive in its argument list. jaroslav@1646: * It limits both JVM signatures and method type objects. jaroslav@1646: * The longest possible invocation will look like jaroslav@1646: * {@code staticMethod(arg1, arg2, ..., arg255)} or jaroslav@1646: * {@code x.virtualMethod(arg1, arg2, ..., arg254)}. jaroslav@1646: */ jaroslav@1646: /*non-public*/ static final int MAX_JVM_ARITY = 255; // this is mandated by the JVM spec. jaroslav@1646: jaroslav@1646: /** This number is the maximum arity of a method handle, 254. jaroslav@1646: * It is derived from the absolute JVM-imposed arity by subtracting one, jaroslav@1646: * which is the slot occupied by the method handle itself at the jaroslav@1646: * beginning of the argument list used to invoke the method handle. jaroslav@1646: * The longest possible invocation will look like jaroslav@1646: * {@code mh.invoke(arg1, arg2, ..., arg254)}. jaroslav@1646: */ jaroslav@1646: // Issue: Should we allow MH.invokeWithArguments to go to the full 255? jaroslav@1646: /*non-public*/ static final int MAX_MH_ARITY = MAX_JVM_ARITY-1; // deduct one for mh receiver jaroslav@1646: jaroslav@1646: /** This number is the maximum arity of a method handle invoker, 253. jaroslav@1646: * It is derived from the absolute JVM-imposed arity by subtracting two, jaroslav@1646: * which are the slots occupied by invoke method handle, and the jaroslav@1646: * target method handle, which are both at the beginning of the argument jaroslav@1646: * list used to invoke the target method handle. jaroslav@1646: * The longest possible invocation will look like jaroslav@1646: * {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}. jaroslav@1646: */ jaroslav@1646: /*non-public*/ static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1; // deduct one more for invoker jaroslav@1646: jaroslav@1646: private static void checkRtype(Class rtype) { jaroslav@1646: Objects.requireNonNull(rtype); jaroslav@1646: } jaroslav@1646: private static void checkPtype(Class ptype) { jaroslav@1646: Objects.requireNonNull(ptype); jaroslav@1646: if (ptype == void.class) jaroslav@1646: throw newIllegalArgumentException("parameter type cannot be void"); jaroslav@1646: } jaroslav@1646: /** Return number of extra slots (count of long/double args). */ jaroslav@1646: private static int checkPtypes(Class[] ptypes) { jaroslav@1646: int slots = 0; jaroslav@1646: for (Class ptype : ptypes) { jaroslav@1646: checkPtype(ptype); jaroslav@1646: if (ptype == double.class || ptype == long.class) { jaroslav@1646: slots++; jaroslav@1646: } jaroslav@1646: } jaroslav@1646: checkSlotCount(ptypes.length + slots); jaroslav@1646: return slots; jaroslav@1646: } jaroslav@1646: static void checkSlotCount(int count) { jaroslav@1646: assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0); jaroslav@1646: // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work: jaroslav@1646: if ((count & MAX_JVM_ARITY) != count) jaroslav@1646: throw newIllegalArgumentException("bad parameter count "+count); jaroslav@1646: } jaroslav@1646: private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) { jaroslav@1646: if (num instanceof Integer) num = "bad index: "+num; jaroslav@1646: return new IndexOutOfBoundsException(num.toString()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: static final ConcurrentWeakInternSet internTable = new ConcurrentWeakInternSet<>(); jaroslav@1646: jaroslav@1646: static final Class[] NO_PTYPES = {}; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates an instance of the given method type. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @param ptypes the parameter types jaroslav@1646: * @return a method type with the given components jaroslav@1646: * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class} jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype, Class[] ptypes) { jaroslav@1646: return makeImpl(rtype, ptypes, false); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with the given components. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @param ptypes the parameter types jaroslav@1646: * @return a method type with the given components jaroslav@1646: * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class} jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype, List> ptypes) { jaroslav@1646: boolean notrust = false; // random List impl. could return evil ptypes array jaroslav@1646: return makeImpl(rtype, listToArray(ptypes), notrust); jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static Class[] listToArray(List> ptypes) { jaroslav@1646: // sanity check the size before the toArray call, since size might be huge jaroslav@1646: checkSlotCount(ptypes.size()); jaroslav@1646: return ptypes.toArray(NO_PTYPES); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with the given components. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * The leading parameter type is prepended to the remaining array. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @param ptype0 the first parameter type jaroslav@1646: * @param ptypes the remaining parameter types jaroslav@1646: * @return a method type with the given components jaroslav@1646: * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null jaroslav@1646: * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class} jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype, Class ptype0, Class... ptypes) { jaroslav@1646: Class[] ptypes1 = new Class[1+ptypes.length]; jaroslav@1646: ptypes1[0] = ptype0; jaroslav@1646: System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length); jaroslav@1646: return makeImpl(rtype, ptypes1, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with the given components. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * The resulting method has no parameter types. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @return a method type with the given return value jaroslav@1646: * @throws NullPointerException if {@code rtype} is null jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype) { jaroslav@1646: return makeImpl(rtype, NO_PTYPES, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with the given components. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * The resulting method has the single given parameter type. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @param ptype0 the parameter type jaroslav@1646: * @return a method type with the given return value and parameter type jaroslav@1646: * @throws NullPointerException if {@code rtype} or {@code ptype0} is null jaroslav@1646: * @throws IllegalArgumentException if {@code ptype0} is {@code void.class} jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype, Class ptype0) { jaroslav@1646: return makeImpl(rtype, new Class[]{ ptype0 }, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with the given components. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * The resulting method has the same parameter types as {@code ptypes}, jaroslav@1646: * and the specified return type. jaroslav@1646: * @param rtype the return type jaroslav@1646: * @param ptypes the method type which supplies the parameter types jaroslav@1646: * @return a method type with the given components jaroslav@1646: * @throws NullPointerException if {@code rtype} or {@code ptypes} is null jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType methodType(Class rtype, MethodType ptypes) { jaroslav@1646: return makeImpl(rtype, ptypes.ptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Sole factory method to find or create an interned method type. jaroslav@1646: * @param rtype desired return type jaroslav@1646: * @param ptypes desired parameter types jaroslav@1646: * @param trusted whether the ptypes can be used without cloning jaroslav@1646: * @return the unique method type of the desired structure jaroslav@1646: */ jaroslav@1646: /*trusted*/ static jaroslav@1646: MethodType makeImpl(Class rtype, Class[] ptypes, boolean trusted) { jaroslav@1646: MethodType mt = internTable.get(new MethodType(ptypes, rtype)); jaroslav@1646: if (mt != null) jaroslav@1646: return mt; jaroslav@1646: if (ptypes.length == 0) { jaroslav@1646: ptypes = NO_PTYPES; trusted = true; jaroslav@1646: } jaroslav@1646: mt = new MethodType(rtype, ptypes, trusted); jaroslav@1646: // promote the object to the Real Thing, and reprobe jaroslav@1646: mt.form = MethodTypeForm.findForm(mt); jaroslav@1646: return internTable.add(mt); jaroslav@1646: } jaroslav@1646: private static final MethodType[] objectOnlyTypes = new MethodType[20]; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * All parameters and the return type will be {@code Object}, jaroslav@1646: * except the final array parameter if any, which will be {@code Object[]}. jaroslav@1646: * @param objectArgCount number of parameters (excluding the final array parameter if any) jaroslav@1646: * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]} jaroslav@1646: * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments jaroslav@1646: * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true) jaroslav@1646: * @see #genericMethodType(int) jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType genericMethodType(int objectArgCount, boolean finalArray) { jaroslav@1646: MethodType mt; jaroslav@1646: checkSlotCount(objectArgCount); jaroslav@1646: int ivarargs = (!finalArray ? 0 : 1); jaroslav@1646: int ootIndex = objectArgCount*2 + ivarargs; jaroslav@1646: if (ootIndex < objectOnlyTypes.length) { jaroslav@1646: mt = objectOnlyTypes[ootIndex]; jaroslav@1646: if (mt != null) return mt; jaroslav@1646: } jaroslav@1646: Class[] ptypes = new Class[objectArgCount + ivarargs]; jaroslav@1646: Arrays.fill(ptypes, Object.class); jaroslav@1646: if (ivarargs != 0) ptypes[objectArgCount] = Object[].class; jaroslav@1646: mt = makeImpl(Object.class, ptypes, true); jaroslav@1646: if (ootIndex < objectOnlyTypes.length) { jaroslav@1646: objectOnlyTypes[ootIndex] = mt; // cache it here also! jaroslav@1646: } jaroslav@1646: return mt; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type whose components are all {@code Object}. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * All parameters and the return type will be Object. jaroslav@1646: * @param objectArgCount number of parameters jaroslav@1646: * @return a generally applicable method type, for all calls of the given argument count jaroslav@1646: * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 jaroslav@1646: * @see #genericMethodType(int, boolean) jaroslav@1646: */ jaroslav@1646: public static jaroslav@1646: MethodType genericMethodType(int objectArgCount) { jaroslav@1646: return genericMethodType(objectArgCount, false); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with a single different parameter type. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param num the index (zero-based) of the parameter type to change jaroslav@1646: * @param nptype a new parameter type to replace the old one with jaroslav@1646: * @return the same type, except with the selected parameter changed jaroslav@1646: * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()} jaroslav@1646: * @throws IllegalArgumentException if {@code nptype} is {@code void.class} jaroslav@1646: * @throws NullPointerException if {@code nptype} is null jaroslav@1646: */ jaroslav@1646: public MethodType changeParameterType(int num, Class nptype) { jaroslav@1646: if (parameterType(num) == nptype) return this; jaroslav@1646: checkPtype(nptype); jaroslav@1646: Class[] nptypes = ptypes.clone(); jaroslav@1646: nptypes[num] = nptype; jaroslav@1646: return makeImpl(rtype, nptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with additional parameter types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param num the position (zero-based) of the inserted parameter type(s) jaroslav@1646: * @param ptypesToInsert zero or more new parameter types to insert into the parameter list jaroslav@1646: * @return the same type, except with the selected parameter(s) inserted jaroslav@1646: * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()} jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class} jaroslav@1646: * or if the resulting method type would have more than 255 parameter slots jaroslav@1646: * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null jaroslav@1646: */ jaroslav@1646: public MethodType insertParameterTypes(int num, Class... ptypesToInsert) { jaroslav@1646: int len = ptypes.length; jaroslav@1646: if (num < 0 || num > len) jaroslav@1646: throw newIndexOutOfBoundsException(num); jaroslav@1646: int ins = checkPtypes(ptypesToInsert); jaroslav@1646: checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins); jaroslav@1646: int ilen = ptypesToInsert.length; jaroslav@1646: if (ilen == 0) return this; jaroslav@1646: Class[] nptypes = Arrays.copyOfRange(ptypes, 0, len+ilen); jaroslav@1646: System.arraycopy(nptypes, num, nptypes, num+ilen, len-num); jaroslav@1646: System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen); jaroslav@1646: return makeImpl(rtype, nptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with additional parameter types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list jaroslav@1646: * @return the same type, except with the selected parameter(s) appended jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class} jaroslav@1646: * or if the resulting method type would have more than 255 parameter slots jaroslav@1646: * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null jaroslav@1646: */ jaroslav@1646: public MethodType appendParameterTypes(Class... ptypesToInsert) { jaroslav@1646: return insertParameterTypes(parameterCount(), ptypesToInsert); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with additional parameter types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param num the position (zero-based) of the inserted parameter type(s) jaroslav@1646: * @param ptypesToInsert zero or more new parameter types to insert into the parameter list jaroslav@1646: * @return the same type, except with the selected parameter(s) inserted jaroslav@1646: * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()} jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class} jaroslav@1646: * or if the resulting method type would have more than 255 parameter slots jaroslav@1646: * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null jaroslav@1646: */ jaroslav@1646: public MethodType insertParameterTypes(int num, List> ptypesToInsert) { jaroslav@1646: return insertParameterTypes(num, listToArray(ptypesToInsert)); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with additional parameter types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list jaroslav@1646: * @return the same type, except with the selected parameter(s) appended jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class} jaroslav@1646: * or if the resulting method type would have more than 255 parameter slots jaroslav@1646: * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null jaroslav@1646: */ jaroslav@1646: public MethodType appendParameterTypes(List> ptypesToInsert) { jaroslav@1646: return insertParameterTypes(parameterCount(), ptypesToInsert); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with modified parameter types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param start the position (zero-based) of the first replaced parameter type(s) jaroslav@1646: * @param end the position (zero-based) after the last replaced parameter type(s) jaroslav@1646: * @param ptypesToInsert zero or more new parameter types to insert into the parameter list jaroslav@1646: * @return the same type, except with the selected parameter(s) replaced jaroslav@1646: * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()} jaroslav@1646: * or if {@code end} is negative or greater than {@code parameterCount()} jaroslav@1646: * or if {@code start} is greater than {@code end} jaroslav@1646: * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class} jaroslav@1646: * or if the resulting method type would have more than 255 parameter slots jaroslav@1646: * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null jaroslav@1646: */ jaroslav@1646: /*non-public*/ MethodType replaceParameterTypes(int start, int end, Class... ptypesToInsert) { jaroslav@1646: if (start == end) jaroslav@1646: return insertParameterTypes(start, ptypesToInsert); jaroslav@1646: int len = ptypes.length; jaroslav@1646: if (!(0 <= start && start <= end && end <= len)) jaroslav@1646: throw newIndexOutOfBoundsException("start="+start+" end="+end); jaroslav@1646: int ilen = ptypesToInsert.length; jaroslav@1646: if (ilen == 0) jaroslav@1646: return dropParameterTypes(start, end); jaroslav@1646: return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with some parameter types omitted. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param start the index (zero-based) of the first parameter type to remove jaroslav@1646: * @param end the index (greater than {@code start}) of the first parameter type after not to remove jaroslav@1646: * @return the same type, except with the selected parameter(s) removed jaroslav@1646: * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()} jaroslav@1646: * or if {@code end} is negative or greater than {@code parameterCount()} jaroslav@1646: * or if {@code start} is greater than {@code end} jaroslav@1646: */ jaroslav@1646: public MethodType dropParameterTypes(int start, int end) { jaroslav@1646: int len = ptypes.length; jaroslav@1646: if (!(0 <= start && start <= end && end <= len)) jaroslav@1646: throw newIndexOutOfBoundsException("start="+start+" end="+end); jaroslav@1646: if (start == end) return this; jaroslav@1646: Class[] nptypes; jaroslav@1646: if (start == 0) { jaroslav@1646: if (end == len) { jaroslav@1646: // drop all parameters jaroslav@1646: nptypes = NO_PTYPES; jaroslav@1646: } else { jaroslav@1646: // drop initial parameter(s) jaroslav@1646: nptypes = Arrays.copyOfRange(ptypes, end, len); jaroslav@1646: } jaroslav@1646: } else { jaroslav@1646: if (end == len) { jaroslav@1646: // drop trailing parameter(s) jaroslav@1646: nptypes = Arrays.copyOfRange(ptypes, 0, start); jaroslav@1646: } else { jaroslav@1646: int tail = len - end; jaroslav@1646: nptypes = Arrays.copyOfRange(ptypes, 0, start + tail); jaroslav@1646: System.arraycopy(ptypes, end, nptypes, start, tail); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: return makeImpl(rtype, nptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates a method type with a different return type. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * @param nrtype a return parameter type to replace the old one with jaroslav@1646: * @return the same type, except with the return type change jaroslav@1646: * @throws NullPointerException if {@code nrtype} is null jaroslav@1646: */ jaroslav@1646: public MethodType changeReturnType(Class nrtype) { jaroslav@1646: if (returnType() == nrtype) return this; jaroslav@1646: return makeImpl(nrtype, ptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Reports if this type contains a primitive argument or return value. jaroslav@1646: * The return type {@code void} counts as a primitive. jaroslav@1646: * @return true if any of the types are primitives jaroslav@1646: */ jaroslav@1646: public boolean hasPrimitives() { jaroslav@1646: return form.hasPrimitives(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Reports if this type contains a wrapper argument or return value. jaroslav@1646: * Wrappers are types which box primitive values, such as {@link Integer}. jaroslav@1646: * The reference type {@code java.lang.Void} counts as a wrapper, jaroslav@1646: * if it occurs as a return type. jaroslav@1646: * @return true if any of the types are wrappers jaroslav@1646: */ jaroslav@1646: public boolean hasWrappers() { jaroslav@1646: return unwrap() != this; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Erases all reference types to {@code Object}. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * All primitive types (including {@code void}) will remain unchanged. jaroslav@1646: * @return a version of the original type with all reference types replaced jaroslav@1646: */ jaroslav@1646: public MethodType erase() { jaroslav@1646: return form.erasedType(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Erases all reference types to {@code Object}, and all subword types to {@code int}. jaroslav@1646: * This is the reduced type polymorphism used by private methods jaroslav@1646: * such as {@link MethodHandle#invokeBasic invokeBasic}. jaroslav@1646: * @return a version of the original type with all reference and subword types replaced jaroslav@1646: */ jaroslav@1646: /*non-public*/ MethodType basicType() { jaroslav@1646: return form.basicType(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * @return a version of the original type with MethodHandle prepended as the first argument jaroslav@1646: */ jaroslav@1646: /*non-public*/ MethodType invokerType() { jaroslav@1646: return insertParameterTypes(0, MethodHandle.class); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Converts all types, both reference and primitive, to {@code Object}. jaroslav@1646: * Convenience method for {@link #genericMethodType(int) genericMethodType}. jaroslav@1646: * The expression {@code type.wrap().erase()} produces the same value jaroslav@1646: * as {@code type.generic()}. jaroslav@1646: * @return a version of the original type with all types replaced jaroslav@1646: */ jaroslav@1646: public MethodType generic() { jaroslav@1646: return genericMethodType(parameterCount()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Converts all primitive types to their corresponding wrapper types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * All reference types (including wrapper types) will remain unchanged. jaroslav@1646: * A {@code void} return type is changed to the type {@code java.lang.Void}. jaroslav@1646: * The expression {@code type.wrap().erase()} produces the same value jaroslav@1646: * as {@code type.generic()}. jaroslav@1646: * @return a version of the original type with all primitive types replaced jaroslav@1646: */ jaroslav@1646: public MethodType wrap() { jaroslav@1646: return hasPrimitives() ? wrapWithPrims(this) : this; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Converts all wrapper types to their corresponding primitive types. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * All primitive types (including {@code void}) will remain unchanged. jaroslav@1646: * A return type of {@code java.lang.Void} is changed to {@code void}. jaroslav@1646: * @return a version of the original type with all wrapper types replaced jaroslav@1646: */ jaroslav@1646: public MethodType unwrap() { jaroslav@1646: MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this); jaroslav@1646: return unwrapWithNoPrims(noprims); jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static MethodType wrapWithPrims(MethodType pt) { jaroslav@1646: assert(pt.hasPrimitives()); jaroslav@1646: MethodType wt = pt.wrapAlt; jaroslav@1646: if (wt == null) { jaroslav@1646: // fill in lazily jaroslav@1646: wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP); jaroslav@1646: assert(wt != null); jaroslav@1646: pt.wrapAlt = wt; jaroslav@1646: } jaroslav@1646: return wt; jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static MethodType unwrapWithNoPrims(MethodType wt) { jaroslav@1646: assert(!wt.hasPrimitives()); jaroslav@1646: MethodType uwt = wt.wrapAlt; jaroslav@1646: if (uwt == null) { jaroslav@1646: // fill in lazily jaroslav@1646: uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP); jaroslav@1646: if (uwt == null) jaroslav@1646: uwt = wt; // type has no wrappers or prims at all jaroslav@1646: wt.wrapAlt = uwt; jaroslav@1646: } jaroslav@1646: return uwt; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns the parameter type at the specified index, within this method type. jaroslav@1646: * @param num the index (zero-based) of the desired parameter type jaroslav@1646: * @return the selected parameter type jaroslav@1646: * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()} jaroslav@1646: */ jaroslav@1646: public Class parameterType(int num) { jaroslav@1646: return ptypes[num]; jaroslav@1646: } jaroslav@1646: /** jaroslav@1646: * Returns the number of parameter types in this method type. jaroslav@1646: * @return the number of parameter types jaroslav@1646: */ jaroslav@1646: public int parameterCount() { jaroslav@1646: return ptypes.length; jaroslav@1646: } jaroslav@1646: /** jaroslav@1646: * Returns the return type of this method type. jaroslav@1646: * @return the return type jaroslav@1646: */ jaroslav@1646: public Class returnType() { jaroslav@1646: return rtype; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Presents the parameter types as a list (a convenience method). jaroslav@1646: * The list will be immutable. jaroslav@1646: * @return the parameter types (as an immutable list) jaroslav@1646: */ jaroslav@1646: public List> parameterList() { jaroslav@1646: return Collections.unmodifiableList(Arrays.asList(ptypes)); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ Class lastParameterType() { jaroslav@1646: int len = ptypes.length; jaroslav@1646: return len == 0 ? void.class : ptypes[len-1]; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Presents the parameter types as an array (a convenience method). jaroslav@1646: * Changes to the array will not result in changes to the type. jaroslav@1646: * @return the parameter types (as a fresh copy if necessary) jaroslav@1646: */ jaroslav@1646: public Class[] parameterArray() { jaroslav@1646: return ptypes.clone(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Compares the specified object with this type for equality. jaroslav@1646: * That is, it returns true if and only if the specified object jaroslav@1646: * is also a method type with exactly the same parameters and return type. jaroslav@1646: * @param x object to compare jaroslav@1646: * @see Object#equals(Object) jaroslav@1646: */ jaroslav@1646: @Override jaroslav@1646: public boolean equals(Object x) { jaroslav@1646: return this == x || x instanceof MethodType && equals((MethodType)x); jaroslav@1646: } jaroslav@1646: jaroslav@1646: private boolean equals(MethodType that) { jaroslav@1646: return this.rtype == that.rtype jaroslav@1646: && Arrays.equals(this.ptypes, that.ptypes); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns the hash code value for this method type. jaroslav@1646: * It is defined to be the same as the hashcode of a List jaroslav@1646: * whose elements are the return type followed by the jaroslav@1646: * parameter types. jaroslav@1646: * @return the hash code value for this method type jaroslav@1646: * @see Object#hashCode() jaroslav@1646: * @see #equals(Object) jaroslav@1646: * @see List#hashCode() jaroslav@1646: */ jaroslav@1646: @Override jaroslav@1646: public int hashCode() { jaroslav@1646: int hashCode = 31 + rtype.hashCode(); jaroslav@1646: for (Class ptype : ptypes) jaroslav@1646: hashCode = 31*hashCode + ptype.hashCode(); jaroslav@1646: return hashCode; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Returns a string representation of the method type, jaroslav@1646: * of the form {@code "(PT0,PT1...)RT"}. jaroslav@1646: * The string representation of a method type is a jaroslav@1646: * parenthesis enclosed, comma separated list of type names, jaroslav@1646: * followed immediately by the return type. jaroslav@1646: *

jaroslav@1646: * Each type is represented by its jaroslav@1646: * {@link java.lang.Class#getSimpleName simple name}. jaroslav@1646: */ jaroslav@1646: @Override jaroslav@1646: public String toString() { jaroslav@1646: StringBuilder sb = new StringBuilder(); jaroslav@1646: sb.append("("); jaroslav@1646: for (int i = 0; i < ptypes.length; i++) { jaroslav@1646: if (i > 0) sb.append(","); jaroslav@1646: sb.append(ptypes[i].getSimpleName()); jaroslav@1646: } jaroslav@1646: sb.append(")"); jaroslav@1646: sb.append(rtype.getSimpleName()); jaroslav@1646: return sb.toString(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: jaroslav@1646: /*non-public*/ jaroslav@1646: boolean isViewableAs(MethodType newType) { jaroslav@1646: if (!VerifyType.isNullConversion(returnType(), newType.returnType())) jaroslav@1646: return false; jaroslav@1646: int argc = parameterCount(); jaroslav@1646: if (argc != newType.parameterCount()) jaroslav@1646: return false; jaroslav@1646: for (int i = 0; i < argc; i++) { jaroslav@1646: if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i))) jaroslav@1646: return false; jaroslav@1646: } jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: /*non-public*/ jaroslav@1646: boolean isCastableTo(MethodType newType) { jaroslav@1646: int argc = parameterCount(); jaroslav@1646: if (argc != newType.parameterCount()) jaroslav@1646: return false; jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: /*non-public*/ jaroslav@1646: boolean isConvertibleTo(MethodType newType) { jaroslav@1646: if (!canConvert(returnType(), newType.returnType())) jaroslav@1646: return false; jaroslav@1646: int argc = parameterCount(); jaroslav@1646: if (argc != newType.parameterCount()) jaroslav@1646: return false; jaroslav@1646: for (int i = 0; i < argc; i++) { jaroslav@1646: if (!canConvert(newType.parameterType(i), parameterType(i))) jaroslav@1646: return false; jaroslav@1646: } jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: /*non-public*/ jaroslav@1646: static boolean canConvert(Class src, Class dst) { jaroslav@1646: // short-circuit a few cases: jaroslav@1646: if (src == dst || dst == Object.class) return true; jaroslav@1646: // the remainder of this logic is documented in MethodHandle.asType jaroslav@1646: if (src.isPrimitive()) { jaroslav@1646: // can force void to an explicit null, a la reflect.Method.invoke jaroslav@1646: // can also force void to a primitive zero, by analogy jaroslav@1646: if (src == void.class) return true; //or !dst.isPrimitive()? jaroslav@1646: Wrapper sw = Wrapper.forPrimitiveType(src); jaroslav@1646: if (dst.isPrimitive()) { jaroslav@1646: // P->P must widen jaroslav@1646: return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw); jaroslav@1646: } else { jaroslav@1646: // P->R must box and widen jaroslav@1646: return dst.isAssignableFrom(sw.wrapperType()); jaroslav@1646: } jaroslav@1646: } else if (dst.isPrimitive()) { jaroslav@1646: // any value can be dropped jaroslav@1646: if (dst == void.class) return true; jaroslav@1646: Wrapper dw = Wrapper.forPrimitiveType(dst); jaroslav@1646: // R->P must be able to unbox (from a dynamically chosen type) and widen jaroslav@1646: // For example: jaroslav@1646: // Byte/Number/Comparable/Object -> dw:Byte -> byte. jaroslav@1646: // Character/Comparable/Object -> dw:Character -> char jaroslav@1646: // Boolean/Comparable/Object -> dw:Boolean -> boolean jaroslav@1646: // This means that dw must be cast-compatible with src. jaroslav@1646: if (src.isAssignableFrom(dw.wrapperType())) { jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: // The above does not work if the source reference is strongly typed jaroslav@1646: // to a wrapper whose primitive must be widened. For example: jaroslav@1646: // Byte -> unbox:byte -> short/int/long/float/double jaroslav@1646: // Character -> unbox:char -> int/long/float/double jaroslav@1646: if (Wrapper.isWrapperType(src) && jaroslav@1646: dw.isConvertibleFrom(Wrapper.forWrapperType(src))) { jaroslav@1646: // can unbox from src and then widen to dst jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: // We have already covered cases which arise due to runtime unboxing jaroslav@1646: // of a reference type which covers several wrapper types: jaroslav@1646: // Object -> cast:Integer -> unbox:int -> long/float/double jaroslav@1646: // Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double jaroslav@1646: // An marginal case is Number -> dw:Character -> char, which would be OK if there were a jaroslav@1646: // subclass of Number which wraps a value that can convert to char. jaroslav@1646: // Since there is none, we don't need an extra check here to cover char or boolean. jaroslav@1646: return false; jaroslav@1646: } else { jaroslav@1646: // R->R always works, since null is always valid dynamically jaroslav@1646: return true; jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: /// Queries which have to do with the bytecode architecture jaroslav@1646: jaroslav@1646: /** Reports the number of JVM stack slots required to invoke a method jaroslav@1646: * of this type. Note that (for historical reasons) the JVM requires jaroslav@1646: * a second stack slot to pass long and double arguments. jaroslav@1646: * So this method returns {@link #parameterCount() parameterCount} plus the jaroslav@1646: * number of long and double parameters (if any). jaroslav@1646: *

jaroslav@1646: * This method is included for the benefit of applications that must jaroslav@1646: * generate bytecodes that process method handles and invokedynamic. jaroslav@1646: * @return the number of JVM stack slots for this type's parameters jaroslav@1646: */ jaroslav@1646: /*non-public*/ int parameterSlotCount() { jaroslav@1646: return form.parameterSlotCount(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ Invokers invokers() { jaroslav@1646: Invokers inv = invokers; jaroslav@1646: if (inv != null) return inv; jaroslav@1646: invokers = inv = new Invokers(this); jaroslav@1646: return inv; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** Reports the number of JVM stack slots which carry all parameters including and after jaroslav@1646: * the given position, which must be in the range of 0 to jaroslav@1646: * {@code parameterCount} inclusive. Successive parameters are jaroslav@1646: * more shallowly stacked, and parameters are indexed in the bytecodes jaroslav@1646: * according to their trailing edge. Thus, to obtain the depth jaroslav@1646: * in the outgoing call stack of parameter {@code N}, obtain jaroslav@1646: * the {@code parameterSlotDepth} of its trailing edge jaroslav@1646: * at position {@code N+1}. jaroslav@1646: *

jaroslav@1646: * Parameters of type {@code long} and {@code double} occupy jaroslav@1646: * two stack slots (for historical reasons) and all others occupy one. jaroslav@1646: * Therefore, the number returned is the number of arguments jaroslav@1646: * including and after the given parameter, jaroslav@1646: * plus the number of long or double arguments jaroslav@1646: * at or after after the argument for the given parameter. jaroslav@1646: *

jaroslav@1646: * This method is included for the benefit of applications that must jaroslav@1646: * generate bytecodes that process method handles and invokedynamic. jaroslav@1646: * @param num an index (zero-based, inclusive) within the parameter types jaroslav@1646: * @return the index of the (shallowest) JVM stack slot transmitting the jaroslav@1646: * given parameter jaroslav@1646: * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()} jaroslav@1646: */ jaroslav@1646: /*non-public*/ int parameterSlotDepth(int num) { jaroslav@1646: if (num < 0 || num > ptypes.length) jaroslav@1646: parameterType(num); // force a range check jaroslav@1646: return form.parameterToArgSlot(num-1); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** Reports the number of JVM stack slots required to receive a return value jaroslav@1646: * from a method of this type. jaroslav@1646: * If the {@link #returnType() return type} is void, it will be zero, jaroslav@1646: * else if the return type is long or double, it will be two, else one. jaroslav@1646: *

jaroslav@1646: * This method is included for the benefit of applications that must jaroslav@1646: * generate bytecodes that process method handles and invokedynamic. jaroslav@1646: * @return the number of JVM stack slots (0, 1, or 2) for this type's return value jaroslav@1646: * Will be removed for PFD. jaroslav@1646: */ jaroslav@1646: /*non-public*/ int returnSlotCount() { jaroslav@1646: return form.returnSlotCount(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor. jaroslav@1646: * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}. jaroslav@1646: * Any class or interface name embedded in the descriptor string jaroslav@1646: * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)} jaroslav@1646: * on the given loader (or if it is null, on the system class loader). jaroslav@1646: *

jaroslav@1646: * Note that it is possible to encounter method types which cannot be jaroslav@1646: * constructed by this method, because their component types are jaroslav@1646: * not all reachable from a common class loader. jaroslav@1646: *

jaroslav@1646: * This method is included for the benefit of applications that must jaroslav@1646: * generate bytecodes that process method handles and {@code invokedynamic}. jaroslav@1646: * @param descriptor a bytecode-level type descriptor string "(T...)T" jaroslav@1646: * @param loader the class loader in which to look up the types jaroslav@1646: * @return a method type matching the bytecode-level type descriptor jaroslav@1646: * @throws NullPointerException if the string is null jaroslav@1646: * @throws IllegalArgumentException if the string is not well-formed jaroslav@1646: * @throws TypeNotPresentException if a named type cannot be found jaroslav@1646: */ jaroslav@1646: public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader) jaroslav@1646: throws IllegalArgumentException, TypeNotPresentException jaroslav@1646: { jaroslav@1646: if (!descriptor.startsWith("(") || // also generates NPE if needed jaroslav@1646: descriptor.indexOf(')') < 0 || jaroslav@1646: descriptor.indexOf('.') >= 0) jaroslav@1646: throw new IllegalArgumentException("not a method descriptor: "+descriptor); jaroslav@1646: List> types = BytecodeDescriptor.parseMethod(descriptor, loader); jaroslav@1646: Class rtype = types.remove(types.size() - 1); jaroslav@1646: checkSlotCount(types.size()); jaroslav@1646: Class[] ptypes = listToArray(types); jaroslav@1646: return makeImpl(rtype, ptypes, true); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Produces a bytecode descriptor representation of the method type. jaroslav@1646: *

jaroslav@1646: * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}. jaroslav@1646: * Two distinct classes which share a common name but have different class loaders jaroslav@1646: * will appear identical when viewed within descriptor strings. jaroslav@1646: *

jaroslav@1646: * This method is included for the benefit of applications that must jaroslav@1646: * generate bytecodes that process method handles and {@code invokedynamic}. jaroslav@1646: * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString}, jaroslav@1646: * because the latter requires a suitable class loader argument. jaroslav@1646: * @return the bytecode type descriptor representation jaroslav@1646: */ jaroslav@1646: public String toMethodDescriptorString() { jaroslav@1646: String desc = methodDescriptor; jaroslav@1646: if (desc == null) { jaroslav@1646: desc = BytecodeDescriptor.unparse(this); jaroslav@1646: methodDescriptor = desc; jaroslav@1646: } jaroslav@1646: return desc; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /*non-public*/ static String toFieldDescriptorString(Class cls) { jaroslav@1646: return BytecodeDescriptor.unparse(cls); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /// Serialization. jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * There are no serializable fields for {@code MethodType}. jaroslav@1646: */ jaroslav@1646: private static final java.io.ObjectStreamField[] serialPersistentFields = { }; jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Save the {@code MethodType} instance to a stream. jaroslav@1646: * jaroslav@1646: * @serialData jaroslav@1646: * For portability, the serialized format does not refer to named fields. jaroslav@1646: * Instead, the return type and parameter type arrays are written directly jaroslav@1646: * from the {@code writeObject} method, using two calls to {@code s.writeObject} jaroslav@1646: * as follows: jaroslav@1646: *

{@code
jaroslav@1646: s.writeObject(this.returnType());
jaroslav@1646: s.writeObject(this.parameterArray());
jaroslav@1646:      * }
jaroslav@1646: *

jaroslav@1646: * The deserialized field values are checked as if they were jaroslav@1646: * provided to the factory method {@link #methodType(Class,Class[]) methodType}. jaroslav@1646: * For example, null values, or {@code void} parameter types, jaroslav@1646: * will lead to exceptions during deserialization. jaroslav@1646: * @param s the stream to write the object to jaroslav@1646: * @throws java.io.IOException if there is a problem writing the object jaroslav@1646: */ jaroslav@1646: private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { jaroslav@1646: s.defaultWriteObject(); // requires serialPersistentFields to be an empty array jaroslav@1646: s.writeObject(returnType()); jaroslav@1646: s.writeObject(parameterArray()); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Reconstitute the {@code MethodType} instance from a stream (that is, jaroslav@1646: * deserialize it). jaroslav@1646: * This instance is a scratch object with bogus final fields. jaroslav@1646: * It provides the parameters to the factory method called by jaroslav@1646: * {@link #readResolve readResolve}. jaroslav@1646: * After that call it is discarded. jaroslav@1646: * @param s the stream to read the object from jaroslav@1646: * @throws java.io.IOException if there is a problem reading the object jaroslav@1646: * @throws ClassNotFoundException if one of the component classes cannot be resolved jaroslav@1646: * @see #MethodType() jaroslav@1646: * @see #readResolve jaroslav@1646: * @see #writeObject jaroslav@1646: */ jaroslav@1646: private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { jaroslav@1646: s.defaultReadObject(); // requires serialPersistentFields to be an empty array jaroslav@1646: jaroslav@1646: Class returnType = (Class) s.readObject(); jaroslav@1646: Class[] parameterArray = (Class[]) s.readObject(); jaroslav@1646: jaroslav@1646: // Probably this object will never escape, but let's check jaroslav@1646: // the field values now, just to be sure. jaroslav@1646: checkRtype(returnType); jaroslav@1646: checkPtypes(parameterArray); jaroslav@1646: jaroslav@1646: parameterArray = parameterArray.clone(); // make sure it is unshared jaroslav@1646: MethodType_init(returnType, parameterArray); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * For serialization only. jaroslav@1646: * Sets the final fields to null, pending {@code Unsafe.putObject}. jaroslav@1646: */ jaroslav@1646: private MethodType() { jaroslav@1646: this.rtype = null; jaroslav@1646: this.ptypes = null; jaroslav@1646: } jaroslav@1646: private void MethodType_init(Class rtype, Class[] ptypes) { jaroslav@1646: // In order to communicate these values to readResolve, we must jaroslav@1646: // store them into the implementation-specific final fields. jaroslav@1646: checkRtype(rtype); jaroslav@1646: checkPtypes(ptypes); jaroslav@1646: UNSAFE.putObject(this, rtypeOffset, rtype); jaroslav@1646: UNSAFE.putObject(this, ptypesOffset, ptypes); jaroslav@1646: } jaroslav@1646: jaroslav@1646: // Support for resetting final fields while deserializing jaroslav@1646: private static final long rtypeOffset, ptypesOffset; jaroslav@1646: static { jaroslav@1646: try { jaroslav@1646: rtypeOffset = UNSAFE.objectFieldOffset jaroslav@1646: (MethodType.class.getDeclaredField("rtype")); jaroslav@1646: ptypesOffset = UNSAFE.objectFieldOffset jaroslav@1646: (MethodType.class.getDeclaredField("ptypes")); jaroslav@1646: } catch (Exception ex) { jaroslav@1646: throw new Error(ex); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Resolves and initializes a {@code MethodType} object jaroslav@1646: * after serialization. jaroslav@1646: * @return the fully initialized {@code MethodType} object jaroslav@1646: */ jaroslav@1646: private Object readResolve() { jaroslav@1646: // Do not use a trusted path for deserialization: jaroslav@1646: //return makeImpl(rtype, ptypes, true); jaroslav@1646: // Verify all operands, and make sure ptypes is unshared: jaroslav@1646: return methodType(rtype, ptypes); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Simple implementation of weak concurrent intern set. jaroslav@1646: * jaroslav@1646: * @param interned type jaroslav@1646: */ jaroslav@1646: private static class ConcurrentWeakInternSet { jaroslav@1646: jaroslav@1646: private final ConcurrentMap, WeakEntry> map; jaroslav@1646: private final ReferenceQueue stale; jaroslav@1646: jaroslav@1646: public ConcurrentWeakInternSet() { jaroslav@1646: this.map = new ConcurrentHashMap<>(); jaroslav@1646: this.stale = new ReferenceQueue<>(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Get the existing interned element. jaroslav@1646: * This method returns null if no element is interned. jaroslav@1646: * jaroslav@1646: * @param elem element to look up jaroslav@1646: * @return the interned element jaroslav@1646: */ jaroslav@1646: public T get(T elem) { jaroslav@1646: if (elem == null) throw new NullPointerException(); jaroslav@1646: expungeStaleElements(); jaroslav@1646: jaroslav@1646: WeakEntry value = map.get(new WeakEntry<>(elem)); jaroslav@1646: if (value != null) { jaroslav@1646: T res = value.get(); jaroslav@1646: if (res != null) { jaroslav@1646: return res; jaroslav@1646: } jaroslav@1646: } jaroslav@1646: return null; jaroslav@1646: } jaroslav@1646: jaroslav@1646: /** jaroslav@1646: * Interns the element. jaroslav@1646: * Always returns non-null element, matching the one in the intern set. jaroslav@1646: * Under the race against another add(), it can return different jaroslav@1646: * element, if another thread beats us to interning it. jaroslav@1646: * jaroslav@1646: * @param elem element to add jaroslav@1646: * @return element that was actually added jaroslav@1646: */ jaroslav@1646: public T add(T elem) { jaroslav@1646: if (elem == null) throw new NullPointerException(); jaroslav@1646: jaroslav@1646: // Playing double race here, and so spinloop is required. jaroslav@1646: // First race is with two concurrent updaters. jaroslav@1646: // Second race is with GC purging weak ref under our feet. jaroslav@1646: // Hopefully, we almost always end up with a single pass. jaroslav@1646: T interned; jaroslav@1646: WeakEntry e = new WeakEntry<>(elem, stale); jaroslav@1646: do { jaroslav@1646: expungeStaleElements(); jaroslav@1646: WeakEntry exist = map.putIfAbsent(e, e); jaroslav@1646: interned = (exist == null) ? elem : exist.get(); jaroslav@1646: } while (interned == null); jaroslav@1646: return interned; jaroslav@1646: } jaroslav@1646: jaroslav@1646: private void expungeStaleElements() { jaroslav@1646: Reference reference; jaroslav@1646: while ((reference = stale.poll()) != null) { jaroslav@1646: map.remove(reference); jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: private static class WeakEntry extends WeakReference { jaroslav@1646: jaroslav@1646: public final int hashcode; jaroslav@1646: jaroslav@1646: public WeakEntry(T key, ReferenceQueue queue) { jaroslav@1646: super(key, queue); jaroslav@1646: hashcode = key.hashCode(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: public WeakEntry(T key) { jaroslav@1646: super(key); jaroslav@1646: hashcode = key.hashCode(); jaroslav@1646: } jaroslav@1646: jaroslav@1646: @Override jaroslav@1646: public boolean equals(Object obj) { jaroslav@1646: if (obj instanceof WeakEntry) { jaroslav@1646: Object that = ((WeakEntry) obj).get(); jaroslav@1646: Object mine = get(); jaroslav@1646: return (that == null || mine == null) ? (this == obj) : mine.equals(that); jaroslav@1646: } jaroslav@1646: return false; jaroslav@1646: } jaroslav@1646: jaroslav@1646: @Override jaroslav@1646: public int hashCode() { jaroslav@1646: return hashcode; jaroslav@1646: } jaroslav@1646: jaroslav@1646: } jaroslav@1646: } jaroslav@1646: jaroslav@1646: }