MethodHandles.java revision 16177:89ef4b822745
1/*
2 * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import jdk.internal.org.objectweb.asm.ClassWriter;
29import jdk.internal.org.objectweb.asm.Opcodes;
30import jdk.internal.reflect.CallerSensitive;
31import jdk.internal.reflect.Reflection;
32import jdk.internal.vm.annotation.ForceInline;
33import sun.invoke.util.ValueConversions;
34import sun.invoke.util.VerifyAccess;
35import sun.invoke.util.Wrapper;
36import sun.reflect.misc.ReflectUtil;
37import sun.security.util.SecurityConstants;
38
39import java.lang.invoke.LambdaForm.BasicType;
40import java.lang.reflect.Constructor;
41import java.lang.reflect.Field;
42import java.lang.reflect.Member;
43import java.lang.reflect.Method;
44import java.lang.reflect.Modifier;
45import java.lang.reflect.Module;
46import java.lang.reflect.ReflectPermission;
47import java.nio.ByteOrder;
48import java.util.ArrayList;
49import java.util.Arrays;
50import java.util.BitSet;
51import java.util.Iterator;
52import java.util.List;
53import java.util.Objects;
54import java.util.concurrent.ConcurrentHashMap;
55import java.util.stream.Collectors;
56import java.util.stream.Stream;
57
58import static java.lang.invoke.MethodHandleImpl.Intrinsic;
59import static java.lang.invoke.MethodHandleNatives.Constants.*;
60import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
61import static java.lang.invoke.MethodType.methodType;
62
63/**
64 * This class consists exclusively of static methods that operate on or return
65 * method handles. They fall into several categories:
66 * <ul>
67 * <li>Lookup methods which help create method handles for methods and fields.
68 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
69 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
70 * </ul>
71 *
72 * @author John Rose, JSR 292 EG
73 * @since 1.7
74 */
75public class MethodHandles {
76
77    private MethodHandles() { }  // do not instantiate
78
79    static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
80
81    // See IMPL_LOOKUP below.
82
83    //// Method handle creation from ordinary methods.
84
85    /**
86     * Returns a {@link Lookup lookup object} with
87     * full capabilities to emulate all supported bytecode behaviors of the caller.
88     * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
89     * Factory methods on the lookup object can create
90     * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
91     * for any member that the caller has access to via bytecodes,
92     * including protected and private fields and methods.
93     * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
94     * Do not store it in place where untrusted code can access it.
95     * <p>
96     * This method is caller sensitive, which means that it may return different
97     * values to different callers.
98     * <p>
99     * For any given caller class {@code C}, the lookup object returned by this call
100     * has equivalent capabilities to any lookup object
101     * supplied by the JVM to the bootstrap method of an
102     * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
103     * executing in the same caller class {@code C}.
104     * @return a lookup object for the caller of this method, with private access
105     */
106    @CallerSensitive
107    @ForceInline // to ensure Reflection.getCallerClass optimization
108    public static Lookup lookup() {
109        return new Lookup(Reflection.getCallerClass());
110    }
111
112    /**
113     * Returns a {@link Lookup lookup object} which is trusted minimally.
114     * It can only be used to create method handles to public members in
115     * public classes in packages that are exported unconditionally.
116     * <p>
117     * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup
118     * object is in an unnamed module.
119     * Consequently, the lookup context of this lookup object will be the bootstrap
120     * class loader, which means it cannot find user classes.
121     *
122     * <p style="font-size:smaller;">
123     * <em>Discussion:</em>
124     * The lookup class can be changed to any other class {@code C} using an expression of the form
125     * {@link Lookup#in publicLookup().in(C.class)}.
126     * but may change the lookup context by virtue of changing the class loader.
127     * A public lookup object is always subject to
128     * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
129     * Also, it cannot access
130     * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
131     * @return a lookup object which is trusted minimally
132     */
133    public static Lookup publicLookup() {
134        // During VM startup then only classes in the java.base module can be
135        // loaded and linked. This is because java.base exports aren't setup until
136        // the module system is initialized, hence types in the unnamed module
137        // (or any named module) can't link to java/lang/Object.
138        if (!jdk.internal.misc.VM.isModuleSystemInited()) {
139            return new Lookup(Object.class, Lookup.PUBLIC);
140        } else {
141            return LookupHelper.PUBLIC_LOOKUP;
142        }
143    }
144
145    /**
146     * Returns a {@link Lookup lookup object} with full capabilities to emulate all
147     * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">
148     * private access</a>, on a target class.
149     * This method checks that a caller, specified as a {@code Lookup} object, is allowed to
150     * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
151     * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
152     * the target class, then this check ensures that
153     * <ul>
154     *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
155     *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
156     *     the target class to at least {@code m1}.</li>
157     *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>
158     * </ul>
159     * <p>
160     * If there is a security manager, its {@code checkPermission} method is called to
161     * check {@code ReflectPermission("suppressAccessChecks")}.
162     * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
163     * was created by code in the caller module (or derived from a lookup object originally
164     * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
165     * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
166     * access to the caller.
167     * @param targetClass the target class
168     * @param lookup the caller lookup object
169     * @return a lookup object for the target class, with private access
170     * @throws IllegalArgumentException if {@code targetClass} is a primitve type or array class
171     * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
172     * @throws IllegalAccessException if the access check specified above fails
173     * @throws SecurityException if denied by the security manager
174     * @since 9
175     */
176    public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
177        SecurityManager sm = System.getSecurityManager();
178        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
179        if (targetClass.isPrimitive())
180            throw new IllegalArgumentException(targetClass + " is a primitive class");
181        if (targetClass.isArray())
182            throw new IllegalArgumentException(targetClass + " is an array class");
183        Module targetModule = targetClass.getModule();
184        Module callerModule = lookup.lookupClass().getModule();
185        if (callerModule != targetModule && targetModule.isNamed()) {
186            if (!callerModule.canRead(targetModule))
187                throw new IllegalAccessException(callerModule + " does not read " + targetModule);
188            String pn = targetClass.getPackageName();
189            assert pn != null && pn.length() > 0 : "unnamed package cannot be in named module";
190            if (!targetModule.isOpen(pn, callerModule))
191                throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
192        }
193        if ((lookup.lookupModes() & Lookup.MODULE) == 0)
194            throw new IllegalAccessException("lookup does not have MODULE lookup mode");
195        return new Lookup(targetClass);
196    }
197
198    /**
199     * Performs an unchecked "crack" of a
200     * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
201     * The result is as if the user had obtained a lookup object capable enough
202     * to crack the target method handle, called
203     * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
204     * on the target to obtain its symbolic reference, and then called
205     * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
206     * to resolve the symbolic reference to a member.
207     * <p>
208     * If there is a security manager, its {@code checkPermission} method
209     * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
210     * @param <T> the desired type of the result, either {@link Member} or a subtype
211     * @param target a direct method handle to crack into symbolic reference components
212     * @param expected a class object representing the desired result type {@code T}
213     * @return a reference to the method, constructor, or field object
214     * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
215     * @exception NullPointerException if either argument is {@code null}
216     * @exception IllegalArgumentException if the target is not a direct method handle
217     * @exception ClassCastException if the member is not of the expected type
218     * @since 1.8
219     */
220    public static <T extends Member> T
221    reflectAs(Class<T> expected, MethodHandle target) {
222        SecurityManager smgr = System.getSecurityManager();
223        if (smgr != null)  smgr.checkPermission(ACCESS_PERMISSION);
224        Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
225        return lookup.revealDirect(target).reflectAs(expected, lookup);
226    }
227    // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
228    private static final java.security.Permission ACCESS_PERMISSION =
229        new ReflectPermission("suppressAccessChecks");
230
231    /**
232     * A <em>lookup object</em> is a factory for creating method handles,
233     * when the creation requires access checking.
234     * Method handles do not perform
235     * access checks when they are called, but rather when they are created.
236     * Therefore, method handle access
237     * restrictions must be enforced when a method handle is created.
238     * The caller class against which those restrictions are enforced
239     * is known as the {@linkplain #lookupClass lookup class}.
240     * <p>
241     * A lookup class which needs to create method handles will call
242     * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
243     * When the {@code Lookup} factory object is created, the identity of the lookup class is
244     * determined, and securely stored in the {@code Lookup} object.
245     * The lookup class (or its delegates) may then use factory methods
246     * on the {@code Lookup} object to create method handles for access-checked members.
247     * This includes all methods, constructors, and fields which are allowed to the lookup class,
248     * even private ones.
249     *
250     * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
251     * The factory methods on a {@code Lookup} object correspond to all major
252     * use cases for methods, constructors, and fields.
253     * Each method handle created by a factory method is the functional
254     * equivalent of a particular <em>bytecode behavior</em>.
255     * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
256     * Here is a summary of the correspondence between these factory methods and
257     * the behavior of the resulting method handles:
258     * <table border=1 cellpadding=5 summary="lookup method behaviors">
259     * <tr>
260     *     <th><a name="equiv"></a>lookup expression</th>
261     *     <th>member</th>
262     *     <th>bytecode behavior</th>
263     * </tr>
264     * <tr>
265     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
266     *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
267     * </tr>
268     * <tr>
269     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
270     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
271     * </tr>
272     * <tr>
273     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
274     *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
275     * </tr>
276     * <tr>
277     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
278     *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
279     * </tr>
280     * <tr>
281     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
282     *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
283     * </tr>
284     * <tr>
285     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
286     *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
287     * </tr>
288     * <tr>
289     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
290     *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
291     * </tr>
292     * <tr>
293     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
294     *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
295     * </tr>
296     * <tr>
297     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
298     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
299     * </tr>
300     * <tr>
301     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
302     *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
303     * </tr>
304     * <tr>
305     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
306     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
307     * </tr>
308     * <tr>
309     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
310     *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
311     * </tr>
312     * <tr>
313     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
314     *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
315     * </tr>
316     * <tr>
317     *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
318     *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
319     * </tr>
320     * </table>
321     *
322     * Here, the type {@code C} is the class or interface being searched for a member,
323     * documented as a parameter named {@code refc} in the lookup methods.
324     * The method type {@code MT} is composed from the return type {@code T}
325     * and the sequence of argument types {@code A*}.
326     * The constructor also has a sequence of argument types {@code A*} and
327     * is deemed to return the newly-created object of type {@code C}.
328     * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
329     * The formal parameter {@code this} stands for the self-reference of type {@code C};
330     * if it is present, it is always the leading argument to the method handle invocation.
331     * (In the case of some {@code protected} members, {@code this} may be
332     * restricted in type to the lookup class; see below.)
333     * The name {@code arg} stands for all the other method handle arguments.
334     * In the code examples for the Core Reflection API, the name {@code thisOrNull}
335     * stands for a null reference if the accessed method or field is static,
336     * and {@code this} otherwise.
337     * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
338     * for reflective objects corresponding to the given members.
339     * <p>
340     * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
341     * as if by {@code ldc CONSTANT_Class}.
342     * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
343     * <p>
344     * In cases where the given member is of variable arity (i.e., a method or constructor)
345     * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
346     * In all other cases, the returned method handle will be of fixed arity.
347     * <p style="font-size:smaller;">
348     * <em>Discussion:</em>
349     * The equivalence between looked-up method handles and underlying
350     * class members and bytecode behaviors
351     * can break down in a few ways:
352     * <ul style="font-size:smaller;">
353     * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
354     * the lookup can still succeed, even when there is no equivalent
355     * Java expression or bytecoded constant.
356     * <li>Likewise, if {@code T} or {@code MT}
357     * is not symbolically accessible from the lookup class's loader,
358     * the lookup can still succeed.
359     * For example, lookups for {@code MethodHandle.invokeExact} and
360     * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
361     * <li>If there is a security manager installed, it can forbid the lookup
362     * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
363     * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
364     * constant is not subject to security manager checks.
365     * <li>If the looked-up method has a
366     * <a href="MethodHandle.html#maxarity">very large arity</a>,
367     * the method handle creation may fail, due to the method handle
368     * type having too many parameters.
369     * </ul>
370     *
371     * <h1><a name="access"></a>Access checking</h1>
372     * Access checks are applied in the factory methods of {@code Lookup},
373     * when a method handle is created.
374     * This is a key difference from the Core Reflection API, since
375     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
376     * performs access checking against every caller, on every call.
377     * <p>
378     * All access checks start from a {@code Lookup} object, which
379     * compares its recorded lookup class against all requests to
380     * create method handles.
381     * A single {@code Lookup} object can be used to create any number
382     * of access-checked method handles, all checked against a single
383     * lookup class.
384     * <p>
385     * A {@code Lookup} object can be shared with other trusted code,
386     * such as a metaobject protocol.
387     * A shared {@code Lookup} object delegates the capability
388     * to create method handles on private members of the lookup class.
389     * Even if privileged code uses the {@code Lookup} object,
390     * the access checking is confined to the privileges of the
391     * original lookup class.
392     * <p>
393     * A lookup can fail, because
394     * the containing class is not accessible to the lookup class, or
395     * because the desired class member is missing, or because the
396     * desired class member is not accessible to the lookup class, or
397     * because the lookup object is not trusted enough to access the member.
398     * In any of these cases, a {@code ReflectiveOperationException} will be
399     * thrown from the attempted lookup.  The exact class will be one of
400     * the following:
401     * <ul>
402     * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
403     * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
404     * <li>IllegalAccessException &mdash; if the member exists but an access check fails
405     * </ul>
406     * <p>
407     * In general, the conditions under which a method handle may be
408     * looked up for a method {@code M} are no more restrictive than the conditions
409     * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
410     * Where the JVM would raise exceptions like {@code NoSuchMethodError},
411     * a method handle lookup will generally raise a corresponding
412     * checked exception, such as {@code NoSuchMethodException}.
413     * And the effect of invoking the method handle resulting from the lookup
414     * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
415     * to executing the compiled, verified, and resolved call to {@code M}.
416     * The same point is true of fields and constructors.
417     * <p style="font-size:smaller;">
418     * <em>Discussion:</em>
419     * Access checks only apply to named and reflected methods,
420     * constructors, and fields.
421     * Other method handle creation methods, such as
422     * {@link MethodHandle#asType MethodHandle.asType},
423     * do not require any access checks, and are used
424     * independently of any {@code Lookup} object.
425     * <p>
426     * If the desired member is {@code protected}, the usual JVM rules apply,
427     * including the requirement that the lookup class must be either be in the
428     * same package as the desired member, or must inherit that member.
429     * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
430     * In addition, if the desired member is a non-static field or method
431     * in a different package, the resulting method handle may only be applied
432     * to objects of the lookup class or one of its subclasses.
433     * This requirement is enforced by narrowing the type of the leading
434     * {@code this} parameter from {@code C}
435     * (which will necessarily be a superclass of the lookup class)
436     * to the lookup class itself.
437     * <p>
438     * The JVM imposes a similar requirement on {@code invokespecial} instruction,
439     * that the receiver argument must match both the resolved method <em>and</em>
440     * the current class.  Again, this requirement is enforced by narrowing the
441     * type of the leading parameter to the resulting method handle.
442     * (See the Java Virtual Machine Specification, section 4.10.1.9.)
443     * <p>
444     * The JVM represents constructors and static initializer blocks as internal methods
445     * with special names ({@code "<init>"} and {@code "<clinit>"}).
446     * The internal syntax of invocation instructions allows them to refer to such internal
447     * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
448     * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
449     * <p>
450     * In some cases, access between nested classes is obtained by the Java compiler by creating
451     * an wrapper method to access a private method of another class
452     * in the same top-level declaration.
453     * For example, a nested class {@code C.D}
454     * can access private members within other related classes such as
455     * {@code C}, {@code C.D.E}, or {@code C.B},
456     * but the Java compiler may need to generate wrapper methods in
457     * those related classes.  In such cases, a {@code Lookup} object on
458     * {@code C.E} would be unable to those private members.
459     * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
460     * which can transform a lookup on {@code C.E} into one on any of those other
461     * classes, without special elevation of privilege.
462     * <p>
463     * The accesses permitted to a given lookup object may be limited,
464     * according to its set of {@link #lookupModes lookupModes},
465     * to a subset of members normally accessible to the lookup class.
466     * For example, the {@link MethodHandles#publicLookup publicLookup}
467     * method produces a lookup object which is only allowed to access
468     * public members in public classes of exported packages.
469     * The caller sensitive method {@link MethodHandles#lookup lookup}
470     * produces a lookup object with full capabilities relative to
471     * its caller class, to emulate all supported bytecode behaviors.
472     * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
473     * with fewer access modes than the original lookup object.
474     *
475     * <p style="font-size:smaller;">
476     * <a name="privacc"></a>
477     * <em>Discussion of private access:</em>
478     * We say that a lookup has <em>private access</em>
479     * if its {@linkplain #lookupModes lookup modes}
480     * include the possibility of accessing {@code private} members.
481     * As documented in the relevant methods elsewhere,
482     * only lookups with private access possess the following capabilities:
483     * <ul style="font-size:smaller;">
484     * <li>access private fields, methods, and constructors of the lookup class
485     * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
486     *     such as {@code Class.forName}
487     * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
488     * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
489     *     for classes accessible to the lookup class
490     * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
491     *     within the same package member
492     * </ul>
493     * <p style="font-size:smaller;">
494     * Each of these permissions is a consequence of the fact that a lookup object
495     * with private access can be securely traced back to an originating class,
496     * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
497     * can be reliably determined and emulated by method handles.
498     *
499     * <h1><a name="secmgr"></a>Security manager interactions</h1>
500     * Although bytecode instructions can only refer to classes in
501     * a related class loader, this API can search for methods in any
502     * class, as long as a reference to its {@code Class} object is
503     * available.  Such cross-loader references are also possible with the
504     * Core Reflection API, and are impossible to bytecode instructions
505     * such as {@code invokestatic} or {@code getfield}.
506     * There is a {@linkplain java.lang.SecurityManager security manager API}
507     * to allow applications to check such cross-loader references.
508     * These checks apply to both the {@code MethodHandles.Lookup} API
509     * and the Core Reflection API
510     * (as found on {@link java.lang.Class Class}).
511     * <p>
512     * If a security manager is present, member and class lookups are subject to
513     * additional checks.
514     * From one to three calls are made to the security manager.
515     * Any of these calls can refuse access by throwing a
516     * {@link java.lang.SecurityException SecurityException}.
517     * Define {@code smgr} as the security manager,
518     * {@code lookc} as the lookup class of the current lookup object,
519     * {@code refc} as the containing class in which the member
520     * is being sought, and {@code defc} as the class in which the
521     * member is actually defined.
522     * (If a class or other type is being accessed,
523     * the {@code refc} and {@code defc} values are the class itself.)
524     * The value {@code lookc} is defined as <em>not present</em>
525     * if the current lookup object does not have
526     * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
527     * The calls are made according to the following rules:
528     * <ul>
529     * <li><b>Step 1:</b>
530     *     If {@code lookc} is not present, or if its class loader is not
531     *     the same as or an ancestor of the class loader of {@code refc},
532     *     then {@link SecurityManager#checkPackageAccess
533     *     smgr.checkPackageAccess(refcPkg)} is called,
534     *     where {@code refcPkg} is the package of {@code refc}.
535     * <li><b>Step 2a:</b>
536     *     If the retrieved member is not public and
537     *     {@code lookc} is not present, then
538     *     {@link SecurityManager#checkPermission smgr.checkPermission}
539     *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
540     * <li><b>Step 2b:</b>
541     *     If the retrieved class has a {@code null} class loader,
542     *     and {@code lookc} is not present, then
543     *     {@link SecurityManager#checkPermission smgr.checkPermission}
544     *     with {@code RuntimePermission("getClassLoader")} is called.
545     * <li><b>Step 3:</b>
546     *     If the retrieved member is not public,
547     *     and if {@code lookc} is not present,
548     *     and if {@code defc} and {@code refc} are different,
549     *     then {@link SecurityManager#checkPackageAccess
550     *     smgr.checkPackageAccess(defcPkg)} is called,
551     *     where {@code defcPkg} is the package of {@code defc}.
552     * </ul>
553     * Security checks are performed after other access checks have passed.
554     * Therefore, the above rules presuppose a member or class that is public,
555     * or else that is being accessed from a lookup class that has
556     * rights to access the member or class.
557     *
558     * <h1><a name="callsens"></a>Caller sensitive methods</h1>
559     * A small number of Java methods have a special property called caller sensitivity.
560     * A <em>caller-sensitive</em> method can behave differently depending on the
561     * identity of its immediate caller.
562     * <p>
563     * If a method handle for a caller-sensitive method is requested,
564     * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
565     * but they take account of the lookup class in a special way.
566     * The resulting method handle behaves as if it were called
567     * from an instruction contained in the lookup class,
568     * so that the caller-sensitive method detects the lookup class.
569     * (By contrast, the invoker of the method handle is disregarded.)
570     * Thus, in the case of caller-sensitive methods,
571     * different lookup classes may give rise to
572     * differently behaving method handles.
573     * <p>
574     * In cases where the lookup object is
575     * {@link MethodHandles#publicLookup() publicLookup()},
576     * or some other lookup object without
577     * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
578     * the lookup class is disregarded.
579     * In such cases, no caller-sensitive method handle can be created,
580     * access is forbidden, and the lookup fails with an
581     * {@code IllegalAccessException}.
582     * <p style="font-size:smaller;">
583     * <em>Discussion:</em>
584     * For example, the caller-sensitive method
585     * {@link java.lang.Class#forName(String) Class.forName(x)}
586     * can return varying classes or throw varying exceptions,
587     * depending on the class loader of the class that calls it.
588     * A public lookup of {@code Class.forName} will fail, because
589     * there is no reasonable way to determine its bytecode behavior.
590     * <p style="font-size:smaller;">
591     * If an application caches method handles for broad sharing,
592     * it should use {@code publicLookup()} to create them.
593     * If there is a lookup of {@code Class.forName}, it will fail,
594     * and the application must take appropriate action in that case.
595     * It may be that a later lookup, perhaps during the invocation of a
596     * bootstrap method, can incorporate the specific identity
597     * of the caller, making the method accessible.
598     * <p style="font-size:smaller;">
599     * The function {@code MethodHandles.lookup} is caller sensitive
600     * so that there can be a secure foundation for lookups.
601     * Nearly all other methods in the JSR 292 API rely on lookup
602     * objects to check access requests.
603     */
604    public static final
605    class Lookup {
606        /** The class on behalf of whom the lookup is being performed. */
607        private final Class<?> lookupClass;
608
609        /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
610        private final int allowedModes;
611
612        /** A single-bit mask representing {@code public} access,
613         *  which may contribute to the result of {@link #lookupModes lookupModes}.
614         *  The value, {@code 0x01}, happens to be the same as the value of the
615         *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
616         */
617        public static final int PUBLIC = Modifier.PUBLIC;
618
619        /** A single-bit mask representing {@code private} access,
620         *  which may contribute to the result of {@link #lookupModes lookupModes}.
621         *  The value, {@code 0x02}, happens to be the same as the value of the
622         *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
623         */
624        public static final int PRIVATE = Modifier.PRIVATE;
625
626        /** A single-bit mask representing {@code protected} access,
627         *  which may contribute to the result of {@link #lookupModes lookupModes}.
628         *  The value, {@code 0x04}, happens to be the same as the value of the
629         *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
630         */
631        public static final int PROTECTED = Modifier.PROTECTED;
632
633        /** A single-bit mask representing {@code package} access (default access),
634         *  which may contribute to the result of {@link #lookupModes lookupModes}.
635         *  The value is {@code 0x08}, which does not correspond meaningfully to
636         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
637         */
638        public static final int PACKAGE = Modifier.STATIC;
639
640        /** A single-bit mask representing {@code module} access (default access),
641         *  which may contribute to the result of {@link #lookupModes lookupModes}.
642         *  The value is {@code 0x10}, which does not correspond meaningfully to
643         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
644         *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
645         *  with this lookup mode can access all public types in the module of the
646         *  lookup class and public types in packages exported by other modules
647         *  to the module of the lookup class.
648         *  @since 9
649         */
650        public static final int MODULE = PACKAGE << 1;
651
652        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE);
653        private static final int TRUSTED   = -1;
654
655        private static int fixmods(int mods) {
656            mods &= (ALL_MODES - PACKAGE - MODULE);
657            return (mods != 0) ? mods : (PACKAGE | MODULE);
658        }
659
660        /** Tells which class is performing the lookup.  It is this class against
661         *  which checks are performed for visibility and access permissions.
662         *  <p>
663         *  The class implies a maximum level of access permission,
664         *  but the permissions may be additionally limited by the bitmask
665         *  {@link #lookupModes lookupModes}, which controls whether non-public members
666         *  can be accessed.
667         *  @return the lookup class, on behalf of which this lookup object finds members
668         */
669        public Class<?> lookupClass() {
670            return lookupClass;
671        }
672
673        // This is just for calling out to MethodHandleImpl.
674        private Class<?> lookupClassOrNull() {
675            return (allowedModes == TRUSTED) ? null : lookupClass;
676        }
677
678        /** Tells which access-protection classes of members this lookup object can produce.
679         *  The result is a bit-mask of the bits
680         *  {@linkplain #PUBLIC PUBLIC (0x01)},
681         *  {@linkplain #PRIVATE PRIVATE (0x02)},
682         *  {@linkplain #PROTECTED PROTECTED (0x04)},
683         *  {@linkplain #PACKAGE PACKAGE (0x08)},
684         *  and {@linkplain #MODULE MODULE (0x10)}.
685         *  <p>
686         *  A freshly-created lookup object
687         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
688         *  has all possible bits set, since the caller class can access all its own members,
689         *  all public types in the caller's module, and all public types in packages exported
690         *  by other modules to the caller's module.
691         *  A lookup object on a new lookup class
692         *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
693         *  may have some mode bits set to zero.
694         *  The purpose of this is to restrict access via the new lookup object,
695         *  so that it can access only names which can be reached by the original
696         *  lookup object, and also by the new lookup class.
697         *  @return the lookup modes, which limit the kinds of access performed by this lookup object
698         */
699        public int lookupModes() {
700            return allowedModes & ALL_MODES;
701        }
702
703        /** Embody the current class (the lookupClass) as a lookup class
704         * for method handle creation.
705         * Must be called by from a method in this package,
706         * which in turn is called by a method not in this package.
707         */
708        Lookup(Class<?> lookupClass) {
709            this(lookupClass, ALL_MODES);
710            // make sure we haven't accidentally picked up a privileged class:
711            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
712        }
713
714        private Lookup(Class<?> lookupClass, int allowedModes) {
715            this.lookupClass = lookupClass;
716            this.allowedModes = allowedModes;
717        }
718
719        /**
720         * Creates a lookup on the specified new lookup class.
721         * The resulting object will report the specified
722         * class as its own {@link #lookupClass lookupClass}.
723         * <p>
724         * However, the resulting {@code Lookup} object is guaranteed
725         * to have no more access capabilities than the original.
726         * In particular, access capabilities can be lost as follows:<ul>
727         * <li>If the lookup class for this {@code Lookup} is not in a named module,
728         * and the new lookup class is in a named module {@code M}, then no members in
729         * {@code M}'s non-exported packages will be accessible.
730         * <li>If the lookup for this {@code Lookup} is in a named module, and the
731         * new lookup class is in a different module {@code M}, then no members, not even
732         * public members in {@code M}'s exported packages, will be accessible.
733         * <li>If the new lookup class differs from the old one,
734         * protected members will not be accessible by virtue of inheritance.
735         * (Protected members may continue to be accessible because of package sharing.)
736         * <li>If the new lookup class is in a different package
737         * than the old one, protected and default (package) members will not be accessible.
738         * <li>If the new lookup class is not within the same package member
739         * as the old one, private members will not be accessible.
740         * <li>If the new lookup class is not accessible to the old lookup class,
741         * then no members, not even public members, will be accessible.
742         * (In all other cases, public members will continue to be accessible.)
743         * </ul>
744         * <p>
745         * The resulting lookup's capabilities for loading classes
746         * (used during {@link #findClass} invocations)
747         * are determined by the lookup class' loader,
748         * which may change due to this operation.
749         *
750         * @param requestedLookupClass the desired lookup class for the new lookup object
751         * @return a lookup object which reports the desired lookup class
752         * @throws NullPointerException if the argument is null
753         */
754        public Lookup in(Class<?> requestedLookupClass) {
755            Objects.requireNonNull(requestedLookupClass);
756            if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
757                return new Lookup(requestedLookupClass, ALL_MODES);
758            if (requestedLookupClass == this.lookupClass)
759                return this;  // keep same capabilities
760
761            int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
762            if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
763                // Allowed to teleport from an unnamed to a named module but resulting
764                // Lookup has no access to module private members
765                if (this.lookupClass.getModule().isNamed()) {
766                    newModes = 0;
767                } else {
768                    newModes &= ~MODULE;
769                }
770            }
771            if ((newModes & PACKAGE) != 0
772                && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
773                newModes &= ~(PACKAGE|PRIVATE);
774            }
775            // Allow nestmate lookups to be created without special privilege:
776            if ((newModes & PRIVATE) != 0
777                && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
778                newModes &= ~PRIVATE;
779            }
780            if ((newModes & PUBLIC) != 0
781                && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
782                // The requested class it not accessible from the lookup class.
783                // No permissions.
784                newModes = 0;
785            }
786
787            checkUnprivilegedlookupClass(requestedLookupClass, newModes);
788            return new Lookup(requestedLookupClass, newModes);
789        }
790
791        // Make sure outer class is initialized first.
792        static { IMPL_NAMES.getClass(); }
793
794        /** Package-private version of lookup which is trusted. */
795        static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
796
797        private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
798            String name = lookupClass.getName();
799            if (name.startsWith("java.lang.invoke."))
800                throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
801
802            // For caller-sensitive MethodHandles.lookup() disallow lookup from
803            // restricted packages.  This a fragile and blunt approach.
804            // TODO replace with a more formal and less fragile mechanism
805            // that does not bluntly restrict classes under packages within
806            // java.base from looking up MethodHandles or VarHandles.
807            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
808                if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) ||
809                        (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
810                    throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
811                }
812            }
813        }
814
815        /**
816         * Displays the name of the class from which lookups are to be made.
817         * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
818         * If there are restrictions on the access permitted to this lookup,
819         * this is indicated by adding a suffix to the class name, consisting
820         * of a slash and a keyword.  The keyword represents the strongest
821         * allowed access, and is chosen as follows:
822         * <ul>
823         * <li>If no access is allowed, the suffix is "/noaccess".
824         * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
825         * <li>If only public and module access are allowed, the suffix is "/module".
826         * <li>If only public, module and package access are allowed, the suffix is "/package".
827         * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
828         * </ul>
829         * If none of the above cases apply, it is the case that full
830         * access (public, module, package, private, and protected) is allowed.
831         * In this case, no suffix is added.
832         * This is true only of an object obtained originally from
833         * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
834         * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
835         * always have restricted access, and will display a suffix.
836         * <p>
837         * (It may seem strange that protected access should be
838         * stronger than private access.  Viewed independently from
839         * package access, protected access is the first to be lost,
840         * because it requires a direct subclass relationship between
841         * caller and callee.)
842         * @see #in
843         */
844        @Override
845        public String toString() {
846            String cname = lookupClass.getName();
847            switch (allowedModes) {
848            case 0:  // no privileges
849                return cname + "/noaccess";
850            case PUBLIC:
851                return cname + "/public";
852            case PUBLIC|MODULE:
853                return cname + "/module";
854            case PUBLIC|MODULE|PACKAGE:
855                return cname + "/package";
856            case ALL_MODES & ~PROTECTED:
857                return cname + "/private";
858            case ALL_MODES:
859                return cname;
860            case TRUSTED:
861                return "/trusted";  // internal only; not exported
862            default:  // Should not happen, but it's a bitfield...
863                cname = cname + "/" + Integer.toHexString(allowedModes);
864                assert(false) : cname;
865                return cname;
866            }
867        }
868
869        /**
870         * Produces a method handle for a static method.
871         * The type of the method handle will be that of the method.
872         * (Since static methods do not take receivers, there is no
873         * additional receiver argument inserted into the method handle type,
874         * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
875         * The method and all its argument types must be accessible to the lookup object.
876         * <p>
877         * The returned method handle will have
878         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
879         * the method's variable arity modifier bit ({@code 0x0080}) is set.
880         * <p>
881         * If the returned method handle is invoked, the method's class will
882         * be initialized, if it has not already been initialized.
883         * <p><b>Example:</b>
884         * <blockquote><pre>{@code
885import static java.lang.invoke.MethodHandles.*;
886import static java.lang.invoke.MethodType.*;
887...
888MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
889  "asList", methodType(List.class, Object[].class));
890assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
891         * }</pre></blockquote>
892         * @param refc the class from which the method is accessed
893         * @param name the name of the method
894         * @param type the type of the method
895         * @return the desired method handle
896         * @throws NoSuchMethodException if the method does not exist
897         * @throws IllegalAccessException if access checking fails,
898         *                                or if the method is not {@code static},
899         *                                or if the method's variable arity modifier bit
900         *                                is set and {@code asVarargsCollector} fails
901         * @exception SecurityException if a security manager is present and it
902         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
903         * @throws NullPointerException if any argument is null
904         */
905        public
906        MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
907            MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
908            return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
909        }
910
911        /**
912         * Produces a method handle for a virtual method.
913         * The type of the method handle will be that of the method,
914         * with the receiver type (usually {@code refc}) prepended.
915         * The method and all its argument types must be accessible to the lookup object.
916         * <p>
917         * When called, the handle will treat the first argument as a receiver
918         * and dispatch on the receiver's type to determine which method
919         * implementation to enter.
920         * (The dispatching action is identical with that performed by an
921         * {@code invokevirtual} or {@code invokeinterface} instruction.)
922         * <p>
923         * The first argument will be of type {@code refc} if the lookup
924         * class has full privileges to access the member.  Otherwise
925         * the member must be {@code protected} and the first argument
926         * will be restricted in type to the lookup class.
927         * <p>
928         * The returned method handle will have
929         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
930         * the method's variable arity modifier bit ({@code 0x0080}) is set.
931         * <p>
932         * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
933         * instructions and method handles produced by {@code findVirtual},
934         * if the class is {@code MethodHandle} and the name string is
935         * {@code invokeExact} or {@code invoke}, the resulting
936         * method handle is equivalent to one produced by
937         * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
938         * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
939         * with the same {@code type} argument.
940         * <p>
941         * If the class is {@code VarHandle} and the name string corresponds to
942         * the name of a signature-polymorphic access mode method, the resulting
943         * method handle is equivalent to one produced by
944         * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
945         * the access mode corresponding to the name string and with the same
946         * {@code type} arguments.
947         * <p>
948         * <b>Example:</b>
949         * <blockquote><pre>{@code
950import static java.lang.invoke.MethodHandles.*;
951import static java.lang.invoke.MethodType.*;
952...
953MethodHandle MH_concat = publicLookup().findVirtual(String.class,
954  "concat", methodType(String.class, String.class));
955MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
956  "hashCode", methodType(int.class));
957MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
958  "hashCode", methodType(int.class));
959assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
960assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
961assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
962// interface method:
963MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
964  "subSequence", methodType(CharSequence.class, int.class, int.class));
965assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
966// constructor "internal method" must be accessed differently:
967MethodType MT_newString = methodType(void.class); //()V for new String()
968try { assertEquals("impossible", lookup()
969        .findVirtual(String.class, "<init>", MT_newString));
970 } catch (NoSuchMethodException ex) { } // OK
971MethodHandle MH_newString = publicLookup()
972  .findConstructor(String.class, MT_newString);
973assertEquals("", (String) MH_newString.invokeExact());
974         * }</pre></blockquote>
975         *
976         * @param refc the class or interface from which the method is accessed
977         * @param name the name of the method
978         * @param type the type of the method, with the receiver argument omitted
979         * @return the desired method handle
980         * @throws NoSuchMethodException if the method does not exist
981         * @throws IllegalAccessException if access checking fails,
982         *                                or if the method is {@code static},
983         *                                or if the method is {@code private} method of interface,
984         *                                or if the method's variable arity modifier bit
985         *                                is set and {@code asVarargsCollector} fails
986         * @exception SecurityException if a security manager is present and it
987         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
988         * @throws NullPointerException if any argument is null
989         */
990        public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
991            if (refc == MethodHandle.class) {
992                MethodHandle mh = findVirtualForMH(name, type);
993                if (mh != null)  return mh;
994            } else if (refc == VarHandle.class) {
995                MethodHandle mh = findVirtualForVH(name, type);
996                if (mh != null)  return mh;
997            }
998            byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
999            MemberName method = resolveOrFail(refKind, refc, name, type);
1000            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
1001        }
1002        private MethodHandle findVirtualForMH(String name, MethodType type) {
1003            // these names require special lookups because of the implicit MethodType argument
1004            if ("invoke".equals(name))
1005                return invoker(type);
1006            if ("invokeExact".equals(name))
1007                return exactInvoker(type);
1008            assert(!MemberName.isMethodHandleInvokeName(name));
1009            return null;
1010        }
1011        private MethodHandle findVirtualForVH(String name, MethodType type) {
1012            try {
1013                return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
1014            } catch (IllegalArgumentException e) {
1015                return null;
1016            }
1017        }
1018
1019        /**
1020         * Produces a method handle which creates an object and initializes it, using
1021         * the constructor of the specified type.
1022         * The parameter types of the method handle will be those of the constructor,
1023         * while the return type will be a reference to the constructor's class.
1024         * The constructor and all its argument types must be accessible to the lookup object.
1025         * <p>
1026         * The requested type must have a return type of {@code void}.
1027         * (This is consistent with the JVM's treatment of constructor type descriptors.)
1028         * <p>
1029         * The returned method handle will have
1030         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1031         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1032         * <p>
1033         * If the returned method handle is invoked, the constructor's class will
1034         * be initialized, if it has not already been initialized.
1035         * <p><b>Example:</b>
1036         * <blockquote><pre>{@code
1037import static java.lang.invoke.MethodHandles.*;
1038import static java.lang.invoke.MethodType.*;
1039...
1040MethodHandle MH_newArrayList = publicLookup().findConstructor(
1041  ArrayList.class, methodType(void.class, Collection.class));
1042Collection orig = Arrays.asList("x", "y");
1043Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
1044assert(orig != copy);
1045assertEquals(orig, copy);
1046// a variable-arity constructor:
1047MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
1048  ProcessBuilder.class, methodType(void.class, String[].class));
1049ProcessBuilder pb = (ProcessBuilder)
1050  MH_newProcessBuilder.invoke("x", "y", "z");
1051assertEquals("[x, y, z]", pb.command().toString());
1052         * }</pre></blockquote>
1053         * @param refc the class or interface from which the method is accessed
1054         * @param type the type of the method, with the receiver argument omitted, and a void return type
1055         * @return the desired method handle
1056         * @throws NoSuchMethodException if the constructor does not exist
1057         * @throws IllegalAccessException if access checking fails
1058         *                                or if the method's variable arity modifier bit
1059         *                                is set and {@code asVarargsCollector} fails
1060         * @exception SecurityException if a security manager is present and it
1061         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1062         * @throws NullPointerException if any argument is null
1063         */
1064        public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1065            if (refc.isArray()) {
1066                throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1067            }
1068            String name = "<init>";
1069            MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
1070            return getDirectConstructor(refc, ctor);
1071        }
1072
1073        /**
1074         * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1075         * initializer of the class is not run.
1076         * <p>
1077         * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1078         * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1079         * load the requested class, and then determines whether the class is accessible to this lookup object.
1080         *
1081         * @param targetName the fully qualified name of the class to be looked up.
1082         * @return the requested class.
1083         * @exception SecurityException if a security manager is present and it
1084         *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1085         * @throws LinkageError if the linkage fails
1086         * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1087         * @throws IllegalAccessException if the class is not accessible, using the allowed access
1088         * modes.
1089         * @exception SecurityException if a security manager is present and it
1090         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1091         * @since 9
1092         */
1093        public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1094            Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1095            return accessClass(targetClass);
1096        }
1097
1098        /**
1099         * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1100         * static initializer of the class is not run.
1101         * <p>
1102         * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1103         * {@linkplain #lookupModes() lookup modes}.
1104         *
1105         * @param targetClass the class to be access-checked
1106         *
1107         * @return the class that has been access-checked
1108         *
1109         * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1110         * modes.
1111         * @exception SecurityException if a security manager is present and it
1112         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1113         * @since 9
1114         */
1115        public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1116            if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
1117                throw new MemberName(targetClass).makeAccessException("access violation", this);
1118            }
1119            checkSecurityManager(targetClass, null);
1120            return targetClass;
1121        }
1122
1123        /**
1124         * Produces an early-bound method handle for a virtual method.
1125         * It will bypass checks for overriding methods on the receiver,
1126         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1127         * instruction from within the explicitly specified {@code specialCaller}.
1128         * The type of the method handle will be that of the method,
1129         * with a suitably restricted receiver type prepended.
1130         * (The receiver type will be {@code specialCaller} or a subtype.)
1131         * The method and all its argument types must be accessible
1132         * to the lookup object.
1133         * <p>
1134         * Before method resolution,
1135         * if the explicitly specified caller class is not identical with the
1136         * lookup class, or if this lookup object does not have
1137         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1138         * privileges, the access fails.
1139         * <p>
1140         * The returned method handle will have
1141         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1142         * the method's variable arity modifier bit ({@code 0x0080}) is set.
1143         * <p style="font-size:smaller;">
1144         * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
1145         * even though the {@code invokespecial} instruction can refer to them
1146         * in special circumstances.  Use {@link #findConstructor findConstructor}
1147         * to access instance initialization methods in a safe manner.)</em>
1148         * <p><b>Example:</b>
1149         * <blockquote><pre>{@code
1150import static java.lang.invoke.MethodHandles.*;
1151import static java.lang.invoke.MethodType.*;
1152...
1153static class Listie extends ArrayList {
1154  public String toString() { return "[wee Listie]"; }
1155  static Lookup lookup() { return MethodHandles.lookup(); }
1156}
1157...
1158// no access to constructor via invokeSpecial:
1159MethodHandle MH_newListie = Listie.lookup()
1160  .findConstructor(Listie.class, methodType(void.class));
1161Listie l = (Listie) MH_newListie.invokeExact();
1162try { assertEquals("impossible", Listie.lookup().findSpecial(
1163        Listie.class, "<init>", methodType(void.class), Listie.class));
1164 } catch (NoSuchMethodException ex) { } // OK
1165// access to super and self methods via invokeSpecial:
1166MethodHandle MH_super = Listie.lookup().findSpecial(
1167  ArrayList.class, "toString" , methodType(String.class), Listie.class);
1168MethodHandle MH_this = Listie.lookup().findSpecial(
1169  Listie.class, "toString" , methodType(String.class), Listie.class);
1170MethodHandle MH_duper = Listie.lookup().findSpecial(
1171  Object.class, "toString" , methodType(String.class), Listie.class);
1172assertEquals("[]", (String) MH_super.invokeExact(l));
1173assertEquals(""+l, (String) MH_this.invokeExact(l));
1174assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1175try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1176        String.class, "toString", methodType(String.class), Listie.class));
1177 } catch (IllegalAccessException ex) { } // OK
1178Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1179assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1180         * }</pre></blockquote>
1181         *
1182         * @param refc the class or interface from which the method is accessed
1183         * @param name the name of the method (which must not be "&lt;init&gt;")
1184         * @param type the type of the method, with the receiver argument omitted
1185         * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1186         * @return the desired method handle
1187         * @throws NoSuchMethodException if the method does not exist
1188         * @throws IllegalAccessException if access checking fails,
1189         *                                or if the method is {@code static},
1190         *                                or if the method's variable arity modifier bit
1191         *                                is set and {@code asVarargsCollector} fails
1192         * @exception SecurityException if a security manager is present and it
1193         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1194         * @throws NullPointerException if any argument is null
1195         */
1196        public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1197                                        Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1198            checkSpecialCaller(specialCaller, refc);
1199            Lookup specialLookup = this.in(specialCaller);
1200            MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1201            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1202        }
1203
1204        /**
1205         * Produces a method handle giving read access to a non-static field.
1206         * The type of the method handle will have a return type of the field's
1207         * value type.
1208         * The method handle's single argument will be the instance containing
1209         * the field.
1210         * Access checking is performed immediately on behalf of the lookup class.
1211         * @param refc the class or interface from which the method is accessed
1212         * @param name the field's name
1213         * @param type the field's type
1214         * @return a method handle which can load values from the field
1215         * @throws NoSuchFieldException if the field does not exist
1216         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1217         * @exception SecurityException if a security manager is present and it
1218         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1219         * @throws NullPointerException if any argument is null
1220         * @see #findVarHandle(Class, String, Class)
1221         */
1222        public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1223            MemberName field = resolveOrFail(REF_getField, refc, name, type);
1224            return getDirectField(REF_getField, refc, field);
1225        }
1226
1227        /**
1228         * Produces a method handle giving write access to a non-static field.
1229         * The type of the method handle will have a void return type.
1230         * The method handle will take two arguments, the instance containing
1231         * the field, and the value to be stored.
1232         * The second argument will be of the field's value type.
1233         * Access checking is performed immediately on behalf of the lookup class.
1234         * @param refc the class or interface from which the method is accessed
1235         * @param name the field's name
1236         * @param type the field's type
1237         * @return a method handle which can store values into the field
1238         * @throws NoSuchFieldException if the field does not exist
1239         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1240         * @exception SecurityException if a security manager is present and it
1241         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1242         * @throws NullPointerException if any argument is null
1243         * @see #findVarHandle(Class, String, Class)
1244         */
1245        public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1246            MemberName field = resolveOrFail(REF_putField, refc, name, type);
1247            return getDirectField(REF_putField, refc, field);
1248        }
1249
1250        /**
1251         * Produces a VarHandle giving access to non-static fields of type
1252         * {@code T} declared by a receiver class of type {@code R}, supporting
1253         * shape {@code (R : T)}.
1254         * <p>
1255         * Access checking is performed immediately on behalf of the lookup
1256         * class.
1257         * <p>
1258         * Certain access modes of the returned VarHandle are unsupported under
1259         * the following conditions:
1260         * <ul>
1261         * <li>if the field is declared {@code final}, then the write, atomic
1262         *     update, numeric atomic update, and bitwise atomic update access
1263         *     modes are unsupported.
1264         * <li>if the field type is anything other than {@code byte},
1265         *     {@code short}, {@code char}, {@code int}, {@code long},
1266         *     {@code float}, or {@code double} then numeric atomic update
1267         *     access modes are unsupported.
1268         * <li>if the field type is anything other than {@code boolean},
1269         *     {@code byte}, {@code short}, {@code char}, {@code int} or
1270         *     {@code long} then bitwise atomic update access modes are
1271         *     unsupported.
1272         * </ul>
1273         * <p>
1274         * If the field is declared {@code volatile} then the returned VarHandle
1275         * will override access to the field (effectively ignore the
1276         * {@code volatile} declaration) in accordance to it's specified
1277         * access modes.
1278         * <p>
1279         * If the field type is {@code float} or {@code double} then numeric
1280         * and atomic update access modes compare values using their bitwise
1281         * representation (see {@link Float#floatToRawIntBits} and
1282         * {@link Double#doubleToRawLongBits}, respectively).
1283         * @apiNote
1284         * Bitwise comparison of {@code float} values or {@code double} values,
1285         * as performed by the numeric and atomic update access modes, differ
1286         * from the primitive {@code ==} operator and the {@link Float#equals}
1287         * and {@link Double#equals} methods, specifically with respect to
1288         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1289         * Care should be taken when performing a compare and set or a compare
1290         * and exchange operation with such values since the operation may
1291         * unexpectedly fail.
1292         * There are many possible NaN values that are considered to be
1293         * {@code NaN} in Java, although no IEEE 754 floating-point operation
1294         * provided by Java can distinguish between them.  Operation failure can
1295         * occur if the expected or witness value is a NaN value and it is
1296         * transformed (perhaps in a platform specific manner) into another NaN
1297         * value, and thus has a different bitwise representation (see
1298         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1299         * details).
1300         * The values {@code -0.0} and {@code +0.0} have different bitwise
1301         * representations but are considered equal when using the primitive
1302         * {@code ==} operator.  Operation failure can occur if, for example, a
1303         * numeric algorithm computes an expected value to be say {@code -0.0}
1304         * and previously computed the witness value to be say {@code +0.0}.
1305         * @param recv the receiver class, of type {@code R}, that declares the
1306         * non-static field
1307         * @param name the field's name
1308         * @param type the field's type, of type {@code T}
1309         * @return a VarHandle giving access to non-static fields.
1310         * @throws NoSuchFieldException if the field does not exist
1311         * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1312         * @exception SecurityException if a security manager is present and it
1313         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1314         * @throws NullPointerException if any argument is null
1315         * @since 9
1316         */
1317        public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1318            MemberName getField = resolveOrFail(REF_getField, recv, name, type);
1319            MemberName putField = resolveOrFail(REF_putField, recv, name, type);
1320            return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
1321        }
1322
1323        /**
1324         * Produces a method handle giving read access to a static field.
1325         * The type of the method handle will have a return type of the field's
1326         * value type.
1327         * The method handle will take no arguments.
1328         * Access checking is performed immediately on behalf of the lookup class.
1329         * <p>
1330         * If the returned method handle is invoked, the field's class will
1331         * be initialized, if it has not already been initialized.
1332         * @param refc the class or interface from which the method is accessed
1333         * @param name the field's name
1334         * @param type the field's type
1335         * @return a method handle which can load values from the field
1336         * @throws NoSuchFieldException if the field does not exist
1337         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1338         * @exception SecurityException if a security manager is present and it
1339         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1340         * @throws NullPointerException if any argument is null
1341         */
1342        public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1343            MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
1344            return getDirectField(REF_getStatic, refc, field);
1345        }
1346
1347        /**
1348         * Produces a method handle giving write access to a static field.
1349         * The type of the method handle will have a void return type.
1350         * The method handle will take a single
1351         * argument, of the field's value type, the value to be stored.
1352         * Access checking is performed immediately on behalf of the lookup class.
1353         * <p>
1354         * If the returned method handle is invoked, the field's class will
1355         * be initialized, if it has not already been initialized.
1356         * @param refc the class or interface from which the method is accessed
1357         * @param name the field's name
1358         * @param type the field's type
1359         * @return a method handle which can store values into the field
1360         * @throws NoSuchFieldException if the field does not exist
1361         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1362         * @exception SecurityException if a security manager is present and it
1363         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1364         * @throws NullPointerException if any argument is null
1365         */
1366        public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1367            MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
1368            return getDirectField(REF_putStatic, refc, field);
1369        }
1370
1371        /**
1372         * Produces a VarHandle giving access to a static field of type
1373         * {@code T} declared by a given declaring class, supporting shape
1374         * {@code ((empty) : T)}.
1375         * <p>
1376         * Access checking is performed immediately on behalf of the lookup
1377         * class.
1378         * <p>
1379         * If the returned VarHandle is operated on, the declaring class will be
1380         * initialized, if it has not already been initialized.
1381         * <p>
1382         * Certain access modes of the returned VarHandle are unsupported under
1383         * the following conditions:
1384         * <ul>
1385         * <li>if the field is declared {@code final}, then the write, atomic
1386         *     update, numeric atomic update, and bitwise atomic update access
1387         *     modes are unsupported.
1388         * <li>if the field type is anything other than {@code byte},
1389         *     {@code short}, {@code char}, {@code int}, {@code long},
1390         *     {@code float}, or {@code double}, then numeric atomic update
1391         *     access modes are unsupported.
1392         * <li>if the field type is anything other than {@code boolean},
1393         *     {@code byte}, {@code short}, {@code char}, {@code int} or
1394         *     {@code long} then bitwise atomic update access modes are
1395         *     unsupported.
1396         * </ul>
1397         * <p>
1398         * If the field is declared {@code volatile} then the returned VarHandle
1399         * will override access to the field (effectively ignore the
1400         * {@code volatile} declaration) in accordance to it's specified
1401         * access modes.
1402         * <p>
1403         * If the field type is {@code float} or {@code double} then numeric
1404         * and atomic update access modes compare values using their bitwise
1405         * representation (see {@link Float#floatToRawIntBits} and
1406         * {@link Double#doubleToRawLongBits}, respectively).
1407         * @apiNote
1408         * Bitwise comparison of {@code float} values or {@code double} values,
1409         * as performed by the numeric and atomic update access modes, differ
1410         * from the primitive {@code ==} operator and the {@link Float#equals}
1411         * and {@link Double#equals} methods, specifically with respect to
1412         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1413         * Care should be taken when performing a compare and set or a compare
1414         * and exchange operation with such values since the operation may
1415         * unexpectedly fail.
1416         * There are many possible NaN values that are considered to be
1417         * {@code NaN} in Java, although no IEEE 754 floating-point operation
1418         * provided by Java can distinguish between them.  Operation failure can
1419         * occur if the expected or witness value is a NaN value and it is
1420         * transformed (perhaps in a platform specific manner) into another NaN
1421         * value, and thus has a different bitwise representation (see
1422         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1423         * details).
1424         * The values {@code -0.0} and {@code +0.0} have different bitwise
1425         * representations but are considered equal when using the primitive
1426         * {@code ==} operator.  Operation failure can occur if, for example, a
1427         * numeric algorithm computes an expected value to be say {@code -0.0}
1428         * and previously computed the witness value to be say {@code +0.0}.
1429         * @param decl the class that declares the static field
1430         * @param name the field's name
1431         * @param type the field's type, of type {@code T}
1432         * @return a VarHandle giving access to a static field
1433         * @throws NoSuchFieldException if the field does not exist
1434         * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1435         * @exception SecurityException if a security manager is present and it
1436         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1437         * @throws NullPointerException if any argument is null
1438         * @since 9
1439         */
1440        public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1441            MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
1442            MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
1443            return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
1444        }
1445
1446        /**
1447         * Produces an early-bound method handle for a non-static method.
1448         * The receiver must have a supertype {@code defc} in which a method
1449         * of the given name and type is accessible to the lookup class.
1450         * The method and all its argument types must be accessible to the lookup object.
1451         * The type of the method handle will be that of the method,
1452         * without any insertion of an additional receiver parameter.
1453         * The given receiver will be bound into the method handle,
1454         * so that every call to the method handle will invoke the
1455         * requested method on the given receiver.
1456         * <p>
1457         * The returned method handle will have
1458         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1459         * the method's variable arity modifier bit ({@code 0x0080}) is set
1460         * <em>and</em> the trailing array argument is not the only argument.
1461         * (If the trailing array argument is the only argument,
1462         * the given receiver value will be bound to it.)
1463         * <p>
1464         * This is equivalent to the following code:
1465         * <blockquote><pre>{@code
1466import static java.lang.invoke.MethodHandles.*;
1467import static java.lang.invoke.MethodType.*;
1468...
1469MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1470MethodHandle mh1 = mh0.bindTo(receiver);
1471mh1 = mh1.withVarargs(mh0.isVarargsCollector());
1472return mh1;
1473         * }</pre></blockquote>
1474         * where {@code defc} is either {@code receiver.getClass()} or a super
1475         * type of that class, in which the requested method is accessible
1476         * to the lookup class.
1477         * (Note that {@code bindTo} does not preserve variable arity.)
1478         * @param receiver the object from which the method is accessed
1479         * @param name the name of the method
1480         * @param type the type of the method, with the receiver argument omitted
1481         * @return the desired method handle
1482         * @throws NoSuchMethodException if the method does not exist
1483         * @throws IllegalAccessException if access checking fails
1484         *                                or if the method's variable arity modifier bit
1485         *                                is set and {@code asVarargsCollector} fails
1486         * @exception SecurityException if a security manager is present and it
1487         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1488         * @throws NullPointerException if any argument is null
1489         * @see MethodHandle#bindTo
1490         * @see #findVirtual
1491         */
1492        public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1493            Class<? extends Object> refc = receiver.getClass(); // may get NPE
1494            MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
1495            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1496            return mh.bindArgumentL(0, receiver).setVarargs(method);
1497        }
1498
1499        /**
1500         * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1501         * to <i>m</i>, if the lookup class has permission.
1502         * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1503         * If <i>m</i> is virtual, overriding is respected on every call.
1504         * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1505         * The type of the method handle will be that of the method,
1506         * with the receiver type prepended (but only if it is non-static).
1507         * If the method's {@code accessible} flag is not set,
1508         * access checking is performed immediately on behalf of the lookup class.
1509         * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1510         * <p>
1511         * The returned method handle will have
1512         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1513         * the method's variable arity modifier bit ({@code 0x0080}) is set.
1514         * <p>
1515         * If <i>m</i> is static, and
1516         * if the returned method handle is invoked, the method's class will
1517         * be initialized, if it has not already been initialized.
1518         * @param m the reflected method
1519         * @return a method handle which can invoke the reflected method
1520         * @throws IllegalAccessException if access checking fails
1521         *                                or if the method's variable arity modifier bit
1522         *                                is set and {@code asVarargsCollector} fails
1523         * @throws NullPointerException if the argument is null
1524         */
1525        public MethodHandle unreflect(Method m) throws IllegalAccessException {
1526            if (m.getDeclaringClass() == MethodHandle.class) {
1527                MethodHandle mh = unreflectForMH(m);
1528                if (mh != null)  return mh;
1529            }
1530            if (m.getDeclaringClass() == VarHandle.class) {
1531                MethodHandle mh = unreflectForVH(m);
1532                if (mh != null)  return mh;
1533            }
1534            MemberName method = new MemberName(m);
1535            byte refKind = method.getReferenceKind();
1536            if (refKind == REF_invokeSpecial)
1537                refKind = REF_invokeVirtual;
1538            assert(method.isMethod());
1539            Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
1540            return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
1541        }
1542        private MethodHandle unreflectForMH(Method m) {
1543            // these names require special lookups because they throw UnsupportedOperationException
1544            if (MemberName.isMethodHandleInvokeName(m.getName()))
1545                return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1546            return null;
1547        }
1548        private MethodHandle unreflectForVH(Method m) {
1549            // these names require special lookups because they throw UnsupportedOperationException
1550            if (MemberName.isVarHandleMethodInvokeName(m.getName()))
1551                return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
1552            return null;
1553        }
1554
1555        /**
1556         * Produces a method handle for a reflected method.
1557         * It will bypass checks for overriding methods on the receiver,
1558         * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1559         * instruction from within the explicitly specified {@code specialCaller}.
1560         * The type of the method handle will be that of the method,
1561         * with a suitably restricted receiver type prepended.
1562         * (The receiver type will be {@code specialCaller} or a subtype.)
1563         * If the method's {@code accessible} flag is not set,
1564         * access checking is performed immediately on behalf of the lookup class,
1565         * as if {@code invokespecial} instruction were being linked.
1566         * <p>
1567         * Before method resolution,
1568         * if the explicitly specified caller class is not identical with the
1569         * lookup class, or if this lookup object does not have
1570         * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1571         * privileges, the access fails.
1572         * <p>
1573         * The returned method handle will have
1574         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1575         * the method's variable arity modifier bit ({@code 0x0080}) is set.
1576         * @param m the reflected method
1577         * @param specialCaller the class nominally calling the method
1578         * @return a method handle which can invoke the reflected method
1579         * @throws IllegalAccessException if access checking fails,
1580         *                                or if the method is {@code static},
1581         *                                or if the method's variable arity modifier bit
1582         *                                is set and {@code asVarargsCollector} fails
1583         * @throws NullPointerException if any argument is null
1584         */
1585        public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1586            checkSpecialCaller(specialCaller, null);
1587            Lookup specialLookup = this.in(specialCaller);
1588            MemberName method = new MemberName(m, true);
1589            assert(method.isMethod());
1590            // ignore m.isAccessible:  this is a new kind of access
1591            return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1592        }
1593
1594        /**
1595         * Produces a method handle for a reflected constructor.
1596         * The type of the method handle will be that of the constructor,
1597         * with the return type changed to the declaring class.
1598         * The method handle will perform a {@code newInstance} operation,
1599         * creating a new instance of the constructor's class on the
1600         * arguments passed to the method handle.
1601         * <p>
1602         * If the constructor's {@code accessible} flag is not set,
1603         * access checking is performed immediately on behalf of the lookup class.
1604         * <p>
1605         * The returned method handle will have
1606         * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1607         * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1608         * <p>
1609         * If the returned method handle is invoked, the constructor's class will
1610         * be initialized, if it has not already been initialized.
1611         * @param c the reflected constructor
1612         * @return a method handle which can invoke the reflected constructor
1613         * @throws IllegalAccessException if access checking fails
1614         *                                or if the method's variable arity modifier bit
1615         *                                is set and {@code asVarargsCollector} fails
1616         * @throws NullPointerException if the argument is null
1617         */
1618        public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1619            MemberName ctor = new MemberName(c);
1620            assert(ctor.isConstructor());
1621            Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
1622            return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
1623        }
1624
1625        /**
1626         * Produces a method handle giving read access to a reflected field.
1627         * The type of the method handle will have a return type of the field's
1628         * value type.
1629         * If the field is static, the method handle will take no arguments.
1630         * Otherwise, its single argument will be the instance containing
1631         * the field.
1632         * If the field's {@code accessible} flag is not set,
1633         * access checking is performed immediately on behalf of the lookup class.
1634         * <p>
1635         * If the field is static, and
1636         * if the returned method handle is invoked, the field's class will
1637         * be initialized, if it has not already been initialized.
1638         * @param f the reflected field
1639         * @return a method handle which can load values from the reflected field
1640         * @throws IllegalAccessException if access checking fails
1641         * @throws NullPointerException if the argument is null
1642         */
1643        public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1644            return unreflectField(f, false);
1645        }
1646        private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1647            MemberName field = new MemberName(f, isSetter);
1648            assert(isSetter
1649                    ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1650                    : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1651            Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
1652            return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
1653        }
1654
1655        /**
1656         * Produces a method handle giving write access to a reflected field.
1657         * The type of the method handle will have a void return type.
1658         * If the field is static, the method handle will take a single
1659         * argument, of the field's value type, the value to be stored.
1660         * Otherwise, the two arguments will be the instance containing
1661         * the field, and the value to be stored.
1662         * If the field's {@code accessible} flag is not set,
1663         * access checking is performed immediately on behalf of the lookup class.
1664         * <p>
1665         * If the field is static, and
1666         * if the returned method handle is invoked, the field's class will
1667         * be initialized, if it has not already been initialized.
1668         * @param f the reflected field
1669         * @return a method handle which can store values into the reflected field
1670         * @throws IllegalAccessException if access checking fails
1671         * @throws NullPointerException if the argument is null
1672         */
1673        public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1674            return unreflectField(f, true);
1675        }
1676
1677        /**
1678         * Produces a VarHandle that accesses fields of type {@code T} declared
1679         * by a class of type {@code R}, as described by the given reflected
1680         * field.
1681         * If the field is non-static the VarHandle supports a shape of
1682         * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}.
1683         * <p>
1684         * Access checking is performed immediately on behalf of the lookup
1685         * class, regardless of the value of the field's {@code accessible}
1686         * flag.
1687         * <p>
1688         * If the field is static, and if the returned VarHandle is operated
1689         * on, the field's declaring class will be initialized, if it has not
1690         * already been initialized.
1691         * <p>
1692         * Certain access modes of the returned VarHandle are unsupported under
1693         * the following conditions:
1694         * <ul>
1695         * <li>if the field is declared {@code final}, then the write, atomic
1696         *     update, numeric atomic update, and bitwise atomic update access
1697         *     modes are unsupported.
1698         * <li>if the field type is anything other than {@code byte},
1699         *     {@code short}, {@code char}, {@code int}, {@code long},
1700         *     {@code float}, or {@code double} then numeric atomic update
1701         *     access modes are unsupported.
1702         * <li>if the field type is anything other than {@code boolean},
1703         *     {@code byte}, {@code short}, {@code char}, {@code int} or
1704         *     {@code long} then bitwise atomic update access modes are
1705         *     unsupported.
1706         * </ul>
1707         * <p>
1708         * If the field is declared {@code volatile} then the returned VarHandle
1709         * will override access to the field (effectively ignore the
1710         * {@code volatile} declaration) in accordance to it's specified
1711         * access modes.
1712         * <p>
1713         * If the field type is {@code float} or {@code double} then numeric
1714         * and atomic update access modes compare values using their bitwise
1715         * representation (see {@link Float#floatToRawIntBits} and
1716         * {@link Double#doubleToRawLongBits}, respectively).
1717         * @apiNote
1718         * Bitwise comparison of {@code float} values or {@code double} values,
1719         * as performed by the numeric and atomic update access modes, differ
1720         * from the primitive {@code ==} operator and the {@link Float#equals}
1721         * and {@link Double#equals} methods, specifically with respect to
1722         * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1723         * Care should be taken when performing a compare and set or a compare
1724         * and exchange operation with such values since the operation may
1725         * unexpectedly fail.
1726         * There are many possible NaN values that are considered to be
1727         * {@code NaN} in Java, although no IEEE 754 floating-point operation
1728         * provided by Java can distinguish between them.  Operation failure can
1729         * occur if the expected or witness value is a NaN value and it is
1730         * transformed (perhaps in a platform specific manner) into another NaN
1731         * value, and thus has a different bitwise representation (see
1732         * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1733         * details).
1734         * The values {@code -0.0} and {@code +0.0} have different bitwise
1735         * representations but are considered equal when using the primitive
1736         * {@code ==} operator.  Operation failure can occur if, for example, a
1737         * numeric algorithm computes an expected value to be say {@code -0.0}
1738         * and previously computed the witness value to be say {@code +0.0}.
1739         * @param f the reflected field, with a field of type {@code T}, and
1740         * a declaring class of type {@code R}
1741         * @return a VarHandle giving access to non-static fields or a static
1742         * field
1743         * @throws IllegalAccessException if access checking fails
1744         * @throws NullPointerException if the argument is null
1745         * @since 9
1746         */
1747        public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
1748            MemberName getField = new MemberName(f, false);
1749            MemberName putField = new MemberName(f, true);
1750            return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
1751                                                      f.getDeclaringClass(), getField, putField);
1752        }
1753
1754        /**
1755         * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1756         * created by this lookup object or a similar one.
1757         * Security and access checks are performed to ensure that this lookup object
1758         * is capable of reproducing the target method handle.
1759         * This means that the cracking may fail if target is a direct method handle
1760         * but was created by an unrelated lookup object.
1761         * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1762         * and was created by a lookup object for a different class.
1763         * @param target a direct method handle to crack into symbolic reference components
1764         * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1765         * @exception SecurityException if a security manager is present and it
1766         *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1767         * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1768         * @exception NullPointerException if the target is {@code null}
1769         * @see MethodHandleInfo
1770         * @since 1.8
1771         */
1772        public MethodHandleInfo revealDirect(MethodHandle target) {
1773            MemberName member = target.internalMemberName();
1774            if (member == null || (!member.isResolved() &&
1775                                   !member.isMethodHandleInvoke() &&
1776                                   !member.isVarHandleMethodInvoke()))
1777                throw newIllegalArgumentException("not a direct method handle");
1778            Class<?> defc = member.getDeclaringClass();
1779            byte refKind = member.getReferenceKind();
1780            assert(MethodHandleNatives.refKindIsValid(refKind));
1781            if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1782                // Devirtualized method invocation is usually formally virtual.
1783                // To avoid creating extra MemberName objects for this common case,
1784                // we encode this extra degree of freedom using MH.isInvokeSpecial.
1785                refKind = REF_invokeVirtual;
1786            if (refKind == REF_invokeVirtual && defc.isInterface())
1787                // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1788                refKind = REF_invokeInterface;
1789            // Check SM permissions and member access before cracking.
1790            try {
1791                checkAccess(refKind, defc, member);
1792                checkSecurityManager(defc, member);
1793            } catch (IllegalAccessException ex) {
1794                throw new IllegalArgumentException(ex);
1795            }
1796            if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1797                Class<?> callerClass = target.internalCallerClass();
1798                if (!hasPrivateAccess() || callerClass != lookupClass())
1799                    throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1800            }
1801            // Produce the handle to the results.
1802            return new InfoFromMemberName(this, member, refKind);
1803        }
1804
1805        /// Helper methods, all package-private.
1806
1807        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1808            checkSymbolicClass(refc);  // do this before attempting to resolve
1809            Objects.requireNonNull(name);
1810            Objects.requireNonNull(type);
1811            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1812                                            NoSuchFieldException.class);
1813        }
1814
1815        MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1816            checkSymbolicClass(refc);  // do this before attempting to resolve
1817            Objects.requireNonNull(name);
1818            Objects.requireNonNull(type);
1819            checkMethodName(refKind, name);  // NPE check on name
1820            return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
1821                                            NoSuchMethodException.class);
1822        }
1823
1824        MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1825            checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
1826            Objects.requireNonNull(member.getName());
1827            Objects.requireNonNull(member.getType());
1828            return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1829                                            ReflectiveOperationException.class);
1830        }
1831
1832        void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
1833            Objects.requireNonNull(refc);
1834            Class<?> caller = lookupClassOrNull();
1835            if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
1836                throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
1837        }
1838
1839        /** Check name for an illegal leading "&lt;" character. */
1840        void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1841            if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1842                throw new NoSuchMethodException("illegal method name: "+name);
1843        }
1844
1845
1846        /**
1847         * Find my trustable caller class if m is a caller sensitive method.
1848         * If this lookup object has private access, then the caller class is the lookupClass.
1849         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
1850         */
1851        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
1852            Class<?> callerClass = null;
1853            if (MethodHandleNatives.isCallerSensitive(m)) {
1854                // Only lookups with private access are allowed to resolve caller-sensitive methods
1855                if (hasPrivateAccess()) {
1856                    callerClass = lookupClass;
1857                } else {
1858                    throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1859                }
1860            }
1861            return callerClass;
1862        }
1863
1864        /**
1865         * Returns {@code true} if this lookup has {@code PRIVATE} access.
1866         * @return {@code true} if this lookup has {@code PRIVATE} acesss.
1867         * @since 9
1868         */
1869        public boolean hasPrivateAccess() {
1870            return (allowedModes & PRIVATE) != 0;
1871        }
1872
1873        /**
1874         * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1875         * Determines a trustable caller class to compare with refc, the symbolic reference class.
1876         * If this lookup object has private access, then the caller class is the lookupClass.
1877         */
1878        void checkSecurityManager(Class<?> refc, MemberName m) {
1879            SecurityManager smgr = System.getSecurityManager();
1880            if (smgr == null)  return;
1881            if (allowedModes == TRUSTED)  return;
1882
1883            // Step 1:
1884            boolean fullPowerLookup = hasPrivateAccess();
1885            if (!fullPowerLookup ||
1886                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1887                ReflectUtil.checkPackageAccess(refc);
1888            }
1889
1890            if (m == null) {  // findClass or accessClass
1891                // Step 2b:
1892                if (!fullPowerLookup) {
1893                    smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1894                }
1895                return;
1896            }
1897
1898            // Step 2a:
1899            if (m.isPublic()) return;
1900            if (!fullPowerLookup) {
1901                smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1902            }
1903
1904            // Step 3:
1905            Class<?> defc = m.getDeclaringClass();
1906            if (!fullPowerLookup && defc != refc) {
1907                ReflectUtil.checkPackageAccess(defc);
1908            }
1909        }
1910
1911        void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1912            boolean wantStatic = (refKind == REF_invokeStatic);
1913            String message;
1914            if (m.isConstructor())
1915                message = "expected a method, not a constructor";
1916            else if (!m.isMethod())
1917                message = "expected a method";
1918            else if (wantStatic != m.isStatic())
1919                message = wantStatic ? "expected a static method" : "expected a non-static method";
1920            else
1921                { checkAccess(refKind, refc, m); return; }
1922            throw m.makeAccessException(message, this);
1923        }
1924
1925        void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1926            boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1927            String message;
1928            if (wantStatic != m.isStatic())
1929                message = wantStatic ? "expected a static field" : "expected a non-static field";
1930            else
1931                { checkAccess(refKind, refc, m); return; }
1932            throw m.makeAccessException(message, this);
1933        }
1934
1935        /** Check public/protected/private bits on the symbolic reference class and its member. */
1936        void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1937            assert(m.referenceKindIsConsistentWith(refKind) &&
1938                   MethodHandleNatives.refKindIsValid(refKind) &&
1939                   (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
1940            int allowedModes = this.allowedModes;
1941            if (allowedModes == TRUSTED)  return;
1942            int mods = m.getModifiers();
1943            if (Modifier.isProtected(mods) &&
1944                    refKind == REF_invokeVirtual &&
1945                    m.getDeclaringClass() == Object.class &&
1946                    m.getName().equals("clone") &&
1947                    refc.isArray()) {
1948                // The JVM does this hack also.
1949                // (See ClassVerifier::verify_invoke_instructions
1950                // and LinkResolver::check_method_accessability.)
1951                // Because the JVM does not allow separate methods on array types,
1952                // there is no separate method for int[].clone.
1953                // All arrays simply inherit Object.clone.
1954                // But for access checking logic, we make Object.clone
1955                // (normally protected) appear to be public.
1956                // Later on, when the DirectMethodHandle is created,
1957                // its leading argument will be restricted to the
1958                // requested array type.
1959                // N.B. The return type is not adjusted, because
1960                // that is *not* the bytecode behavior.
1961                mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1962            }
1963            if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
1964                // cannot "new" a protected ctor in a different package
1965                mods ^= Modifier.PROTECTED;
1966            }
1967            if (Modifier.isFinal(mods) &&
1968                    MethodHandleNatives.refKindIsSetter(refKind))
1969                throw m.makeAccessException("unexpected set of a final field", this);
1970            int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
1971            if ((requestedModes & allowedModes) != 0) {
1972                if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1973                                                    mods, lookupClass(), allowedModes))
1974                    return;
1975            } else {
1976                // Protected members can also be checked as if they were package-private.
1977                if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1978                        && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1979                    return;
1980            }
1981            throw m.makeAccessException(accessFailedMessage(refc, m), this);
1982        }
1983
1984        String accessFailedMessage(Class<?> refc, MemberName m) {
1985            Class<?> defc = m.getDeclaringClass();
1986            int mods = m.getModifiers();
1987            // check the class first:
1988            boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1989                               (defc == refc ||
1990                                Modifier.isPublic(refc.getModifiers())));
1991            if (!classOK && (allowedModes & PACKAGE) != 0) {
1992                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1993                           (defc == refc ||
1994                            VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1995            }
1996            if (!classOK)
1997                return "class is not public";
1998            if (Modifier.isPublic(mods))
1999                return "access to public member failed";  // (how?, module not readable?)
2000            if (Modifier.isPrivate(mods))
2001                return "member is private";
2002            if (Modifier.isProtected(mods))
2003                return "member is protected";
2004            return "member is private to package";
2005        }
2006
2007        private static final boolean ALLOW_NESTMATE_ACCESS = false;
2008
2009        private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
2010            int allowedModes = this.allowedModes;
2011            if (allowedModes == TRUSTED)  return;
2012            if (!hasPrivateAccess()
2013                || (specialCaller != lookupClass()
2014                       // ensure non-abstract methods in superinterfaces can be special-invoked
2015                    && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
2016                    && !(ALLOW_NESTMATE_ACCESS &&
2017                         VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
2018                throw new MemberName(specialCaller).
2019                    makeAccessException("no private access for invokespecial", this);
2020        }
2021
2022        private boolean restrictProtectedReceiver(MemberName method) {
2023            // The accessing class only has the right to use a protected member
2024            // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
2025            if (!method.isProtected() || method.isStatic()
2026                || allowedModes == TRUSTED
2027                || method.getDeclaringClass() == lookupClass()
2028                || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
2029                || (ALLOW_NESTMATE_ACCESS &&
2030                    VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
2031                return false;
2032            return true;
2033        }
2034        private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
2035            assert(!method.isStatic());
2036            // receiver type of mh is too wide; narrow to caller
2037            if (!method.getDeclaringClass().isAssignableFrom(caller)) {
2038                throw method.makeAccessException("caller class must be a subclass below the method", caller);
2039            }
2040            MethodType rawType = mh.type();
2041            if (rawType.parameterType(0) == caller)  return mh;
2042            MethodType narrowType = rawType.changeParameterType(0, caller);
2043            assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
2044            assert(mh.viewAsTypeChecks(narrowType, true));
2045            return mh.copyWith(narrowType, mh.form);
2046        }
2047
2048        /** Check access and get the requested method. */
2049        private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
2050            final boolean doRestrict    = true;
2051            final boolean checkSecurity = true;
2052            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
2053        }
2054        /** Check access and get the requested method, eliding receiver narrowing rules. */
2055        private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
2056            final boolean doRestrict    = false;
2057            final boolean checkSecurity = true;
2058            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
2059        }
2060        /** Check access and get the requested method, eliding security manager checks. */
2061        private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
2062            final boolean doRestrict    = true;
2063            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2064            return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
2065        }
2066        /** Common code for all methods; do not call directly except from immediately above. */
2067        private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
2068                                                   boolean checkSecurity,
2069                                                   boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
2070            checkMethod(refKind, refc, method);
2071            // Optionally check with the security manager; this isn't needed for unreflect* calls.
2072            if (checkSecurity)
2073                checkSecurityManager(refc, method);
2074            assert(!method.isMethodHandleInvoke());
2075
2076            if (refKind == REF_invokeSpecial &&
2077                refc != lookupClass() &&
2078                !refc.isInterface() &&
2079                refc != lookupClass().getSuperclass() &&
2080                refc.isAssignableFrom(lookupClass())) {
2081                assert(!method.getName().equals("<init>"));  // not this code path
2082                // Per JVMS 6.5, desc. of invokespecial instruction:
2083                // If the method is in a superclass of the LC,
2084                // and if our original search was above LC.super,
2085                // repeat the search (symbolic lookup) from LC.super
2086                // and continue with the direct superclass of that class,
2087                // and so forth, until a match is found or no further superclasses exist.
2088                // FIXME: MemberName.resolve should handle this instead.
2089                Class<?> refcAsSuper = lookupClass();
2090                MemberName m2;
2091                do {
2092                    refcAsSuper = refcAsSuper.getSuperclass();
2093                    m2 = new MemberName(refcAsSuper,
2094                                        method.getName(),
2095                                        method.getMethodType(),
2096                                        REF_invokeSpecial);
2097                    m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
2098                } while (m2 == null &&         // no method is found yet
2099                         refc != refcAsSuper); // search up to refc
2100                if (m2 == null)  throw new InternalError(method.toString());
2101                method = m2;
2102                refc = refcAsSuper;
2103                // redo basic checks
2104                checkMethod(refKind, refc, method);
2105            }
2106
2107            DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
2108            MethodHandle mh = dmh;
2109            // Optionally narrow the receiver argument to refc using restrictReceiver.
2110            if (doRestrict &&
2111                   (refKind == REF_invokeSpecial ||
2112                       (MethodHandleNatives.refKindHasReceiver(refKind) &&
2113                           restrictProtectedReceiver(method)))) {
2114                mh = restrictReceiver(method, dmh, lookupClass());
2115            }
2116            mh = maybeBindCaller(method, mh, callerClass);
2117            mh = mh.setVarargs(method);
2118            return mh;
2119        }
2120        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
2121                                             Class<?> callerClass)
2122                                             throws IllegalAccessException {
2123            if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
2124                return mh;
2125            Class<?> hostClass = lookupClass;
2126            if (!hasPrivateAccess())  // caller must have private access
2127                hostClass = callerClass;  // callerClass came from a security manager style stack walk
2128            MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
2129            // Note: caller will apply varargs after this step happens.
2130            return cbmh;
2131        }
2132        /** Check access and get the requested field. */
2133        private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2134            final boolean checkSecurity = true;
2135            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2136        }
2137        /** Check access and get the requested field, eliding security manager checks. */
2138        private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2139            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2140            return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2141        }
2142        /** Common code for all fields; do not call directly except from immediately above. */
2143        private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
2144                                                  boolean checkSecurity) throws IllegalAccessException {
2145            checkField(refKind, refc, field);
2146            // Optionally check with the security manager; this isn't needed for unreflect* calls.
2147            if (checkSecurity)
2148                checkSecurityManager(refc, field);
2149            DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
2150            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
2151                                    restrictProtectedReceiver(field));
2152            if (doRestrict)
2153                return restrictReceiver(field, dmh, lookupClass());
2154            return dmh;
2155        }
2156        private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
2157                                            Class<?> refc, MemberName getField, MemberName putField)
2158                throws IllegalAccessException {
2159            final boolean checkSecurity = true;
2160            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2161        }
2162        private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
2163                                                             Class<?> refc, MemberName getField, MemberName putField)
2164                throws IllegalAccessException {
2165            final boolean checkSecurity = false;
2166            return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2167        }
2168        private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
2169                                                  Class<?> refc, MemberName getField, MemberName putField,
2170                                                  boolean checkSecurity) throws IllegalAccessException {
2171            assert getField.isStatic() == putField.isStatic();
2172            assert getField.isGetter() && putField.isSetter();
2173            assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
2174            assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
2175
2176            checkField(getRefKind, refc, getField);
2177            if (checkSecurity)
2178                checkSecurityManager(refc, getField);
2179
2180            if (!putField.isFinal()) {
2181                // A VarHandle does not support updates to final fields, any
2182                // such VarHandle to a final field will be read-only and
2183                // therefore the following write-based accessibility checks are
2184                // only required for non-final fields
2185                checkField(putRefKind, refc, putField);
2186                if (checkSecurity)
2187                    checkSecurityManager(refc, putField);
2188            }
2189
2190            boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
2191                                  restrictProtectedReceiver(getField));
2192            if (doRestrict) {
2193                assert !getField.isStatic();
2194                // receiver type of VarHandle is too wide; narrow to caller
2195                if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
2196                    throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
2197                }
2198                refc = lookupClass();
2199            }
2200            return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
2201        }
2202        /** Check access and get the requested constructor. */
2203        private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2204            final boolean checkSecurity = true;
2205            return getDirectConstructorCommon(refc, ctor, checkSecurity);
2206        }
2207        /** Check access and get the requested constructor, eliding security manager checks. */
2208        private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2209            final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
2210            return getDirectConstructorCommon(refc, ctor, checkSecurity);
2211        }
2212        /** Common code for all constructors; do not call directly except from immediately above. */
2213        private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
2214                                                  boolean checkSecurity) throws IllegalAccessException {
2215            assert(ctor.isConstructor());
2216            checkAccess(REF_newInvokeSpecial, refc, ctor);
2217            // Optionally check with the security manager; this isn't needed for unreflect* calls.
2218            if (checkSecurity)
2219                checkSecurityManager(refc, ctor);
2220            assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
2221            return DirectMethodHandle.make(ctor).setVarargs(ctor);
2222        }
2223
2224        /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
2225         */
2226        /*non-public*/
2227        MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
2228            if (!(type instanceof Class || type instanceof MethodType))
2229                throw new InternalError("unresolved MemberName");
2230            MemberName member = new MemberName(refKind, defc, name, type);
2231            MethodHandle mh = LOOKASIDE_TABLE.get(member);
2232            if (mh != null) {
2233                checkSymbolicClass(defc);
2234                return mh;
2235            }
2236            // Treat MethodHandle.invoke and invokeExact specially.
2237            if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
2238                mh = findVirtualForMH(member.getName(), member.getMethodType());
2239                if (mh != null) {
2240                    return mh;
2241                }
2242            }
2243            MemberName resolved = resolveOrFail(refKind, member);
2244            mh = getDirectMethodForConstant(refKind, defc, resolved);
2245            if (mh instanceof DirectMethodHandle
2246                    && canBeCached(refKind, defc, resolved)) {
2247                MemberName key = mh.internalMemberName();
2248                if (key != null) {
2249                    key = key.asNormalOriginal();
2250                }
2251                if (member.equals(key)) {  // better safe than sorry
2252                    LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
2253                }
2254            }
2255            return mh;
2256        }
2257        private
2258        boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
2259            if (refKind == REF_invokeSpecial) {
2260                return false;
2261            }
2262            if (!Modifier.isPublic(defc.getModifiers()) ||
2263                    !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
2264                    !member.isPublic() ||
2265                    member.isCallerSensitive()) {
2266                return false;
2267            }
2268            ClassLoader loader = defc.getClassLoader();
2269            if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
2270                ClassLoader sysl = ClassLoader.getSystemClassLoader();
2271                boolean found = false;
2272                while (sysl != null) {
2273                    if (loader == sysl) { found = true; break; }
2274                    sysl = sysl.getParent();
2275                }
2276                if (!found) {
2277                    return false;
2278                }
2279            }
2280            try {
2281                MemberName resolved2 = publicLookup().resolveOrFail(refKind,
2282                    new MemberName(refKind, defc, member.getName(), member.getType()));
2283                checkSecurityManager(defc, resolved2);
2284            } catch (ReflectiveOperationException | SecurityException ex) {
2285                return false;
2286            }
2287            return true;
2288        }
2289        private
2290        MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2291                throws ReflectiveOperationException {
2292            if (MethodHandleNatives.refKindIsField(refKind)) {
2293                return getDirectFieldNoSecurityManager(refKind, defc, member);
2294            } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
2295                return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
2296            } else if (refKind == REF_newInvokeSpecial) {
2297                return getDirectConstructorNoSecurityManager(defc, member);
2298            }
2299            // oops
2300            throw newIllegalArgumentException("bad MethodHandle constant #"+member);
2301        }
2302
2303        static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
2304    }
2305
2306    /**
2307     * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
2308     * in an <em>unnamed module</em>.
2309     *
2310     * @see Lookup#publicLookup
2311     */
2312    private static class LookupHelper {
2313        private static final String UNNAMED = "Unnamed";
2314        private static final String OBJECT  = "java/lang/Object";
2315
2316        private static Class<?> createClass() {
2317            try {
2318                ClassWriter cw = new ClassWriter(0);
2319                cw.visit(Opcodes.V1_8,
2320                         Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
2321                         UNNAMED,
2322                         null,
2323                         OBJECT,
2324                         null);
2325                cw.visitSource(UNNAMED, null);
2326                cw.visitEnd();
2327                byte[] bytes = cw.toByteArray();
2328                ClassLoader loader = new ClassLoader(null) {
2329                    @Override
2330                    protected Class<?> findClass(String cn) throws ClassNotFoundException {
2331                        if (cn.equals(UNNAMED))
2332                            return super.defineClass(UNNAMED, bytes, 0, bytes.length);
2333                        throw new ClassNotFoundException(cn);
2334                    }
2335                };
2336                return loader.loadClass(UNNAMED);
2337            } catch (Exception e) {
2338                throw new InternalError(e);
2339            }
2340        }
2341
2342        private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass();
2343
2344        /**
2345         * Lookup that is trusted minimally. It can only be used to create
2346         * method handles to publicly accessible members in exported packages.
2347         *
2348         * @see MethodHandles#publicLookup
2349         */
2350        static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
2351    }
2352
2353    /**
2354     * Produces a method handle constructing arrays of a desired type.
2355     * The return type of the method handle will be the array type.
2356     * The type of its sole argument will be {@code int}, which specifies the size of the array.
2357     * @param arrayClass an array type
2358     * @return a method handle which can create arrays of the given type
2359     * @throws NullPointerException if the argument is {@code null}
2360     * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2361     * @see java.lang.reflect.Array#newInstance(Class, int)
2362     * @since 9
2363     */
2364    public static
2365    MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2366        if (!arrayClass.isArray()) {
2367            throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2368        }
2369        MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2370                bindTo(arrayClass.getComponentType());
2371        return ani.asType(ani.type().changeReturnType(arrayClass));
2372    }
2373
2374    /**
2375     * Produces a method handle returning the length of an array.
2376     * The type of the method handle will have {@code int} as return type,
2377     * and its sole argument will be the array type.
2378     * @param arrayClass an array type
2379     * @return a method handle which can retrieve the length of an array of the given array type
2380     * @throws NullPointerException if the argument is {@code null}
2381     * @throws IllegalArgumentException if arrayClass is not an array type
2382     * @since 9
2383     */
2384    public static
2385    MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
2386        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
2387    }
2388
2389    /**
2390     * Produces a method handle giving read access to elements of an array.
2391     * The type of the method handle will have a return type of the array's
2392     * element type.  Its first argument will be the array type,
2393     * and the second will be {@code int}.
2394     * @param arrayClass an array type
2395     * @return a method handle which can load values from the given array type
2396     * @throws NullPointerException if the argument is null
2397     * @throws  IllegalArgumentException if arrayClass is not an array type
2398     */
2399    public static
2400    MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2401        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
2402    }
2403
2404    /**
2405     * Produces a method handle giving write access to elements of an array.
2406     * The type of the method handle will have a void return type.
2407     * Its last argument will be the array's element type.
2408     * The first and second arguments will be the array type and int.
2409     * @param arrayClass the class of an array
2410     * @return a method handle which can store values into the array type
2411     * @throws NullPointerException if the argument is null
2412     * @throws IllegalArgumentException if arrayClass is not an array type
2413     */
2414    public static
2415    MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2416        return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
2417    }
2418
2419    /**
2420     *
2421     * Produces a VarHandle giving access to elements of an array type
2422     * {@code T[]}, supporting shape {@code (T[], int : T)}.
2423     * <p>
2424     * Certain access modes of the returned VarHandle are unsupported under
2425     * the following conditions:
2426     * <ul>
2427     * <li>if the component type is anything other than {@code byte},
2428     *     {@code short}, {@code char}, {@code int}, {@code long},
2429     *     {@code float}, or {@code double} then numeric atomic update access
2430     *     modes are unsupported.
2431     * <li>if the field type is anything other than {@code boolean},
2432     *     {@code byte}, {@code short}, {@code char}, {@code int} or
2433     *     {@code long} then bitwise atomic update access modes are
2434     *     unsupported.
2435     * </ul>
2436     * <p>
2437     * If the component type is {@code float} or {@code double} then numeric
2438     * and atomic update access modes compare values using their bitwise
2439     * representation (see {@link Float#floatToRawIntBits} and
2440     * {@link Double#doubleToRawLongBits}, respectively).
2441     * @apiNote
2442     * Bitwise comparison of {@code float} values or {@code double} values,
2443     * as performed by the numeric and atomic update access modes, differ
2444     * from the primitive {@code ==} operator and the {@link Float#equals}
2445     * and {@link Double#equals} methods, specifically with respect to
2446     * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2447     * Care should be taken when performing a compare and set or a compare
2448     * and exchange operation with such values since the operation may
2449     * unexpectedly fail.
2450     * There are many possible NaN values that are considered to be
2451     * {@code NaN} in Java, although no IEEE 754 floating-point operation
2452     * provided by Java can distinguish between them.  Operation failure can
2453     * occur if the expected or witness value is a NaN value and it is
2454     * transformed (perhaps in a platform specific manner) into another NaN
2455     * value, and thus has a different bitwise representation (see
2456     * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2457     * details).
2458     * The values {@code -0.0} and {@code +0.0} have different bitwise
2459     * representations but are considered equal when using the primitive
2460     * {@code ==} operator.  Operation failure can occur if, for example, a
2461     * numeric algorithm computes an expected value to be say {@code -0.0}
2462     * and previously computed the witness value to be say {@code +0.0}.
2463     * @param arrayClass the class of an array, of type {@code T[]}
2464     * @return a VarHandle giving access to elements of an array
2465     * @throws NullPointerException if the arrayClass is null
2466     * @throws IllegalArgumentException if arrayClass is not an array type
2467     * @since 9
2468     */
2469    public static
2470    VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2471        return VarHandles.makeArrayElementHandle(arrayClass);
2472    }
2473
2474    /**
2475     * Produces a VarHandle giving access to elements of a {@code byte[]} array
2476     * viewed as if it were a different primitive array type, such as
2477     * {@code int[]} or {@code long[]}.  The shape of the resulting VarHandle is
2478     * {@code (byte[], int : T)}, where the {@code int} coordinate type
2479     * corresponds to an argument that is an index in a {@code byte[]} array,
2480     * and {@code T} is the component type of the given view array class.  The
2481     * returned VarHandle accesses bytes at an index in a {@code byte[]} array,
2482     * composing bytes to or from a value of {@code T} according to the given
2483     * endianness.
2484     * <p>
2485     * The supported component types (variables types) are {@code short},
2486     * {@code char}, {@code int}, {@code long}, {@code float} and
2487     * {@code double}.
2488     * <p>
2489     * Access of bytes at a given index will result in an
2490     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2491     * or greater than the {@code byte[]} array length minus the size (in bytes)
2492     * of {@code T}.
2493     * <p>
2494     * Access of bytes at an index may be aligned or misaligned for {@code T},
2495     * with respect to the underlying memory address, {@code A} say, associated
2496     * with the array and index.
2497     * If access is misaligned then access for anything other than the
2498     * {@code get} and {@code set} access modes will result in an
2499     * {@code IllegalStateException}.  In such cases atomic access is only
2500     * guaranteed with respect to the largest power of two that divides the GCD
2501     * of {@code A} and the size (in bytes) of {@code T}.
2502     * If access is aligned then following access modes are supported and are
2503     * guaranteed to support atomic access:
2504     * <ul>
2505     * <li>read write access modes for all {@code T}, with the exception of
2506     *     access modes {@code get} and {@code set} for {@code long} and
2507     *     {@code double} on 32-bit platforms.
2508     * <li>atomic update access modes for {@code int}, {@code long},
2509     *     {@code float} or {@code double}.
2510     *     (Future major platform releases of the JDK may support additional
2511     *     types for certain currently unsupported access modes.)
2512     * <li>numeric atomic update access modes for {@code int} and {@code long}.
2513     *     (Future major platform releases of the JDK may support additional
2514     *     numeric types for certain currently unsupported access modes.)
2515     * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2516     *     (Future major platform releases of the JDK may support additional
2517     *     numeric types for certain currently unsupported access modes.)
2518     * </ul>
2519     * <p>
2520     * Misaligned access, and therefore atomicity guarantees, may be determined
2521     * for {@code byte[]} arrays without operating on a specific array.  Given
2522     * an {@code index}, {@code T} and it's corresponding boxed type,
2523     * {@code T_BOX}, misalignment may be determined as follows:
2524     * <pre>{@code
2525     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2526     * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2527     *     alignmentOffset(0, sizeOfT);
2528     * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2529     * boolean isMisaligned = misalignedAtIndex != 0;
2530     * }</pre>
2531     * <p>
2532     * If the variable type is {@code float} or {@code double} then atomic
2533     * update access modes compare values using their bitwise representation
2534     * (see {@link Float#floatToRawIntBits} and
2535     * {@link Double#doubleToRawLongBits}, respectively).
2536     * @param viewArrayClass the view array class, with a component type of
2537     * type {@code T}
2538     * @param byteOrder the endianness of the view array elements, as
2539     * stored in the underlying {@code byte} array
2540     * @return a VarHandle giving access to elements of a {@code byte[]} array
2541     * viewed as if elements corresponding to the components type of the view
2542     * array class
2543     * @throws NullPointerException if viewArrayClass or byteOrder is null
2544     * @throws IllegalArgumentException if viewArrayClass is not an array type
2545     * @throws UnsupportedOperationException if the component type of
2546     * viewArrayClass is not supported as a variable type
2547     * @since 9
2548     */
2549    public static
2550    VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
2551                                     ByteOrder byteOrder) throws IllegalArgumentException {
2552        Objects.requireNonNull(byteOrder);
2553        return VarHandles.byteArrayViewHandle(viewArrayClass,
2554                                              byteOrder == ByteOrder.BIG_ENDIAN);
2555    }
2556
2557    /**
2558     * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2559     * viewed as if it were an array of elements of a different primitive
2560     * component type to that of {@code byte}, such as {@code int[]} or
2561     * {@code long[]}.  The shape of the resulting VarHandle is
2562     * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type
2563     * corresponds to an argument that is an index in a {@code ByteBuffer}, and
2564     * {@code T} is the component type of the given view array class.  The
2565     * returned VarHandle accesses bytes at an index in a {@code ByteBuffer},
2566     * composing bytes to or from a value of {@code T} according to the given
2567     * endianness.
2568     * <p>
2569     * The supported component types (variables types) are {@code short},
2570     * {@code char}, {@code int}, {@code long}, {@code float} and
2571     * {@code double}.
2572     * <p>
2573     * Access will result in a {@code ReadOnlyBufferException} for anything
2574     * other than the read access modes if the {@code ByteBuffer} is read-only.
2575     * <p>
2576     * Access of bytes at a given index will result in an
2577     * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2578     * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2579     * {@code T}.
2580     * <p>
2581     * Access of bytes at an index may be aligned or misaligned for {@code T},
2582     * with respect to the underlying memory address, {@code A} say, associated
2583     * with the {@code ByteBuffer} and index.
2584     * If access is misaligned then access for anything other than the
2585     * {@code get} and {@code set} access modes will result in an
2586     * {@code IllegalStateException}.  In such cases atomic access is only
2587     * guaranteed with respect to the largest power of two that divides the GCD
2588     * of {@code A} and the size (in bytes) of {@code T}.
2589     * If access is aligned then following access modes are supported and are
2590     * guaranteed to support atomic access:
2591     * <ul>
2592     * <li>read write access modes for all {@code T}, with the exception of
2593     *     access modes {@code get} and {@code set} for {@code long} and
2594     *     {@code double} on 32-bit platforms.
2595     * <li>atomic update access modes for {@code int}, {@code long},
2596     *     {@code float} or {@code double}.
2597     *     (Future major platform releases of the JDK may support additional
2598     *     types for certain currently unsupported access modes.)
2599     * <li>numeric atomic update access modes for {@code int} and {@code long}.
2600     *     (Future major platform releases of the JDK may support additional
2601     *     numeric types for certain currently unsupported access modes.)
2602     * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2603     *     (Future major platform releases of the JDK may support additional
2604     *     numeric types for certain currently unsupported access modes.)
2605     * </ul>
2606     * <p>
2607     * Misaligned access, and therefore atomicity guarantees, may be determined
2608     * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2609     * {@code index}, {@code T} and it's corresponding boxed type,
2610     * {@code T_BOX}, as follows:
2611     * <pre>{@code
2612     * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
2613     * ByteBuffer bb = ...
2614     * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2615     * boolean isMisaligned = misalignedAtIndex != 0;
2616     * }</pre>
2617     * <p>
2618     * If the variable type is {@code float} or {@code double} then atomic
2619     * update access modes compare values using their bitwise representation
2620     * (see {@link Float#floatToRawIntBits} and
2621     * {@link Double#doubleToRawLongBits}, respectively).
2622     * @param viewArrayClass the view array class, with a component type of
2623     * type {@code T}
2624     * @param byteOrder the endianness of the view array elements, as
2625     * stored in the underlying {@code ByteBuffer} (Note this overrides the
2626     * endianness of a {@code ByteBuffer})
2627     * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2628     * viewed as if elements corresponding to the components type of the view
2629     * array class
2630     * @throws NullPointerException if viewArrayClass or byteOrder is null
2631     * @throws IllegalArgumentException if viewArrayClass is not an array type
2632     * @throws UnsupportedOperationException if the component type of
2633     * viewArrayClass is not supported as a variable type
2634     * @since 9
2635     */
2636    public static
2637    VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
2638                                      ByteOrder byteOrder) throws IllegalArgumentException {
2639        Objects.requireNonNull(byteOrder);
2640        return VarHandles.makeByteBufferViewHandle(viewArrayClass,
2641                                                   byteOrder == ByteOrder.BIG_ENDIAN);
2642    }
2643
2644
2645    /// method handle invocation (reflective style)
2646
2647    /**
2648     * Produces a method handle which will invoke any method handle of the
2649     * given {@code type}, with a given number of trailing arguments replaced by
2650     * a single trailing {@code Object[]} array.
2651     * The resulting invoker will be a method handle with the following
2652     * arguments:
2653     * <ul>
2654     * <li>a single {@code MethodHandle} target
2655     * <li>zero or more leading values (counted by {@code leadingArgCount})
2656     * <li>an {@code Object[]} array containing trailing arguments
2657     * </ul>
2658     * <p>
2659     * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
2660     * the indicated {@code type}.
2661     * That is, if the target is exactly of the given {@code type}, it will behave
2662     * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
2663     * is used to convert the target to the required {@code type}.
2664     * <p>
2665     * The type of the returned invoker will not be the given {@code type}, but rather
2666     * will have all parameters except the first {@code leadingArgCount}
2667     * replaced by a single array of type {@code Object[]}, which will be
2668     * the final parameter.
2669     * <p>
2670     * Before invoking its target, the invoker will spread the final array, apply
2671     * reference casts as necessary, and unbox and widen primitive arguments.
2672     * If, when the invoker is called, the supplied array argument does
2673     * not have the correct number of elements, the invoker will throw
2674     * an {@link IllegalArgumentException} instead of invoking the target.
2675     * <p>
2676     * This method is equivalent to the following code (though it may be more efficient):
2677     * <blockquote><pre>{@code
2678MethodHandle invoker = MethodHandles.invoker(type);
2679int spreadArgCount = type.parameterCount() - leadingArgCount;
2680invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2681return invoker;
2682     * }</pre></blockquote>
2683     * This method throws no reflective or security exceptions.
2684     * @param type the desired target type
2685     * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2686     * @return a method handle suitable for invoking any method handle of the given type
2687     * @throws NullPointerException if {@code type} is null
2688     * @throws IllegalArgumentException if {@code leadingArgCount} is not in
2689     *                  the range from 0 to {@code type.parameterCount()} inclusive,
2690     *                  or if the resulting method handle's type would have
2691     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2692     */
2693    public static
2694    MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2695        if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
2696            throw newIllegalArgumentException("bad argument count", leadingArgCount);
2697        type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
2698        return type.invokers().spreadInvoker(leadingArgCount);
2699    }
2700
2701    /**
2702     * Produces a special <em>invoker method handle</em> which can be used to
2703     * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
2704     * The resulting invoker will have a type which is
2705     * exactly equal to the desired type, except that it will accept
2706     * an additional leading argument of type {@code MethodHandle}.
2707     * <p>
2708     * This method is equivalent to the following code (though it may be more efficient):
2709     * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
2710     *
2711     * <p style="font-size:smaller;">
2712     * <em>Discussion:</em>
2713     * Invoker method handles can be useful when working with variable method handles
2714     * of unknown types.
2715     * For example, to emulate an {@code invokeExact} call to a variable method
2716     * handle {@code M}, extract its type {@code T},
2717     * look up the invoker method {@code X} for {@code T},
2718     * and call the invoker method, as {@code X.invoke(T, A...)}.
2719     * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2720     * is unknown.)
2721     * If spreading, collecting, or other argument transformations are required,
2722     * they can be applied once to the invoker {@code X} and reused on many {@code M}
2723     * method handle values, as long as they are compatible with the type of {@code X}.
2724     * <p style="font-size:smaller;">
2725     * <em>(Note:  The invoker method is not available via the Core Reflection API.
2726     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2727     * on the declared {@code invokeExact} or {@code invoke} method will raise an
2728     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2729     * <p>
2730     * This method throws no reflective or security exceptions.
2731     * @param type the desired target type
2732     * @return a method handle suitable for invoking any method handle of the given type
2733     * @throws IllegalArgumentException if the resulting method handle's type would have
2734     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2735     */
2736    public static
2737    MethodHandle exactInvoker(MethodType type) {
2738        return type.invokers().exactInvoker();
2739    }
2740
2741    /**
2742     * Produces a special <em>invoker method handle</em> which can be used to
2743     * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2744     * The resulting invoker will have a type which is
2745     * exactly equal to the desired type, except that it will accept
2746     * an additional leading argument of type {@code MethodHandle}.
2747     * <p>
2748     * Before invoking its target, if the target differs from the expected type,
2749     * the invoker will apply reference casts as
2750     * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2751     * Similarly, the return value will be converted as necessary.
2752     * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2753     * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2754     * <p>
2755     * This method is equivalent to the following code (though it may be more efficient):
2756     * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2757     * <p style="font-size:smaller;">
2758     * <em>Discussion:</em>
2759     * A {@linkplain MethodType#genericMethodType general method type} is one which
2760     * mentions only {@code Object} arguments and return values.
2761     * An invoker for such a type is capable of calling any method handle
2762     * of the same arity as the general type.
2763     * <p style="font-size:smaller;">
2764     * <em>(Note:  The invoker method is not available via the Core Reflection API.
2765     * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2766     * on the declared {@code invokeExact} or {@code invoke} method will raise an
2767     * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2768     * <p>
2769     * This method throws no reflective or security exceptions.
2770     * @param type the desired target type
2771     * @return a method handle suitable for invoking any method handle convertible to the given type
2772     * @throws IllegalArgumentException if the resulting method handle's type would have
2773     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
2774     */
2775    public static
2776    MethodHandle invoker(MethodType type) {
2777        return type.invokers().genericInvoker();
2778    }
2779
2780    /**
2781     * Produces a special <em>invoker method handle</em> which can be used to
2782     * invoke a signature-polymorphic access mode method on any VarHandle whose
2783     * associated access mode type is compatible with the given type.
2784     * The resulting invoker will have a type which is exactly equal to the
2785     * desired given type, except that it will accept an additional leading
2786     * argument of type {@code VarHandle}.
2787     *
2788     * @param accessMode the VarHandle access mode
2789     * @param type the desired target type
2790     * @return a method handle suitable for invoking an access mode method of
2791     *         any VarHandle whose access mode type is of the given type.
2792     * @since 9
2793     */
2794    static public
2795    MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2796        return type.invokers().varHandleMethodExactInvoker(accessMode);
2797    }
2798
2799    /**
2800     * Produces a special <em>invoker method handle</em> which can be used to
2801     * invoke a signature-polymorphic access mode method on any VarHandle whose
2802     * associated access mode type is compatible with the given type.
2803     * The resulting invoker will have a type which is exactly equal to the
2804     * desired given type, except that it will accept an additional leading
2805     * argument of type {@code VarHandle}.
2806     * <p>
2807     * Before invoking its target, if the access mode type differs from the
2808     * desired given type, the invoker will apply reference casts as necessary
2809     * and box, unbox, or widen primitive values, as if by
2810     * {@link MethodHandle#asType asType}.  Similarly, the return value will be
2811     * converted as necessary.
2812     * <p>
2813     * This method is equivalent to the following code (though it may be more
2814     * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2815     *
2816     * @param accessMode the VarHandle access mode
2817     * @param type the desired target type
2818     * @return a method handle suitable for invoking an access mode method of
2819     *         any VarHandle whose access mode type is convertible to the given
2820     *         type.
2821     * @since 9
2822     */
2823    static public
2824    MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2825        return type.invokers().varHandleMethodInvoker(accessMode);
2826    }
2827
2828    static /*non-public*/
2829    MethodHandle basicInvoker(MethodType type) {
2830        return type.invokers().basicInvoker();
2831    }
2832
2833     /// method handle modification (creation from other method handles)
2834
2835    /**
2836     * Produces a method handle which adapts the type of the
2837     * given method handle to a new type by pairwise argument and return type conversion.
2838     * The original type and new type must have the same number of arguments.
2839     * The resulting method handle is guaranteed to report a type
2840     * which is equal to the desired new type.
2841     * <p>
2842     * If the original type and new type are equal, returns target.
2843     * <p>
2844     * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2845     * and some additional conversions are also applied if those conversions fail.
2846     * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2847     * if possible, before or instead of any conversions done by {@code asType}:
2848     * <ul>
2849     * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2850     *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2851     *     (This treatment of interfaces follows the usage of the bytecode verifier.)
2852     * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2853     *     the boolean is converted to a byte value, 1 for true, 0 for false.
2854     *     (This treatment follows the usage of the bytecode verifier.)
2855     * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2856     *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2857     *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2858     * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2859     *     then a Java casting conversion (JLS 5.5) is applied.
2860     *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
2861     *     widening and/or narrowing.)
2862     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2863     *     conversion will be applied at runtime, possibly followed
2864     *     by a Java casting conversion (JLS 5.5) on the primitive value,
2865     *     possibly followed by a conversion from byte to boolean by testing
2866     *     the low-order bit.
2867     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2868     *     and if the reference is null at runtime, a zero value is introduced.
2869     * </ul>
2870     * @param target the method handle to invoke after arguments are retyped
2871     * @param newType the expected type of the new method handle
2872     * @return a method handle which delegates to the target after performing
2873     *           any necessary argument conversions, and arranges for any
2874     *           necessary return value conversions
2875     * @throws NullPointerException if either argument is null
2876     * @throws WrongMethodTypeException if the conversion cannot be made
2877     * @see MethodHandle#asType
2878     */
2879    public static
2880    MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2881        explicitCastArgumentsChecks(target, newType);
2882        // use the asTypeCache when possible:
2883        MethodType oldType = target.type();
2884        if (oldType == newType)  return target;
2885        if (oldType.explicitCastEquivalentToAsType(newType)) {
2886            return target.asFixedArity().asType(newType);
2887        }
2888        return MethodHandleImpl.makePairwiseConvert(target, newType, false);
2889    }
2890
2891    private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2892        if (target.type().parameterCount() != newType.parameterCount()) {
2893            throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2894        }
2895    }
2896
2897    /**
2898     * Produces a method handle which adapts the calling sequence of the
2899     * given method handle to a new type, by reordering the arguments.
2900     * The resulting method handle is guaranteed to report a type
2901     * which is equal to the desired new type.
2902     * <p>
2903     * The given array controls the reordering.
2904     * Call {@code #I} the number of incoming parameters (the value
2905     * {@code newType.parameterCount()}, and call {@code #O} the number
2906     * of outgoing parameters (the value {@code target.type().parameterCount()}).
2907     * Then the length of the reordering array must be {@code #O},
2908     * and each element must be a non-negative number less than {@code #I}.
2909     * For every {@code N} less than {@code #O}, the {@code N}-th
2910     * outgoing argument will be taken from the {@code I}-th incoming
2911     * argument, where {@code I} is {@code reorder[N]}.
2912     * <p>
2913     * No argument or return value conversions are applied.
2914     * The type of each incoming argument, as determined by {@code newType},
2915     * must be identical to the type of the corresponding outgoing parameter
2916     * or parameters in the target method handle.
2917     * The return type of {@code newType} must be identical to the return
2918     * type of the original target.
2919     * <p>
2920     * The reordering array need not specify an actual permutation.
2921     * An incoming argument will be duplicated if its index appears
2922     * more than once in the array, and an incoming argument will be dropped
2923     * if its index does not appear in the array.
2924     * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2925     * incoming arguments which are not mentioned in the reordering array
2926     * may be of any type, as determined only by {@code newType}.
2927     * <blockquote><pre>{@code
2928import static java.lang.invoke.MethodHandles.*;
2929import static java.lang.invoke.MethodType.*;
2930...
2931MethodType intfn1 = methodType(int.class, int.class);
2932MethodType intfn2 = methodType(int.class, int.class, int.class);
2933MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2934assert(sub.type().equals(intfn2));
2935MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2936MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2937assert((int)rsub.invokeExact(1, 100) == 99);
2938MethodHandle add = ... (int x, int y) -> (x+y) ...;
2939assert(add.type().equals(intfn2));
2940MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2941assert(twice.type().equals(intfn1));
2942assert((int)twice.invokeExact(21) == 42);
2943     * }</pre></blockquote>
2944     * <p>
2945     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
2946     * variable-arity method handle}, even if the original target method handle was.
2947     * @param target the method handle to invoke after arguments are reordered
2948     * @param newType the expected type of the new method handle
2949     * @param reorder an index array which controls the reordering
2950     * @return a method handle which delegates to the target after it
2951     *           drops unused arguments and moves and/or duplicates the other arguments
2952     * @throws NullPointerException if any argument is null
2953     * @throws IllegalArgumentException if the index array length is not equal to
2954     *                  the arity of the target, or if any index array element
2955     *                  not a valid index for a parameter of {@code newType},
2956     *                  or if two corresponding parameter types in
2957     *                  {@code target.type()} and {@code newType} are not identical,
2958     */
2959    public static
2960    MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2961        reorder = reorder.clone();  // get a private copy
2962        MethodType oldType = target.type();
2963        permuteArgumentChecks(reorder, newType, oldType);
2964        // first detect dropped arguments and handle them separately
2965        int[] originalReorder = reorder;
2966        BoundMethodHandle result = target.rebind();
2967        LambdaForm form = result.form;
2968        int newArity = newType.parameterCount();
2969        // Normalize the reordering into a real permutation,
2970        // by removing duplicates and adding dropped elements.
2971        // This somewhat improves lambda form caching, as well
2972        // as simplifying the transform by breaking it up into steps.
2973        for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
2974            if (ddIdx > 0) {
2975                // We found a duplicated entry at reorder[ddIdx].
2976                // Example:  (x,y,z)->asList(x,y,z)
2977                // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
2978                // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
2979                // The starred element corresponds to the argument
2980                // deleted by the dupArgumentForm transform.
2981                int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
2982                boolean killFirst = false;
2983                for (int val; (val = reorder[--dstPos]) != dupVal; ) {
2984                    // Set killFirst if the dup is larger than an intervening position.
2985                    // This will remove at least one inversion from the permutation.
2986                    if (dupVal > val) killFirst = true;
2987                }
2988                if (!killFirst) {
2989                    srcPos = dstPos;
2990                    dstPos = ddIdx;
2991                }
2992                form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
2993                assert (reorder[srcPos] == reorder[dstPos]);
2994                oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
2995                // contract the reordering by removing the element at dstPos
2996                int tailPos = dstPos + 1;
2997                System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
2998                reorder = Arrays.copyOf(reorder, reorder.length - 1);
2999            } else {
3000                int dropVal = ~ddIdx, insPos = 0;
3001                while (insPos < reorder.length && reorder[insPos] < dropVal) {
3002                    // Find first element of reorder larger than dropVal.
3003                    // This is where we will insert the dropVal.
3004                    insPos += 1;
3005                }
3006                Class<?> ptype = newType.parameterType(dropVal);
3007                form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
3008                oldType = oldType.insertParameterTypes(insPos, ptype);
3009                // expand the reordering by inserting an element at insPos
3010                int tailPos = insPos + 1;
3011                reorder = Arrays.copyOf(reorder, reorder.length + 1);
3012                System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
3013                reorder[insPos] = dropVal;
3014            }
3015            assert (permuteArgumentChecks(reorder, newType, oldType));
3016        }
3017        assert (reorder.length == newArity);  // a perfect permutation
3018        // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
3019        form = form.editor().permuteArgumentsForm(1, reorder);
3020        if (newType == result.type() && form == result.internalForm())
3021            return result;
3022        return result.copyWith(newType, form);
3023    }
3024
3025    /**
3026     * Return an indication of any duplicate or omission in reorder.
3027     * If the reorder contains a duplicate entry, return the index of the second occurrence.
3028     * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
3029     * Otherwise, return zero.
3030     * If an element not in [0..newArity-1] is encountered, return reorder.length.
3031     */
3032    private static int findFirstDupOrDrop(int[] reorder, int newArity) {
3033        final int BIT_LIMIT = 63;  // max number of bits in bit mask
3034        if (newArity < BIT_LIMIT) {
3035            long mask = 0;
3036            for (int i = 0; i < reorder.length; i++) {
3037                int arg = reorder[i];
3038                if (arg >= newArity) {
3039                    return reorder.length;
3040                }
3041                long bit = 1L << arg;
3042                if ((mask & bit) != 0) {
3043                    return i;  // >0 indicates a dup
3044                }
3045                mask |= bit;
3046            }
3047            if (mask == (1L << newArity) - 1) {
3048                assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
3049                return 0;
3050            }
3051            // find first zero
3052            long zeroBit = Long.lowestOneBit(~mask);
3053            int zeroPos = Long.numberOfTrailingZeros(zeroBit);
3054            assert(zeroPos <= newArity);
3055            if (zeroPos == newArity) {
3056                return 0;
3057            }
3058            return ~zeroPos;
3059        } else {
3060            // same algorithm, different bit set
3061            BitSet mask = new BitSet(newArity);
3062            for (int i = 0; i < reorder.length; i++) {
3063                int arg = reorder[i];
3064                if (arg >= newArity) {
3065                    return reorder.length;
3066                }
3067                if (mask.get(arg)) {
3068                    return i;  // >0 indicates a dup
3069                }
3070                mask.set(arg);
3071            }
3072            int zeroPos = mask.nextClearBit(0);
3073            assert(zeroPos <= newArity);
3074            if (zeroPos == newArity) {
3075                return 0;
3076            }
3077            return ~zeroPos;
3078        }
3079    }
3080
3081    private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
3082        if (newType.returnType() != oldType.returnType())
3083            throw newIllegalArgumentException("return types do not match",
3084                    oldType, newType);
3085        if (reorder.length == oldType.parameterCount()) {
3086            int limit = newType.parameterCount();
3087            boolean bad = false;
3088            for (int j = 0; j < reorder.length; j++) {
3089                int i = reorder[j];
3090                if (i < 0 || i >= limit) {
3091                    bad = true; break;
3092                }
3093                Class<?> src = newType.parameterType(i);
3094                Class<?> dst = oldType.parameterType(j);
3095                if (src != dst)
3096                    throw newIllegalArgumentException("parameter types do not match after reorder",
3097                            oldType, newType);
3098            }
3099            if (!bad)  return true;
3100        }
3101        throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
3102    }
3103
3104    /**
3105     * Produces a method handle of the requested return type which returns the given
3106     * constant value every time it is invoked.
3107     * <p>
3108     * Before the method handle is returned, the passed-in value is converted to the requested type.
3109     * If the requested type is primitive, widening primitive conversions are attempted,
3110     * else reference conversions are attempted.
3111     * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
3112     * @param type the return type of the desired method handle
3113     * @param value the value to return
3114     * @return a method handle of the given return type and no arguments, which always returns the given value
3115     * @throws NullPointerException if the {@code type} argument is null
3116     * @throws ClassCastException if the value cannot be converted to the required return type
3117     * @throws IllegalArgumentException if the given type is {@code void.class}
3118     */
3119    public static
3120    MethodHandle constant(Class<?> type, Object value) {
3121        if (type.isPrimitive()) {
3122            if (type == void.class)
3123                throw newIllegalArgumentException("void type");
3124            Wrapper w = Wrapper.forPrimitiveType(type);
3125            value = w.convert(value, type);
3126            if (w.zero().equals(value))
3127                return zero(w, type);
3128            return insertArguments(identity(type), 0, value);
3129        } else {
3130            if (value == null)
3131                return zero(Wrapper.OBJECT, type);
3132            return identity(type).bindTo(value);
3133        }
3134    }
3135
3136    /**
3137     * Produces a method handle which returns its sole argument when invoked.
3138     * @param type the type of the sole parameter and return value of the desired method handle
3139     * @return a unary method handle which accepts and returns the given type
3140     * @throws NullPointerException if the argument is null
3141     * @throws IllegalArgumentException if the given type is {@code void.class}
3142     */
3143    public static
3144    MethodHandle identity(Class<?> type) {
3145        Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
3146        int pos = btw.ordinal();
3147        MethodHandle ident = IDENTITY_MHS[pos];
3148        if (ident == null) {
3149            ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
3150        }
3151        if (ident.type().returnType() == type)
3152            return ident;
3153        // something like identity(Foo.class); do not bother to intern these
3154        assert (btw == Wrapper.OBJECT);
3155        return makeIdentity(type);
3156    }
3157
3158    /**
3159     * Produces a constant method handle of the requested return type which
3160     * returns the default value for that type every time it is invoked.
3161     * The resulting constant method handle will have no side effects.
3162     * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
3163     * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
3164     * since {@code explicitCastArguments} converts {@code null} to default values.
3165     * @param type the expected return type of the desired method handle
3166     * @return a constant method handle that takes no arguments
3167     *         and returns the default value of the given type (or void, if the type is void)
3168     * @throws NullPointerException if the argument is null
3169     * @see MethodHandles#constant
3170     * @see MethodHandles#empty
3171     * @see MethodHandles#explicitCastArguments
3172     * @since 9
3173     */
3174    public static MethodHandle zero(Class<?> type) {
3175        Objects.requireNonNull(type);
3176        return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3177    }
3178
3179    private static MethodHandle identityOrVoid(Class<?> type) {
3180        return type == void.class ? zero(type) : identity(type);
3181    }
3182
3183    /**
3184     * Produces a method handle of the requested type which ignores any arguments, does nothing,
3185     * and returns a suitable default depending on the return type.
3186     * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3187     * <p>The returned method handle is equivalent to
3188     * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3189     * <p>
3190     * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3191     * {@code guardWithTest(pred, target, empty(target.type())}.
3192     * @param type the type of the desired method handle
3193     * @return a constant method handle of the given type, which returns a default value of the given return type
3194     * @throws NullPointerException if the argument is null
3195     * @see MethodHandles#zero
3196     * @see MethodHandles#constant
3197     * @since 9
3198     */
3199    public static  MethodHandle empty(MethodType type) {
3200        Objects.requireNonNull(type);
3201        return dropArguments(zero(type.returnType()), 0, type.parameterList());
3202    }
3203
3204    private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
3205    private static MethodHandle makeIdentity(Class<?> ptype) {
3206        MethodType mtype = methodType(ptype, ptype);
3207        LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3208        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3209    }
3210
3211    private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3212        int pos = btw.ordinal();
3213        MethodHandle zero = ZERO_MHS[pos];
3214        if (zero == null) {
3215            zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3216        }
3217        if (zero.type().returnType() == rtype)
3218            return zero;
3219        assert(btw == Wrapper.OBJECT);
3220        return makeZero(rtype);
3221    }
3222    private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
3223    private static MethodHandle makeZero(Class<?> rtype) {
3224        MethodType mtype = methodType(rtype);
3225        LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3226        return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3227    }
3228
3229    private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
3230        // Simulate a CAS, to avoid racy duplication of results.
3231        MethodHandle prev = cache[pos];
3232        if (prev != null) return prev;
3233        return cache[pos] = value;
3234    }
3235
3236    /**
3237     * Provides a target method handle with one or more <em>bound arguments</em>
3238     * in advance of the method handle's invocation.
3239     * The formal parameters to the target corresponding to the bound
3240     * arguments are called <em>bound parameters</em>.
3241     * Returns a new method handle which saves away the bound arguments.
3242     * When it is invoked, it receives arguments for any non-bound parameters,
3243     * binds the saved arguments to their corresponding parameters,
3244     * and calls the original target.
3245     * <p>
3246     * The type of the new method handle will drop the types for the bound
3247     * parameters from the original target type, since the new method handle
3248     * will no longer require those arguments to be supplied by its callers.
3249     * <p>
3250     * Each given argument object must match the corresponding bound parameter type.
3251     * If a bound parameter type is a primitive, the argument object
3252     * must be a wrapper, and will be unboxed to produce the primitive value.
3253     * <p>
3254     * The {@code pos} argument selects which parameters are to be bound.
3255     * It may range between zero and <i>N-L</i> (inclusively),
3256     * where <i>N</i> is the arity of the target method handle
3257     * and <i>L</i> is the length of the values array.
3258     * <p>
3259     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3260     * variable-arity method handle}, even if the original target method handle was.
3261     * @param target the method handle to invoke after the argument is inserted
3262     * @param pos where to insert the argument (zero for the first)
3263     * @param values the series of arguments to insert
3264     * @return a method handle which inserts an additional argument,
3265     *         before calling the original method handle
3266     * @throws NullPointerException if the target or the {@code values} array is null
3267     * @see MethodHandle#bindTo
3268     */
3269    public static
3270    MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3271        int insCount = values.length;
3272        Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3273        if (insCount == 0)  return target;
3274        BoundMethodHandle result = target.rebind();
3275        for (int i = 0; i < insCount; i++) {
3276            Object value = values[i];
3277            Class<?> ptype = ptypes[pos+i];
3278            if (ptype.isPrimitive()) {
3279                result = insertArgumentPrimitive(result, pos, ptype, value);
3280            } else {
3281                value = ptype.cast(value);  // throw CCE if needed
3282                result = result.bindArgumentL(pos, value);
3283            }
3284        }
3285        return result;
3286    }
3287
3288    private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3289                                                             Class<?> ptype, Object value) {
3290        Wrapper w = Wrapper.forPrimitiveType(ptype);
3291        // perform unboxing and/or primitive conversion
3292        value = w.convert(value, ptype);
3293        switch (w) {
3294        case INT:     return result.bindArgumentI(pos, (int)value);
3295        case LONG:    return result.bindArgumentJ(pos, (long)value);
3296        case FLOAT:   return result.bindArgumentF(pos, (float)value);
3297        case DOUBLE:  return result.bindArgumentD(pos, (double)value);
3298        default:      return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3299        }
3300    }
3301
3302    private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
3303        MethodType oldType = target.type();
3304        int outargs = oldType.parameterCount();
3305        int inargs  = outargs - insCount;
3306        if (inargs < 0)
3307            throw newIllegalArgumentException("too many values to insert");
3308        if (pos < 0 || pos > inargs)
3309            throw newIllegalArgumentException("no argument type to append");
3310        return oldType.ptypes();
3311    }
3312
3313    /**
3314     * Produces a method handle which will discard some dummy arguments
3315     * before calling some other specified <i>target</i> method handle.
3316     * The type of the new method handle will be the same as the target's type,
3317     * except it will also include the dummy argument types,
3318     * at some given position.
3319     * <p>
3320     * The {@code pos} argument may range between zero and <i>N</i>,
3321     * where <i>N</i> is the arity of the target.
3322     * If {@code pos} is zero, the dummy arguments will precede
3323     * the target's real arguments; if {@code pos} is <i>N</i>
3324     * they will come after.
3325     * <p>
3326     * <b>Example:</b>
3327     * <blockquote><pre>{@code
3328import static java.lang.invoke.MethodHandles.*;
3329import static java.lang.invoke.MethodType.*;
3330...
3331MethodHandle cat = lookup().findVirtual(String.class,
3332  "concat", methodType(String.class, String.class));
3333assertEquals("xy", (String) cat.invokeExact("x", "y"));
3334MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3335MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3336assertEquals(bigType, d0.type());
3337assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
3338     * }</pre></blockquote>
3339     * <p>
3340     * This method is also equivalent to the following code:
3341     * <blockquote><pre>
3342     * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
3343     * </pre></blockquote>
3344     * @param target the method handle to invoke after the arguments are dropped
3345     * @param valueTypes the type(s) of the argument(s) to drop
3346     * @param pos position of first argument to drop (zero for the leftmost)
3347     * @return a method handle which drops arguments of the given types,
3348     *         before calling the original method handle
3349     * @throws NullPointerException if the target is null,
3350     *                              or if the {@code valueTypes} list or any of its elements is null
3351     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3352     *                  or if {@code pos} is negative or greater than the arity of the target,
3353     *                  or if the new method handle's type would have too many parameters
3354     */
3355    public static
3356    MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3357        return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
3358    }
3359
3360    private static List<Class<?>> copyTypes(Object[] array) {
3361        return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
3362    }
3363
3364    private static
3365    MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3366        MethodType oldType = target.type();  // get NPE
3367        int dropped = dropArgumentChecks(oldType, pos, valueTypes);
3368        MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
3369        if (dropped == 0)  return target;
3370        BoundMethodHandle result = target.rebind();
3371        LambdaForm lform = result.form;
3372        int insertFormArg = 1 + pos;
3373        for (Class<?> ptype : valueTypes) {
3374            lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
3375        }
3376        result = result.copyWith(newType, lform);
3377        return result;
3378    }
3379
3380    private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
3381        int dropped = valueTypes.size();
3382        MethodType.checkSlotCount(dropped);
3383        int outargs = oldType.parameterCount();
3384        int inargs  = outargs + dropped;
3385        if (pos < 0 || pos > outargs)
3386            throw newIllegalArgumentException("no argument type to remove"
3387                    + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3388                    );
3389        return dropped;
3390    }
3391
3392    /**
3393     * Produces a method handle which will discard some dummy arguments
3394     * before calling some other specified <i>target</i> method handle.
3395     * The type of the new method handle will be the same as the target's type,
3396     * except it will also include the dummy argument types,
3397     * at some given position.
3398     * <p>
3399     * The {@code pos} argument may range between zero and <i>N</i>,
3400     * where <i>N</i> is the arity of the target.
3401     * If {@code pos} is zero, the dummy arguments will precede
3402     * the target's real arguments; if {@code pos} is <i>N</i>
3403     * they will come after.
3404     * @apiNote
3405     * <blockquote><pre>{@code
3406import static java.lang.invoke.MethodHandles.*;
3407import static java.lang.invoke.MethodType.*;
3408...
3409MethodHandle cat = lookup().findVirtual(String.class,
3410  "concat", methodType(String.class, String.class));
3411assertEquals("xy", (String) cat.invokeExact("x", "y"));
3412MethodHandle d0 = dropArguments(cat, 0, String.class);
3413assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
3414MethodHandle d1 = dropArguments(cat, 1, String.class);
3415assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
3416MethodHandle d2 = dropArguments(cat, 2, String.class);
3417assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
3418MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
3419assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
3420     * }</pre></blockquote>
3421     * <p>
3422     * This method is also equivalent to the following code:
3423     * <blockquote><pre>
3424     * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
3425     * </pre></blockquote>
3426     * @param target the method handle to invoke after the arguments are dropped
3427     * @param valueTypes the type(s) of the argument(s) to drop
3428     * @param pos position of first argument to drop (zero for the leftmost)
3429     * @return a method handle which drops arguments of the given types,
3430     *         before calling the original method handle
3431     * @throws NullPointerException if the target is null,
3432     *                              or if the {@code valueTypes} array or any of its elements is null
3433     * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3434     *                  or if {@code pos} is negative or greater than the arity of the target,
3435     *                  or if the new method handle's type would have
3436     *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
3437     */
3438    public static
3439    MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
3440        return dropArguments0(target, pos, copyTypes(valueTypes));
3441    }
3442
3443    // private version which allows caller some freedom with error handling
3444    private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
3445                                      boolean nullOnFailure) {
3446        newTypes = copyTypes(newTypes.toArray());
3447        List<Class<?>> oldTypes = target.type().parameterList();
3448        int match = oldTypes.size();
3449        if (skip != 0) {
3450            if (skip < 0 || skip > match) {
3451                throw newIllegalArgumentException("illegal skip", skip, target);
3452            }
3453            oldTypes = oldTypes.subList(skip, match);
3454            match -= skip;
3455        }
3456        List<Class<?>> addTypes = newTypes;
3457        int add = addTypes.size();
3458        if (pos != 0) {
3459            if (pos < 0 || pos > add) {
3460                throw newIllegalArgumentException("illegal pos", pos, newTypes);
3461            }
3462            addTypes = addTypes.subList(pos, add);
3463            add -= pos;
3464            assert(addTypes.size() == add);
3465        }
3466        // Do not add types which already match the existing arguments.
3467        if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
3468            if (nullOnFailure) {
3469                return null;
3470            }
3471            throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
3472        }
3473        addTypes = addTypes.subList(match, add);
3474        add -= match;
3475        assert(addTypes.size() == add);
3476        // newTypes:     (   P*[pos], M*[match], A*[add] )
3477        // target: ( S*[skip],        M*[match]  )
3478        MethodHandle adapter = target;
3479        if (add > 0) {
3480            adapter = dropArguments0(adapter, skip+ match, addTypes);
3481        }
3482        // adapter: (S*[skip],        M*[match], A*[add] )
3483        if (pos > 0) {
3484            adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
3485        }
3486        // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
3487        return adapter;
3488    }
3489
3490    /**
3491     * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
3492     * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
3493     * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
3494     * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
3495     * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
3496     * {@link #dropArguments(MethodHandle, int, Class[])}.
3497     * <p>
3498     * The resulting handle will have the same return type as the target handle.
3499     * <p>
3500     * In more formal terms, assume these two type lists:<ul>
3501     * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
3502     * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
3503     * {@code newTypes}.
3504     * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
3505     * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
3506     * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
3507     * sub-list.
3508     * </ul>
3509     * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
3510     * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
3511     * {@link #dropArguments(MethodHandle, int, Class[])}.
3512     * <p>
3513     * @apiNote
3514     * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
3515     * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
3516     * <blockquote><pre>{@code
3517import static java.lang.invoke.MethodHandles.*;
3518import static java.lang.invoke.MethodType.*;
3519...
3520...
3521MethodHandle h0 = constant(boolean.class, true);
3522MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
3523MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
3524MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
3525if (h1.type().parameterCount() < h2.type().parameterCount())
3526    h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
3527else
3528    h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
3529MethodHandle h3 = guardWithTest(h0, h1, h2);
3530assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
3531     * }</pre></blockquote>
3532     * @param target the method handle to adapt
3533     * @param skip number of targets parameters to disregard (they will be unchanged)
3534     * @param newTypes the list of types to match {@code target}'s parameter type list to
3535     * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
3536     * @return a possibly adapted method handle
3537     * @throws NullPointerException if either argument is null
3538     * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
3539     *         or if {@code skip} is negative or greater than the arity of the target,
3540     *         or if {@code pos} is negative or greater than the newTypes list size,
3541     *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
3542     *         {@code pos}.
3543     * @since 9
3544     */
3545    public static
3546    MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
3547        Objects.requireNonNull(target);
3548        Objects.requireNonNull(newTypes);
3549        return dropArgumentsToMatch(target, skip, newTypes, pos, false);
3550    }
3551
3552    /**
3553     * Adapts a target method handle by pre-processing
3554     * one or more of its arguments, each with its own unary filter function,
3555     * and then calling the target with each pre-processed argument
3556     * replaced by the result of its corresponding filter function.
3557     * <p>
3558     * The pre-processing is performed by one or more method handles,
3559     * specified in the elements of the {@code filters} array.
3560     * The first element of the filter array corresponds to the {@code pos}
3561     * argument of the target, and so on in sequence.
3562     * <p>
3563     * Null arguments in the array are treated as identity functions,
3564     * and the corresponding arguments left unchanged.
3565     * (If there are no non-null elements in the array, the original target is returned.)
3566     * Each filter is applied to the corresponding argument of the adapter.
3567     * <p>
3568     * If a filter {@code F} applies to the {@code N}th argument of
3569     * the target, then {@code F} must be a method handle which
3570     * takes exactly one argument.  The type of {@code F}'s sole argument
3571     * replaces the corresponding argument type of the target
3572     * in the resulting adapted method handle.
3573     * The return type of {@code F} must be identical to the corresponding
3574     * parameter type of the target.
3575     * <p>
3576     * It is an error if there are elements of {@code filters}
3577     * (null or not)
3578     * which do not correspond to argument positions in the target.
3579     * <p><b>Example:</b>
3580     * <blockquote><pre>{@code
3581import static java.lang.invoke.MethodHandles.*;
3582import static java.lang.invoke.MethodType.*;
3583...
3584MethodHandle cat = lookup().findVirtual(String.class,
3585  "concat", methodType(String.class, String.class));
3586MethodHandle upcase = lookup().findVirtual(String.class,
3587  "toUpperCase", methodType(String.class));
3588assertEquals("xy", (String) cat.invokeExact("x", "y"));
3589MethodHandle f0 = filterArguments(cat, 0, upcase);
3590assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
3591MethodHandle f1 = filterArguments(cat, 1, upcase);
3592assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
3593MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
3594assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
3595     * }</pre></blockquote>
3596     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3597     * denotes the return type of both the {@code target} and resulting adapter.
3598     * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
3599     * of the parameters and arguments that precede and follow the filter position
3600     * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
3601     * values of the filtered parameters and arguments; they also represent the
3602     * return types of the {@code filter[i]} handles. The latter accept arguments
3603     * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
3604     * the resulting adapter.
3605     * <blockquote><pre>{@code
3606     * T target(P... p, A[i]... a[i], B... b);
3607     * A[i] filter[i](V[i]);
3608     * T adapter(P... p, V[i]... v[i], B... b) {
3609     *   return target(p..., filter[i](v[i])..., b...);
3610     * }
3611     * }</pre></blockquote>
3612     * <p>
3613     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3614     * variable-arity method handle}, even if the original target method handle was.
3615     *
3616     * @param target the method handle to invoke after arguments are filtered
3617     * @param pos the position of the first argument to filter
3618     * @param filters method handles to call initially on filtered arguments
3619     * @return method handle which incorporates the specified argument filtering logic
3620     * @throws NullPointerException if the target is null
3621     *                              or if the {@code filters} array is null
3622     * @throws IllegalArgumentException if a non-null element of {@code filters}
3623     *          does not match a corresponding argument type of target as described above,
3624     *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3625     *          or if the resulting method handle's type would have
3626     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3627     */
3628    public static
3629    MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
3630        filterArgumentsCheckArity(target, pos, filters);
3631        MethodHandle adapter = target;
3632        int curPos = pos-1;  // pre-incremented
3633        for (MethodHandle filter : filters) {
3634            curPos += 1;
3635            if (filter == null)  continue;  // ignore null elements of filters
3636            adapter = filterArgument(adapter, curPos, filter);
3637        }
3638        return adapter;
3639    }
3640
3641    /*non-public*/ static
3642    MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
3643        filterArgumentChecks(target, pos, filter);
3644        MethodType targetType = target.type();
3645        MethodType filterType = filter.type();
3646        BoundMethodHandle result = target.rebind();
3647        Class<?> newParamType = filterType.parameterType(0);
3648        LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
3649        MethodType newType = targetType.changeParameterType(pos, newParamType);
3650        result = result.copyWithExtendL(newType, lform, filter);
3651        return result;
3652    }
3653
3654    private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3655        MethodType targetType = target.type();
3656        int maxPos = targetType.parameterCount();
3657        if (pos + filters.length > maxPos)
3658            throw newIllegalArgumentException("too many filters");
3659    }
3660
3661    private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3662        MethodType targetType = target.type();
3663        MethodType filterType = filter.type();
3664        if (filterType.parameterCount() != 1
3665            || filterType.returnType() != targetType.parameterType(pos))
3666            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3667    }
3668
3669    /**
3670     * Adapts a target method handle by pre-processing
3671     * a sub-sequence of its arguments with a filter (another method handle).
3672     * The pre-processed arguments are replaced by the result (if any) of the
3673     * filter function.
3674     * The target is then called on the modified (usually shortened) argument list.
3675     * <p>
3676     * If the filter returns a value, the target must accept that value as
3677     * its argument in position {@code pos}, preceded and/or followed by
3678     * any arguments not passed to the filter.
3679     * If the filter returns void, the target must accept all arguments
3680     * not passed to the filter.
3681     * No arguments are reordered, and a result returned from the filter
3682     * replaces (in order) the whole subsequence of arguments originally
3683     * passed to the adapter.
3684     * <p>
3685     * The argument types (if any) of the filter
3686     * replace zero or one argument types of the target, at position {@code pos},
3687     * in the resulting adapted method handle.
3688     * The return type of the filter (if any) must be identical to the
3689     * argument type of the target at position {@code pos}, and that target argument
3690     * is supplied by the return value of the filter.
3691     * <p>
3692     * In all cases, {@code pos} must be greater than or equal to zero, and
3693     * {@code pos} must also be less than or equal to the target's arity.
3694     * <p><b>Example:</b>
3695     * <blockquote><pre>{@code
3696import static java.lang.invoke.MethodHandles.*;
3697import static java.lang.invoke.MethodType.*;
3698...
3699MethodHandle deepToString = publicLookup()
3700  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3701
3702MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3703assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3704
3705MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3706assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3707
3708MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3709MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3710assertEquals("[top, [up, down], strange]",
3711             (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3712
3713MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3714assertEquals("[top, [up, down], [strange]]",
3715             (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3716
3717MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3718assertEquals("[top, [[up, down, strange], charm], bottom]",
3719             (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
3720     * }</pre></blockquote>
3721     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3722     * represents the return type of the {@code target} and resulting adapter.
3723     * {@code V}/{@code v} stand for the return type and value of the
3724     * {@code filter}, which are also found in the signature and arguments of
3725     * the {@code target}, respectively, unless {@code V} is {@code void}.
3726     * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
3727     * and values preceding and following the collection position, {@code pos},
3728     * in the {@code target}'s signature. They also turn up in the resulting
3729     * adapter's signature and arguments, where they surround
3730     * {@code B}/{@code b}, which represent the parameter types and arguments
3731     * to the {@code filter} (if any).
3732     * <blockquote><pre>{@code
3733     * T target(A...,V,C...);
3734     * V filter(B...);
3735     * T adapter(A... a,B... b,C... c) {
3736     *   V v = filter(b...);
3737     *   return target(a...,v,c...);
3738     * }
3739     * // and if the filter has no arguments:
3740     * T target2(A...,V,C...);
3741     * V filter2();
3742     * T adapter2(A... a,C... c) {
3743     *   V v = filter2();
3744     *   return target2(a...,v,c...);
3745     * }
3746     * // and if the filter has a void return:
3747     * T target3(A...,C...);
3748     * void filter3(B...);
3749     * T adapter3(A... a,B... b,C... c) {
3750     *   filter3(b...);
3751     *   return target3(a...,c...);
3752     * }
3753     * }</pre></blockquote>
3754     * <p>
3755     * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3756     * one which first "folds" the affected arguments, and then drops them, in separate
3757     * steps as follows:
3758     * <blockquote><pre>{@code
3759     * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3760     * mh = MethodHandles.foldArguments(mh, coll); //step 1
3761     * }</pre></blockquote>
3762     * If the target method handle consumes no arguments besides than the result
3763     * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3764     * is equivalent to {@code filterReturnValue(coll, mh)}.
3765     * If the filter method handle {@code coll} consumes one argument and produces
3766     * a non-void result, then {@code collectArguments(mh, N, coll)}
3767     * is equivalent to {@code filterArguments(mh, N, coll)}.
3768     * Other equivalences are possible but would require argument permutation.
3769     * <p>
3770     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3771     * variable-arity method handle}, even if the original target method handle was.
3772     *
3773     * @param target the method handle to invoke after filtering the subsequence of arguments
3774     * @param pos the position of the first adapter argument to pass to the filter,
3775     *            and/or the target argument which receives the result of the filter
3776     * @param filter method handle to call on the subsequence of arguments
3777     * @return method handle which incorporates the specified argument subsequence filtering logic
3778     * @throws NullPointerException if either argument is null
3779     * @throws IllegalArgumentException if the return type of {@code filter}
3780     *          is non-void and is not the same as the {@code pos} argument of the target,
3781     *          or if {@code pos} is not between 0 and the target's arity, inclusive,
3782     *          or if the resulting method handle's type would have
3783     *          <a href="MethodHandle.html#maxarity">too many parameters</a>
3784     * @see MethodHandles#foldArguments
3785     * @see MethodHandles#filterArguments
3786     * @see MethodHandles#filterReturnValue
3787     */
3788    public static
3789    MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
3790        MethodType newType = collectArgumentsChecks(target, pos, filter);
3791        MethodType collectorType = filter.type();
3792        BoundMethodHandle result = target.rebind();
3793        LambdaForm lform;
3794        if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
3795            lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
3796            if (lform != null) {
3797                return result.copyWith(newType, lform);
3798            }
3799        }
3800        lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
3801        return result.copyWithExtendL(newType, lform, filter);
3802    }
3803
3804    private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3805        MethodType targetType = target.type();
3806        MethodType filterType = filter.type();
3807        Class<?> rtype = filterType.returnType();
3808        List<Class<?>> filterArgs = filterType.parameterList();
3809        if (rtype == void.class) {
3810            return targetType.insertParameterTypes(pos, filterArgs);
3811        }
3812        if (rtype != targetType.parameterType(pos)) {
3813            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3814        }
3815        return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
3816    }
3817
3818    /**
3819     * Adapts a target method handle by post-processing
3820     * its return value (if any) with a filter (another method handle).
3821     * The result of the filter is returned from the adapter.
3822     * <p>
3823     * If the target returns a value, the filter must accept that value as
3824     * its only argument.
3825     * If the target returns void, the filter must accept no arguments.
3826     * <p>
3827     * The return type of the filter
3828     * replaces the return type of the target
3829     * in the resulting adapted method handle.
3830     * The argument type of the filter (if any) must be identical to the
3831     * return type of the target.
3832     * <p><b>Example:</b>
3833     * <blockquote><pre>{@code
3834import static java.lang.invoke.MethodHandles.*;
3835import static java.lang.invoke.MethodType.*;
3836...
3837MethodHandle cat = lookup().findVirtual(String.class,
3838  "concat", methodType(String.class, String.class));
3839MethodHandle length = lookup().findVirtual(String.class,
3840  "length", methodType(int.class));
3841System.out.println((String) cat.invokeExact("x", "y")); // xy
3842MethodHandle f0 = filterReturnValue(cat, length);
3843System.out.println((int) f0.invokeExact("x", "y")); // 2
3844     * }</pre></blockquote>
3845     * <p>Here is pseudocode for the resulting adapter. In the code,
3846     * {@code T}/{@code t} represent the result type and value of the
3847     * {@code target}; {@code V}, the result type of the {@code filter}; and
3848     * {@code A}/{@code a}, the types and values of the parameters and arguments
3849     * of the {@code target} as well as the resulting adapter.
3850     * <blockquote><pre>{@code
3851     * T target(A...);
3852     * V filter(T);
3853     * V adapter(A... a) {
3854     *   T t = target(a...);
3855     *   return filter(t);
3856     * }
3857     * // and if the target has a void return:
3858     * void target2(A...);
3859     * V filter2();
3860     * V adapter2(A... a) {
3861     *   target2(a...);
3862     *   return filter2();
3863     * }
3864     * // and if the filter has a void return:
3865     * T target3(A...);
3866     * void filter3(V);
3867     * void adapter3(A... a) {
3868     *   T t = target3(a...);
3869     *   filter3(t);
3870     * }
3871     * }</pre></blockquote>
3872     * <p>
3873     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3874     * variable-arity method handle}, even if the original target method handle was.
3875     * @param target the method handle to invoke before filtering the return value
3876     * @param filter method handle to call on the return value
3877     * @return method handle which incorporates the specified return value filtering logic
3878     * @throws NullPointerException if either argument is null
3879     * @throws IllegalArgumentException if the argument list of {@code filter}
3880     *          does not match the return type of target as described above
3881     */
3882    public static
3883    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3884        MethodType targetType = target.type();
3885        MethodType filterType = filter.type();
3886        filterReturnValueChecks(targetType, filterType);
3887        BoundMethodHandle result = target.rebind();
3888        BasicType rtype = BasicType.basicType(filterType.returnType());
3889        LambdaForm lform = result.editor().filterReturnForm(rtype, false);
3890        MethodType newType = targetType.changeReturnType(filterType.returnType());
3891        result = result.copyWithExtendL(newType, lform, filter);
3892        return result;
3893    }
3894
3895    private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
3896        Class<?> rtype = targetType.returnType();
3897        int filterValues = filterType.parameterCount();
3898        if (filterValues == 0
3899                ? (rtype != void.class)
3900                : (rtype != filterType.parameterType(0) || filterValues != 1))
3901            throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3902    }
3903
3904    /**
3905     * Adapts a target method handle by pre-processing
3906     * some of its arguments, and then calling the target with
3907     * the result of the pre-processing, inserted into the original
3908     * sequence of arguments.
3909     * <p>
3910     * The pre-processing is performed by {@code combiner}, a second method handle.
3911     * Of the arguments passed to the adapter, the first {@code N} arguments
3912     * are copied to the combiner, which is then called.
3913     * (Here, {@code N} is defined as the parameter count of the combiner.)
3914     * After this, control passes to the target, with any result
3915     * from the combiner inserted before the original {@code N} incoming
3916     * arguments.
3917     * <p>
3918     * If the combiner returns a value, the first parameter type of the target
3919     * must be identical with the return type of the combiner, and the next
3920     * {@code N} parameter types of the target must exactly match the parameters
3921     * of the combiner.
3922     * <p>
3923     * If the combiner has a void return, no result will be inserted,
3924     * and the first {@code N} parameter types of the target
3925     * must exactly match the parameters of the combiner.
3926     * <p>
3927     * The resulting adapter is the same type as the target, except that the
3928     * first parameter type is dropped,
3929     * if it corresponds to the result of the combiner.
3930     * <p>
3931     * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
3932     * that either the combiner or the target does not wish to receive.
3933     * If some of the incoming arguments are destined only for the combiner,
3934     * consider using {@link MethodHandle#asCollector asCollector} instead, since those
3935     * arguments will not need to be live on the stack on entry to the
3936     * target.)
3937     * <p><b>Example:</b>
3938     * <blockquote><pre>{@code
3939import static java.lang.invoke.MethodHandles.*;
3940import static java.lang.invoke.MethodType.*;
3941...
3942MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3943  "println", methodType(void.class, String.class))
3944    .bindTo(System.out);
3945MethodHandle cat = lookup().findVirtual(String.class,
3946  "concat", methodType(String.class, String.class));
3947assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3948MethodHandle catTrace = foldArguments(cat, trace);
3949// also prints "boo":
3950assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3951     * }</pre></blockquote>
3952     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3953     * represents the result type of the {@code target} and resulting adapter.
3954     * {@code V}/{@code v} represent the type and value of the parameter and argument
3955     * of {@code target} that precedes the folding position; {@code V} also is
3956     * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3957     * types and values of the {@code N} parameters and arguments at the folding
3958     * position. {@code B}/{@code b} represent the types and values of the
3959     * {@code target} parameters and arguments that follow the folded parameters
3960     * and arguments.
3961     * <blockquote><pre>{@code
3962     * // there are N arguments in A...
3963     * T target(V, A[N]..., B...);
3964     * V combiner(A...);
3965     * T adapter(A... a, B... b) {
3966     *   V v = combiner(a...);
3967     *   return target(v, a..., b...);
3968     * }
3969     * // and if the combiner has a void return:
3970     * T target2(A[N]..., B...);
3971     * void combiner2(A...);
3972     * T adapter2(A... a, B... b) {
3973     *   combiner2(a...);
3974     *   return target2(a..., b...);
3975     * }
3976     * }</pre></blockquote>
3977     * <p>
3978     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3979     * variable-arity method handle}, even if the original target method handle was.
3980     * @param target the method handle to invoke after arguments are combined
3981     * @param combiner method handle to call initially on the incoming arguments
3982     * @return method handle which incorporates the specified argument folding logic
3983     * @throws NullPointerException if either argument is null
3984     * @throws IllegalArgumentException if {@code combiner}'s return type
3985     *          is non-void and not the same as the first argument type of
3986     *          the target, or if the initial {@code N} argument types
3987     *          of the target
3988     *          (skipping one matching the {@code combiner}'s return type)
3989     *          are not identical with the argument types of {@code combiner}
3990     */
3991    public static
3992    MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
3993        return foldArguments(target, 0, combiner);
3994    }
3995
3996    /**
3997     * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
3998     * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
3999     * before the folded arguments.
4000     * <p>
4001     * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
4002     * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
4003     * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
4004     * 0.
4005     * <p>
4006     * @apiNote Example:
4007     * <blockquote><pre>{@code
4008    import static java.lang.invoke.MethodHandles.*;
4009    import static java.lang.invoke.MethodType.*;
4010    ...
4011    MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4012    "println", methodType(void.class, String.class))
4013    .bindTo(System.out);
4014    MethodHandle cat = lookup().findVirtual(String.class,
4015    "concat", methodType(String.class, String.class));
4016    assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4017    MethodHandle catTrace = foldArguments(cat, 1, trace);
4018    // also prints "jum":
4019    assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4020     * }</pre></blockquote>
4021     * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4022     * represents the result type of the {@code target} and resulting adapter.
4023     * {@code V}/{@code v} represent the type and value of the parameter and argument
4024     * of {@code target} that precedes the folding position; {@code V} also is
4025     * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4026     * types and values of the {@code N} parameters and arguments at the folding
4027     * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
4028     * and values of the {@code target} parameters and arguments that precede and
4029     * follow the folded parameters and arguments starting at {@code pos},
4030     * respectively.
4031     * <blockquote><pre>{@code
4032     * // there are N arguments in A...
4033     * T target(Z..., V, A[N]..., B...);
4034     * V combiner(A...);
4035     * T adapter(Z... z, A... a, B... b) {
4036     *   V v = combiner(a...);
4037     *   return target(z..., v, a..., b...);
4038     * }
4039     * // and if the combiner has a void return:
4040     * T target2(Z..., A[N]..., B...);
4041     * void combiner2(A...);
4042     * T adapter2(Z... z, A... a, B... b) {
4043     *   combiner2(a...);
4044     *   return target2(z..., a..., b...);
4045     * }
4046     * }</pre></blockquote>
4047     * <p>
4048     * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4049     * variable-arity method handle}, even if the original target method handle was.
4050     *
4051     * @param target the method handle to invoke after arguments are combined
4052     * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
4053     *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4054     * @param combiner method handle to call initially on the incoming arguments
4055     * @return method handle which incorporates the specified argument folding logic
4056     * @throws NullPointerException if either argument is null
4057     * @throws IllegalArgumentException if either of the following two conditions holds:
4058     *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
4059     *              {@code pos} of the target signature;
4060     *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
4061     *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
4062     *
4063     * @see #foldArguments(MethodHandle, MethodHandle)
4064     * @since 9
4065     */
4066    public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
4067        MethodType targetType = target.type();
4068        MethodType combinerType = combiner.type();
4069        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4070        BoundMethodHandle result = target.rebind();
4071        boolean dropResult = rtype == void.class;
4072        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4073        MethodType newType = targetType;
4074        if (!dropResult) {
4075            newType = newType.dropParameterTypes(pos, pos + 1);
4076        }
4077        result = result.copyWithExtendL(newType, lform, combiner);
4078        return result;
4079    }
4080
4081    /**
4082     * As {@see foldArguments(MethodHandle, int, MethodHandle)}, but with the
4083     * added capability of selecting the arguments from the targets parameters
4084     * to call the combiner with. This allows us to avoid some simple cases of
4085     * permutations and padding the combiner with dropArguments to select the
4086     * right argument, which may ultimately produce fewer intermediaries.
4087     */
4088    static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner, int ... argPositions) {
4089        MethodType targetType = target.type();
4090        MethodType combinerType = combiner.type();
4091        Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType, argPositions);
4092        BoundMethodHandle result = target.rebind();
4093        boolean dropResult = rtype == void.class;
4094        LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType(), argPositions);
4095        MethodType newType = targetType;
4096        if (!dropResult) {
4097            newType = newType.dropParameterTypes(pos, pos + 1);
4098        }
4099        result = result.copyWithExtendL(newType, lform, combiner);
4100        return result;
4101    }
4102
4103    private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
4104        int foldArgs   = combinerType.parameterCount();
4105        Class<?> rtype = combinerType.returnType();
4106        int foldVals = rtype == void.class ? 0 : 1;
4107        int afterInsertPos = foldPos + foldVals;
4108        boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
4109        if (ok) {
4110            for (int i = 0; i < foldArgs; i++) {
4111                if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
4112                    ok = false;
4113                    break;
4114                }
4115            }
4116        }
4117        if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
4118            ok = false;
4119        if (!ok)
4120            throw misMatchedTypes("target and combiner types", targetType, combinerType);
4121        return rtype;
4122    }
4123
4124    private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType, int ... argPos) {
4125        int foldArgs = combinerType.parameterCount();
4126        if (argPos.length != foldArgs) {
4127            throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
4128        }
4129        Class<?> rtype = combinerType.returnType();
4130        int foldVals = rtype == void.class ? 0 : 1;
4131        boolean ok = true;
4132        for (int i = 0; i < foldArgs; i++) {
4133            int arg = argPos[i];
4134            if (arg < 0 || arg > targetType.parameterCount()) {
4135                throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
4136            }
4137            if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
4138                throw newIllegalArgumentException("target argument type at position " + arg
4139                        + " must match combiner argument type at index " + i + ": " + targetType
4140                        + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
4141            }
4142        }
4143        if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) {
4144            ok = false;
4145        }
4146        if (!ok)
4147            throw misMatchedTypes("target and combiner types", targetType, combinerType);
4148        return rtype;
4149    }
4150
4151    /**
4152     * Makes a method handle which adapts a target method handle,
4153     * by guarding it with a test, a boolean-valued method handle.
4154     * If the guard fails, a fallback handle is called instead.
4155     * All three method handles must have the same corresponding
4156     * argument and return types, except that the return type
4157     * of the test must be boolean, and the test is allowed
4158     * to have fewer arguments than the other two method handles.
4159     * <p>
4160     * Here is pseudocode for the resulting adapter. In the code, {@code T}
4161     * represents the uniform result type of the three involved handles;
4162     * {@code A}/{@code a}, the types and values of the {@code target}
4163     * parameters and arguments that are consumed by the {@code test}; and
4164     * {@code B}/{@code b}, those types and values of the {@code target}
4165     * parameters and arguments that are not consumed by the {@code test}.
4166     * <blockquote><pre>{@code
4167     * boolean test(A...);
4168     * T target(A...,B...);
4169     * T fallback(A...,B...);
4170     * T adapter(A... a,B... b) {
4171     *   if (test(a...))
4172     *     return target(a..., b...);
4173     *   else
4174     *     return fallback(a..., b...);
4175     * }
4176     * }</pre></blockquote>
4177     * Note that the test arguments ({@code a...} in the pseudocode) cannot
4178     * be modified by execution of the test, and so are passed unchanged
4179     * from the caller to the target or fallback as appropriate.
4180     * @param test method handle used for test, must return boolean
4181     * @param target method handle to call if test passes
4182     * @param fallback method handle to call if test fails
4183     * @return method handle which incorporates the specified if/then/else logic
4184     * @throws NullPointerException if any argument is null
4185     * @throws IllegalArgumentException if {@code test} does not return boolean,
4186     *          or if all three method types do not match (with the return
4187     *          type of {@code test} changed to match that of the target).
4188     */
4189    public static
4190    MethodHandle guardWithTest(MethodHandle test,
4191                               MethodHandle target,
4192                               MethodHandle fallback) {
4193        MethodType gtype = test.type();
4194        MethodType ttype = target.type();
4195        MethodType ftype = fallback.type();
4196        if (!ttype.equals(ftype))
4197            throw misMatchedTypes("target and fallback types", ttype, ftype);
4198        if (gtype.returnType() != boolean.class)
4199            throw newIllegalArgumentException("guard type is not a predicate "+gtype);
4200        List<Class<?>> targs = ttype.parameterList();
4201        test = dropArgumentsToMatch(test, 0, targs, 0, true);
4202        if (test == null) {
4203            throw misMatchedTypes("target and test types", ttype, gtype);
4204        }
4205        return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
4206    }
4207
4208    static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
4209        return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
4210    }
4211
4212    /**
4213     * Makes a method handle which adapts a target method handle,
4214     * by running it inside an exception handler.
4215     * If the target returns normally, the adapter returns that value.
4216     * If an exception matching the specified type is thrown, the fallback
4217     * handle is called instead on the exception, plus the original arguments.
4218     * <p>
4219     * The target and handler must have the same corresponding
4220     * argument and return types, except that handler may omit trailing arguments
4221     * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
4222     * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
4223     * <p>
4224     * Here is pseudocode for the resulting adapter. In the code, {@code T}
4225     * represents the return type of the {@code target} and {@code handler},
4226     * and correspondingly that of the resulting adapter; {@code A}/{@code a},
4227     * the types and values of arguments to the resulting handle consumed by
4228     * {@code handler}; and {@code B}/{@code b}, those of arguments to the
4229     * resulting handle discarded by {@code handler}.
4230     * <blockquote><pre>{@code
4231     * T target(A..., B...);
4232     * T handler(ExType, A...);
4233     * T adapter(A... a, B... b) {
4234     *   try {
4235     *     return target(a..., b...);
4236     *   } catch (ExType ex) {
4237     *     return handler(ex, a...);
4238     *   }
4239     * }
4240     * }</pre></blockquote>
4241     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4242     * be modified by execution of the target, and so are passed unchanged
4243     * from the caller to the handler, if the handler is invoked.
4244     * <p>
4245     * The target and handler must return the same type, even if the handler
4246     * always throws.  (This might happen, for instance, because the handler
4247     * is simulating a {@code finally} clause).
4248     * To create such a throwing handler, compose the handler creation logic
4249     * with {@link #throwException throwException},
4250     * in order to create a method handle of the correct return type.
4251     * @param target method handle to call
4252     * @param exType the type of exception which the handler will catch
4253     * @param handler method handle to call if a matching exception is thrown
4254     * @return method handle which incorporates the specified try/catch logic
4255     * @throws NullPointerException if any argument is null
4256     * @throws IllegalArgumentException if {@code handler} does not accept
4257     *          the given exception type, or if the method handle types do
4258     *          not match in their return types and their
4259     *          corresponding parameters
4260     * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
4261     */
4262    public static
4263    MethodHandle catchException(MethodHandle target,
4264                                Class<? extends Throwable> exType,
4265                                MethodHandle handler) {
4266        MethodType ttype = target.type();
4267        MethodType htype = handler.type();
4268        if (!Throwable.class.isAssignableFrom(exType))
4269            throw new ClassCastException(exType.getName());
4270        if (htype.parameterCount() < 1 ||
4271            !htype.parameterType(0).isAssignableFrom(exType))
4272            throw newIllegalArgumentException("handler does not accept exception type "+exType);
4273        if (htype.returnType() != ttype.returnType())
4274            throw misMatchedTypes("target and handler return types", ttype, htype);
4275        handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
4276        if (handler == null) {
4277            throw misMatchedTypes("target and handler types", ttype, htype);
4278        }
4279        return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
4280    }
4281
4282    /**
4283     * Produces a method handle which will throw exceptions of the given {@code exType}.
4284     * The method handle will accept a single argument of {@code exType},
4285     * and immediately throw it as an exception.
4286     * The method type will nominally specify a return of {@code returnType}.
4287     * The return type may be anything convenient:  It doesn't matter to the
4288     * method handle's behavior, since it will never return normally.
4289     * @param returnType the return type of the desired method handle
4290     * @param exType the parameter type of the desired method handle
4291     * @return method handle which can throw the given exceptions
4292     * @throws NullPointerException if either argument is null
4293     */
4294    public static
4295    MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
4296        if (!Throwable.class.isAssignableFrom(exType))
4297            throw new ClassCastException(exType.getName());
4298        return MethodHandleImpl.throwException(methodType(returnType, exType));
4299    }
4300
4301    /**
4302     * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
4303     * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
4304     * delivers the loop's result, which is the return value of the resulting handle.
4305     * <p>
4306     * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
4307     * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
4308     * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
4309     * terms of method handles, each clause will specify up to four independent actions:<ul>
4310     * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
4311     * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
4312     * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
4313     * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
4314     * </ul>
4315     * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
4316     * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
4317     * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
4318     * <p>
4319     * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
4320     * this case. See below for a detailed description.
4321     * <p>
4322     * <em>Parameters optional everywhere:</em>
4323     * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
4324     * As an exception, the init functions cannot take any {@code v} parameters,
4325     * because those values are not yet computed when the init functions are executed.
4326     * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
4327     * In fact, any clause function may take no arguments at all.
4328     * <p>
4329     * <em>Loop parameters:</em>
4330     * A clause function may take all the iteration variable values it is entitled to, in which case
4331     * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
4332     * with their types and values notated as {@code (A...)} and {@code (a...)}.
4333     * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
4334     * (Since init functions do not accept iteration variables {@code v}, any parameter to an
4335     * init function is automatically a loop parameter {@code a}.)
4336     * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
4337     * These loop parameters act as loop-invariant values visible across the whole loop.
4338     * <p>
4339     * <em>Parameters visible everywhere:</em>
4340     * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
4341     * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
4342     * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
4343     * Most clause functions will not need all of this information, but they will be formally connected to it
4344     * as if by {@link #dropArguments}.
4345     * <a name="astar"></a>
4346     * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
4347     * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
4348     * In that notation, the general form of an init function parameter list
4349     * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
4350     * <p>
4351     * <em>Checking clause structure:</em>
4352     * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
4353     * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
4354     * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
4355     * met by the inputs to the loop combinator.
4356     * <p>
4357     * <em>Effectively identical sequences:</em>
4358     * <a name="effid"></a>
4359     * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
4360     * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
4361     * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
4362     * as a whole if the set contains a longest list, and all members of the set are effectively identical to
4363     * that longest list.
4364     * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
4365     * and the same is true if more sequences of the form {@code (V... A*)} are added.
4366     * <p>
4367     * <em>Step 0: Determine clause structure.</em><ol type="a">
4368     * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
4369     * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
4370     * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
4371     * four. Padding takes place by appending elements to the array.
4372     * <li>Clauses with all {@code null}s are disregarded.
4373     * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
4374     * </ol>
4375     * <p>
4376     * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
4377     * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
4378     * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
4379     * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
4380     * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
4381     * iteration variable type.
4382     * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
4383     * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
4384     * </ol>
4385     * <p>
4386     * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
4387     * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
4388     * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
4389     * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
4390     * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
4391     * (These types will checked in step 2, along with all the clause function types.)
4392     * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
4393     * <li>All of the collected parameter lists must be effectively identical.
4394     * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
4395     * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
4396     * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
4397     * the "internal parameter list".
4398     * </ul>
4399     * <p>
4400     * <em>Step 1C: Determine loop return type.</em><ol type="a">
4401     * <li>Examine fini function return types, disregarding omitted fini functions.
4402     * <li>If there are no fini functions, the loop return type is {@code void}.
4403     * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
4404     * type.
4405     * </ol>
4406     * <p>
4407     * <em>Step 1D: Check other types.</em><ol type="a">
4408     * <li>There must be at least one non-omitted pred function.
4409     * <li>Every non-omitted pred function must have a {@code boolean} return type.
4410     * </ol>
4411     * <p>
4412     * <em>Step 2: Determine parameter lists.</em><ol type="a">
4413     * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
4414     * <li>The parameter list for init functions will be adjusted to the external parameter list.
4415     * (Note that their parameter lists are already effectively identical to this list.)
4416     * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
4417     * effectively identical to the internal parameter list {@code (V... A...)}.
4418     * </ol>
4419     * <p>
4420     * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4421     * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
4422     * type.
4423     * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4424     * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4425     * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4426     * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4427     * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
4428     * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
4429     * loop return type.
4430     * </ol>
4431     * <p>
4432     * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4433     * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
4434     * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
4435     * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
4436     * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
4437     * pad out the end of the list.
4438     * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch dropping unused trailing arguments}.
4439     * </ol>
4440     * <p>
4441     * <em>Final observations.</em><ol type="a">
4442     * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4443     * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
4444     * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
4445     * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
4446     * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
4447     * <li>Each pair of init and step functions agrees in their return type {@code V}.
4448     * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
4449     * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
4450     * </ol>
4451     * <p>
4452     * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
4453     * <ul>
4454     * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
4455     * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
4456     * (Only one {@code Pn} has to be non-{@code null}.)
4457     * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
4458     * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
4459     * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
4460     * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
4461     * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
4462     * the resulting loop handle's parameter types {@code (A...)}.
4463     * </ul>
4464     * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
4465     * which is natural if most of the loop computation happens in the steps.  For some loops,
4466     * the burden of computation might be heaviest in the pred functions, and so the pred functions
4467     * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
4468     * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
4469     * where the init functions will need the extra parameters.  For such reasons, the rules for
4470     * determining these parameters are as symmetric as possible, across all clause parts.
4471     * In general, the loop parameters function as common invariant values across the whole
4472     * loop, while the iteration variables function as common variant values, or (if there is
4473     * no step function) as internal loop invariant temporaries.
4474     * <p>
4475     * <em>Loop execution.</em><ol type="a">
4476     * <li>When the loop is called, the loop input values are saved in locals, to be passed to
4477     * every clause function. These locals are loop invariant.
4478     * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
4479     * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
4480     * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
4481     * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
4482     * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
4483     * (in argument order).
4484     * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
4485     * returns {@code false}.
4486     * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
4487     * sequence {@code (v...)} of loop variables.
4488     * The updated value is immediately visible to all subsequent function calls.
4489     * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
4490     * (of type {@code R}) is returned from the loop as a whole.
4491     * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
4492     * except by throwing an exception.
4493     * </ol>
4494     * <p>
4495     * <em>Usage tips.</em>
4496     * <ul>
4497     * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
4498     * sometimes a step function only needs to observe the current value of its own variable.
4499     * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
4500     * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
4501     * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
4502     * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
4503     * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
4504     * <li>If some of the clause functions are virtual methods on an instance, the instance
4505     * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
4506     * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
4507     * will be the first iteration variable value, and it will be easy to use virtual
4508     * methods as clause parts, since all of them will take a leading instance reference matching that value.
4509     * </ul>
4510     * <p>
4511     * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
4512     * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
4513     * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
4514     * <blockquote><pre>{@code
4515     * V... init...(A...);
4516     * boolean pred...(V..., A...);
4517     * V... step...(V..., A...);
4518     * R fini...(V..., A...);
4519     * R loop(A... a) {
4520     *   V... v... = init...(a...);
4521     *   for (;;) {
4522     *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4523     *       v = s(v..., a...);
4524     *       if (!p(v..., a...)) {
4525     *         return f(v..., a...);
4526     *       }
4527     *     }
4528     *   }
4529     * }
4530     * }</pre></blockquote>
4531     * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
4532     * to their full length, even though individual clause functions may neglect to take them all.
4533     * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch}.
4534     * <p>
4535     * @apiNote Example:
4536     * <blockquote><pre>{@code
4537     * // iterative implementation of the factorial function as a loop handle
4538     * static int one(int k) { return 1; }
4539     * static int inc(int i, int acc, int k) { return i + 1; }
4540     * static int mult(int i, int acc, int k) { return i * acc; }
4541     * static boolean pred(int i, int acc, int k) { return i < k; }
4542     * static int fin(int i, int acc, int k) { return acc; }
4543     * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4544     * // null initializer for counter, should initialize to 0
4545     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4546     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4547     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4548     * assertEquals(120, loop.invoke(5));
4549     * }</pre></blockquote>
4550     * The same example, dropping arguments and using combinators:
4551     * <blockquote><pre>{@code
4552     * // simplified implementation of the factorial function as a loop handle
4553     * static int inc(int i) { return i + 1; } // drop acc, k
4554     * static int mult(int i, int acc) { return i * acc; } //drop k
4555     * static boolean cmp(int i, int k) { return i < k; }
4556     * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
4557     * // null initializer for counter, should initialize to 0
4558     * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
4559     * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
4560     * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
4561     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4562     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4563     * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4564     * assertEquals(720, loop.invoke(6));
4565     * }</pre></blockquote>
4566     * A similar example, using a helper object to hold a loop parameter:
4567     * <blockquote><pre>{@code
4568     * // instance-based implementation of the factorial function as a loop handle
4569     * static class FacLoop {
4570     *   final int k;
4571     *   FacLoop(int k) { this.k = k; }
4572     *   int inc(int i) { return i + 1; }
4573     *   int mult(int i, int acc) { return i * acc; }
4574     *   boolean pred(int i) { return i < k; }
4575     *   int fin(int i, int acc) { return acc; }
4576     * }
4577     * // assume MH_FacLoop is a handle to the constructor
4578     * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4579     * // null initializer for counter, should initialize to 0
4580     * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
4581     * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
4582     * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4583     * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4584     * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
4585     * assertEquals(5040, loop.invoke(7));
4586     * }</pre></blockquote>
4587     *
4588     * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
4589     *
4590     * @return a method handle embodying the looping behavior as defined by the arguments.
4591     *
4592     * @throws IllegalArgumentException in case any of the constraints described above is violated.
4593     *
4594     * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
4595     * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4596     * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
4597     * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
4598     * @since 9
4599     */
4600    public static MethodHandle loop(MethodHandle[]... clauses) {
4601        // Step 0: determine clause structure.
4602        loopChecks0(clauses);
4603
4604        List<MethodHandle> init = new ArrayList<>();
4605        List<MethodHandle> step = new ArrayList<>();
4606        List<MethodHandle> pred = new ArrayList<>();
4607        List<MethodHandle> fini = new ArrayList<>();
4608
4609        Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
4610            init.add(clause[0]); // all clauses have at least length 1
4611            step.add(clause.length <= 1 ? null : clause[1]);
4612            pred.add(clause.length <= 2 ? null : clause[2]);
4613            fini.add(clause.length <= 3 ? null : clause[3]);
4614        });
4615
4616        assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
4617        final int nclauses = init.size();
4618
4619        // Step 1A: determine iteration variables (V...).
4620        final List<Class<?>> iterationVariableTypes = new ArrayList<>();
4621        for (int i = 0; i < nclauses; ++i) {
4622            MethodHandle in = init.get(i);
4623            MethodHandle st = step.get(i);
4624            if (in == null && st == null) {
4625                iterationVariableTypes.add(void.class);
4626            } else if (in != null && st != null) {
4627                loopChecks1a(i, in, st);
4628                iterationVariableTypes.add(in.type().returnType());
4629            } else {
4630                iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
4631            }
4632        }
4633        final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
4634                collect(Collectors.toList());
4635
4636        // Step 1B: determine loop parameters (A...).
4637        final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
4638        loopChecks1b(init, commonSuffix);
4639
4640        // Step 1C: determine loop return type.
4641        // Step 1D: check other types.
4642        final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
4643                map(MethodType::returnType).findFirst().orElse(void.class);
4644        loopChecks1cd(pred, fini, loopReturnType);
4645
4646        // Step 2: determine parameter lists.
4647        final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
4648        commonParameterSequence.addAll(commonSuffix);
4649        loopChecks2(step, pred, fini, commonParameterSequence);
4650
4651        // Step 3: fill in omitted functions.
4652        for (int i = 0; i < nclauses; ++i) {
4653            Class<?> t = iterationVariableTypes.get(i);
4654            if (init.get(i) == null) {
4655                init.set(i, empty(methodType(t, commonSuffix)));
4656            }
4657            if (step.get(i) == null) {
4658                step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
4659            }
4660            if (pred.get(i) == null) {
4661                pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
4662            }
4663            if (fini.get(i) == null) {
4664                fini.set(i, empty(methodType(t, commonParameterSequence)));
4665            }
4666        }
4667
4668        // Step 4: fill in missing parameter types.
4669        // Also convert all handles to fixed-arity handles.
4670        List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
4671        List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
4672        List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
4673        List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
4674
4675        assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
4676                allMatch(pl -> pl.equals(commonSuffix));
4677        assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
4678                allMatch(pl -> pl.equals(commonParameterSequence));
4679
4680        return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
4681    }
4682
4683    private static void loopChecks0(MethodHandle[][] clauses) {
4684        if (clauses == null || clauses.length == 0) {
4685            throw newIllegalArgumentException("null or no clauses passed");
4686        }
4687        if (Stream.of(clauses).anyMatch(Objects::isNull)) {
4688            throw newIllegalArgumentException("null clauses are not allowed");
4689        }
4690        if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4691            throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4692        }
4693    }
4694
4695    private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
4696        if (in.type().returnType() != st.type().returnType()) {
4697            throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4698                    st.type().returnType());
4699        }
4700    }
4701
4702    private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
4703        final List<Class<?>> empty = List.of();
4704        final List<Class<?>> longest = mhs.filter(Objects::nonNull).
4705                // take only those that can contribute to a common suffix because they are longer than the prefix
4706                        map(MethodHandle::type).
4707                        filter(t -> t.parameterCount() > skipSize).
4708                        map(MethodType::parameterList).
4709                        reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4710        return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size());
4711    }
4712
4713    private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
4714        final List<Class<?>> empty = List.of();
4715        return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4716    }
4717
4718    private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
4719        final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
4720        final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
4721        return longestParameterList(Arrays.asList(longest1, longest2));
4722    }
4723
4724    private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4725        if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
4726                anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
4727            throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4728                    " (common suffix: " + commonSuffix + ")");
4729        }
4730    }
4731
4732    private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4733        if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4734                anyMatch(t -> t != loopReturnType)) {
4735            throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4736                    loopReturnType + ")");
4737        }
4738
4739        if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4740            throw newIllegalArgumentException("no predicate found", pred);
4741        }
4742        if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4743                anyMatch(t -> t != boolean.class)) {
4744            throw newIllegalArgumentException("predicates must have boolean return type", pred);
4745        }
4746    }
4747
4748    private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
4749        if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
4750                anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
4751            throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4752                    "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4753        }
4754    }
4755
4756    private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
4757        return hs.stream().map(h -> {
4758            int pc = h.type().parameterCount();
4759            int tpsize = targetParams.size();
4760            return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
4761        }).collect(Collectors.toList());
4762    }
4763
4764    private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
4765        return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList());
4766    }
4767
4768    /**
4769     * Constructs a {@code while} loop from an initializer, a body, and a predicate.
4770     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4771     * <p>
4772     * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
4773     * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
4774     * evaluates to {@code true}).
4775     * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
4776     * <p>
4777     * The {@code init} handle describes the initial value of an additional optional loop-local variable.
4778     * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
4779     * and updated with the value returned from its invocation. The result of loop execution will be
4780     * the final value of the additional loop-local variable (if present).
4781     * <p>
4782     * The following rules hold for these argument handles:<ul>
4783     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
4784     * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
4785     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
4786     * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
4787     * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
4788     * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
4789     * It will constrain the parameter lists of the other loop parts.
4790     * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
4791     * list {@code (A...)} is called the <em>external parameter list</em>.
4792     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
4793     * additional state variable of the loop.
4794     * The body must both accept and return a value of this type {@code V}.
4795     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
4796     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
4797     * <a href="MethodHandles.html#effid">effectively identical</a>
4798     * to the external parameter list {@code (A...)}.
4799     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
4800     * {@linkplain #empty default value}.
4801     * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
4802     * Its parameter list (either empty or of the form {@code (V A*)}) must be
4803     * effectively identical to the internal parameter list.
4804     * </ul>
4805     * <p>
4806     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
4807     * <li>The loop handle's result type is the result type {@code V} of the body.
4808     * <li>The loop handle's parameter types are the types {@code (A...)},
4809     * from the external parameter list.
4810     * </ul>
4811     * <p>
4812     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4813     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4814     * passed to the loop.
4815     * <blockquote><pre>{@code
4816     * V init(A...);
4817     * boolean pred(V, A...);
4818     * V body(V, A...);
4819     * V whileLoop(A... a...) {
4820     *   V v = init(a...);
4821     *   while (pred(v, a...)) {
4822     *     v = body(v, a...);
4823     *   }
4824     *   return v;
4825     * }
4826     * }</pre></blockquote>
4827     * <p>
4828     * @apiNote Example:
4829     * <blockquote><pre>{@code
4830     * // implement the zip function for lists as a loop handle
4831     * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
4832     * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
4833     * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
4834     *   zip.add(a.next());
4835     *   zip.add(b.next());
4836     *   return zip;
4837     * }
4838     * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
4839     * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
4840     * List<String> a = Arrays.asList("a", "b", "c", "d");
4841     * List<String> b = Arrays.asList("e", "f", "g", "h");
4842     * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
4843     * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
4844     * }</pre></blockquote>
4845     *
4846     * <p>
4847     * @apiNote The implementation of this method can be expressed as follows:
4848     * <blockquote><pre>{@code
4849     * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4850     *     MethodHandle fini = (body.type().returnType() == void.class
4851     *                         ? null : identity(body.type().returnType()));
4852     *     MethodHandle[]
4853     *         checkExit = { null, null, pred, fini },
4854     *         varBody   = { init, body };
4855     *     return loop(checkExit, varBody);
4856     * }
4857     * }</pre></blockquote>
4858     *
4859     * @param init optional initializer, providing the initial value of the loop variable.
4860     *             May be {@code null}, implying a default initial value.  See above for other constraints.
4861     * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
4862     *             above for other constraints.
4863     * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
4864     *             See above for other constraints.
4865     *
4866     * @return a method handle implementing the {@code while} loop as described by the arguments.
4867     * @throws IllegalArgumentException if the rules for the arguments are violated.
4868     * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
4869     *
4870     * @see #loop(MethodHandle[][])
4871     * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4872     * @since 9
4873     */
4874    public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4875        whileLoopChecks(init, pred, body);
4876        MethodHandle fini = identityOrVoid(body.type().returnType());
4877        MethodHandle[] checkExit = { null, null, pred, fini };
4878        MethodHandle[] varBody = { init, body };
4879        return loop(checkExit, varBody);
4880    }
4881
4882    /**
4883     * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
4884     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4885     * <p>
4886     * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
4887     * method will, in each iteration, first execute its body and then evaluate the predicate.
4888     * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
4889     * <p>
4890     * The {@code init} handle describes the initial value of an additional optional loop-local variable.
4891     * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
4892     * and updated with the value returned from its invocation. The result of loop execution will be
4893     * the final value of the additional loop-local variable (if present).
4894     * <p>
4895     * The following rules hold for these argument handles:<ul>
4896     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
4897     * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
4898     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
4899     * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
4900     * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
4901     * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
4902     * It will constrain the parameter lists of the other loop parts.
4903     * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
4904     * list {@code (A...)} is called the <em>external parameter list</em>.
4905     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
4906     * additional state variable of the loop.
4907     * The body must both accept and return a value of this type {@code V}.
4908     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
4909     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
4910     * <a href="MethodHandles.html#effid">effectively identical</a>
4911     * to the external parameter list {@code (A...)}.
4912     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
4913     * {@linkplain #empty default value}.
4914     * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
4915     * Its parameter list (either empty or of the form {@code (V A*)}) must be
4916     * effectively identical to the internal parameter list.
4917     * </ul>
4918     * <p>
4919     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
4920     * <li>The loop handle's result type is the result type {@code V} of the body.
4921     * <li>The loop handle's parameter types are the types {@code (A...)},
4922     * from the external parameter list.
4923     * </ul>
4924     * <p>
4925     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4926     * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4927     * passed to the loop.
4928     * <blockquote><pre>{@code
4929     * V init(A...);
4930     * boolean pred(V, A...);
4931     * V body(V, A...);
4932     * V doWhileLoop(A... a...) {
4933     *   V v = init(a...);
4934     *   do {
4935     *     v = body(v, a...);
4936     *   } while (pred(v, a...));
4937     *   return v;
4938     * }
4939     * }</pre></blockquote>
4940     * <p>
4941     * @apiNote Example:
4942     * <blockquote><pre>{@code
4943     * // int i = 0; while (i < limit) { ++i; } return i; => limit
4944     * static int zero(int limit) { return 0; }
4945     * static int step(int i, int limit) { return i + 1; }
4946     * static boolean pred(int i, int limit) { return i < limit; }
4947     * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
4948     * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
4949     * assertEquals(23, loop.invoke(23));
4950     * }</pre></blockquote>
4951     *
4952     * <p>
4953     * @apiNote The implementation of this method can be expressed as follows:
4954     * <blockquote><pre>{@code
4955     * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4956     *     MethodHandle fini = (body.type().returnType() == void.class
4957     *                         ? null : identity(body.type().returnType()));
4958     *     MethodHandle[] clause = { init, body, pred, fini };
4959     *     return loop(clause);
4960     * }
4961     * }</pre></blockquote>
4962     *
4963     * @param init optional initializer, providing the initial value of the loop variable.
4964     *             May be {@code null}, implying a default initial value.  See above for other constraints.
4965     * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
4966     *             See above for other constraints.
4967     * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
4968     *             above for other constraints.
4969     *
4970     * @return a method handle implementing the {@code while} loop as described by the arguments.
4971     * @throws IllegalArgumentException if the rules for the arguments are violated.
4972     * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
4973     *
4974     * @see #loop(MethodHandle[][])
4975     * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
4976     * @since 9
4977     */
4978    public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4979        whileLoopChecks(init, pred, body);
4980        MethodHandle fini = identityOrVoid(body.type().returnType());
4981        MethodHandle[] clause = {init, body, pred, fini };
4982        return loop(clause);
4983    }
4984
4985    private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
4986        Objects.requireNonNull(pred);
4987        Objects.requireNonNull(body);
4988        MethodType bodyType = body.type();
4989        Class<?> returnType = bodyType.returnType();
4990        List<Class<?>> innerList = bodyType.parameterList();
4991        List<Class<?>> outerList = innerList;
4992        if (returnType == void.class) {
4993            // OK
4994        } else if (innerList.size() == 0 || innerList.get(0) != returnType) {
4995            // leading V argument missing => error
4996            MethodType expected = bodyType.insertParameterTypes(0, returnType);
4997            throw misMatchedTypes("body function", bodyType, expected);
4998        } else {
4999            outerList = innerList.subList(1, innerList.size());
5000        }
5001        MethodType predType = pred.type();
5002        if (predType.returnType() != boolean.class ||
5003                !predType.effectivelyIdenticalParameters(0, innerList)) {
5004            throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
5005        }
5006        if (init != null) {
5007            MethodType initType = init.type();
5008            if (initType.returnType() != returnType ||
5009                    !initType.effectivelyIdenticalParameters(0, outerList)) {
5010                throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
5011            }
5012        }
5013    }
5014
5015    /**
5016     * Constructs a loop that runs a given number of iterations.
5017     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5018     * <p>
5019     * The number of iterations is determined by the {@code iterations} handle evaluation result.
5020     * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
5021     * It will be initialized to 0 and incremented by 1 in each iteration.
5022     * <p>
5023     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5024     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
5025     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5026     * <p>
5027     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5028     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5029     * iteration variable.
5030     * The result of the loop handle execution will be the final {@code V} value of that variable
5031     * (or {@code void} if there is no {@code V} variable).
5032     * <p>
5033     * The following rules hold for the argument handles:<ul>
5034     * <li>The {@code iterations} handle must not be {@code null}, and must return
5035     * the type {@code int}, referred to here as {@code I} in parameter type lists.
5036     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5037     * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
5038     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5039     * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
5040     * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
5041     * <li>The parameter list {@code (V I A...)} of the body contributes to a list
5042     * of types called the <em>internal parameter list</em>.
5043     * It will constrain the parameter lists of the other loop parts.
5044     * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
5045     * with no additional {@code A} types, then the internal parameter list is extended by
5046     * the argument types {@code A...} of the {@code iterations} handle.
5047     * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
5048     * list {@code (A...)} is called the <em>external parameter list</em>.
5049     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5050     * additional state variable of the loop.
5051     * The body must both accept a leading parameter and return a value of this type {@code V}.
5052     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5053     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5054     * <a href="MethodHandles.html#effid">effectively identical</a>
5055     * to the external parameter list {@code (A...)}.
5056     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5057     * {@linkplain #empty default value}.
5058     * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
5059     * effectively identical to the external parameter list {@code (A...)}.
5060     * </ul>
5061     * <p>
5062     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5063     * <li>The loop handle's result type is the result type {@code V} of the body.
5064     * <li>The loop handle's parameter types are the types {@code (A...)},
5065     * from the external parameter list.
5066     * </ul>
5067     * <p>
5068     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5069     * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
5070     * arguments passed to the loop.
5071     * <blockquote><pre>{@code
5072     * int iterations(A...);
5073     * V init(A...);
5074     * V body(V, int, A...);
5075     * V countedLoop(A... a...) {
5076     *   int end = iterations(a...);
5077     *   V v = init(a...);
5078     *   for (int i = 0; i < end; ++i) {
5079     *     v = body(v, i, a...);
5080     *   }
5081     *   return v;
5082     * }
5083     * }</pre></blockquote>
5084     * <p>
5085     * @apiNote Example with a fully conformant body method:
5086     * <blockquote><pre>{@code
5087     * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
5088     * // => a variation on a well known theme
5089     * static String step(String v, int counter, String init) { return "na " + v; }
5090     * // assume MH_step is a handle to the method above
5091     * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
5092     * MethodHandle start = MethodHandles.identity(String.class);
5093     * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
5094     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
5095     * }</pre></blockquote>
5096     * <p>
5097     * @apiNote Example with the simplest possible body method type,
5098     * and passing the number of iterations to the loop invocation:
5099     * <blockquote><pre>{@code
5100     * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
5101     * // => a variation on a well known theme
5102     * static String step(String v, int counter ) { return "na " + v; }
5103     * // assume MH_step is a handle to the method above
5104     * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
5105     * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
5106     * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
5107     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
5108     * }</pre></blockquote>
5109     * <p>
5110     * @apiNote Example that treats the number of iterations, string to append to, and string to append
5111     * as loop parameters:
5112     * <blockquote><pre>{@code
5113     * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5114     * // => a variation on a well known theme
5115     * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
5116     * // assume MH_step is a handle to the method above
5117     * MethodHandle count = MethodHandles.identity(int.class);
5118     * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
5119     * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
5120     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
5121     * }</pre></blockquote>
5122     * <p>
5123     * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
5124     * to enforce a loop type:
5125     * <blockquote><pre>{@code
5126     * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5127     * // => a variation on a well known theme
5128     * static String step(String v, int counter, String pre) { return pre + " " + v; }
5129     * // assume MH_step is a handle to the method above
5130     * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
5131     * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
5132     * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
5133     * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
5134     * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
5135     * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
5136     * }</pre></blockquote>
5137     * <p>
5138     * @apiNote The implementation of this method can be expressed as follows:
5139     * <blockquote><pre>{@code
5140     * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5141     *     return countedLoop(empty(iterations.type()), iterations, init, body);
5142     * }
5143     * }</pre></blockquote>
5144     *
5145     * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
5146     *                   result type must be {@code int}. See above for other constraints.
5147     * @param init optional initializer, providing the initial value of the loop variable.
5148     *             May be {@code null}, implying a default initial value.  See above for other constraints.
5149     * @param body body of the loop, which may not be {@code null}.
5150     *             It controls the loop parameters and result type in the standard case (see above for details).
5151     *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5152     *             and may accept any number of additional types.
5153     *             See above for other constraints.
5154     *
5155     * @return a method handle representing the loop.
5156     * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
5157     * @throws IllegalArgumentException if any argument violates the rules formulated above.
5158     *
5159     * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
5160     * @since 9
5161     */
5162    public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5163        return countedLoop(empty(iterations.type()), iterations, init, body);
5164    }
5165
5166    /**
5167     * Constructs a loop that counts over a range of numbers.
5168     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5169     * <p>
5170     * The loop counter {@code i} is a loop iteration variable of type {@code int}.
5171     * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
5172     * values of the loop counter.
5173     * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
5174     * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
5175     * <p>
5176     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5177     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
5178     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5179     * <p>
5180     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5181     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5182     * iteration variable.
5183     * The result of the loop handle execution will be the final {@code V} value of that variable
5184     * (or {@code void} if there is no {@code V} variable).
5185     * <p>
5186     * The following rules hold for the argument handles:<ul>
5187     * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
5188     * the common type {@code int}, referred to here as {@code I} in parameter type lists.
5189     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5190     * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
5191     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5192     * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
5193     * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
5194     * <li>The parameter list {@code (V I A...)} of the body contributes to a list
5195     * of types called the <em>internal parameter list</em>.
5196     * It will constrain the parameter lists of the other loop parts.
5197     * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
5198     * with no additional {@code A} types, then the internal parameter list is extended by
5199     * the argument types {@code A...} of the {@code end} handle.
5200     * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
5201     * list {@code (A...)} is called the <em>external parameter list</em>.
5202     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5203     * additional state variable of the loop.
5204     * The body must both accept a leading parameter and return a value of this type {@code V}.
5205     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5206     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5207     * <a href="MethodHandles.html#effid">effectively identical</a>
5208     * to the external parameter list {@code (A...)}.
5209     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5210     * {@linkplain #empty default value}.
5211     * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
5212     * effectively identical to the external parameter list {@code (A...)}.
5213     * <li>Likewise, the parameter list of {@code end} must be effectively identical
5214     * to the external parameter list.
5215     * </ul>
5216     * <p>
5217     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5218     * <li>The loop handle's result type is the result type {@code V} of the body.
5219     * <li>The loop handle's parameter types are the types {@code (A...)},
5220     * from the external parameter list.
5221     * </ul>
5222     * <p>
5223     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5224     * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
5225     * arguments passed to the loop.
5226     * <blockquote><pre>{@code
5227     * int start(A...);
5228     * int end(A...);
5229     * V init(A...);
5230     * V body(V, int, A...);
5231     * V countedLoop(A... a...) {
5232     *   int e = end(a...);
5233     *   int s = start(a...);
5234     *   V v = init(a...);
5235     *   for (int i = s; i < e; ++i) {
5236     *     v = body(v, i, a...);
5237     *   }
5238     *   return v;
5239     * }
5240     * }</pre></blockquote>
5241     *
5242     * <p>
5243     * @apiNote The implementation of this method can be expressed as follows:
5244     * <blockquote><pre>{@code
5245     * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5246     *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
5247     *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
5248     *     // the following semantics:
5249     *     // MH_increment: (int limit, int counter) -> counter + 1
5250     *     // MH_predicate: (int limit, int counter) -> counter < limit
5251     *     Class<?> counterType = start.type().returnType();  // int
5252     *     Class<?> returnType = body.type().returnType();
5253     *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
5254     *     if (returnType != void.class) {  // ignore the V variable
5255     *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
5256     *         pred = dropArguments(pred, 1, returnType);  // ditto
5257     *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
5258     *     }
5259     *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
5260     *     MethodHandle[]
5261     *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
5262     *         bodyClause = { init, body },            // v = init(); v = body(v, i)
5263     *         indexVar   = { start, incr };           // i = start(); i = i + 1
5264     *     return loop(loopLimit, bodyClause, indexVar);
5265     * }
5266     * }</pre></blockquote>
5267     *
5268     * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
5269     *              See above for other constraints.
5270     * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
5271     *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
5272     * @param init optional initializer, providing the initial value of the loop variable.
5273     *             May be {@code null}, implying a default initial value.  See above for other constraints.
5274     * @param body body of the loop, which may not be {@code null}.
5275     *             It controls the loop parameters and result type in the standard case (see above for details).
5276     *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5277     *             and may accept any number of additional types.
5278     *             See above for other constraints.
5279     *
5280     * @return a method handle representing the loop.
5281     * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
5282     * @throws IllegalArgumentException if any argument violates the rules formulated above.
5283     *
5284     * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
5285     * @since 9
5286     */
5287    public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5288        countedLoopChecks(start, end, init, body);
5289        Class<?> counterType = start.type().returnType();  // int, but who's counting?
5290        Class<?> limitType   = end.type().returnType();    // yes, int again
5291        Class<?> returnType  = body.type().returnType();
5292        MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
5293        MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
5294        MethodHandle retv = null;
5295        if (returnType != void.class) {
5296            incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
5297            pred = dropArguments(pred, 1, returnType);  // ditto
5298            retv = dropArguments(identity(returnType), 0, counterType);
5299        }
5300        body = dropArguments(body, 0, counterType);  // ignore the limit variable
5301        MethodHandle[]
5302            loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
5303            bodyClause = { init, body },            // v = init(); v = body(v, i)
5304            indexVar   = { start, incr };           // i = start(); i = i + 1
5305        return loop(loopLimit, bodyClause, indexVar);
5306    }
5307
5308    private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5309        Objects.requireNonNull(start);
5310        Objects.requireNonNull(end);
5311        Objects.requireNonNull(body);
5312        Class<?> counterType = start.type().returnType();
5313        if (counterType != int.class) {
5314            MethodType expected = start.type().changeReturnType(int.class);
5315            throw misMatchedTypes("start function", start.type(), expected);
5316        } else if (end.type().returnType() != counterType) {
5317            MethodType expected = end.type().changeReturnType(counterType);
5318            throw misMatchedTypes("end function", end.type(), expected);
5319        }
5320        MethodType bodyType = body.type();
5321        Class<?> returnType = bodyType.returnType();
5322        List<Class<?>> innerList = bodyType.parameterList();
5323        // strip leading V value if present
5324        int vsize = (returnType == void.class ? 0 : 1);
5325        if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) {
5326            // argument list has no "V" => error
5327            MethodType expected = bodyType.insertParameterTypes(0, returnType);
5328            throw misMatchedTypes("body function", bodyType, expected);
5329        } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
5330            // missing I type => error
5331            MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
5332            throw misMatchedTypes("body function", bodyType, expected);
5333        }
5334        List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
5335        if (outerList.isEmpty()) {
5336            // special case; take lists from end handle
5337            outerList = end.type().parameterList();
5338            innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
5339        }
5340        MethodType expected = methodType(counterType, outerList);
5341        if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
5342            throw misMatchedTypes("start parameter types", start.type(), expected);
5343        }
5344        if (end.type() != start.type() &&
5345            !end.type().effectivelyIdenticalParameters(0, outerList)) {
5346            throw misMatchedTypes("end parameter types", end.type(), expected);
5347        }
5348        if (init != null) {
5349            MethodType initType = init.type();
5350            if (initType.returnType() != returnType ||
5351                !initType.effectivelyIdenticalParameters(0, outerList)) {
5352                throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
5353            }
5354        }
5355    }
5356
5357    /**
5358     * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
5359     * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5360     * <p>
5361     * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
5362     * Each value it produces will be stored in a loop iteration variable of type {@code T}.
5363     * <p>
5364     * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5365     * of that type is also present.  This variable is initialized using the optional {@code init} handle,
5366     * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5367     * <p>
5368     * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5369     * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5370     * iteration variable.
5371     * The result of the loop handle execution will be the final {@code V} value of that variable
5372     * (or {@code void} if there is no {@code V} variable).
5373     * <p>
5374     * The following rules hold for the argument handles:<ul>
5375     * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5376     * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
5377     * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5378     * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
5379     * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
5380     * <li>The parameter list {@code (V T A...)} of the body contributes to a list
5381     * of types called the <em>internal parameter list</em>.
5382     * It will constrain the parameter lists of the other loop parts.
5383     * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
5384     * with no additional {@code A} types, then the internal parameter list is extended by
5385     * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
5386     * single type {@code Iterable} is added and constitutes the {@code A...} list.
5387     * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
5388     * list {@code (A...)} is called the <em>external parameter list</em>.
5389     * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5390     * additional state variable of the loop.
5391     * The body must both accept a leading parameter and return a value of this type {@code V}.
5392     * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5393     * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5394     * <a href="MethodHandles.html#effid">effectively identical</a>
5395     * to the external parameter list {@code (A...)}.
5396     * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5397     * {@linkplain #empty default value}.
5398     * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
5399     * type {@code java.util.Iterator} or a subtype thereof.
5400     * The iterator it produces when the loop is executed will be assumed
5401     * to yield values which can be converted to type {@code T}.
5402     * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
5403     * effectively identical to the external parameter list {@code (A...)}.
5404     * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
5405     * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
5406     * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
5407     * handle parameter is adjusted to accept the leading {@code A} type, as if by
5408     * the {@link MethodHandle#asType asType} conversion method.
5409     * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
5410     * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
5411     * </ul>
5412     * <p>
5413     * The type {@code T} may be either a primitive or reference.
5414     * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
5415     * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
5416     * as if by the {@link MethodHandle#asType asType} conversion method.
5417     * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
5418     * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
5419     * <p>
5420     * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5421     * <li>The loop handle's result type is the result type {@code V} of the body.
5422     * <li>The loop handle's parameter types are the types {@code (A...)},
5423     * from the external parameter list.
5424     * </ul>
5425     * <p>
5426     * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5427     * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
5428     * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
5429     * <blockquote><pre>{@code
5430     * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
5431     * V init(A...);
5432     * V body(V,T,A...);
5433     * V iteratedLoop(A... a...) {
5434     *   Iterator<T> it = iterator(a...);
5435     *   V v = init(a...);
5436     *   while (it.hasNext()) {
5437     *     T t = it.next();
5438     *     v = body(v, t, a...);
5439     *   }
5440     *   return v;
5441     * }
5442     * }</pre></blockquote>
5443     * <p>
5444     * @apiNote Example:
5445     * <blockquote><pre>{@code
5446     * // get an iterator from a list
5447     * static List<String> reverseStep(List<String> r, String e) {
5448     *   r.add(0, e);
5449     *   return r;
5450     * }
5451     * static List<String> newArrayList() { return new ArrayList<>(); }
5452     * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
5453     * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
5454     * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
5455     * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
5456     * assertEquals(reversedList, (List<String>) loop.invoke(list));
5457     * }</pre></blockquote>
5458     * <p>
5459     * @apiNote The implementation of this method can be expressed approximately as follows:
5460     * <blockquote><pre>{@code
5461     * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5462     *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
5463     *     Class<?> returnType = body.type().returnType();
5464     *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
5465     *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
5466     *     MethodHandle retv = null, step = body, startIter = iterator;
5467     *     if (returnType != void.class) {
5468     *         // the simple thing first:  in (I V A...), drop the I to get V
5469     *         retv = dropArguments(identity(returnType), 0, Iterator.class);
5470     *         // body type signature (V T A...), internal loop types (I V A...)
5471     *         step = swapArguments(body, 0, 1);  // swap V <-> T
5472     *     }
5473     *     if (startIter == null)  startIter = MH_getIter;
5474     *     MethodHandle[]
5475     *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
5476     *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
5477     *     return loop(iterVar, bodyClause);
5478     * }
5479     * }</pre></blockquote>
5480     *
5481     * @param iterator an optional handle to return the iterator to start the loop.
5482     *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
5483     *                 See above for other constraints.
5484     * @param init optional initializer, providing the initial value of the loop variable.
5485     *             May be {@code null}, implying a default initial value.  See above for other constraints.
5486     * @param body body of the loop, which may not be {@code null}.
5487     *             It controls the loop parameters and result type in the standard case (see above for details).
5488     *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
5489     *             and may accept any number of additional types.
5490     *             See above for other constraints.
5491     *
5492     * @return a method handle embodying the iteration loop functionality.
5493     * @throws NullPointerException if the {@code body} handle is {@code null}.
5494     * @throws IllegalArgumentException if any argument violates the above requirements.
5495     *
5496     * @since 9
5497     */
5498    public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5499        Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
5500        Class<?> returnType = body.type().returnType();
5501        MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
5502        MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
5503        MethodHandle startIter;
5504        MethodHandle nextVal;
5505        {
5506            MethodType iteratorType;
5507            if (iterator == null) {
5508                // derive argument type from body, if available, else use Iterable
5509                startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
5510                iteratorType = startIter.type().changeParameterType(0, iterableType);
5511            } else {
5512                // force return type to the internal iterator class
5513                iteratorType = iterator.type().changeReturnType(Iterator.class);
5514                startIter = iterator;
5515            }
5516            Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
5517            MethodType nextValType = nextRaw.type().changeReturnType(ttype);
5518
5519            // perform the asType transforms under an exception transformer, as per spec.:
5520            try {
5521                startIter = startIter.asType(iteratorType);
5522                nextVal = nextRaw.asType(nextValType);
5523            } catch (WrongMethodTypeException ex) {
5524                throw new IllegalArgumentException(ex);
5525            }
5526        }
5527
5528        MethodHandle retv = null, step = body;
5529        if (returnType != void.class) {
5530            // the simple thing first:  in (I V A...), drop the I to get V
5531            retv = dropArguments(identity(returnType), 0, Iterator.class);
5532            // body type signature (V T A...), internal loop types (I V A...)
5533            step = swapArguments(body, 0, 1);  // swap V <-> T
5534        }
5535
5536        MethodHandle[]
5537            iterVar    = { startIter, null, hasNext, retv },
5538            bodyClause = { init, filterArgument(step, 0, nextVal) };
5539        return loop(iterVar, bodyClause);
5540    }
5541
5542    private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5543        Objects.requireNonNull(body);
5544        MethodType bodyType = body.type();
5545        Class<?> returnType = bodyType.returnType();
5546        List<Class<?>> internalParamList = bodyType.parameterList();
5547        // strip leading V value if present
5548        int vsize = (returnType == void.class ? 0 : 1);
5549        if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) {
5550            // argument list has no "V" => error
5551            MethodType expected = bodyType.insertParameterTypes(0, returnType);
5552            throw misMatchedTypes("body function", bodyType, expected);
5553        } else if (internalParamList.size() <= vsize) {
5554            // missing T type => error
5555            MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
5556            throw misMatchedTypes("body function", bodyType, expected);
5557        }
5558        List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
5559        Class<?> iterableType = null;
5560        if (iterator != null) {
5561            // special case; if the body handle only declares V and T then
5562            // the external parameter list is obtained from iterator handle
5563            if (externalParamList.isEmpty()) {
5564                externalParamList = iterator.type().parameterList();
5565            }
5566            MethodType itype = iterator.type();
5567            if (!Iterator.class.isAssignableFrom(itype.returnType())) {
5568                throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
5569            }
5570            if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
5571                MethodType expected = methodType(itype.returnType(), externalParamList);
5572                throw misMatchedTypes("iterator parameters", itype, expected);
5573            }
5574        } else {
5575            if (externalParamList.isEmpty()) {
5576                // special case; if the iterator handle is null and the body handle
5577                // only declares V and T then the external parameter list consists
5578                // of Iterable
5579                externalParamList = Arrays.asList(Iterable.class);
5580                iterableType = Iterable.class;
5581            } else {
5582                // special case; if the iterator handle is null and the external
5583                // parameter list is not empty then the first parameter must be
5584                // assignable to Iterable
5585                iterableType = externalParamList.get(0);
5586                if (!Iterable.class.isAssignableFrom(iterableType)) {
5587                    throw newIllegalArgumentException(
5588                            "inferred first loop argument must inherit from Iterable: " + iterableType);
5589                }
5590            }
5591        }
5592        if (init != null) {
5593            MethodType initType = init.type();
5594            if (initType.returnType() != returnType ||
5595                    !initType.effectivelyIdenticalParameters(0, externalParamList)) {
5596                throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
5597            }
5598        }
5599        return iterableType;  // help the caller a bit
5600    }
5601
5602    /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
5603        // there should be a better way to uncross my wires
5604        int arity = mh.type().parameterCount();
5605        int[] order = new int[arity];
5606        for (int k = 0; k < arity; k++)  order[k] = k;
5607        order[i] = j; order[j] = i;
5608        Class<?>[] types = mh.type().parameterArray();
5609        Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
5610        MethodType swapType = methodType(mh.type().returnType(), types);
5611        return permuteArguments(mh, swapType, order);
5612    }
5613
5614    /**
5615     * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
5616     * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
5617     * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
5618     * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
5619     * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
5620     * {@code try-finally} handle.
5621     * <p>
5622     * The {@code cleanup} handle will be passed one or two additional leading arguments.
5623     * The first is the exception thrown during the
5624     * execution of the {@code target} handle, or {@code null} if no exception was thrown.
5625     * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
5626     * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
5627     * The second argument is not present if the {@code target} handle has a {@code void} return type.
5628     * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
5629     * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
5630     * <p>
5631     * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
5632     * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
5633     * two extra leading parameters:<ul>
5634     * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
5635     * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
5636     * the result from the execution of the {@code target} handle.
5637     * This parameter is not present if the {@code target} returns {@code void}.
5638     * </ul>
5639     * <p>
5640     * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
5641     * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
5642     * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
5643     * the cleanup.
5644     * <blockquote><pre>{@code
5645     * V target(A..., B...);
5646     * V cleanup(Throwable, V, A...);
5647     * V adapter(A... a, B... b) {
5648     *   V result = (zero value for V);
5649     *   Throwable throwable = null;
5650     *   try {
5651     *     result = target(a..., b...);
5652     *   } catch (Throwable t) {
5653     *     throwable = t;
5654     *     throw t;
5655     *   } finally {
5656     *     result = cleanup(throwable, result, a...);
5657     *   }
5658     *   return result;
5659     * }
5660     * }</pre></blockquote>
5661     * <p>
5662     * Note that the saved arguments ({@code a...} in the pseudocode) cannot
5663     * be modified by execution of the target, and so are passed unchanged
5664     * from the caller to the cleanup, if it is invoked.
5665     * <p>
5666     * The target and cleanup must return the same type, even if the cleanup
5667     * always throws.
5668     * To create such a throwing cleanup, compose the cleanup logic
5669     * with {@link #throwException throwException},
5670     * in order to create a method handle of the correct return type.
5671     * <p>
5672     * Note that {@code tryFinally} never converts exceptions into normal returns.
5673     * In rare cases where exceptions must be converted in that way, first wrap
5674     * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
5675     * to capture an outgoing exception, and then wrap with {@code tryFinally}.
5676     *
5677     * @param target the handle whose execution is to be wrapped in a {@code try} block.
5678     * @param cleanup the handle that is invoked in the finally block.
5679     *
5680     * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
5681     * @throws NullPointerException if any argument is null
5682     * @throws IllegalArgumentException if {@code cleanup} does not accept
5683     *          the required leading arguments, or if the method handle types do
5684     *          not match in their return types and their
5685     *          corresponding trailing parameters
5686     *
5687     * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
5688     * @since 9
5689     */
5690    public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
5691        List<Class<?>> targetParamTypes = target.type().parameterList();
5692        List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
5693        Class<?> rtype = target.type().returnType();
5694
5695        tryFinallyChecks(target, cleanup);
5696
5697        // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
5698        // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
5699        // target parameter list.
5700        cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
5701
5702        // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
5703        return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
5704    }
5705
5706    private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
5707        Class<?> rtype = target.type().returnType();
5708        if (rtype != cleanup.type().returnType()) {
5709            throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
5710        }
5711        MethodType cleanupType = cleanup.type();
5712        if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
5713            throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
5714        }
5715        if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
5716            throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
5717        }
5718        // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
5719        // target parameter list.
5720        int cleanupArgIndex = rtype == void.class ? 1 : 2;
5721        if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
5722            throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
5723                    cleanup.type(), target.type());
5724        }
5725    }
5726
5727}
5728