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