rt/emul/compact/src/main/java/java/lang/invoke/MethodHandle.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 06:13:36 +0200
branchjdk8
changeset 1651 5c990ed353e9
parent 1646 c880a8a8803b
permissions -rw-r--r--
Almost compiled java.lang.invoke, except the parts that deal with Asm bytecode generator
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
jaroslav@1646
    29
import java.util.*;
jaroslav@1646
    30
import sun.invoke.util.*;
jaroslav@1646
    31
jaroslav@1646
    32
import static java.lang.invoke.MethodHandleStatics.*;
jaroslav@1646
    33
import java.util.logging.Level;
jaroslav@1646
    34
import java.util.logging.Logger;
jaroslav@1646
    35
jaroslav@1646
    36
/**
jaroslav@1646
    37
 * A method handle is a typed, directly executable reference to an underlying method,
jaroslav@1646
    38
 * constructor, field, or similar low-level operation, with optional
jaroslav@1646
    39
 * transformations of arguments or return values.
jaroslav@1646
    40
 * These transformations are quite general, and include such patterns as
jaroslav@1646
    41
 * {@linkplain #asType conversion},
jaroslav@1646
    42
 * {@linkplain #bindTo insertion},
jaroslav@1646
    43
 * {@linkplain java.lang.invoke.MethodHandles#dropArguments deletion},
jaroslav@1646
    44
 * and {@linkplain java.lang.invoke.MethodHandles#filterArguments substitution}.
jaroslav@1646
    45
 *
jaroslav@1646
    46
 * <h1>Method handle contents</h1>
jaroslav@1646
    47
 * Method handles are dynamically and strongly typed according to their parameter and return types.
jaroslav@1646
    48
 * They are not distinguished by the name or the defining class of their underlying methods.
jaroslav@1646
    49
 * A method handle must be invoked using a symbolic type descriptor which matches
jaroslav@1646
    50
 * the method handle's own {@linkplain #type type descriptor}.
jaroslav@1646
    51
 * <p>
jaroslav@1646
    52
 * Every method handle reports its type descriptor via the {@link #type type} accessor.
jaroslav@1646
    53
 * This type descriptor is a {@link java.lang.invoke.MethodType MethodType} object,
jaroslav@1646
    54
 * whose structure is a series of classes, one of which is
jaroslav@1646
    55
 * the return type of the method (or {@code void.class} if none).
jaroslav@1646
    56
 * <p>
jaroslav@1646
    57
 * A method handle's type controls the types of invocations it accepts,
jaroslav@1646
    58
 * and the kinds of transformations that apply to it.
jaroslav@1646
    59
 * <p>
jaroslav@1646
    60
 * A method handle contains a pair of special invoker methods
jaroslav@1646
    61
 * called {@link #invokeExact invokeExact} and {@link #invoke invoke}.
jaroslav@1646
    62
 * Both invoker methods provide direct access to the method handle's
jaroslav@1646
    63
 * underlying method, constructor, field, or other operation,
jaroslav@1646
    64
 * as modified by transformations of arguments and return values.
jaroslav@1646
    65
 * Both invokers accept calls which exactly match the method handle's own type.
jaroslav@1646
    66
 * The plain, inexact invoker also accepts a range of other call types.
jaroslav@1646
    67
 * <p>
jaroslav@1646
    68
 * Method handles are immutable and have no visible state.
jaroslav@1646
    69
 * Of course, they can be bound to underlying methods or data which exhibit state.
jaroslav@1646
    70
 * With respect to the Java Memory Model, any method handle will behave
jaroslav@1646
    71
 * as if all of its (internal) fields are final variables.  This means that any method
jaroslav@1646
    72
 * handle made visible to the application will always be fully formed.
jaroslav@1646
    73
 * This is true even if the method handle is published through a shared
jaroslav@1646
    74
 * variable in a data race.
jaroslav@1646
    75
 * <p>
jaroslav@1646
    76
 * Method handles cannot be subclassed by the user.
jaroslav@1646
    77
 * Implementations may (or may not) create internal subclasses of {@code MethodHandle}
jaroslav@1646
    78
 * which may be visible via the {@link java.lang.Object#getClass Object.getClass}
jaroslav@1646
    79
 * operation.  The programmer should not draw conclusions about a method handle
jaroslav@1646
    80
 * from its specific class, as the method handle class hierarchy (if any)
jaroslav@1646
    81
 * may change from time to time or across implementations from different vendors.
jaroslav@1646
    82
 *
jaroslav@1646
    83
 * <h1>Method handle compilation</h1>
jaroslav@1646
    84
 * A Java method call expression naming {@code invokeExact} or {@code invoke}
jaroslav@1646
    85
 * can invoke a method handle from Java source code.
jaroslav@1646
    86
 * From the viewpoint of source code, these methods can take any arguments
jaroslav@1646
    87
 * and their result can be cast to any return type.
jaroslav@1646
    88
 * Formally this is accomplished by giving the invoker methods
jaroslav@1646
    89
 * {@code Object} return types and variable arity {@code Object} arguments,
jaroslav@1646
    90
 * but they have an additional quality called <em>signature polymorphism</em>
jaroslav@1646
    91
 * which connects this freedom of invocation directly to the JVM execution stack.
jaroslav@1646
    92
 * <p>
jaroslav@1646
    93
 * As is usual with virtual methods, source-level calls to {@code invokeExact}
jaroslav@1646
    94
 * and {@code invoke} compile to an {@code invokevirtual} instruction.
jaroslav@1646
    95
 * More unusually, the compiler must record the actual argument types,
jaroslav@1646
    96
 * and may not perform method invocation conversions on the arguments.
jaroslav@1646
    97
 * Instead, it must push them on the stack according to their own unconverted types.
jaroslav@1646
    98
 * The method handle object itself is pushed on the stack before the arguments.
jaroslav@1646
    99
 * The compiler then calls the method handle with a symbolic type descriptor which
jaroslav@1646
   100
 * describes the argument and return types.
jaroslav@1646
   101
 * <p>
jaroslav@1646
   102
 * To issue a complete symbolic type descriptor, the compiler must also determine
jaroslav@1646
   103
 * the return type.  This is based on a cast on the method invocation expression,
jaroslav@1646
   104
 * if there is one, or else {@code Object} if the invocation is an expression
jaroslav@1646
   105
 * or else {@code void} if the invocation is a statement.
jaroslav@1646
   106
 * The cast may be to a primitive type (but not {@code void}).
jaroslav@1646
   107
 * <p>
jaroslav@1646
   108
 * As a corner case, an uncasted {@code null} argument is given
jaroslav@1646
   109
 * a symbolic type descriptor of {@code java.lang.Void}.
jaroslav@1646
   110
 * The ambiguity with the type {@code Void} is harmless, since there are no references of type
jaroslav@1646
   111
 * {@code Void} except the null reference.
jaroslav@1646
   112
 *
jaroslav@1646
   113
 * <h1>Method handle invocation</h1>
jaroslav@1646
   114
 * The first time a {@code invokevirtual} instruction is executed
jaroslav@1646
   115
 * it is linked, by symbolically resolving the names in the instruction
jaroslav@1646
   116
 * and verifying that the method call is statically legal.
jaroslav@1646
   117
 * This is true of calls to {@code invokeExact} and {@code invoke}.
jaroslav@1646
   118
 * In this case, the symbolic type descriptor emitted by the compiler is checked for
jaroslav@1646
   119
 * correct syntax and names it contains are resolved.
jaroslav@1646
   120
 * Thus, an {@code invokevirtual} instruction which invokes
jaroslav@1646
   121
 * a method handle will always link, as long
jaroslav@1646
   122
 * as the symbolic type descriptor is syntactically well-formed
jaroslav@1646
   123
 * and the types exist.
jaroslav@1646
   124
 * <p>
jaroslav@1646
   125
 * When the {@code invokevirtual} is executed after linking,
jaroslav@1646
   126
 * the receiving method handle's type is first checked by the JVM
jaroslav@1646
   127
 * to ensure that it matches the symbolic type descriptor.
jaroslav@1646
   128
 * If the type match fails, it means that the method which the
jaroslav@1646
   129
 * caller is invoking is not present on the individual
jaroslav@1646
   130
 * method handle being invoked.
jaroslav@1646
   131
 * <p>
jaroslav@1646
   132
 * In the case of {@code invokeExact}, the type descriptor of the invocation
jaroslav@1646
   133
 * (after resolving symbolic type names) must exactly match the method type
jaroslav@1646
   134
 * of the receiving method handle.
jaroslav@1646
   135
 * In the case of plain, inexact {@code invoke}, the resolved type descriptor
jaroslav@1646
   136
 * must be a valid argument to the receiver's {@link #asType asType} method.
jaroslav@1646
   137
 * Thus, plain {@code invoke} is more permissive than {@code invokeExact}.
jaroslav@1646
   138
 * <p>
jaroslav@1646
   139
 * After type matching, a call to {@code invokeExact} directly
jaroslav@1646
   140
 * and immediately invoke the method handle's underlying method
jaroslav@1646
   141
 * (or other behavior, as the case may be).
jaroslav@1646
   142
 * <p>
jaroslav@1646
   143
 * A call to plain {@code invoke} works the same as a call to
jaroslav@1646
   144
 * {@code invokeExact}, if the symbolic type descriptor specified by the caller
jaroslav@1646
   145
 * exactly matches the method handle's own type.
jaroslav@1646
   146
 * If there is a type mismatch, {@code invoke} attempts
jaroslav@1646
   147
 * to adjust the type of the receiving method handle,
jaroslav@1646
   148
 * as if by a call to {@link #asType asType},
jaroslav@1646
   149
 * to obtain an exactly invokable method handle {@code M2}.
jaroslav@1646
   150
 * This allows a more powerful negotiation of method type
jaroslav@1646
   151
 * between caller and callee.
jaroslav@1646
   152
 * <p>
jaroslav@1646
   153
 * (<em>Note:</em> The adjusted method handle {@code M2} is not directly observable,
jaroslav@1646
   154
 * and implementations are therefore not required to materialize it.)
jaroslav@1646
   155
 *
jaroslav@1646
   156
 * <h1>Invocation checking</h1>
jaroslav@1646
   157
 * In typical programs, method handle type matching will usually succeed.
jaroslav@1646
   158
 * But if a match fails, the JVM will throw a {@link WrongMethodTypeException},
jaroslav@1646
   159
 * either directly (in the case of {@code invokeExact}) or indirectly as if
jaroslav@1646
   160
 * by a failed call to {@code asType} (in the case of {@code invoke}).
jaroslav@1646
   161
 * <p>
jaroslav@1646
   162
 * Thus, a method type mismatch which might show up as a linkage error
jaroslav@1646
   163
 * in a statically typed program can show up as
jaroslav@1646
   164
 * a dynamic {@code WrongMethodTypeException}
jaroslav@1646
   165
 * in a program which uses method handles.
jaroslav@1646
   166
 * <p>
jaroslav@1646
   167
 * Because method types contain "live" {@code Class} objects,
jaroslav@1646
   168
 * method type matching takes into account both types names and class loaders.
jaroslav@1646
   169
 * Thus, even if a method handle {@code M} is created in one
jaroslav@1646
   170
 * class loader {@code L1} and used in another {@code L2},
jaroslav@1646
   171
 * method handle calls are type-safe, because the caller's symbolic type
jaroslav@1646
   172
 * descriptor, as resolved in {@code L2},
jaroslav@1646
   173
 * is matched against the original callee method's symbolic type descriptor,
jaroslav@1646
   174
 * as resolved in {@code L1}.
jaroslav@1646
   175
 * The resolution in {@code L1} happens when {@code M} is created
jaroslav@1646
   176
 * and its type is assigned, while the resolution in {@code L2} happens
jaroslav@1646
   177
 * when the {@code invokevirtual} instruction is linked.
jaroslav@1646
   178
 * <p>
jaroslav@1646
   179
 * Apart from the checking of type descriptors,
jaroslav@1646
   180
 * a method handle's capability to call its underlying method is unrestricted.
jaroslav@1646
   181
 * If a method handle is formed on a non-public method by a class
jaroslav@1646
   182
 * that has access to that method, the resulting handle can be used
jaroslav@1646
   183
 * in any place by any caller who receives a reference to it.
jaroslav@1646
   184
 * <p>
jaroslav@1646
   185
 * Unlike with the Core Reflection API, where access is checked every time
jaroslav@1646
   186
 * a reflective method is invoked,
jaroslav@1646
   187
 * method handle access checking is performed
jaroslav@1646
   188
 * <a href="MethodHandles.Lookup.html#access">when the method handle is created</a>.
jaroslav@1646
   189
 * In the case of {@code ldc} (see below), access checking is performed as part of linking
jaroslav@1646
   190
 * the constant pool entry underlying the constant method handle.
jaroslav@1646
   191
 * <p>
jaroslav@1646
   192
 * Thus, handles to non-public methods, or to methods in non-public classes,
jaroslav@1646
   193
 * should generally be kept secret.
jaroslav@1646
   194
 * They should not be passed to untrusted code unless their use from
jaroslav@1646
   195
 * the untrusted code would be harmless.
jaroslav@1646
   196
 *
jaroslav@1646
   197
 * <h1>Method handle creation</h1>
jaroslav@1646
   198
 * Java code can create a method handle that directly accesses
jaroslav@1646
   199
 * any method, constructor, or field that is accessible to that code.
jaroslav@1646
   200
 * This is done via a reflective, capability-based API called
jaroslav@1646
   201
 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}
jaroslav@1646
   202
 * For example, a static method handle can be obtained
jaroslav@1646
   203
 * from {@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}.
jaroslav@1646
   204
 * There are also conversion methods from Core Reflection API objects,
jaroslav@1646
   205
 * such as {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
jaroslav@1646
   206
 * <p>
jaroslav@1646
   207
 * Like classes and strings, method handles that correspond to accessible
jaroslav@1646
   208
 * fields, methods, and constructors can also be represented directly
jaroslav@1646
   209
 * in a class file's constant pool as constants to be loaded by {@code ldc} bytecodes.
jaroslav@1646
   210
 * A new type of constant pool entry, {@code CONSTANT_MethodHandle},
jaroslav@1646
   211
 * refers directly to an associated {@code CONSTANT_Methodref},
jaroslav@1646
   212
 * {@code CONSTANT_InterfaceMethodref}, or {@code CONSTANT_Fieldref}
jaroslav@1646
   213
 * constant pool entry.
jaroslav@1646
   214
 * (For full details on method handle constants,
jaroslav@1646
   215
 * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
jaroslav@1646
   216
 * <p>
jaroslav@1646
   217
 * Method handles produced by lookups or constant loads from methods or
jaroslav@1646
   218
 * constructors with the variable arity modifier bit ({@code 0x0080})
jaroslav@1646
   219
 * have a corresponding variable arity, as if they were defined with
jaroslav@1646
   220
 * the help of {@link #asVarargsCollector asVarargsCollector}.
jaroslav@1646
   221
 * <p>
jaroslav@1646
   222
 * A method reference may refer either to a static or non-static method.
jaroslav@1646
   223
 * In the non-static case, the method handle type includes an explicit
jaroslav@1646
   224
 * receiver argument, prepended before any other arguments.
jaroslav@1646
   225
 * In the method handle's type, the initial receiver argument is typed
jaroslav@1646
   226
 * according to the class under which the method was initially requested.
jaroslav@1646
   227
 * (E.g., if a non-static method handle is obtained via {@code ldc},
jaroslav@1646
   228
 * the type of the receiver is the class named in the constant pool entry.)
jaroslav@1646
   229
 * <p>
jaroslav@1646
   230
 * Method handle constants are subject to the same link-time access checks
jaroslav@1646
   231
 * their corresponding bytecode instructions, and the {@code ldc} instruction
jaroslav@1646
   232
 * will throw corresponding linkage errors if the bytecode behaviors would
jaroslav@1646
   233
 * throw such errors.
jaroslav@1646
   234
 * <p>
jaroslav@1646
   235
 * As a corollary of this, access to protected members is restricted
jaroslav@1646
   236
 * to receivers only of the accessing class, or one of its subclasses,
jaroslav@1646
   237
 * and the accessing class must in turn be a subclass (or package sibling)
jaroslav@1646
   238
 * of the protected member's defining class.
jaroslav@1646
   239
 * If a method reference refers to a protected non-static method or field
jaroslav@1646
   240
 * of a class outside the current package, the receiver argument will
jaroslav@1646
   241
 * be narrowed to the type of the accessing class.
jaroslav@1646
   242
 * <p>
jaroslav@1646
   243
 * When a method handle to a virtual method is invoked, the method is
jaroslav@1646
   244
 * always looked up in the receiver (that is, the first argument).
jaroslav@1646
   245
 * <p>
jaroslav@1646
   246
 * A non-virtual method handle to a specific virtual method implementation
jaroslav@1646
   247
 * can also be created.  These do not perform virtual lookup based on
jaroslav@1646
   248
 * receiver type.  Such a method handle simulates the effect of
jaroslav@1646
   249
 * an {@code invokespecial} instruction to the same method.
jaroslav@1646
   250
 *
jaroslav@1646
   251
 * <h1>Usage examples</h1>
jaroslav@1646
   252
 * Here are some examples of usage:
jaroslav@1646
   253
 * <blockquote><pre>{@code
jaroslav@1646
   254
Object x, y; String s; int i;
jaroslav@1646
   255
MethodType mt; MethodHandle mh;
jaroslav@1646
   256
MethodHandles.Lookup lookup = MethodHandles.lookup();
jaroslav@1646
   257
// mt is (char,char)String
jaroslav@1646
   258
mt = MethodType.methodType(String.class, char.class, char.class);
jaroslav@1646
   259
mh = lookup.findVirtual(String.class, "replace", mt);
jaroslav@1646
   260
s = (String) mh.invokeExact("daddy",'d','n');
jaroslav@1646
   261
// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
jaroslav@1646
   262
assertEquals(s, "nanny");
jaroslav@1646
   263
// weakly typed invocation (using MHs.invoke)
jaroslav@1646
   264
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
jaroslav@1646
   265
assertEquals(s, "savvy");
jaroslav@1646
   266
// mt is (Object[])List
jaroslav@1646
   267
mt = MethodType.methodType(java.util.List.class, Object[].class);
jaroslav@1646
   268
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
jaroslav@1646
   269
assert(mh.isVarargsCollector());
jaroslav@1646
   270
x = mh.invoke("one", "two");
jaroslav@1646
   271
// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
jaroslav@1646
   272
assertEquals(x, java.util.Arrays.asList("one","two"));
jaroslav@1646
   273
// mt is (Object,Object,Object)Object
jaroslav@1646
   274
mt = MethodType.genericMethodType(3);
jaroslav@1646
   275
mh = mh.asType(mt);
jaroslav@1646
   276
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
jaroslav@1646
   277
// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
jaroslav@1646
   278
assertEquals(x, java.util.Arrays.asList(1,2,3));
jaroslav@1646
   279
// mt is ()int
jaroslav@1646
   280
mt = MethodType.methodType(int.class);
jaroslav@1646
   281
mh = lookup.findVirtual(java.util.List.class, "size", mt);
jaroslav@1646
   282
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
jaroslav@1646
   283
// invokeExact(Ljava/util/List;)I
jaroslav@1646
   284
assert(i == 3);
jaroslav@1646
   285
mt = MethodType.methodType(void.class, String.class);
jaroslav@1646
   286
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
jaroslav@1646
   287
mh.invokeExact(System.out, "Hello, world.");
jaroslav@1646
   288
// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
jaroslav@1646
   289
 * }</pre></blockquote>
jaroslav@1646
   290
 * Each of the above calls to {@code invokeExact} or plain {@code invoke}
jaroslav@1646
   291
 * generates a single invokevirtual instruction with
jaroslav@1646
   292
 * the symbolic type descriptor indicated in the following comment.
jaroslav@1646
   293
 * In these examples, the helper method {@code assertEquals} is assumed to
jaroslav@1646
   294
 * be a method which calls {@link java.util.Objects#equals(Object,Object) Objects.equals}
jaroslav@1646
   295
 * on its arguments, and asserts that the result is true.
jaroslav@1646
   296
 *
jaroslav@1646
   297
 * <h1>Exceptions</h1>
jaroslav@1646
   298
 * The methods {@code invokeExact} and {@code invoke} are declared
jaroslav@1646
   299
 * to throw {@link java.lang.Throwable Throwable},
jaroslav@1646
   300
 * which is to say that there is no static restriction on what a method handle
jaroslav@1646
   301
 * can throw.  Since the JVM does not distinguish between checked
jaroslav@1646
   302
 * and unchecked exceptions (other than by their class, of course),
jaroslav@1646
   303
 * there is no particular effect on bytecode shape from ascribing
jaroslav@1646
   304
 * checked exceptions to method handle invocations.  But in Java source
jaroslav@1646
   305
 * code, methods which perform method handle calls must either explicitly
jaroslav@1646
   306
 * throw {@code Throwable}, or else must catch all
jaroslav@1646
   307
 * throwables locally, rethrowing only those which are legal in the context,
jaroslav@1646
   308
 * and wrapping ones which are illegal.
jaroslav@1646
   309
 *
jaroslav@1646
   310
 * <h1><a name="sigpoly"></a>Signature polymorphism</h1>
jaroslav@1646
   311
 * The unusual compilation and linkage behavior of
jaroslav@1646
   312
 * {@code invokeExact} and plain {@code invoke}
jaroslav@1646
   313
 * is referenced by the term <em>signature polymorphism</em>.
jaroslav@1646
   314
 * As defined in the Java Language Specification,
jaroslav@1646
   315
 * a signature polymorphic method is one which can operate with
jaroslav@1646
   316
 * any of a wide range of call signatures and return types.
jaroslav@1646
   317
 * <p>
jaroslav@1646
   318
 * In source code, a call to a signature polymorphic method will
jaroslav@1646
   319
 * compile, regardless of the requested symbolic type descriptor.
jaroslav@1646
   320
 * As usual, the Java compiler emits an {@code invokevirtual}
jaroslav@1646
   321
 * instruction with the given symbolic type descriptor against the named method.
jaroslav@1646
   322
 * The unusual part is that the symbolic type descriptor is derived from
jaroslav@1646
   323
 * the actual argument and return types, not from the method declaration.
jaroslav@1646
   324
 * <p>
jaroslav@1646
   325
 * When the JVM processes bytecode containing signature polymorphic calls,
jaroslav@1646
   326
 * it will successfully link any such call, regardless of its symbolic type descriptor.
jaroslav@1646
   327
 * (In order to retain type safety, the JVM will guard such calls with suitable
jaroslav@1646
   328
 * dynamic type checks, as described elsewhere.)
jaroslav@1646
   329
 * <p>
jaroslav@1646
   330
 * Bytecode generators, including the compiler back end, are required to emit
jaroslav@1646
   331
 * untransformed symbolic type descriptors for these methods.
jaroslav@1646
   332
 * Tools which determine symbolic linkage are required to accept such
jaroslav@1646
   333
 * untransformed descriptors, without reporting linkage errors.
jaroslav@1646
   334
 *
jaroslav@1646
   335
 * <h1>Interoperation between method handles and the Core Reflection API</h1>
jaroslav@1646
   336
 * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup Lookup} API,
jaroslav@1646
   337
 * any class member represented by a Core Reflection API object
jaroslav@1646
   338
 * can be converted to a behaviorally equivalent method handle.
jaroslav@1646
   339
 * For example, a reflective {@link java.lang.reflect.Method Method} can
jaroslav@1646
   340
 * be converted to a method handle using
jaroslav@1646
   341
 * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
jaroslav@1646
   342
 * The resulting method handles generally provide more direct and efficient
jaroslav@1646
   343
 * access to the underlying class members.
jaroslav@1646
   344
 * <p>
jaroslav@1646
   345
 * As a special case,
jaroslav@1646
   346
 * when the Core Reflection API is used to view the signature polymorphic
jaroslav@1646
   347
 * methods {@code invokeExact} or plain {@code invoke} in this class,
jaroslav@1646
   348
 * they appear as ordinary non-polymorphic methods.
jaroslav@1646
   349
 * Their reflective appearance, as viewed by
jaroslav@1646
   350
 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
jaroslav@1646
   351
 * is unaffected by their special status in this API.
jaroslav@1646
   352
 * For example, {@link java.lang.reflect.Method#getModifiers Method.getModifiers}
jaroslav@1646
   353
 * will report exactly those modifier bits required for any similarly
jaroslav@1646
   354
 * declared method, including in this case {@code native} and {@code varargs} bits.
jaroslav@1646
   355
 * <p>
jaroslav@1646
   356
 * As with any reflected method, these methods (when reflected) may be
jaroslav@1646
   357
 * invoked via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.
jaroslav@1646
   358
 * However, such reflective calls do not result in method handle invocations.
jaroslav@1646
   359
 * Such a call, if passed the required argument
jaroslav@1646
   360
 * (a single one, of type {@code Object[]}), will ignore the argument and
jaroslav@1646
   361
 * will throw an {@code UnsupportedOperationException}.
jaroslav@1646
   362
 * <p>
jaroslav@1646
   363
 * Since {@code invokevirtual} instructions can natively
jaroslav@1646
   364
 * invoke method handles under any symbolic type descriptor, this reflective view conflicts
jaroslav@1646
   365
 * with the normal presentation of these methods via bytecodes.
jaroslav@1646
   366
 * Thus, these two native methods, when reflectively viewed by
jaroslav@1646
   367
 * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
jaroslav@1646
   368
 * <p>
jaroslav@1646
   369
 * In order to obtain an invoker method for a particular type descriptor,
jaroslav@1646
   370
 * use {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker},
jaroslav@1646
   371
 * or {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}.
jaroslav@1646
   372
 * The {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
jaroslav@1646
   373
 * API is also able to return a method handle
jaroslav@1646
   374
 * to call {@code invokeExact} or plain {@code invoke},
jaroslav@1646
   375
 * for any specified type descriptor .
jaroslav@1646
   376
 *
jaroslav@1646
   377
 * <h1>Interoperation between method handles and Java generics</h1>
jaroslav@1646
   378
 * A method handle can be obtained on a method, constructor, or field
jaroslav@1646
   379
 * which is declared with Java generic types.
jaroslav@1646
   380
 * As with the Core Reflection API, the type of the method handle
jaroslav@1646
   381
 * will constructed from the erasure of the source-level type.
jaroslav@1646
   382
 * When a method handle is invoked, the types of its arguments
jaroslav@1646
   383
 * or the return value cast type may be generic types or type instances.
jaroslav@1646
   384
 * If this occurs, the compiler will replace those
jaroslav@1646
   385
 * types by their erasures when it constructs the symbolic type descriptor
jaroslav@1646
   386
 * for the {@code invokevirtual} instruction.
jaroslav@1646
   387
 * <p>
jaroslav@1646
   388
 * Method handles do not represent
jaroslav@1646
   389
 * their function-like types in terms of Java parameterized (generic) types,
jaroslav@1646
   390
 * because there are three mismatches between function-like types and parameterized
jaroslav@1646
   391
 * Java types.
jaroslav@1646
   392
 * <ul>
jaroslav@1646
   393
 * <li>Method types range over all possible arities,
jaroslav@1646
   394
 * from no arguments to up to the  <a href="MethodHandle.html#maxarity">maximum number</a> of allowed arguments.
jaroslav@1646
   395
 * Generics are not variadic, and so cannot represent this.</li>
jaroslav@1646
   396
 * <li>Method types can specify arguments of primitive types,
jaroslav@1646
   397
 * which Java generic types cannot range over.</li>
jaroslav@1646
   398
 * <li>Higher order functions over method handles (combinators) are
jaroslav@1646
   399
 * often generic across a wide range of function types, including
jaroslav@1646
   400
 * those of multiple arities.  It is impossible to represent such
jaroslav@1646
   401
 * genericity with a Java type parameter.</li>
jaroslav@1646
   402
 * </ul>
jaroslav@1646
   403
 *
jaroslav@1646
   404
 * <h1><a name="maxarity"></a>Arity limits</h1>
jaroslav@1646
   405
 * The JVM imposes on all methods and constructors of any kind an absolute
jaroslav@1646
   406
 * limit of 255 stacked arguments.  This limit can appear more restrictive
jaroslav@1646
   407
 * in certain cases:
jaroslav@1646
   408
 * <ul>
jaroslav@1646
   409
 * <li>A {@code long} or {@code double} argument counts (for purposes of arity limits) as two argument slots.
jaroslav@1646
   410
 * <li>A non-static method consumes an extra argument for the object on which the method is called.
jaroslav@1646
   411
 * <li>A constructor consumes an extra argument for the object which is being constructed.
jaroslav@1646
   412
 * <li>Since a method handle&rsquo;s {@code invoke} method (or other signature-polymorphic method) is non-virtual,
jaroslav@1646
   413
 *     it consumes an extra argument for the method handle itself, in addition to any non-virtual receiver object.
jaroslav@1646
   414
 * </ul>
jaroslav@1646
   415
 * These limits imply that certain method handles cannot be created, solely because of the JVM limit on stacked arguments.
jaroslav@1646
   416
 * For example, if a static JVM method accepts exactly 255 arguments, a method handle cannot be created for it.
jaroslav@1646
   417
 * Attempts to create method handles with impossible method types lead to an {@link IllegalArgumentException}.
jaroslav@1646
   418
 * In particular, a method handle&rsquo;s type must not have an arity of the exact maximum 255.
jaroslav@1646
   419
 *
jaroslav@1646
   420
 * @see MethodType
jaroslav@1646
   421
 * @see MethodHandles
jaroslav@1646
   422
 * @author John Rose, JSR 292 EG
jaroslav@1646
   423
 */
