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