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