jaroslav@1646
   424
public abstract class MethodHandle {
jaroslav@1646
   425
    static { MethodHandleImpl.initStatics(); }
jaroslav@1646
   426
jaroslav@1646
   427
    /**
jaroslav@1646
   428
     * Internal marker interface which distinguishes (to the Java compiler)
jaroslav@1646
   429
     * those methods which are <a href="MethodHandle.html#sigpoly">signature polymorphic</a>.
jaroslav@1646
   430
     */
jaroslav@1646
   431
    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
jaroslav@1646
   432
    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
jaroslav@1646
   433
    @interface PolymorphicSignature { }
jaroslav@1646
   434
jaroslav@1646
   435
    private final MethodType type;
jaroslav@1651
   436
    /*private*/ LambdaForm form;
jaroslav@1646
   437
    // form is not private so that invokers can easily fetch it
jaroslav@1646
   438
    /*private*/ MethodHandle asTypeCache;
jaroslav@1646
   439
    // asTypeCache is not private so that invokers can easily fetch it
jaroslav@1646
   440
jaroslav@1646
   441
    /**
jaroslav@1646
   442
     * Reports the type of this method handle.
jaroslav@1646
   443
     * Every invocation of this method handle via {@code invokeExact} must exactly match this type.
jaroslav@1646
   444
     * @return the method handle type
jaroslav@1646
   445
     */
jaroslav@1646
   446
    public MethodType type() {
jaroslav@1646
   447
        return type;
jaroslav@1646
   448
    }
jaroslav@1646
   449
jaroslav@1646
   450
    /**
jaroslav@1646
   451
     * Package-private constructor for the method handle implementation hierarchy.
jaroslav@1646
   452
     * Method handle inheritance will be contained completely within
jaroslav@1646
   453
     * the {@code java.lang.invoke} package.
jaroslav@1646
   454
     */
jaroslav@1646
   455
    // @param type type (permanently assigned) of the new method handle
jaroslav@1646
   456
    /*non-public*/ MethodHandle(MethodType type, LambdaForm form) {
jaroslav@1646
   457
        type.getClass();  // explicit NPE
jaroslav@1646
   458
        form.getClass();  // explicit NPE
jaroslav@1646
   459
        this.type = type;
jaroslav@1646
   460
        this.form = form;
jaroslav@1646
   461
jaroslav@1646
   462
        form.prepare();  // TO DO:  Try to delay this step until just before invocation.
jaroslav@1646
   463
    }
jaroslav@1646
   464
jaroslav@1646
   465
    /**
jaroslav@1646
   466
     * Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match.
jaroslav@1646
   467
     * The symbolic type descriptor at the call site of {@code invokeExact} must
jaroslav@1646
   468
     * exactly match this method handle's {@link #type type}.
jaroslav@1646
   469
     * No conversions are allowed on arguments or return values.
jaroslav@1646
   470
     * <p>
jaroslav@1646
   471
     * When this method is observed via the Core Reflection API,
jaroslav@1646
   472
     * it will appear as a single native method, taking an object array and returning an object.
jaroslav@1646
   473
     * If this native method is invoked directly via
jaroslav@1646
   474
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
jaroslav@1646
   475
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
jaroslav@1646
   476
     * it will throw an {@code UnsupportedOperationException}.
jaroslav@1646
   477
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   478
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   479
     * @throws WrongMethodTypeException if the target's type is not identical with the caller's symbolic type descriptor
jaroslav@1646
   480
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
jaroslav@1646
   481
     */
jaroslav@1646
   482
    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;
jaroslav@1646
   483
jaroslav@1646
   484
    /**
jaroslav@1646
   485
     * Invokes the method handle, allowing any caller type descriptor,
jaroslav@1646
   486
     * and optionally performing conversions on arguments and return values.
jaroslav@1646
   487
     * <p>
jaroslav@1646
   488
     * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
jaroslav@1646
   489
     * the call proceeds as if by {@link #invokeExact invokeExact}.
jaroslav@1646
   490
     * <p>
jaroslav@1646
   491
     * Otherwise, the call proceeds as if this method handle were first
jaroslav@1646
   492
     * adjusted by calling {@link #asType asType} to adjust this method handle
jaroslav@1646
   493
     * to the required type, and then the call proceeds as if by
jaroslav@1646
   494
     * {@link #invokeExact invokeExact} on the adjusted method handle.
jaroslav@1646
   495
     * <p>
jaroslav@1646
   496
     * There is no guarantee that the {@code asType} call is actually made.
jaroslav@1646
   497
     * If the JVM can predict the results of making the call, it may perform
jaroslav@1646
   498
     * adaptations directly on the caller's arguments,
jaroslav@1646
   499
     * and call the target method handle according to its own exact type.
jaroslav@1646
   500
     * <p>
jaroslav@1646
   501
     * The resolved type descriptor at the call site of {@code invoke} must
jaroslav@1646
   502
     * be a valid argument to the receivers {@code asType} method.
jaroslav@1646
   503
     * In particular, the caller must specify the same argument arity
jaroslav@1646
   504
     * as the callee's type,
jaroslav@1646
   505
     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
jaroslav@1646
   506
     * <p>
jaroslav@1646
   507
     * When this method is observed via the Core Reflection API,
jaroslav@1646
   508
     * it will appear as a single native method, taking an object array and returning an object.
jaroslav@1646
   509
     * If this native method is invoked directly via
jaroslav@1646
   510
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
jaroslav@1646
   511
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
jaroslav@1646
   512
     * it will throw an {@code UnsupportedOperationException}.
jaroslav@1646
   513
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   514
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   515
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
jaroslav@1646
   516
     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
jaroslav@1646
   517
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
jaroslav@1646
   518
     */
jaroslav@1646
   519
    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;
jaroslav@1646
   520
jaroslav@1646
   521
    /**
jaroslav@1646
   522
     * Private method for trusted invocation of a method handle respecting simplified signatures.
jaroslav@1646
   523
     * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
jaroslav@1646
   524
     * <p>
jaroslav@1646
   525
     * The caller signature is restricted to the following basic types:
jaroslav@1646
   526
     * Object, int, long, float, double, and void return.
jaroslav@1646
   527
     * <p>
jaroslav@1646
   528
     * The caller is responsible for maintaining type correctness by ensuring
jaroslav@1646
   529
     * that the each outgoing argument value is a member of the range of the corresponding
jaroslav@1646
   530
     * callee argument type.
jaroslav@1646
   531
     * (The caller should therefore issue appropriate casts and integer narrowing
jaroslav@1646
   532
     * operations on outgoing argument values.)
jaroslav@1646
   533
     * The caller can assume that the incoming result value is part of the range
jaroslav@1646
   534
     * of the callee's return type.
jaroslav@1646
   535
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   536
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   537
     */
jaroslav@1646
   538
    /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;
jaroslav@1646
   539
jaroslav@1646
   540
    /**
jaroslav@1646
   541
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
jaroslav@1646
   542
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1646
   543
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1646
   544
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   545
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   546
     */
jaroslav@1646
   547
    /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;
jaroslav@1646
   548
jaroslav@1646
   549
    /**
jaroslav@1646
   550
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
jaroslav@1646
   551
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1646
   552
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1646
   553
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   554
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   555
     */
jaroslav@1646
   556
    /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;
jaroslav@1646
   557
jaroslav@1646
   558
    /**
jaroslav@1646
   559
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
jaroslav@1646
   560
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1646
   561
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1646
   562
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   563
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   564
     */
jaroslav@1646
   565
    /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;
jaroslav@1646
   566
jaroslav@1646
   567
    /**
jaroslav@1646
   568
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
jaroslav@1646
   569
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
jaroslav@1646
   570
     * The trailing (not leading) argument must be a MemberName.
jaroslav@1646
   571
     * @param args the signature-polymorphic parameter list, statically represented using varargs
jaroslav@1646
   572
     * @return the signature-polymorphic result, statically represented using {@code Object}
jaroslav@1646
   573
     */
jaroslav@1646
   574
    /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;
jaroslav@1646
   575
jaroslav@1646
   576
    /**
jaroslav@1646
   577
     * Performs a variable arity invocation, passing the arguments in the given list
jaroslav@1646
   578
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
jaroslav@1646
   579
     * which mentions only the type {@code Object}, and whose arity is the length
jaroslav@1646
   580
     * of the argument list.
jaroslav@1646
   581
     * <p>
jaroslav@1646
   582
     * Specifically, execution proceeds as if by the following steps,
jaroslav@1646
   583
     * although the methods are not guaranteed to be called if the JVM
jaroslav@1646
   584
     * can predict their effects.
jaroslav@1646
   585
     * <ul>
jaroslav@1646
   586
     * <li>Determine the length of the argument array as {@code N}.
jaroslav@1646
   587
     *     For a null reference, {@code N=0}. </li>
jaroslav@1646
   588
     * <li>Determine the general type {@code TN} of {@code N} arguments as
jaroslav@1646
   589
     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
jaroslav@1646
   590
     * <li>Force the original target method handle {@code MH0} to the
jaroslav@1646
   591
     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
jaroslav@1646
   592
     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
jaroslav@1646
   593
     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
jaroslav@1646
   594
     *     MH1.invokeExact(A0, ...). </li>
jaroslav@1646
   595
     * <li>Take the return value as an {@code Object} reference. </li>
jaroslav@1646
   596
     * </ul>
jaroslav@1646
   597
     * <p>
jaroslav@1646
   598
     * Because of the action of the {@code asType} step, the following argument
jaroslav@1646
   599
     * conversions are applied as necessary:
jaroslav@1646
   600
     * <ul>
jaroslav@1646
   601
     * <li>reference casting
jaroslav@1646
   602
     * <li>unboxing
jaroslav@1646
   603
     * <li>widening primitive conversions
jaroslav@1646
   604
     * </ul>
jaroslav@1646
   605
     * <p>
jaroslav@1646
   606
     * The result returned by the call is boxed if it is a primitive,
jaroslav@1646
   607
     * or forced to null if the return type is void.
jaroslav@1646
   608
     * <p>
jaroslav@1646
   609
     * This call is equivalent to the following code:
jaroslav@1646
   610
     * <blockquote><pre>{@code
jaroslav@1646
   611
     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
jaroslav@1646
   612
     * Object result = invoker.invokeExact(this, arguments);
jaroslav@1646
   613
     * }</pre></blockquote>
jaroslav@1646
   614
     * <p>
jaroslav@1646
   615
     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
jaroslav@1646
   616
     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
jaroslav@1646
   617
     * It can therefore be used as a bridge between native or reflective code and method handles.
jaroslav@1646
   618
     *
jaroslav@1646
   619
     * @param arguments the arguments to pass to the target
jaroslav@1646
   620
     * @return the result returned by the target
jaroslav@1646
   621
     * @throws ClassCastException if an argument cannot be converted by reference casting
jaroslav@1646
   622
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
jaroslav@1646
   623
     * @throws Throwable anything thrown by the target method invocation
jaroslav@1646
   624
     * @see MethodHandles#spreadInvoker
jaroslav@1646
   625
     */
jaroslav@1646
   626
    public Object invokeWithArguments(Object... arguments) throws Throwable {
jaroslav@1646
   627
        int argc = arguments == null ? 0 : arguments.length;
jaroslav@1646
   628
        @SuppressWarnings("LocalVariableHidesMemberVariable")
jaroslav@1646
   629
        MethodType type = type();
jaroslav@1646
   630
        if (type.parameterCount() != argc || isVarargsCollector()) {
jaroslav@1646
   631
            // simulate invoke
jaroslav@1646
   632
            return asType(MethodType.genericMethodType(argc)).invokeWithArguments(arguments);
jaroslav@1646
   633
        }
jaroslav@1646
   634
        MethodHandle invoker = type.invokers().varargsInvoker();
jaroslav@1646
   635
        return invoker.invokeExact(this, arguments);
jaroslav@1646
   636
    }
jaroslav@1646
   637
jaroslav@1646
   638
    /**
jaroslav@1646
   639
     * Performs a variable arity invocation, passing the arguments in the given array
jaroslav@1646
   640
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
jaroslav@1646
   641
     * which mentions only the type {@code Object}, and whose arity is the length
jaroslav@1646
   642
     * of the argument array.
jaroslav@1646
   643
     * <p>
jaroslav@1646
   644
     * This method is also equivalent to the following code:
jaroslav@1646
   645
     * <blockquote><pre>{@code
jaroslav@1646
   646
     *   invokeWithArguments(arguments.toArray()
jaroslav@1646
   647
     * }</pre></blockquote>
jaroslav@1646
   648
     *
jaroslav@1646
   649
     * @param arguments the arguments to pass to the target
jaroslav@1646
   650
     * @return the result returned by the target
jaroslav@1646
   651
     * @throws NullPointerException if {@code arguments} is a null reference
jaroslav@1646
   652
     * @throws ClassCastException if an argument cannot be converted by reference casting
jaroslav@1646
   653
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
jaroslav@1646
   654
     * @throws Throwable anything thrown by the target method invocation
jaroslav@1646
   655
     */
jaroslav@1646
   656
    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
jaroslav@1646
   657
        return invokeWithArguments(arguments.toArray());
jaroslav@1646
   658
    }
