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