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