jaroslav@1646
   659
jaroslav@1646
   660
    /**
jaroslav@1646
   661
     * Produces an adapter method handle which adapts the type of the
jaroslav@1646
   662
     * current method handle to a new type.
jaroslav@1646
   663
     * The resulting method handle is guaranteed to report a type
jaroslav@1646
   664
     * which is equal to the desired new type.
jaroslav@1646
   665
     * <p>
jaroslav@1646
   666
     * If the original type and new type are equal, returns {@code this}.
jaroslav@1646
   667
     * <p>
jaroslav@1646
   668
     * The new method handle, when invoked, will perform the following
jaroslav@1646
   669
     * steps:
jaroslav@1646
   670
     * <ul>
jaroslav@1646
   671
     * <li>Convert the incoming argument list to match the original
jaroslav@1646
   672
     *     method handle's argument list.
jaroslav@1646
   673
     * <li>Invoke the original method handle on the converted argument list.
jaroslav@1646
   674
     * <li>Convert any result returned by the original method handle
jaroslav@1646
   675
     *     to the return type of new method handle.
jaroslav@1646
   676
     * </ul>
jaroslav@1646
   677
     * <p>
jaroslav@1646
   678
     * This method provides the crucial behavioral difference between
jaroslav@1646
   679
     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
jaroslav@1646
   680
     * The two methods
jaroslav@1646
   681
     * perform the same steps when the caller's type descriptor exactly m atches
jaroslav@1646
   682
     * the callee's, but when the types differ, plain {@link #invoke invoke}
jaroslav@1646
   683
     * also calls {@code asType} (or some internal equivalent) in order
jaroslav@1646
   684
     * to match up the caller's and callee's types.
jaroslav@1646
   685
     * <p>
jaroslav@1646
   686
     * If the current method is a variable arity method handle
jaroslav@1646
   687
     * argument list conversion may involve the conversion and collection
jaroslav@1646
   688
     * of several arguments into an array, as
jaroslav@1646
   689
     * {@linkplain #asVarargsCollector described elsewhere}.
jaroslav@1646
   690
     * In every other case, all conversions are applied <em>pairwise</em>,
jaroslav@1646
   691
     * which means that each argument or return value is converted to
jaroslav@1646
   692
     * exactly one argument or return value (or no return value).
jaroslav@1646
   693
     * The applied conversions are defined by consulting the
jaroslav@1646
   694
     * the corresponding component types of the old and new
jaroslav@1646
   695
     * method handle types.
jaroslav@1646
   696
     * <p>
jaroslav@1646
   697
     * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
jaroslav@1646
   698
     * or old and new return types.  Specifically, for some valid index {@code i}, let
jaroslav@1646
   699
     * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
jaroslav@1646
   700
     * Or else, going the other way for return values, let
jaroslav@1646
   701
     * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
jaroslav@1646
   702
     * If the types are the same, the new method handle makes no change
jaroslav@1646
   703
     * to the corresponding argument or return value (if any).
jaroslav@1646
   704
     * Otherwise, one of the following conversions is applied
jaroslav@1646
   705
     * if possible:
jaroslav@1646
   706
     * <ul>
jaroslav@1646
   707
     * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
jaroslav@1646
   708
     *     (The types do not need to be related in any particular way.
jaroslav@1646
   709
     *     This is because a dynamic value of null can convert to any reference type.)
jaroslav@1646
   710
     * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
jaroslav@1646
   711
     *     conversion (JLS 5.3) is applied, if one exists.
jaroslav@1646
   712
     *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
jaroslav@1646
   713
     * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
jaroslav@1646
   714
     *     a Java casting conversion (JLS 5.5) is applied if one exists.
jaroslav@1646
   715
     *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
jaroslav@1646
   716
     *     which is then widened as needed to <em>T1</em>.)
jaroslav@1646
   717
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
jaroslav@1646
   718
     *     conversion will be applied at runtime, possibly followed
jaroslav@1646
   719
     *     by a Java method invocation conversion (JLS 5.3)
jaroslav@1646
   720
     *     on the primitive value.  (These are the primitive widening conversions.)
jaroslav@1646
   721
     *     <em>T0</em> must be a wrapper class or a supertype of one.
jaroslav@1646
   722
     *     (In the case where <em>T0</em> is Object, these are the conversions
jaroslav@1646
   723
     *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
jaroslav@1646
   724
     *     The unboxing conversion must have a possibility of success, which means that
jaroslav@1646
   725
     *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
jaroslav@1646
   726
     *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
jaroslav@1646
   727
     *     primitive value can be widened to <em>T1</em>.
jaroslav@1646
   728
     * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
jaroslav@1646
   729
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
jaroslav@1646
   730
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
jaroslav@1646
   731
     *     a zero value is introduced.
jaroslav@1646
   732
     * </ul>
jaroslav@1646
   733
    * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
jaroslav@1646
   734
     * because neither corresponds specifically to the <em>dynamic type</em> of any
jaroslav@1646
   735
     * actual argument or return value.)
jaroslav@1646
   736
     * <p>
jaroslav@1646
   737
     * The method handle conversion cannot be made if any one of the required
jaroslav@1646
   738
     * pairwise conversions cannot be made.
jaroslav@1646
   739
     * <p>
jaroslav@1646
   740
     * At runtime, the conversions applied to reference arguments
jaroslav@1646
   741
     * or return values may require additional runtime checks which can fail.
jaroslav@1646
   742
     * An unboxing operation may fail because the original reference is null,
jaroslav@1646
   743
     * causing a {@link java.lang.NullPointerException NullPointerException}.
jaroslav@1646
   744
     * An unboxing operation or a reference cast may also fail on a reference
jaroslav@1646
   745
     * to an object of the wrong type,
jaroslav@1646
   746
     * causing a {@link java.lang.ClassCastException ClassCastException}.
jaroslav@1646
   747
     * Although an unboxing operation may accept several kinds of wrappers,
jaroslav@1646
   748
     * if none are available, a {@code ClassCastException} will be thrown.
jaroslav@1646
   749
     *
jaroslav@1646
   750
     * @param newType the expected type of the new method handle
jaroslav@1646
   751
     * @return a method handle which delegates to {@code this} after performing
jaroslav@1646
   752
     *           any necessary argument conversions, and arranges for any
jaroslav@1646
   753
     *           necessary return value conversions
jaroslav@1646
   754
     * @throws NullPointerException if {@code newType} is a null reference
jaroslav@1646
   755
     * @throws WrongMethodTypeException if the conversion cannot be made
jaroslav@1646
   756
     * @see MethodHandles#explicitCastArguments
jaroslav@1646
   757
     */
