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