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