jaroslav@1646
   758
    public MethodHandle asType(MethodType newType) {
jaroslav@1646
   759
        // Fast path alternative to a heavyweight {@code asType} call.
jaroslav@1646
   760
        // Return 'this' if the conversion will be a no-op.
jaroslav@1646
   761
        if (newType == type) {
jaroslav@1646
   762
            return this;
jaroslav@1646
   763
        }
jaroslav@1646
   764
        // Return 'this.asTypeCache' if the conversion is already memoized.
jaroslav@1646
   765
        MethodHandle atc = asTypeCache;
jaroslav@1646
   766
        if (atc != null && newType == atc.type) {
jaroslav@1646
   767
            return atc;
jaroslav@1646
   768
        }
jaroslav@1646
   769
        return asTypeUncached(newType);
jaroslav@1646
   770
    }
jaroslav@1646
   771
jaroslav@1646
   772
    /** Override this to change asType behavior. */
jaroslav@1646
   773
    /*non-public*/ MethodHandle asTypeUncached(MethodType newType) {
jaroslav@1646
   774
        if (!type.isConvertibleTo(newType))
jaroslav@1646
   775
            throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
jaroslav@1646
   776
        return asTypeCache = convertArguments(newType);
jaroslav@1646
   777
    }
jaroslav@1646
   778
