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