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