jaroslav@1646
   779
    /**
jaroslav@1646
   780
     * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
jaroslav@1646
   781
     * and spreads its elements as positional arguments.
jaroslav@1646
   782
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1646
   783
     * the current method handle.  The type of the adapter will be
jaroslav@1646
   784
     * the same as the type of the target, except that the final
jaroslav@1646
   785
     * {@code arrayLength} parameters of the target's type are replaced
jaroslav@1646
   786
     * by a single array parameter of type {@code arrayType}.
jaroslav@1646
   787
     * <p>
jaroslav@1646
   788
     * If the array element type differs from any of the corresponding
jaroslav@1646
   789
     * argument types on the original target,
jaroslav@1646
   790
     * the original target is adapted to take the array elements directly,
jaroslav@1646
   791
     * as if by a call to {@link #asType asType}.
jaroslav@1646
   792
     * <p>
jaroslav@1646
   793
     * When called, the adapter replaces a trailing array argument
jaroslav@1646
   794
     * by the array's elements, each as its own argument to the target.
jaroslav@1646
   795
     * (The order of the arguments is preserved.)
jaroslav@1646
   796
     * They are converted pairwise by casting and/or unboxing
jaroslav@1646
   797
     * to the types of the trailing parameters of the target.
jaroslav@1646
   798
     * Finally the target is called.
jaroslav@1646
   799
     * What the target eventually returns is returned unchanged by the adapter.
jaroslav@1646
   800
     * <p>
jaroslav@1646
   801
     * Before calling the target, the adapter verifies that the array
jaroslav@1646
   802
     * contains exactly enough elements to provide a correct argument count
jaroslav@1646
   803
     * to the target method handle.
jaroslav@1646
   804
     * (The array may also be null when zero elements are required.)
jaroslav@1646
   805
     * <p>
jaroslav@1646
   806
     * If, when the adapter is called, the supplied array argument does
jaroslav@1646
   807
     * not have the correct number of elements, the adapter will throw
jaroslav@1646
   808
     * an {@link IllegalArgumentException} instead of invoking the target.
jaroslav@1646
   809
     * <p>
jaroslav@1646
   810
     * Here are some simple examples of array-spreading method handles:
jaroslav@1646
   811
     * <blockquote><pre>{@code
jaroslav@1646
   812
MethodHandle equals = publicLookup()
jaroslav@1646
   813
  .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
jaroslav@1646
   814
assert( (boolean) equals.invokeExact("me", (Object)"me"));
jaroslav@1646
   815
assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
jaroslav@1646
   816
// spread both arguments from a 2-array:
jaroslav@1646
   817
MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
jaroslav@1646
   818
assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
jaroslav@1646
   819
assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
jaroslav@1646
   820
// try to spread from anything but a 2-array:
jaroslav@1646
   821
for (int n = 0; n <= 10; n++) {
jaroslav@1646
   822
  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
jaroslav@1646
   823
  try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
jaroslav@1646
   824
  catch (IllegalArgumentException ex) { } // OK
jaroslav@1646
   825
}
jaroslav@1646
   826
// spread both arguments from a String array:
jaroslav@1646
   827
MethodHandle eq2s = equals.asSpreader(String[].class, 2);
jaroslav@1646
   828
assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
jaroslav@1646
   829
assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
jaroslav@1646
   830
// spread second arguments from a 1-array:
jaroslav@1646
   831
MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
jaroslav@1646
   832
assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
jaroslav@1646
   833
assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
jaroslav@1646
   834
// spread no arguments from a 0-array or null:
jaroslav@1646
   835
MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
jaroslav@1646
   836
assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
jaroslav@1646
   837
assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
jaroslav@1646
   838
// asSpreader and asCollector are approximate inverses:
jaroslav@1646
   839
for (int n = 0; n <= 2; n++) {
jaroslav@1646
   840
    for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
jaroslav@1646
   841
        MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
jaroslav@1646
   842
        assert( (boolean) equals2.invokeWithArguments("me", "me"));
jaroslav@1646
   843
        assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
jaroslav@1646
   844
    }
jaroslav@1646
   845
}
jaroslav@1646
   846
MethodHandle caToString = publicLookup()
jaroslav@1646
   847
  .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
jaroslav@1646
   848
assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
jaroslav@1646
   849
MethodHandle caString3 = caToString.asCollector(char[].class, 3);
jaroslav@1646
   850
assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
jaroslav@1646
   851
MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
jaroslav@1646
   852
assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
jaroslav@1646
   853
     * }</pre></blockquote>
jaroslav@1646
   854
     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
jaroslav@1646
   855
     * @param arrayLength the number of arguments to spread from an incoming array argument
jaroslav@1646
   856
     * @return a new method handle which spreads its final array argument,
jaroslav@1646
   857
     *         before calling the original method handle
jaroslav@1646
   858
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1646
   859
     * @throws IllegalArgumentException if {@code arrayType} is not an array type,
jaroslav@1646
   860
     *         or if target does not have at least
jaroslav@1646
   861
     *         {@code arrayLength} parameter types,
jaroslav@1646
   862
     *         or if {@code arrayLength} is negative,
jaroslav@1646
   863
     *         or if the resulting method handle's type would have
jaroslav@1646
   864
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
   865
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
jaroslav@1646
   866
     * @see #asCollector
jaroslav@1646
   867
     */
jaroslav@1646
   868
    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
jaroslav@1646
   869
        asSpreaderChecks(arrayType, arrayLength);
jaroslav@1646
   870
        int spreadArgPos = type.parameterCount() - arrayLength;
jaroslav@1646
   871
        return MethodHandleImpl.makeSpreadArguments(this, arrayType, spreadArgPos, arrayLength);
jaroslav@1646
   872
    }
jaroslav@1646
   873
jaroslav@1646
   874
    private void asSpreaderChecks(Class<?> arrayType, int arrayLength) {
jaroslav@1646
   875
        spreadArrayChecks(arrayType, arrayLength);
jaroslav@1646
   876
        int nargs = type().parameterCount();
jaroslav@1646
   877
        if (nargs < arrayLength || arrayLength < 0)
jaroslav@1646
   878
            throw newIllegalArgumentException("bad spread array length");
jaroslav@1646
   879
        if (arrayType != Object[].class && arrayLength != 0) {
jaroslav@1646
   880
            boolean sawProblem = false;
jaroslav@1646
   881
            Class<?> arrayElement = arrayType.getComponentType();
jaroslav@1646
   882
            for (int i = nargs - arrayLength; i < nargs; i++) {
jaroslav@1646
   883
                if (!MethodType.canConvert(arrayElement, type().parameterType(i))) {
jaroslav@1646
   884
                    sawProblem = true;
jaroslav@1646
   885
                    break;
jaroslav@1646
   886
                }
jaroslav@1646
   887
            }
jaroslav@1646
   888
            if (sawProblem) {
jaroslav@1646
   889
                ArrayList<Class<?>> ptypes = new ArrayList<>(type().parameterList());
jaroslav@1646
   890
                for (int i = nargs - arrayLength; i < nargs; i++) {
jaroslav@1646
   891
                    ptypes.set(i, arrayElement);
jaroslav@1646
   892
                }
jaroslav@1646
   893
                // elicit an error:
jaroslav@1646
   894
                this.asType(MethodType.methodType(type().returnType(), ptypes));
jaroslav@1646
   895
            }
jaroslav@1646
   896
        }
jaroslav@1646
   897
    }
jaroslav@1646
   898
jaroslav@1646
   899
    private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
jaroslav@1646
   900
        Class<?> arrayElement = arrayType.getComponentType();
jaroslav@1646
   901
        if (arrayElement == null)
jaroslav@1646
   902
            throw newIllegalArgumentException("not an array type", arrayType);
jaroslav@1646
   903
        if ((arrayLength & 0x7F) != arrayLength) {
jaroslav@1646
   904
            if ((arrayLength & 0xFF) != arrayLength)
jaroslav@1646
   905
                throw newIllegalArgumentException("array length is not legal", arrayLength);
jaroslav@1646
   906
            assert(arrayLength >= 128);
jaroslav@1646
   907
            if (arrayElement == long.class ||
jaroslav@1646
   908
                arrayElement == double.class)
jaroslav@1646
   909
                throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
jaroslav@1646
   910
        }
jaroslav@1646
   911
    }
jaroslav@1646
   912
jaroslav@1646
   913
    /**
jaroslav@1646
   914
     * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
jaroslav@1646
   915
     * positional arguments and collects them into an array argument.
jaroslav@1646
   916
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1646
   917
     * the current method handle.  The type of the adapter will be
jaroslav@1646
   918
     * the same as the type of the target, except that a single trailing
jaroslav@1646
   919
     * parameter (usually of type {@code arrayType}) is replaced by
jaroslav@1646
   920
     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
jaroslav@1646
   921
     * <p>
jaroslav@1646
   922
     * If the array type differs from the final argument type on the original target,
jaroslav@1646
   923
     * the original target is adapted to take the array type directly,
jaroslav@1646
   924
     * as if by a call to {@link #asType asType}.
jaroslav@1646
   925
     * <p>
jaroslav@1646
   926
     * When called, the adapter replaces its trailing {@code arrayLength}
jaroslav@1646
   927
     * arguments by a single new array of type {@code arrayType}, whose elements
jaroslav@1646
   928
     * comprise (in order) the replaced arguments.
jaroslav@1646
   929
     * Finally the target is called.
jaroslav@1646
   930
     * What the target eventually returns is returned unchanged by the adapter.
jaroslav@1646
   931
     * <p>
jaroslav@1646
   932
     * (The array may also be a shared constant when {@code arrayLength} is zero.)
jaroslav@1646
   933
     * <p>
jaroslav@1646
   934
     * (<em>Note:</em> The {@code arrayType} is often identical to the last
jaroslav@1646
   935
     * parameter type of the original target.
jaroslav@1646
   936
     * It is an explicit argument for symmetry with {@code asSpreader}, and also
jaroslav@1646
   937
     * to allow the target to use a simple {@code Object} as its last parameter type.)
jaroslav@1646
   938
     * <p>
jaroslav@1646
   939
     * In order to create a collecting adapter which is not restricted to a particular
jaroslav@1646
   940
     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
jaroslav@1646
   941
     * <p>
jaroslav@1646
   942
     * Here are some examples of array-collecting method handles:
jaroslav@1646
   943
     * <blockquote><pre>{@code
jaroslav@1646
   944
MethodHandle deepToString = publicLookup()
jaroslav@1646
   945
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646
   946
assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
jaroslav@1646
   947
MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
jaroslav@1646
   948
assertEquals(methodType(String.class, Object.class), ts1.type());
jaroslav@1646
   949
//assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
jaroslav@1646
   950
assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
jaroslav@1646
   951
// arrayType can be a subtype of Object[]
jaroslav@1646
   952
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
jaroslav@1646
   953
assertEquals(methodType(String.class, String.class, String.class), ts2.type());
jaroslav@1646
   954
assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
jaroslav@1646
   955
MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
jaroslav@1646
   956
assertEquals("[]", (String) ts0.invokeExact());
jaroslav@1646
   957
// collectors can be nested, Lisp-style
jaroslav@1646
   958
MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
jaroslav@1646
   959
assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
jaroslav@1646
   960
// arrayType can be any primitive array type
jaroslav@1646
   961
MethodHandle bytesToString = publicLookup()
jaroslav@1646
   962
  .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
jaroslav@1646
   963
  .asCollector(byte[].class, 3);
jaroslav@1646
   964
assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
jaroslav@1646
   965
MethodHandle longsToString = publicLookup()
jaroslav@1646
   966
  .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
jaroslav@1646
   967
  .asCollector(long[].class, 1);
jaroslav@1646
   968
assertEquals("[123]", (String) longsToString.invokeExact((long)123));
jaroslav@1646
   969
     * }</pre></blockquote>
jaroslav@1646
   970
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
jaroslav@1646
   971
     * @param arrayLength the number of arguments to collect into a new array argument
jaroslav@1646
   972
     * @return a new method handle which collects some trailing argument
jaroslav@1646
   973
     *         into an array, before calling the original method handle
jaroslav@1646
   974
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1646
   975
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
jaroslav@1646
   976
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
jaroslav@1646
   977
     *         or {@code arrayLength} is not a legal array size,
jaroslav@1646
   978
     *         or the resulting method handle's type would have
jaroslav@1646
   979
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
jaroslav@1646
   980
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
jaroslav@1646
   981
     * @see #asSpreader
jaroslav@1646
   982
     * @see #asVarargsCollector
jaroslav@1646
   983
     */
jaroslav@1646
   984
    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
jaroslav@1646
   985
        asCollectorChecks(arrayType, arrayLength);
jaroslav@1646
   986
        int collectArgPos = type().parameterCount()-1;
jaroslav@1646
   987
        MethodHandle target = this;
jaroslav@1646
   988
        if (arrayType != type().parameterType(collectArgPos))
jaroslav@1646
   989
            target = convertArguments(type().changeParameterType(collectArgPos, arrayType));
jaroslav@1646
   990
        MethodHandle collector = ValueConversions.varargsArray(arrayType, arrayLength);
jaroslav@1646
   991
        return MethodHandles.collectArguments(target, collectArgPos, collector);
jaroslav@1646
   992
    }
jaroslav@1646
   993
jaroslav@1646
   994
    // private API: return true if last param exactly matches arrayType
jaroslav@1646
   995
    private boolean asCollectorChecks(Class<?> arrayType, int arrayLength) {
jaroslav@1646
   996
        spreadArrayChecks(arrayType, arrayLength);
jaroslav@1646
   997
        int nargs = type().parameterCount();
jaroslav@1646
   998
        if (nargs != 0) {
jaroslav@1646
   999
            Class<?> lastParam = type().parameterType(nargs-1);
jaroslav@1646
  1000
            if (lastParam == arrayType)  return true;
jaroslav@1646
  1001
            if (lastParam.isAssignableFrom(arrayType))  return false;
jaroslav@1646
  1002
        }
jaroslav@1646
  1003
        throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType);
jaroslav@1646
  1004
    }
jaroslav@1646
  1005
jaroslav@1646
  1006
    /**
jaroslav@1646
  1007
     * Makes a <em>variable arity</em> adapter which is able to accept
jaroslav@1646
  1008
     * any number of trailing positional arguments and collect them
jaroslav@1646
  1009
     * into an array argument.
jaroslav@1646
  1010
     * <p>
jaroslav@1646
  1011
     * The type and behavior of the adapter will be the same as
jaroslav@1646
  1012
     * the type and behavior of the target, except that certain
jaroslav@1646
  1013
     * {@code invoke} and {@code asType} requests can lead to
jaroslav@1646
  1014
     * trailing positional arguments being collected into target's
jaroslav@1646
  1015
     * trailing parameter.
jaroslav@1646
  1016
     * Also, the last parameter type of the adapter will be
jaroslav@1646
  1017
     * {@code arrayType}, even if the target has a different
jaroslav@1646
  1018
     * last parameter type.
jaroslav@1646
  1019
     * <p>
jaroslav@1646
  1020
     * This transformation may return {@code this} if the method handle is
jaroslav@1646
  1021
     * already of variable arity and its trailing parameter type
jaroslav@1646
  1022
     * is identical to {@code arrayType}.
jaroslav@1646
  1023
     * <p>
jaroslav@1646
  1024
     * When called with {@link #invokeExact invokeExact}, the adapter invokes
jaroslav@1646
  1025
     * the target with no argument changes.
jaroslav@1646
  1026
     * (<em>Note:</em> This behavior is different from a
jaroslav@1646
  1027
     * {@linkplain #asCollector fixed arity collector},
jaroslav@1646
  1028
     * since it accepts a whole array of indeterminate length,
jaroslav@1646
  1029
     * rather than a fixed number of arguments.)
jaroslav@1646
  1030
     * <p>
jaroslav@1646
  1031
     * When called with plain, inexact {@link #invoke invoke}, if the caller
jaroslav@1646
  1032
     * type is the same as the adapter, the adapter invokes the target as with
jaroslav@1646
  1033
     * {@code invokeExact}.
jaroslav@1646
  1034
     * (This is the normal behavior for {@code invoke} when types match.)
jaroslav@1646
  1035
     * <p>
jaroslav@1646
  1036
     * Otherwise, if the caller and adapter arity are the same, and the
jaroslav@1646
  1037
     * trailing parameter type of the caller is a reference type identical to
jaroslav@1646
  1038
     * or assignable to the trailing parameter type of the adapter,
jaroslav@1646
  1039
     * the arguments and return values are converted pairwise,
jaroslav@1646
  1040
     * as if by {@link #asType asType} on a fixed arity
jaroslav@1646
  1041
     * method handle.
jaroslav@1646
  1042
     * <p>
jaroslav@1646
  1043
     * Otherwise, the arities differ, or the adapter's trailing parameter
jaroslav@1646
  1044
     * type is not assignable from the corresponding caller type.
jaroslav@1646
  1045
     * In this case, the adapter replaces all trailing arguments from
jaroslav@1646
  1046
     * the original trailing argument position onward, by
jaroslav@1646
  1047
     * a new array of type {@code arrayType}, whose elements
jaroslav@1646
  1048
     * comprise (in order) the replaced arguments.
jaroslav@1646
  1049
     * <p>
jaroslav@1646
  1050
     * The caller type must provides as least enough arguments,
jaroslav@1646
  1051
     * and of the correct type, to satisfy the target's requirement for
jaroslav@1646
  1052
     * positional arguments before the trailing array argument.
jaroslav@1646
  1053
     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
jaroslav@1646
  1054
     * where {@code N} is the arity of the target.
jaroslav@1646
  1055
     * Also, there must exist conversions from the incoming arguments
jaroslav@1646
  1056
     * to the target's arguments.
jaroslav@1646
  1057
     * As with other uses of plain {@code invoke}, if these basic
jaroslav@1646
  1058
     * requirements are not fulfilled, a {@code WrongMethodTypeException}
jaroslav@1646
  1059
     * may be thrown.
jaroslav@1646
  1060
     * <p>
jaroslav@1646
  1061
     * In all cases, what the target eventually returns is returned unchanged by the adapter.
jaroslav@1646
  1062
     * <p>
jaroslav@1646
  1063
     * In the final case, it is exactly as if the target method handle were
jaroslav@1646
  1064
     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
jaroslav@1646
  1065
     * to the arity required by the caller type.
jaroslav@1646
  1066
     * (As with {@code asCollector}, if the array length is zero,
jaroslav@1646
  1067
     * a shared constant may be used instead of a new array.
jaroslav@1646
  1068
     * If the implied call to {@code asCollector} would throw
jaroslav@1646
  1069
     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
jaroslav@1646
  1070
     * the call to the variable arity adapter must throw
jaroslav@1646
  1071
     * {@code WrongMethodTypeException}.)
jaroslav@1646
  1072
     * <p>
jaroslav@1646
  1073
     * The behavior of {@link #asType asType} is also specialized for
jaroslav@1646
  1074
     * variable arity adapters, to maintain the invariant that
jaroslav@1646
  1075
     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
jaroslav@1646
  1076
     * call to adjust the target type, followed by {@code invokeExact}.
jaroslav@1646
  1077
     * Therefore, a variable arity adapter responds
jaroslav@1646
  1078
     * to an {@code asType} request by building a fixed arity collector,
jaroslav@1646
  1079
     * if and only if the adapter and requested type differ either
jaroslav@1646
  1080
     * in arity or trailing argument type.
jaroslav@1646
  1081
     * The resulting fixed arity collector has its type further adjusted
jaroslav@1646
  1082
     * (if necessary) to the requested type by pairwise conversion,
jaroslav@1646
  1083
     * as if by another application of {@code asType}.
jaroslav@1646
  1084
     * <p>
jaroslav@1646
  1085
     * When a method handle is obtained by executing an {@code ldc} instruction
jaroslav@1646
  1086
     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
jaroslav@1646
  1087
     * as a variable arity method (with the modifier bit {@code 0x0080}),
jaroslav@1646
  1088
     * the method handle will accept multiple arities, as if the method handle
jaroslav@1646
  1089
     * constant were created by means of a call to {@code asVarargsCollector}.
jaroslav@1646
  1090
     * <p>
jaroslav@1646
  1091
     * In order to create a collecting adapter which collects a predetermined
jaroslav@1646
  1092
     * number of arguments, and whose type reflects this predetermined number,
jaroslav@1646
  1093
     * use {@link #asCollector asCollector} instead.
jaroslav@1646
  1094
     * <p>
jaroslav@1646
  1095
     * No method handle transformations produce new method handles with
jaroslav@1646
  1096
     * variable arity, unless they are documented as doing so.
jaroslav@1646
  1097
     * Therefore, besides {@code asVarargsCollector},
jaroslav@1646
  1098
     * all methods in {@code MethodHandle} and {@code MethodHandles}
jaroslav@1646
  1099
     * will return a method handle with fixed arity,
jaroslav@1646
  1100
     * except in the cases where they are specified to return their original
jaroslav@1646
  1101
     * operand (e.g., {@code asType} of the method handle's own type).
jaroslav@1646
  1102
     * <p>
jaroslav@1646
  1103
     * Calling {@code asVarargsCollector} on a method handle which is already
jaroslav@1646
  1104
     * of variable arity will produce a method handle with the same type and behavior.
jaroslav@1646
  1105
     * It may (or may not) return the original variable arity method handle.
jaroslav@1646
  1106
     * <p>
jaroslav@1646
  1107
     * Here is an example, of a list-making variable arity method handle:
jaroslav@1646
  1108
     * <blockquote><pre>{@code
jaroslav@1646
  1109
MethodHandle deepToString = publicLookup()
jaroslav@1646
  1110
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
jaroslav@1646
  1111
MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
jaroslav@1646
  1112
assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
jaroslav@1646
  1113
assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
jaroslav@1646
  1114
assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
jaroslav@1646
  1115
assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
jaroslav@1646
  1116
// findStatic of Arrays.asList(...) produces a variable arity method handle:
jaroslav@1646
  1117
MethodHandle asList = publicLookup()
jaroslav@1646
  1118
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
jaroslav@1646
  1119
assertEquals(methodType(List.class, Object[].class), asList.type());
jaroslav@1646
  1120
assert(asList.isVarargsCollector());
jaroslav@1646
  1121
assertEquals("[]", asList.invoke().toString());
jaroslav@1646
  1122
assertEquals("[1]", asList.invoke(1).toString());
jaroslav@1646
  1123
assertEquals("[two, too]", asList.invoke("two", "too").toString());
jaroslav@1646
  1124
String[] argv = { "three", "thee", "tee" };
jaroslav@1646
  1125
assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
jaroslav@1646
  1126
assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
jaroslav@1646
  1127
List ls = (List) asList.invoke((Object)argv);
jaroslav@1646
  1128
assertEquals(1, ls.size());
jaroslav@1646
  1129
assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
jaroslav@1646
  1130
     * }</pre></blockquote>
jaroslav@1646
  1131
     * <p style="font-size:smaller;">
jaroslav@1646
  1132
     * <em>Discussion:</em>
jaroslav@1646
  1133
     * These rules are designed as a dynamically-typed variation
jaroslav@1646
  1134
     * of the Java rules for variable arity methods.
jaroslav@1646
  1135
     * In both cases, callers to a variable arity method or method handle
jaroslav@1646
  1136
     * can either pass zero or more positional arguments, or else pass
jaroslav@1646
  1137
     * pre-collected arrays of any length.  Users should be aware of the
jaroslav@1646
  1138
     * special role of the final argument, and of the effect of a
jaroslav@1646
  1139
     * type match on that final argument, which determines whether
jaroslav@1646
  1140
     * or not a single trailing argument is interpreted as a whole
jaroslav@1646
  1141
     * array or a single element of an array to be collected.
jaroslav@1646
  1142
     * Note that the dynamic type of the trailing argument has no
jaroslav@1646
  1143
     * effect on this decision, only a comparison between the symbolic
jaroslav@1646
  1144
     * type descriptor of the call site and the type descriptor of the method handle.)
jaroslav@1646
  1145
     *
jaroslav@1646
  1146
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
jaroslav@1646
  1147
     * @return a new method handle which can collect any number of trailing arguments
jaroslav@1646
  1148
     *         into an array, before calling the original method handle
jaroslav@1646
  1149
     * @throws NullPointerException if {@code arrayType} is a null reference
jaroslav@1646
  1150
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
jaroslav@1646
  1151
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
jaroslav@1646
  1152
     * @see #asCollector
jaroslav@1646
  1153
     * @see #isVarargsCollector
jaroslav@1646
  1154
     * @see #asFixedArity
jaroslav@1646
  1155
     */
jaroslav@1646
  1156
    public MethodHandle asVarargsCollector(Class<?> arrayType) {
jaroslav@1646
  1157
        Class<?> arrayElement = arrayType.getComponentType();
jaroslav@1646
  1158
        boolean lastMatch = asCollectorChecks(arrayType, 0);
jaroslav@1646
  1159
        if (isVarargsCollector() && lastMatch)
jaroslav@1646
  1160
            return this;
jaroslav@1646
  1161
        return MethodHandleImpl.makeVarargsCollector(this, arrayType);
jaroslav@1646
  1162
    }
jaroslav@1646
  1163
jaroslav@1646
  1164
    /**
jaroslav@1646
  1165
     * Determines if this method handle
jaroslav@1646
  1166
     * supports {@linkplain #asVarargsCollector variable arity} calls.
jaroslav@1646
  1167
     * Such method handles arise from the following sources:
jaroslav@1646
  1168
     * <ul>
jaroslav@1646
  1169
     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
jaroslav@1646
  1170
     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
jaroslav@1646
  1171
     *     which resolves to a variable arity Java method or constructor
jaroslav@1646
  1172
     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
jaroslav@1646
  1173
     *     which resolves to a variable arity Java method or constructor
jaroslav@1646
  1174
     * </ul>
jaroslav@1646
  1175
     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
jaroslav@1646
  1176
     * @see #asVarargsCollector
jaroslav@1646
  1177
     * @see #asFixedArity
jaroslav@1646
  1178
     */
jaroslav@1646
  1179
    public boolean isVarargsCollector() {
jaroslav@1646
  1180
        return false;
jaroslav@1646
  1181
    }
jaroslav@1646
  1182
jaroslav@1646
  1183
    /**
jaroslav@1646
  1184
     * Makes a <em>fixed arity</em> method handle which is otherwise
jaroslav@1646
  1185
     * equivalent to the current method handle.
jaroslav@1646
  1186
     * <p>
jaroslav@1646
  1187
     * If the current method handle is not of
jaroslav@1646
  1188
     * {@linkplain #asVarargsCollector variable arity},
jaroslav@1646
  1189
     * the current method handle is returned.
jaroslav@1646
  1190
     * This is true even if the current method handle
jaroslav@1646
  1191
     * could not be a valid input to {@code asVarargsCollector}.
jaroslav@1646
  1192
     * <p>
jaroslav@1646
  1193
     * Otherwise, the resulting fixed-arity method handle has the same
jaroslav@1646
  1194
     * type and behavior of the current method handle,
jaroslav@1646
  1195
     * except that {@link #isVarargsCollector isVarargsCollector}
jaroslav@1646
  1196
     * will be false.
jaroslav@1646
  1197
     * The fixed-arity method handle may (or may not) be the
jaroslav@1646
  1198
     * a previous argument to {@code asVarargsCollector}.
jaroslav@1646
  1199
     * <p>
jaroslav@1646
  1200
     * Here is an example, of a list-making variable arity method handle:
jaroslav@1646
  1201
     * <blockquote><pre>{@code
jaroslav@1646
  1202
MethodHandle asListVar = publicLookup()
jaroslav@1646
  1203
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
jaroslav@1646
  1204
  .asVarargsCollector(Object[].class);
jaroslav@1646
  1205
MethodHandle asListFix = asListVar.asFixedArity();
jaroslav@1646
  1206
assertEquals("[1]", asListVar.invoke(1).toString());
jaroslav@1646
  1207
Exception caught = null;
jaroslav@1646
  1208
try { asListFix.invoke((Object)1); }
jaroslav@1646
  1209
catch (Exception ex) { caught = ex; }
jaroslav@1646
  1210
assert(caught instanceof ClassCastException);
jaroslav@1646
  1211
assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
jaroslav@1646
  1212
try { asListFix.invoke("two", "too"); }
jaroslav@1646
  1213
catch (Exception ex) { caught = ex; }
jaroslav@1646
  1214
assert(caught instanceof WrongMethodTypeException);
jaroslav@1646
  1215
Object[] argv = { "three", "thee", "tee" };
jaroslav@1646
  1216
assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
jaroslav@1646
  1217
assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
jaroslav@1646
  1218
assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
jaroslav@1646
  1219
assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
jaroslav@1646
  1220
     * }</pre></blockquote>
jaroslav@1646
  1221
     *
jaroslav@1646
  1222
     * @return a new method handle which accepts only a fixed number of arguments
jaroslav@1646
  1223
     * @see #asVarargsCollector
jaroslav@1646
  1224
     * @see #isVarargsCollector
jaroslav@1646
  1225
     */
jaroslav@1646
  1226
    public MethodHandle asFixedArity() {
jaroslav@1646
  1227
        assert(!isVarargsCollector());
jaroslav@1646
  1228
        return this;
jaroslav@1646
  1229
    }
jaroslav@1646
  1230
jaroslav@1646
  1231
    /**
jaroslav@1646
  1232
     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
jaroslav@1646
  1233
     * The new method handle adapts, as its <i>target</i>,
jaroslav@1646
  1234
     * the current method handle by binding it to the given argument.
jaroslav@1646
  1235
     * The type of the bound handle will be
jaroslav@1646
  1236
     * the same as the type of the target, except that a single leading
jaroslav@1646
  1237
     * reference parameter will be omitted.
jaroslav@1646
  1238
     * <p>
jaroslav@1646
  1239
     * When called, the bound handle inserts the given value {@code x}
jaroslav@1646
  1240
     * as a new leading argument to the target.  The other arguments are
jaroslav@1646
  1241
     * also passed unchanged.
jaroslav@1646
  1242
     * What the target eventually returns is returned unchanged by the bound handle.
jaroslav@1646
  1243
     * <p>
jaroslav@1646
  1244
     * The reference {@code x} must be convertible to the first parameter
jaroslav@1646
  1245
     * type of the target.
jaroslav@1646
  1246
     * <p>
jaroslav@1646
  1247
     * (<em>Note:</em>  Because method handles are immutable, the target method handle
jaroslav@1646
  1248
     * retains its original type and behavior.)
jaroslav@1646
  1249
     * @param x  the value to bind to the first argument of the target
jaroslav@1646
  1250
     * @return a new method handle which prepends the given value to the incoming
jaroslav@1646
  1251
     *         argument list, before calling the original method handle
jaroslav@1646
  1252
     * @throws IllegalArgumentException if the target does not have a
jaroslav@1646
  1253
     *         leading parameter type that is a reference type
jaroslav@1646
  1254
     * @throws ClassCastException if {@code x} cannot be converted
jaroslav@1646
  1255
     *         to the leading parameter type of the target
jaroslav@1646
  1256
     * @see MethodHandles#insertArguments
jaroslav@1646
  1257
     */
jaroslav@1646
  1258
    public MethodHandle bindTo(Object x) {
jaroslav@1646
  1259
        Class<?> ptype;
jaroslav@1646
  1260
        @SuppressWarnings("LocalVariableHidesMemberVariable")
jaroslav@1646
  1261
        MethodType type = type();
jaroslav@1646
  1262
        if (type.parameterCount() == 0 ||
jaroslav@1646
  1263
            (ptype = type.parameterType(0)).isPrimitive())
jaroslav@1646
  1264
            throw newIllegalArgumentException("no leading reference parameter", x);
jaroslav@1646
  1265
        x = ptype.cast(x);  // throw CCE if needed
jaroslav@1646
  1266
        return bindReceiver(x);
jaroslav@1646
  1267
    }
jaroslav@1646
  1268
jaroslav@1646
  1269
    /**
jaroslav@1646
  1270
     * Returns a string representation of the method handle,
jaroslav@1646
  1271
     * starting with the string {@code "MethodHandle"} and
jaroslav@1646
  1272
     * ending with the string representation of the method handle's type.
jaroslav@1646
  1273
     * In other words, this method returns a string equal to the value of:
jaroslav@1646
  1274
     * <blockquote><pre>{@code
jaroslav@1646
  1275
     * "MethodHandle" + type().toString()
jaroslav@1646
  1276
     * }</pre></blockquote>
jaroslav@1646
  1277
     * <p>
jaroslav@1646
  1278
     * (<em>Note:</em>  Future releases of this API may add further information
jaroslav@1646
  1279
     * to the string representation.
jaroslav@1646
  1280
     * Therefore, the present syntax should not be parsed by applications.)
jaroslav@1646
  1281
     *
jaroslav@1646
  1282
     * @return a string representation of the method handle
jaroslav@1646
  1283
     */
jaroslav@1646
  1284
    @Override
jaroslav@1646
  1285
    public String toString() {
jaroslav@1646
  1286
        if (DEBUG_METHOD_HANDLE_NAMES)  return debugString();
jaroslav@1646
  1287
        return standardString();
jaroslav@1646
  1288
    }
jaroslav@1646
  1289
    String standardString() {
jaroslav@1646
  1290
        return "MethodHandle"+type;
jaroslav@1646
  1291
    }
jaroslav@1646
  1292
    String debugString() {
jaroslav@1646
  1293
        return standardString()+"/LF="+internalForm()+internalProperties();
jaroslav@1646
  1294
    }
jaroslav@1646
  1295
jaroslav@1646
  1296
    //// Implementation methods.
jaroslav@1646
  1297
    //// Sub-classes can override these default implementations.
jaroslav@1646
  1298
    //// All these methods assume arguments are already validated.
jaroslav@1646
  1299
jaroslav@1646
  1300
    // Other transforms to do:  convert, explicitCast, permute, drop, filter, fold, GWT, catch
jaroslav@1646
  1301
jaroslav@1646
  1302
    /*non-public*/
jaroslav@1646
  1303
    MethodHandle setVarargs(MemberName member) throws IllegalAccessException {
jaroslav@1646
  1304
        if (!member.isVarargs())  return this;
jaroslav@1646
  1305
        int argc = type().parameterCount();
jaroslav@1646
  1306
        if (argc != 0) {
jaroslav@1646
  1307
            Class<?> arrayType = type().parameterType(argc-1);
jaroslav@1646
  1308
            if (arrayType.isArray()) {
jaroslav@1646
  1309
                return MethodHandleImpl.makeVarargsCollector(this, arrayType);
jaroslav@1646
  1310
            }
jaroslav@1646
  1311
        }
jaroslav@1646
  1312
        throw member.makeAccessException("cannot make variable arity", null);
jaroslav@1646
  1313
    }
jaroslav@1646
  1314
    /*non-public*/
jaroslav@1646
  1315
    MethodHandle viewAsType(MethodType newType) {
jaroslav@1646
  1316
        // No actual conversions, just a new view of the same method.
jaroslav@1646
  1317
        return MethodHandleImpl.makePairwiseConvert(this, newType, 0);
jaroslav@1646
  1318
    }
jaroslav@1646
  1319
jaroslav@1646
  1320
    // Decoding
jaroslav@1646
  1321
jaroslav@1646
  1322
    /*non-public*/
jaroslav@1646
  1323
    LambdaForm internalForm() {
jaroslav@1646
  1324
        return form;
jaroslav@1646
  1325
    }
jaroslav@1646
  1326
jaroslav@1646
  1327
    /*non-public*/
jaroslav@1646
  1328
    MemberName internalMemberName() {
jaroslav@1646
  1329
        return null;  // DMH returns DMH.member
jaroslav@1646
  1330
    }
jaroslav@1646
  1331
jaroslav@1646
  1332
    /*non-public*/
jaroslav@1646
  1333
    Class<?> internalCallerClass() {
jaroslav@1646
  1334
        return null;  // caller-bound MH for @CallerSensitive method returns caller
jaroslav@1646
  1335
    }
jaroslav@1646
  1336
jaroslav@1646
  1337
    /*non-public*/
jaroslav@1646
  1338
    MethodHandle withInternalMemberName(MemberName member) {
jaroslav@1646
  1339
        if (member != null) {
jaroslav@1646
  1340
            return MethodHandleImpl.makeWrappedMember(this, member);
jaroslav@1646
  1341
        } else if (internalMemberName() == null) {
jaroslav@1646
  1342
            // The required internaMemberName is null, and this MH (like most) doesn't have one.
jaroslav@1646
  1343
            return this;
jaroslav@1646
  1344
        } else {
jaroslav@1646
  1345
            // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH.
jaroslav@1646
  1346
            MethodHandle result = rebind();
jaroslav@1646
  1347
            assert (result.internalMemberName() == null);
jaroslav@1646
  1348
            return result;
jaroslav@1646
  1349
        }
jaroslav@1646
  1350
    }
jaroslav@1646
  1351
jaroslav@1646
  1352
    /*non-public*/
jaroslav@1646
  1353
    boolean isInvokeSpecial() {
jaroslav@1646
  1354
        return false;  // DMH.Special returns true
jaroslav@1646
  1355
    }
jaroslav@1646
  1356
jaroslav@1646
  1357
    /*non-public*/
jaroslav@1646
  1358
    Object internalValues() {
jaroslav@1646
  1359
        return null;
jaroslav@1646
  1360
    }
jaroslav@1646
  1361
jaroslav@1646
  1362
    /*non-public*/
jaroslav@1646
  1363
    Object internalProperties() {
jaroslav@1646
  1364
        // Override to something like "/FOO=bar"
jaroslav@1646
  1365
        return "";
jaroslav@1646
  1366
    }
jaroslav@1646
  1367
jaroslav@1646
  1368
    //// Method handle implementation methods.
jaroslav@1646
  1369
    //// Sub-classes can override these default implementations.
jaroslav@1646
  1370
    //// All these methods assume arguments are already validated.
jaroslav@1646
  1371
jaroslav@1646
  1372
    /*non-public*/ MethodHandle convertArguments(MethodType newType) {
jaroslav@1646
  1373
        // Override this if it can be improved.
jaroslav@1646
  1374
        return MethodHandleImpl.makePairwiseConvert(this, newType, 1);
jaroslav@1646
  1375
    }
jaroslav@1646
  1376
jaroslav@1646
  1377
    /*non-public*/
jaroslav@1646
  1378
    MethodHandle bindArgument(int pos, char basicType, Object value) {
jaroslav@1646
  1379
        // Override this if it can be improved.
jaroslav@1646
  1380
        return rebind().bindArgument(pos, basicType, value);
jaroslav@1646
  1381
    }
jaroslav@1646
  1382
jaroslav@1646
  1383
    /*non-public*/
jaroslav@1646
  1384
    MethodHandle bindReceiver(Object receiver) {
jaroslav@1646
  1385
        // Override this if it can be improved.
jaroslav@1646
  1386
        return bindArgument(0, 'L', receiver);
jaroslav@1646
  1387
    }
jaroslav@1646
  1388
jaroslav@1646
  1389
    /*non-public*/
jaroslav@1646
  1390
    MethodHandle bindImmediate(int pos, char basicType, Object value) {
jaroslav@1646
  1391
        // Bind an immediate value to a position in the arguments.
jaroslav@1646
  1392
        // This means, elide the respective argument,
jaroslav@1646
  1393
        // and replace all references to it in NamedFunction args with the specified value.
jaroslav@1646
  1394
jaroslav@1646
  1395
        // CURRENT RESTRICTIONS
jaroslav@1646
  1396
        // * only for pos 0 and UNSAFE (position is adjusted in MHImpl to make API usable for others)
jaroslav@1651
  1397
//        assert pos == 0 && basicType == 'L' && value instanceof Unsafe;
jaroslav@1646
  1398
        MethodType type2 = type.dropParameterTypes(pos, pos + 1); // adjustment: ignore receiver!
jaroslav@1646
  1399
        LambdaForm form2 = form.bindImmediate(pos + 1, basicType, value); // adjust pos to form-relative pos
jaroslav@1646
  1400
        return copyWith(type2, form2);
jaroslav@1646
  1401
    }
jaroslav@1646
  1402
jaroslav@1646
  1403
    /*non-public*/
jaroslav@1646
  1404
    MethodHandle copyWith(MethodType mt, LambdaForm lf) {
jaroslav@1646
  1405
        throw new InternalError("copyWith: " + this.getClass());
jaroslav@1646
  1406
    }
jaroslav@1646
  1407
jaroslav@1646
  1408
    /*non-public*/
jaroslav@1646
  1409
    MethodHandle dropArguments(MethodType srcType, int pos, int drops) {
jaroslav@1646
  1410
        // Override this if it can be improved.
jaroslav@1646
  1411
        return rebind().dropArguments(srcType, pos, drops);
jaroslav@1646
  1412
    }
jaroslav@1646
  1413
jaroslav@1646
  1414
    /*non-public*/
jaroslav@1646
  1415
    MethodHandle permuteArguments(MethodType newType, int[] reorder) {
jaroslav@1646
  1416
        // Override this if it can be improved.
jaroslav@1646
  1417
        return rebind().permuteArguments(newType, reorder);
jaroslav@1646
  1418
    }
jaroslav@1646
  1419
jaroslav@1646
  1420
    /*non-public*/
jaroslav@1646
  1421
    MethodHandle rebind() {
jaroslav@1646
  1422
        // Bind 'this' into a new invoker, of the known class BMH.
jaroslav@1646
  1423
        MethodType type2 = type();
jaroslav@1646
  1424
        LambdaForm form2 = reinvokerForm(this);
jaroslav@1646
  1425
        // form2 = lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }
jaroslav@1646
  1426
        return BoundMethodHandle.bindSingle(type2, form2, this);
jaroslav@1646
  1427
    }
jaroslav@1646
  1428
jaroslav@1646
  1429
    /*non-public*/
jaroslav@1646
  1430
    MethodHandle reinvokerTarget() {
jaroslav@1646
  1431
        throw new InternalError("not a reinvoker MH: "+this.getClass().getName()+": "+this);
jaroslav@1646
  1432
    }
jaroslav@1646
  1433
jaroslav@1646
  1434
    /** Create a LF which simply reinvokes a target of the given basic type.
jaroslav@1646
  1435
     *  The target MH must override {@link #reinvokerTarget} to provide the target.
jaroslav@1646
  1436
     */
jaroslav@1646
  1437
    static LambdaForm reinvokerForm(MethodHandle target) {
jaroslav@1646
  1438
        MethodType mtype = target.type().basicType();
jaroslav@1646
  1439
        LambdaForm reinvoker = mtype.form().cachedLambdaForm(MethodTypeForm.LF_REINVOKE);
jaroslav@1646
  1440
        if (reinvoker != null)  return reinvoker;
jaroslav@1646
  1441
        if (mtype.parameterSlotCount() >= MethodType.MAX_MH_ARITY)
jaroslav@1646
  1442
            return makeReinvokerForm(target.type(), target);  // cannot cache this
jaroslav@1646
  1443
        reinvoker = makeReinvokerForm(mtype, null);
jaroslav@1646
  1444
        return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_REINVOKE, reinvoker);
jaroslav@1646
  1445
    }
jaroslav@1646
  1446
    private static LambdaForm makeReinvokerForm(MethodType mtype, MethodHandle customTargetOrNull) {
jaroslav@1646
  1447
        boolean customized = (customTargetOrNull != null);
jaroslav@1646
  1448
        MethodHandle MH_invokeBasic = customized ? null : MethodHandles.basicInvoker(mtype);
jaroslav@1646
  1449
        final int THIS_BMH    = 0;
jaroslav@1646
  1450
        final int ARG_BASE    = 1;
jaroslav@1646
  1451
        final int ARG_LIMIT   = ARG_BASE + mtype.parameterCount();
jaroslav@1646
  1452
        int nameCursor = ARG_LIMIT;
jaroslav@1646
  1453
        final int NEXT_MH     = customized ? -1 : nameCursor++;
jaroslav@1646
  1454
        final int REINVOKE    = nameCursor++;
jaroslav@1646
  1455
        LambdaForm.Name[] names = LambdaForm.arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
jaroslav@1646
  1456
        Object[] targetArgs;
jaroslav@1646
  1457
        MethodHandle targetMH;
jaroslav@1646
  1458
        if (customized) {
jaroslav@1646
  1459
            targetArgs = Arrays.copyOfRange(names, ARG_BASE, ARG_LIMIT, Object[].class);
jaroslav@1646
  1460
            targetMH = customTargetOrNull;
jaroslav@1646
  1461
        } else {
jaroslav@1646
  1462
            names[NEXT_MH] = new LambdaForm.Name(NF_reinvokerTarget, names[THIS_BMH]);
jaroslav@1646
  1463
            targetArgs = Arrays.copyOfRange(names, THIS_BMH, ARG_LIMIT, Object[].class);
jaroslav@1646
  1464
            targetArgs[0] = names[NEXT_MH];  // overwrite this MH with next MH
jaroslav@1646
  1465
            targetMH = MethodHandles.basicInvoker(mtype);
jaroslav@1646
  1466
        }
jaroslav@1646
  1467
        names[REINVOKE] = new LambdaForm.Name(targetMH, targetArgs);
jaroslav@1646
  1468
        return new LambdaForm("BMH.reinvoke", ARG_LIMIT, names);
jaroslav@1646
  1469
    }
jaroslav@1646
  1470
jaroslav@1646
  1471
    private static final LambdaForm.NamedFunction NF_reinvokerTarget;
jaroslav@1646
  1472
    static {
jaroslav@1646
  1473
        try {
jaroslav@1646
  1474
            NF_reinvokerTarget = new LambdaForm.NamedFunction(MethodHandle.class
jaroslav@1646
  1475
                .getDeclaredMethod("reinvokerTarget"));
jaroslav@1646
  1476
        } catch (ReflectiveOperationException ex) {
jaroslav@1646
  1477
            throw newInternalError(ex);
jaroslav@1646
  1478
        }
jaroslav@1646
  1479
    }
jaroslav@1646
  1480
jaroslav@1646
  1481
    /**
jaroslav@1646
  1482
     * Replace the old lambda form of this method handle with a new one.
jaroslav@1646
  1483
     * The new one must be functionally equivalent to the old one.
jaroslav@1646
  1484
     * Threads may continue running the old form indefinitely,
jaroslav@1646
  1485
     * but it is likely that the new one will be preferred for new executions.
jaroslav@1646
  1486
     * Use with discretion.
jaroslav@1646
  1487
     */
jaroslav@1646
  1488
    /*non-public*/
jaroslav@1646
  1489
    void updateForm(LambdaForm newForm) {
jaroslav@1646
  1490
        if (form == newForm)  return;
jaroslav@1651
  1491
        this.form = newForm;
jaroslav@1646
  1492
        this.form.prepare();  // as in MethodHandle.<init>
jaroslav@1646
  1493
    }
jaroslav@1646
  1494
}