1 /*
   2  * Copyright (c) 2008, 2021, 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.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.Reflection;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 import sun.invoke.util.ValueConversions;
  38 import sun.invoke.util.VerifyAccess;
  39 import sun.invoke.util.Wrapper;
  40 import sun.reflect.misc.ReflectUtil;
  41 import sun.security.util.SecurityConstants;
  42 
  43 import java.lang.constant.ConstantDescs;
  44 import java.lang.invoke.LambdaForm.BasicType;
  45 import java.lang.reflect.Constructor;
  46 import java.lang.reflect.Field;
  47 import java.lang.reflect.Member;
  48 import java.lang.reflect.Method;
  49 import java.lang.reflect.Modifier;
  50 import java.lang.reflect.ReflectPermission;
  51 import java.nio.ByteOrder;
  52 import java.security.ProtectionDomain;
  53 import java.util.ArrayList;
  54 import java.util.Arrays;
  55 import java.util.BitSet;
  56 import java.util.Iterator;
  57 import java.util.List;
  58 import java.util.Objects;
  59 import java.util.Set;
  60 import java.util.concurrent.ConcurrentHashMap;
  61 import java.util.stream.Stream;
  62 
  63 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  64 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  65 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  66 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  67 import static java.lang.invoke.MethodType.methodType;
  68 
  69 /**
  70  * This class consists exclusively of static methods that operate on or return
  71  * method handles. They fall into several categories:
  72  * <ul>
  73  * <li>Lookup methods which help create method handles for methods and fields.
  74  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  75  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  76  * </ul>
  77  * A lookup, combinator, or factory method will fail and throw an
  78  * {@code IllegalArgumentException} if the created method handle's type
  79  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  80  *
  81  * @author John Rose, JSR 292 EG
  82  * @since 1.7
  83  */
  84 public class MethodHandles {
  85 
  86     private MethodHandles() { }  // do not instantiate
  87 
  88     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  89 
  90     // See IMPL_LOOKUP below.
  91 
  92     //// Method handle creation from ordinary methods.
  93 
  94     /**
  95      * Returns a {@link Lookup lookup object} with
  96      * full capabilities to emulate all supported bytecode behaviors of the caller.
  97      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
  98      * Factory methods on the lookup object can create
  99      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 100      * for any member that the caller has access to via bytecodes,
 101      * including protected and private fields and methods.
 102      * This lookup object is created by the original lookup class
 103      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 104      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 105      * Do not store it in place where untrusted code can access it.
 106      * <p>
 107      * This method is caller sensitive, which means that it may return different
 108      * values to different callers.
 109      * @return a lookup object for the caller of this method, with
 110      * {@linkplain Lookup#ORIGINAL original} and
 111      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 112      */
 113     @CallerSensitive
 114     @ForceInline // to ensure Reflection.getCallerClass optimization
 115     public static Lookup lookup() {
 116         return new Lookup(Reflection.getCallerClass());
 117     }
 118 
 119     /**
 120      * This reflected$lookup method is the alternate implementation of
 121      * the lookup method when being invoked by reflection.
 122      */
 123     @CallerSensitive
 124     private static Lookup reflected$lookup() {
 125         Class<?> caller = Reflection.getCallerClass();
 126         if (caller.getClassLoader() == null) {
 127             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 128         }
 129         return new Lookup(caller);
 130     }
 131 
 132     /**
 133      * Returns a {@link Lookup lookup object} which is trusted minimally.
 134      * The lookup has the {@code UNCONDITIONAL} mode.
 135      * It can only be used to create method handles to public members of
 136      * public classes in packages that are exported unconditionally.
 137      * <p>
 138      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 139      * of this lookup object will be {@link java.lang.Object}.
 140      *
 141      * @apiNote The use of Object is conventional, and because the lookup modes are
 142      * limited, there is no special access provided to the internals of Object, its package
 143      * or its module.  This public lookup object or other lookup object with
 144      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 145      * is not used to determine the lookup context.
 146      *
 147      * <p style="font-size:smaller;">
 148      * <em>Discussion:</em>
 149      * The lookup class can be changed to any other class {@code C} using an expression of the form
 150      * {@link Lookup#in publicLookup().in(C.class)}.
 151      * A public lookup object is always subject to
 152      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 153      * Also, it cannot access
 154      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 155      * @return a lookup object which is trusted minimally
 156      *
 157      * @revised 9
 158      */
 159     public static Lookup publicLookup() {
 160         return Lookup.PUBLIC_LOOKUP;
 161     }
 162 
 163     /**
 164      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 165      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 166      * The returned lookup object can provide access to classes in modules and packages,
 167      * and members of those classes, outside the normal rules of Java access control,
 168      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 169      * <p>
 170      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 171      * allowed to do deep reflection on module {@code M2} and package of the target class
 172      * if and only if all of the following conditions are {@code true}:
 173      * <ul>
 174      * <li>If there is a security manager, its {@code checkPermission} method is
 175      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 176      * that must return normally.
 177      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 178      * full privilege access}.  Specifically:
 179      *   <ul>
 180      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 181      *         (This is because otherwise there would be no way to ensure the original lookup
 182      *         creator was a member of any particular module, and so any subsequent checks
 183      *         for readability and qualified exports would become ineffective.)
 184      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 185      *         (This is because an application intending to share intra-module access
 186      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 187      *         deep reflection to its own module.)
 188      *   </ul>
 189      * <li>The target class must be a proper class, not a primitive or array class.
 190      * (Thus, {@code M2} is well-defined.)
 191      * <li>If the caller module {@code M1} differs from
 192      * the target module {@code M2} then both of the following must be true:
 193      *   <ul>
 194      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 195      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 196      *         containing the target class to at least {@code M1}.</li>
 197      *   </ul>
 198      * </ul>
 199      * <p>
 200      * If any of the above checks is violated, this method fails with an
 201      * exception.
 202      * <p>
 203      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 204      * returns a {@code Lookup} on {@code targetClass} with
 205      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 206      * with {@code null} previous lookup class.
 207      * <p>
 208      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 209      * returns a {@code Lookup} on {@code targetClass} that records
 210      * the lookup class of the caller as the new previous lookup class with
 211      * {@code PRIVATE} access but no {@code MODULE} access.
 212      * <p>
 213      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 214      *
 215      * @param targetClass the target class
 216      * @param caller the caller lookup object
 217      * @return a lookup object for the target class, with private access
 218      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 219      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 220      * @throws SecurityException if denied by the security manager
 221      * @throws IllegalAccessException if any of the other access checks specified above fails
 222      * @since 9
 223      * @see Lookup#dropLookupMode
 224      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 225      */
 226     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 227         if (caller.allowedModes == Lookup.TRUSTED) {
 228             return new Lookup(targetClass);
 229         }
 230 
 231         @SuppressWarnings("removal")
 232         SecurityManager sm = System.getSecurityManager();
 233         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 234         if (targetClass.isPrimitive())
 235             throw new IllegalArgumentException(targetClass + " is a primitive class");
 236         if (targetClass.isArray())
 237             throw new IllegalArgumentException(targetClass + " is an array class");
 238         // Ensure that we can reason accurately about private and module access.
 239         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 240         if ((caller.lookupModes() & requireAccess) != requireAccess)
 241             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 242 
 243         // previous lookup class is never set if it has MODULE access
 244         assert caller.previousLookupClass() == null;
 245 
 246         Class<?> callerClass = caller.lookupClass();
 247         Module callerModule = callerClass.getModule();  // M1
 248         Module targetModule = targetClass.getModule();  // M2
 249         Class<?> newPreviousClass = null;
 250         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 251 
 252         if (targetModule != callerModule) {
 253             if (!callerModule.canRead(targetModule))
 254                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 255             if (targetModule.isNamed()) {
 256                 String pn = targetClass.getPackageName();
 257                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 258                 if (!targetModule.isOpen(pn, callerModule))
 259                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 260             }
 261 
 262             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 263             newPreviousClass = callerClass;
 264             newModes &= ~Lookup.MODULE;
 265         }
 266         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 267     }
 268 
 269     /**
 270      * Returns the <em>class data</em> associated with the lookup class
 271      * of the given {@code caller} lookup object, or {@code null}.
 272      *
 273      * <p> A hidden class with class data can be created by calling
 274      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 275      * Lookup::defineHiddenClassWithClassData}.
 276      * This method will cause the static class initializer of the lookup
 277      * class of the given {@code caller} lookup object be executed if
 278      * it has not been initialized.
 279      *
 280      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 281      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 282      * {@code null} is returned if this method is called on the lookup object
 283      * on these classes.
 284      *
 285      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 286      * must have {@linkplain Lookup#ORIGINAL original access}
 287      * in order to retrieve the class data.
 288      *
 289      * @apiNote
 290      * This method can be called as a bootstrap method for a dynamically computed
 291      * constant.  A framework can create a hidden class with class data, for
 292      * example that can be {@code Class} or {@code MethodHandle} object.
 293      * The class data is accessible only to the lookup object
 294      * created by the original caller but inaccessible to other members
 295      * in the same nest.  If a framework passes security sensitive objects
 296      * to a hidden class via class data, it is recommended to load the value
 297      * of class data as a dynamically computed constant instead of storing
 298      * the class data in private static field(s) which are accessible to
 299      * other nestmates.
 300      *
 301      * @param <T> the type to cast the class data object to
 302      * @param caller the lookup context describing the class performing the
 303      * operation (normally stacked by the JVM)
 304      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 305      *             ({@code "_"})
 306      * @param type the type of the class data
 307      * @return the value of the class data if present in the lookup class;
 308      * otherwise {@code null}
 309      * @throws IllegalArgumentException if name is not {@code "_"}
 310      * @throws IllegalAccessException if the lookup context does not have
 311      * {@linkplain Lookup#ORIGINAL original} access
 312      * @throws ClassCastException if the class data cannot be converted to
 313      * the given {@code type}
 314      * @throws NullPointerException if {@code caller} or {@code type} argument
 315      * is {@code null}
 316      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 317      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 318      * @since 16
 319      * @jvms 5.5 Initialization
 320      */
 321      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 322          Objects.requireNonNull(caller);
 323          Objects.requireNonNull(type);
 324          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 325              throw new IllegalArgumentException("name must be \"_\": " + name);
 326          }
 327 
 328          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 329              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 330          }
 331 
 332          Object classdata = MethodHandleNatives.classData(caller.lookupClass());
 333          if (classdata == null) return null;
 334 
 335          try {
 336              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 337          } catch (RuntimeException|Error e) {
 338              throw e; // let CCE and other runtime exceptions through
 339          } catch (Throwable e) {
 340              throw new InternalError(e);
 341          }
 342     }
 343 
 344     /**
 345      * Returns the element at the specified index in the
 346      * {@linkplain #classData(Lookup, String, Class) class data},
 347      * if the class data associated with the lookup class
 348      * of the given {@code caller} lookup object is a {@code List}.
 349      * If the class data is not present in this lookup class, this method
 350      * returns {@code null}.
 351      *
 352      * <p> A hidden class with class data can be created by calling
 353      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 354      * Lookup::defineHiddenClassWithClassData}.
 355      * This method will cause the static class initializer of the lookup
 356      * class of the given {@code caller} lookup object be executed if
 357      * it has not been initialized.
 358      *
 359      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 360      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 361      * {@code null} is returned if this method is called on the lookup object
 362      * on these classes.
 363      *
 364      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 365      * must have {@linkplain Lookup#ORIGINAL original access}
 366      * in order to retrieve the class data.
 367      *
 368      * @apiNote
 369      * This method can be called as a bootstrap method for a dynamically computed
 370      * constant.  A framework can create a hidden class with class data, for
 371      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 372      * one object and use this method to load one element at a specific index.
 373      * The class data is accessible only to the lookup object
 374      * created by the original caller but inaccessible to other members
 375      * in the same nest.  If a framework passes security sensitive objects
 376      * to a hidden class via class data, it is recommended to load the value
 377      * of class data as a dynamically computed constant instead of storing
 378      * the class data in private static field(s) which are accessible to other
 379      * nestmates.
 380      *
 381      * @param <T> the type to cast the result object to
 382      * @param caller the lookup context describing the class performing the
 383      * operation (normally stacked by the JVM)
 384      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 385      *             ({@code "_"})
 386      * @param type the type of the element at the given index in the class data
 387      * @param index index of the element in the class data
 388      * @return the element at the given index in the class data
 389      * if the class data is present; otherwise {@code null}
 390      * @throws IllegalArgumentException if name is not {@code "_"}
 391      * @throws IllegalAccessException if the lookup context does not have
 392      * {@linkplain Lookup#ORIGINAL original} access
 393      * @throws ClassCastException if the class data cannot be converted to {@code List}
 394      * or the element at the specified index cannot be converted to the given type
 395      * @throws IndexOutOfBoundsException if the index is out of range
 396      * @throws NullPointerException if {@code caller} or {@code type} argument is
 397      * {@code null}; or if unboxing operation fails because
 398      * the element at the given index is {@code null}
 399      *
 400      * @since 16
 401      * @see #classData(Lookup, String, Class)
 402      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 403      */
 404     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 405             throws IllegalAccessException
 406     {
 407         @SuppressWarnings("unchecked")
 408         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 409         if (classdata == null) return null;
 410 
 411         try {
 412             Object element = classdata.get(index);
 413             return BootstrapMethodInvoker.widenAndCast(element, type);
 414         } catch (RuntimeException|Error e) {
 415             throw e; // let specified exceptions and other runtime exceptions/errors through
 416         } catch (Throwable e) {
 417             throw new InternalError(e);
 418         }
 419     }
 420 
 421     /**
 422      * Performs an unchecked "crack" of a
 423      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 424      * The result is as if the user had obtained a lookup object capable enough
 425      * to crack the target method handle, called
 426      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 427      * on the target to obtain its symbolic reference, and then called
 428      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 429      * to resolve the symbolic reference to a member.
 430      * <p>
 431      * If there is a security manager, its {@code checkPermission} method
 432      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 433      * @param <T> the desired type of the result, either {@link Member} or a subtype
 434      * @param target a direct method handle to crack into symbolic reference components
 435      * @param expected a class object representing the desired result type {@code T}
 436      * @return a reference to the method, constructor, or field object
 437      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 438      * @throws    NullPointerException if either argument is {@code null}
 439      * @throws    IllegalArgumentException if the target is not a direct method handle
 440      * @throws    ClassCastException if the member is not of the expected type
 441      * @since 1.8
 442      */
 443     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 444         @SuppressWarnings("removal")
 445         SecurityManager smgr = System.getSecurityManager();
 446         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 447         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 448         return lookup.revealDirect(target).reflectAs(expected, lookup);
 449     }
 450 
 451     /**
 452      * A <em>lookup object</em> is a factory for creating method handles,
 453      * when the creation requires access checking.
 454      * Method handles do not perform
 455      * access checks when they are called, but rather when they are created.
 456      * Therefore, method handle access
 457      * restrictions must be enforced when a method handle is created.
 458      * The caller class against which those restrictions are enforced
 459      * is known as the {@linkplain #lookupClass() lookup class}.
 460      * <p>
 461      * A lookup class which needs to create method handles will call
 462      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 463      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 464      * determined, and securely stored in the {@code Lookup} object.
 465      * The lookup class (or its delegates) may then use factory methods
 466      * on the {@code Lookup} object to create method handles for access-checked members.
 467      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 468      * even private ones.
 469      *
 470      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 471      * The factory methods on a {@code Lookup} object correspond to all major
 472      * use cases for methods, constructors, and fields.
 473      * Each method handle created by a factory method is the functional
 474      * equivalent of a particular <em>bytecode behavior</em>.
 475      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 476      * the Java Virtual Machine Specification.)
 477      * Here is a summary of the correspondence between these factory methods and
 478      * the behavior of the resulting method handles:
 479      * <table class="striped">
 480      * <caption style="display:none">lookup method behaviors</caption>
 481      * <thead>
 482      * <tr>
 483      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 484      *     <th scope="col">member</th>
 485      *     <th scope="col">bytecode behavior</th>
 486      * </tr>
 487      * </thead>
 488      * <tbody>
 489      * <tr>
 490      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 491      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 492      * </tr>
 493      * <tr>
 494      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 495      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 496      * </tr>
 497      * <tr>
 498      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 499      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 500      * </tr>
 501      * <tr>
 502      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 503      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 504      * </tr>
 505      * <tr>
 506      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 507      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 508      * </tr>
 509      * <tr>
 510      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 511      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 512      * </tr>
 513      * <tr>
 514      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 515      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 516      * </tr>
 517      * <tr>
 518      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 519      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 520      * </tr>
 521      * <tr>
 522      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 523      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 524      * </tr>
 525      * <tr>
 526      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 527      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 528      * </tr>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 531      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 535      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 539      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 543      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 544      * </tr>
 545      * </tbody>
 546      * </table>
 547      *
 548      * Here, the type {@code C} is the class or interface being searched for a member,
 549      * documented as a parameter named {@code refc} in the lookup methods.
 550      * The method type {@code MT} is composed from the return type {@code T}
 551      * and the sequence of argument types {@code A*}.
 552      * The constructor also has a sequence of argument types {@code A*} and
 553      * is deemed to return the newly-created object of type {@code C}.
 554      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 555      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 556      * if it is present, it is always the leading argument to the method handle invocation.
 557      * (In the case of some {@code protected} members, {@code this} may be
 558      * restricted in type to the lookup class; see below.)
 559      * The name {@code arg} stands for all the other method handle arguments.
 560      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 561      * stands for a null reference if the accessed method or field is static,
 562      * and {@code this} otherwise.
 563      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 564      * for reflective objects corresponding to the given members declared in type {@code C}.
 565      * <p>
 566      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 567      * as if by {@code ldc CONSTANT_Class}.
 568      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 569      * <p>
 570      * In cases where the given member is of variable arity (i.e., a method or constructor)
 571      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 572      * In all other cases, the returned method handle will be of fixed arity.
 573      * <p style="font-size:smaller;">
 574      * <em>Discussion:</em>
 575      * The equivalence between looked-up method handles and underlying
 576      * class members and bytecode behaviors
 577      * can break down in a few ways:
 578      * <ul style="font-size:smaller;">
 579      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 580      * the lookup can still succeed, even when there is no equivalent
 581      * Java expression or bytecoded constant.
 582      * <li>Likewise, if {@code T} or {@code MT}
 583      * is not symbolically accessible from the lookup class's loader,
 584      * the lookup can still succeed.
 585      * For example, lookups for {@code MethodHandle.invokeExact} and
 586      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 587      * <li>If there is a security manager installed, it can forbid the lookup
 588      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 589      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 590      * constant is not subject to security manager checks.
 591      * <li>If the looked-up method has a
 592      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 593      * the method handle creation may fail with an
 594      * {@code IllegalArgumentException}, due to the method handle type having
 595      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 596      * </ul>
 597      *
 598      * <h2><a id="access"></a>Access checking</h2>
 599      * Access checks are applied in the factory methods of {@code Lookup},
 600      * when a method handle is created.
 601      * This is a key difference from the Core Reflection API, since
 602      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 603      * performs access checking against every caller, on every call.
 604      * <p>
 605      * All access checks start from a {@code Lookup} object, which
 606      * compares its recorded lookup class against all requests to
 607      * create method handles.
 608      * A single {@code Lookup} object can be used to create any number
 609      * of access-checked method handles, all checked against a single
 610      * lookup class.
 611      * <p>
 612      * A {@code Lookup} object can be shared with other trusted code,
 613      * such as a metaobject protocol.
 614      * A shared {@code Lookup} object delegates the capability
 615      * to create method handles on private members of the lookup class.
 616      * Even if privileged code uses the {@code Lookup} object,
 617      * the access checking is confined to the privileges of the
 618      * original lookup class.
 619      * <p>
 620      * A lookup can fail, because
 621      * the containing class is not accessible to the lookup class, or
 622      * because the desired class member is missing, or because the
 623      * desired class member is not accessible to the lookup class, or
 624      * because the lookup object is not trusted enough to access the member.
 625      * In the case of a field setter function on a {@code final} field,
 626      * finality enforcement is treated as a kind of access control,
 627      * and the lookup will fail, except in special cases of
 628      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 629      * In any of these cases, a {@code ReflectiveOperationException} will be
 630      * thrown from the attempted lookup.  The exact class will be one of
 631      * the following:
 632      * <ul>
 633      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 634      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 635      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 636      * </ul>
 637      * <p>
 638      * In general, the conditions under which a method handle may be
 639      * looked up for a method {@code M} are no more restrictive than the conditions
 640      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 641      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 642      * a method handle lookup will generally raise a corresponding
 643      * checked exception, such as {@code NoSuchMethodException}.
 644      * And the effect of invoking the method handle resulting from the lookup
 645      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 646      * to executing the compiled, verified, and resolved call to {@code M}.
 647      * The same point is true of fields and constructors.
 648      * <p style="font-size:smaller;">
 649      * <em>Discussion:</em>
 650      * Access checks only apply to named and reflected methods,
 651      * constructors, and fields.
 652      * Other method handle creation methods, such as
 653      * {@link MethodHandle#asType MethodHandle.asType},
 654      * do not require any access checks, and are used
 655      * independently of any {@code Lookup} object.
 656      * <p>
 657      * If the desired member is {@code protected}, the usual JVM rules apply,
 658      * including the requirement that the lookup class must either be in the
 659      * same package as the desired member, or must inherit that member.
 660      * (See the Java Virtual Machine Specification, sections {@jvms
 661      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 662      * In addition, if the desired member is a non-static field or method
 663      * in a different package, the resulting method handle may only be applied
 664      * to objects of the lookup class or one of its subclasses.
 665      * This requirement is enforced by narrowing the type of the leading
 666      * {@code this} parameter from {@code C}
 667      * (which will necessarily be a superclass of the lookup class)
 668      * to the lookup class itself.
 669      * <p>
 670      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 671      * that the receiver argument must match both the resolved method <em>and</em>
 672      * the current class.  Again, this requirement is enforced by narrowing the
 673      * type of the leading parameter to the resulting method handle.
 674      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 675      * <p>
 676      * The JVM represents constructors and static initializer blocks as internal methods
 677      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 678      * The internal syntax of invocation instructions allows them to refer to such internal
 679      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 680      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 681      * <p>
 682      * If the relationship between nested types is expressed directly through the
 683      * {@code NestHost} and {@code NestMembers} attributes
 684      * (see the Java Virtual Machine Specification, sections {@jvms
 685      * 4.7.28} and {@jvms 4.7.29}),
 686      * then the associated {@code Lookup} object provides direct access to
 687      * the lookup class and all of its nestmates
 688      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 689      * Otherwise, access between nested classes is obtained by the Java compiler creating
 690      * a wrapper method to access a private method of another class in the same nest.
 691      * For example, a nested class {@code C.D}
 692      * can access private members within other related classes such as
 693      * {@code C}, {@code C.D.E}, or {@code C.B},
 694      * but the Java compiler may need to generate wrapper methods in
 695      * those related classes.  In such cases, a {@code Lookup} object on
 696      * {@code C.E} would be unable to access those private members.
 697      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 698      * which can transform a lookup on {@code C.E} into one on any of those other
 699      * classes, without special elevation of privilege.
 700      * <p>
 701      * The accesses permitted to a given lookup object may be limited,
 702      * according to its set of {@link #lookupModes lookupModes},
 703      * to a subset of members normally accessible to the lookup class.
 704      * For example, the {@link MethodHandles#publicLookup publicLookup}
 705      * method produces a lookup object which is only allowed to access
 706      * public members in public classes of exported packages.
 707      * The caller sensitive method {@link MethodHandles#lookup lookup}
 708      * produces a lookup object with full capabilities relative to
 709      * its caller class, to emulate all supported bytecode behaviors.
 710      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 711      * with fewer access modes than the original lookup object.
 712      *
 713      * <p style="font-size:smaller;">
 714      * <a id="privacc"></a>
 715      * <em>Discussion of private and module access:</em>
 716      * We say that a lookup has <em>private access</em>
 717      * if its {@linkplain #lookupModes lookup modes}
 718      * include the possibility of accessing {@code private} members
 719      * (which includes the private members of nestmates).
 720      * As documented in the relevant methods elsewhere,
 721      * only lookups with private access possess the following capabilities:
 722      * <ul style="font-size:smaller;">
 723      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 724      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 725      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 726      *     for classes accessible to the lookup class
 727      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 728      *     within the same package member
 729      * </ul>
 730      * <p style="font-size:smaller;">
 731      * Similarly, a lookup with module access ensures that the original lookup creator was
 732      * a member in the same module as the lookup class.
 733      * <p style="font-size:smaller;">
 734      * Private and module access are independently determined modes; a lookup may have
 735      * either or both or neither.  A lookup which possesses both access modes is said to
 736      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 737      * <p style="font-size:smaller;">
 738      * A lookup with <em>original access</em> ensures that this lookup is created by
 739      * the original lookup class and the bootstrap method invoked by the VM.
 740      * Such a lookup with original access also has private and module access
 741      * which has the following additional capability:
 742      * <ul style="font-size:smaller;">
 743      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 744      *     such as {@code Class.forName}
 745      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 746      * class data} associated with the lookup class</li>
 747      * </ul>
 748      * <p style="font-size:smaller;">
 749      * Each of these permissions is a consequence of the fact that a lookup object
 750      * with private access can be securely traced back to an originating class,
 751      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 752      * can be reliably determined and emulated by method handles.
 753      *
 754      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 755      * When a lookup class in one module {@code M1} accesses a class in another module
 756      * {@code M2}, extra access checking is performed beyond the access mode bits.
 757      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 758      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 759      * and when the type is in a package of {@code M2} that is exported to
 760      * at least {@code M1}.
 761      * <p>
 762      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 763      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 764      * MethodHandles.privateLookupIn} methods.
 765      * Teleporting across modules will always record the original lookup class as
 766      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 767      * and drops {@link Lookup#MODULE MODULE} access.
 768      * If the target class is in the same module as the lookup class {@code C},
 769      * then the target class becomes the new lookup class
 770      * and there is no change to the previous lookup class.
 771      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 772      * {@code C} becomes the new previous lookup class
 773      * and the target class becomes the new lookup class.
 774      * In that case, if there was already a previous lookup class in {@code M0},
 775      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 776      * drops all privileges.
 777      * For example,
 778      * <blockquote><pre>
 779      * {@code
 780      * Lookup lookup = MethodHandles.lookup();   // in class C
 781      * Lookup lookup2 = lookup.in(D.class);
 782      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 783      * }</pre></blockquote>
 784      * <p>
 785      * The {@link #lookup()} factory method produces a {@code Lookup} object
 786      * with {@code null} previous lookup class.
 787      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 788      * to class {@code D} without elevation of privileges.
 789      * If {@code C} and {@code D} are in the same module,
 790      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 791      * same previous lookup class as the original {@code lookup}, or
 792      * {@code null} if not present.
 793      * <p>
 794      * When a {@code Lookup} teleports from a class
 795      * in one nest to another nest, {@code PRIVATE} access is dropped.
 796      * When a {@code Lookup} teleports from a class in one package to
 797      * another package, {@code PACKAGE} access is dropped.
 798      * When a {@code Lookup} teleports from a class in one module to another module,
 799      * {@code MODULE} access is dropped.
 800      * Teleporting across modules drops the ability to access non-exported classes
 801      * in both the module of the new lookup class and the module of the old lookup class
 802      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 803      * A {@code Lookup} can teleport back and forth to a class in the module of
 804      * the lookup class and the module of the previous class lookup.
 805      * Teleporting across modules can only decrease access but cannot increase it.
 806      * Teleporting to some third module drops all accesses.
 807      * <p>
 808      * In the above example, if {@code C} and {@code D} are in different modules,
 809      * {@code lookup2} records {@code D} as its lookup class and
 810      * {@code C} as its previous lookup class and {@code lookup2} has only
 811      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 812      * {@code C}'s module and {@code D}'s module.
 813      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 814      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 815      * class {@code D} is recorded as its previous lookup class.
 816      * <p>
 817      * Teleporting across modules restricts access to the public types that
 818      * both the lookup class and the previous lookup class can equally access
 819      * (see below).
 820      * <p>
 821      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 822      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 823      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 824      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 825      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 826      * to call {@code privateLookupIn}.
 827      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 828      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 829      * produces a new {@code Lookup} on {@code T} with full capabilities.
 830      * A {@code lookup} on {@code C} is also allowed
 831      * to do deep reflection on {@code T} in another module {@code M2} if
 832      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 833      * the package containing {@code T} to at least {@code M1}.
 834      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 835      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 836      * The resulting {@code Lookup} can be used to do member lookup or teleport
 837      * to another lookup class by calling {@link #in Lookup::in}.  But
 838      * it cannot be used to obtain another private {@code Lookup} by calling
 839      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 840      * because it has no {@code MODULE} access.
 841      *
 842      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 843      *
 844      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 845      * allows cross-module access. The access checking is performed with respect
 846      * to both the lookup class and the previous lookup class if present.
 847      * <p>
 848      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 849      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 850      * exported unconditionally}.
 851      * <p>
 852      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 853      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 854      * that are readable to {@code M1} and the type is in a package that is exported
 855      * at least to {@code M1}.
 856      * <p>
 857      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 858      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 859      * the intersection of all public types that are accessible to {@code M1}
 860      * with all public types that are accessible to {@code M0}. {@code M0}
 861      * reads {@code M1} and hence the set of accessible types includes:
 862      *
 863      * <table class="striped">
 864      * <caption style="display:none">
 865      * Public types in the following packages are accessible to the
 866      * lookup class and the previous lookup class.
 867      * </caption>
 868      * <thead>
 869      * <tr>
 870      * <th scope="col">Equally accessible types to {@code M0} and {@code M1}</th>
 871      * </tr>
 872      * </thead>
 873      * <tbody>
 874      * <tr>
 875      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M1}</th>
 876      * </tr>
 877      * <tr>
 878      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</th>
 879      * </tr>
 880      * <tr>
 881      * <th scope="row" style="text-align:left">unconditional-exported packages from a third module {@code M2}
 882      * if both {@code M0} and {@code M1} read {@code M2}</th>
 883      * </tr>
 884      * <tr>
 885      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M1} to {@code M0}</th>
 886      * </tr>
 887      * <tr>
 888      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M0} to {@code M1}
 889      * if {@code M1} reads {@code M0}</th>
 890      * </tr>
 891      * <tr>
 892      * <th scope="row" style="text-align:left">qualified-exported packages from a third module {@code M2} to
 893      * both {@code M0} and {@code M1} if both {@code M0} and {@code M1} read {@code M2}</th>
 894      * </tr>
 895      * </tbody>
 896      * </table>
 897      *
 898      * <h2><a id="access-modes"></a>Access modes</h2>
 899      *
 900      * The table below shows the access modes of a {@code Lookup} produced by
 901      * any of the following factory or transformation methods:
 902      * <ul>
 903      * <li>{@link #lookup() MethodHandles::lookup}</li>
 904      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 905      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 906      * <li>{@link Lookup#in Lookup::in}</li>
 907      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 908      * </ul>
 909      *
 910      * <table class="striped">
 911      * <caption style="display:none">
 912      * Access mode summary
 913      * </caption>
 914      * <thead>
 915      * <tr>
 916      * <th scope="col">Lookup object</th>
 917      * <th style="text-align:center">original</th>
 918      * <th style="text-align:center">protected</th>
 919      * <th style="text-align:center">private</th>
 920      * <th style="text-align:center">package</th>
 921      * <th style="text-align:center">module</th>
 922      * <th style="text-align:center">public</th>
 923      * </tr>
 924      * </thead>
 925      * <tbody>
 926      * <tr>
 927      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 928      * <td style="text-align:center">ORI</td>
 929      * <td style="text-align:center">PRO</td>
 930      * <td style="text-align:center">PRI</td>
 931      * <td style="text-align:center">PAC</td>
 932      * <td style="text-align:center">MOD</td>
 933      * <td style="text-align:center">1R</td>
 934      * </tr>
 935      * <tr>
 936      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 937      * <td></td>
 938      * <td></td>
 939      * <td></td>
 940      * <td style="text-align:center">PAC</td>
 941      * <td style="text-align:center">MOD</td>
 942      * <td style="text-align:center">1R</td>
 943      * </tr>
 944      * <tr>
 945      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 946      * <td></td>
 947      * <td></td>
 948      * <td></td>
 949      * <td></td>
 950      * <td style="text-align:center">MOD</td>
 951      * <td style="text-align:center">1R</td>
 952      * </tr>
 953      * <tr>
 954      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 955      * <td></td>
 956      * <td></td>
 957      * <td></td>
 958      * <td></td>
 959      * <td></td>
 960      * <td style="text-align:center">2R</td>
 961      * </tr>
 962      * <tr>
 963      * <td>{@code CL.in(D).in(C)} hop back to module</td>
 964      * <td></td>
 965      * <td></td>
 966      * <td></td>
 967      * <td></td>
 968      * <td></td>
 969      * <td style="text-align:center">2R</td>
 970      * </tr>
 971      * <tr>
 972      * <td>{@code PRI1 = privateLookupIn(C1,CL)}</td>
 973      * <td></td>
 974      * <td style="text-align:center">PRO</td>
 975      * <td style="text-align:center">PRI</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 PRI1a = privateLookupIn(C,PRI1)}</td>
 982      * <td></td>
 983      * <td style="text-align:center">PRO</td>
 984      * <td style="text-align:center">PRI</td>
 985      * <td style="text-align:center">PAC</td>
 986      * <td style="text-align:center">MOD</td>
 987      * <td style="text-align:center">1R</td>
 988      * </tr>
 989      * <tr>
 990      * <td>{@code PRI1.in(C1)} same package</td>
 991      * <td></td>
 992      * <td></td>
 993      * <td></td>
 994      * <td style="text-align:center">PAC</td>
 995      * <td style="text-align:center">MOD</td>
 996      * <td style="text-align:center">1R</td>
 997      * </tr>
 998      * <tr>
 999      * <td>{@code PRI1.in(C1)} different package</td>
1000      * <td></td>
1001      * <td></td>
1002      * <td></td>
1003      * <td></td>
1004      * <td style="text-align:center">MOD</td>
1005      * <td style="text-align:center">1R</td>
1006      * </tr>
1007      * <tr>
1008      * <td>{@code PRI1.in(D)} different module</td>
1009      * <td></td>
1010      * <td></td>
1011      * <td></td>
1012      * <td></td>
1013      * <td></td>
1014      * <td style="text-align:center">2R</td>
1015      * </tr>
1016      * <tr>
1017      * <td>{@code PRI1.dropLookupMode(PROTECTED)}</td>
1018      * <td></td>
1019      * <td></td>
1020      * <td style="text-align:center">PRI</td>
1021      * <td style="text-align:center">PAC</td>
1022      * <td style="text-align:center">MOD</td>
1023      * <td style="text-align:center">1R</td>
1024      * </tr>
1025      * <tr>
1026      * <td>{@code PRI1.dropLookupMode(PRIVATE)}</td>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td style="text-align:center">PAC</td>
1031      * <td style="text-align:center">MOD</td>
1032      * <td style="text-align:center">1R</td>
1033      * </tr>
1034      * <tr>
1035      * <td>{@code PRI1.dropLookupMode(PACKAGE)}</td>
1036      * <td></td>
1037      * <td></td>
1038      * <td></td>
1039      * <td></td>
1040      * <td style="text-align:center">MOD</td>
1041      * <td style="text-align:center">1R</td>
1042      * </tr>
1043      * <tr>
1044      * <td>{@code PRI1.dropLookupMode(MODULE)}</td>
1045      * <td></td>
1046      * <td></td>
1047      * <td></td>
1048      * <td></td>
1049      * <td></td>
1050      * <td style="text-align:center">1R</td>
1051      * </tr>
1052      * <tr>
1053      * <td>{@code PRI1.dropLookupMode(PUBLIC)}</td>
1054      * <td></td>
1055      * <td></td>
1056      * <td></td>
1057      * <td></td>
1058      * <td></td>
1059      * <td style="text-align:center">none</td>
1060      * <tr>
1061      * <td>{@code PRI2 = privateLookupIn(D,CL)}</td>
1062      * <td></td>
1063      * <td style="text-align:center">PRO</td>
1064      * <td style="text-align:center">PRI</td>
1065      * <td style="text-align:center">PAC</td>
1066      * <td></td>
1067      * <td style="text-align:center">2R</td>
1068      * </tr>
1069      * <tr>
1070      * <td>{@code privateLookupIn(D,PRI1)}</td>
1071      * <td></td>
1072      * <td style="text-align:center">PRO</td>
1073      * <td style="text-align:center">PRI</td>
1074      * <td style="text-align:center">PAC</td>
1075      * <td></td>
1076      * <td style="text-align:center">2R</td>
1077      * </tr>
1078      * <tr>
1079      * <td>{@code privateLookupIn(C,PRI2)} fails</td>
1080      * <td></td>
1081      * <td></td>
1082      * <td></td>
1083      * <td></td>
1084      * <td></td>
1085      * <td style="text-align:center">IAE</td>
1086      * </tr>
1087      * <tr>
1088      * <td>{@code PRI2.in(D2)} same package</td>
1089      * <td></td>
1090      * <td></td>
1091      * <td></td>
1092      * <td style="text-align:center">PAC</td>
1093      * <td></td>
1094      * <td style="text-align:center">2R</td>
1095      * </tr>
1096      * <tr>
1097      * <td>{@code PRI2.in(D2)} different package</td>
1098      * <td></td>
1099      * <td></td>
1100      * <td></td>
1101      * <td></td>
1102      * <td></td>
1103      * <td style="text-align:center">2R</td>
1104      * </tr>
1105      * <tr>
1106      * <td>{@code PRI2.in(C1)} hop back to module</td>
1107      * <td></td>
1108      * <td></td>
1109      * <td></td>
1110      * <td></td>
1111      * <td></td>
1112      * <td style="text-align:center">2R</td>
1113      * </tr>
1114      * <tr>
1115      * <td>{@code PRI2.in(E)} hop to third module</td>
1116      * <td></td>
1117      * <td></td>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td style="text-align:center">none</td>
1122      * </tr>
1123      * <tr>
1124      * <td>{@code PRI2.dropLookupMode(PROTECTED)}</td>
1125      * <td></td>
1126      * <td></td>
1127      * <td style="text-align:center">PRI</td>
1128      * <td style="text-align:center">PAC</td>
1129      * <td></td>
1130      * <td style="text-align:center">2R</td>
1131      * </tr>
1132      * <tr>
1133      * <td>{@code PRI2.dropLookupMode(PRIVATE)}</td>
1134      * <td></td>
1135      * <td></td>
1136      * <td></td>
1137      * <td style="text-align:center">PAC</td>
1138      * <td></td>
1139      * <td style="text-align:center">2R</td>
1140      * </tr>
1141      * <tr>
1142      * <td>{@code PRI2.dropLookupMode(PACKAGE)}</td>
1143      * <td></td>
1144      * <td></td>
1145      * <td></td>
1146      * <td></td>
1147      * <td></td>
1148      * <td style="text-align:center">2R</td>
1149      * </tr>
1150      * <tr>
1151      * <td>{@code PRI2.dropLookupMode(MODULE)}</td>
1152      * <td></td>
1153      * <td></td>
1154      * <td></td>
1155      * <td></td>
1156      * <td></td>
1157      * <td style="text-align:center">2R</td>
1158      * </tr>
1159      * <tr>
1160      * <td>{@code PRI2.dropLookupMode(PUBLIC)}</td>
1161      * <td></td>
1162      * <td></td>
1163      * <td></td>
1164      * <td></td>
1165      * <td></td>
1166      * <td style="text-align:center">none</td>
1167      * </tr>
1168      * <tr>
1169      * <td>{@code CL.dropLookupMode(PROTECTED)}</td>
1170      * <td></td>
1171      * <td></td>
1172      * <td style="text-align:center">PRI</td>
1173      * <td style="text-align:center">PAC</td>
1174      * <td style="text-align:center">MOD</td>
1175      * <td style="text-align:center">1R</td>
1176      * </tr>
1177      * <tr>
1178      * <td>{@code CL.dropLookupMode(PRIVATE)}</td>
1179      * <td></td>
1180      * <td></td>
1181      * <td></td>
1182      * <td style="text-align:center">PAC</td>
1183      * <td style="text-align:center">MOD</td>
1184      * <td style="text-align:center">1R</td>
1185      * </tr>
1186      * <tr>
1187      * <td>{@code CL.dropLookupMode(PACKAGE)}</td>
1188      * <td></td>
1189      * <td></td>
1190      * <td></td>
1191      * <td></td>
1192      * <td style="text-align:center">MOD</td>
1193      * <td style="text-align:center">1R</td>
1194      * </tr>
1195      * <tr>
1196      * <td>{@code CL.dropLookupMode(MODULE)}</td>
1197      * <td></td>
1198      * <td></td>
1199      * <td></td>
1200      * <td></td>
1201      * <td></td>
1202      * <td style="text-align:center">1R</td>
1203      * </tr>
1204      * <tr>
1205      * <td>{@code CL.dropLookupMode(PUBLIC)}</td>
1206      * <td></td>
1207      * <td></td>
1208      * <td></td>
1209      * <td></td>
1210      * <td></td>
1211      * <td style="text-align:center">none</td>
1212      * </tr>
1213      * <tr>
1214      * <td>{@code PUB = publicLookup()}</td>
1215      * <td></td>
1216      * <td></td>
1217      * <td></td>
1218      * <td></td>
1219      * <td></td>
1220      * <td style="text-align:center">U</td>
1221      * </tr>
1222      * <tr>
1223      * <td>{@code PUB.in(D)} different module</td>
1224      * <td></td>
1225      * <td></td>
1226      * <td></td>
1227      * <td></td>
1228      * <td></td>
1229      * <td style="text-align:center">U</td>
1230      * </tr>
1231      * <tr>
1232      * <td>{@code PUB.in(D).in(E)} third module</td>
1233      * <td></td>
1234      * <td></td>
1235      * <td></td>
1236      * <td></td>
1237      * <td></td>
1238      * <td style="text-align:center">U</td>
1239      * </tr>
1240      * <tr>
1241      * <td>{@code PUB.dropLookupMode(UNCONDITIONAL)}</td>
1242      * <td></td>
1243      * <td></td>
1244      * <td></td>
1245      * <td></td>
1246      * <td></td>
1247      * <td style="text-align:center">none</td>
1248      * </tr>
1249      * <tr>
1250      * <td>{@code privateLookupIn(C1,PUB)} fails</td>
1251      * <td></td>
1252      * <td></td>
1253      * <td></td>
1254      * <td></td>
1255      * <td></td>
1256      * <td style="text-align:center">IAE</td>
1257      * </tr>
1258      * <tr>
1259      * <td>{@code ANY.in(X)}, for inaccessible {@code X}</td>
1260      * <td></td>
1261      * <td></td>
1262      * <td></td>
1263      * <td></td>
1264      * <td></td>
1265      * <td style="text-align:center">none</td>
1266      * </tr>
1267      * </tbody>
1268      * </table>
1269      *
1270      * <p>
1271      * Notes:
1272      * <ul>
1273      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1274      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1275      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1276      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1277      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1278      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1279      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1280      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1281      *     {@code MOD} indicates {@link #MODULE} bit set,
1282      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1283      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1284      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1285      * <li>Public access comes in three kinds:
1286      * <ul>
1287      * <li>unconditional ({@code U}): the lookup assumes readability.
1288      *     The lookup has {@code null} previous lookup class.
1289      * <li>one-module-reads ({@code 1R}): the module access checking is
1290      *     performed with respect to the lookup class.  The lookup has {@code null}
1291      *     previous lookup class.
1292      * <li>two-module-reads ({@code 2R}): the module access checking is
1293      *     performed with respect to the lookup class and the previous lookup class.
1294      *     The lookup has a non-null previous lookup class which is in a
1295      *     different module from the current lookup class.
1296      * </ul>
1297      * <li>Any attempt to reach a third module loses all access.</li>
1298      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1299      * all access modes are dropped.</li>
1300      * </ul>
1301      *
1302      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1303      * Although bytecode instructions can only refer to classes in
1304      * a related class loader, this API can search for methods in any
1305      * class, as long as a reference to its {@code Class} object is
1306      * available.  Such cross-loader references are also possible with the
1307      * Core Reflection API, and are impossible to bytecode instructions
1308      * such as {@code invokestatic} or {@code getfield}.
1309      * There is a {@linkplain java.lang.SecurityManager security manager API}
1310      * to allow applications to check such cross-loader references.
1311      * These checks apply to both the {@code MethodHandles.Lookup} API
1312      * and the Core Reflection API
1313      * (as found on {@link java.lang.Class Class}).
1314      * <p>
1315      * If a security manager is present, member and class lookups are subject to
1316      * additional checks.
1317      * From one to three calls are made to the security manager.
1318      * Any of these calls can refuse access by throwing a
1319      * {@link java.lang.SecurityException SecurityException}.
1320      * Define {@code smgr} as the security manager,
1321      * {@code lookc} as the lookup class of the current lookup object,
1322      * {@code refc} as the containing class in which the member
1323      * is being sought, and {@code defc} as the class in which the
1324      * member is actually defined.
1325      * (If a class or other type is being accessed,
1326      * the {@code refc} and {@code defc} values are the class itself.)
1327      * The value {@code lookc} is defined as <em>not present</em>
1328      * if the current lookup object does not have
1329      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1330      * The calls are made according to the following rules:
1331      * <ul>
1332      * <li><b>Step 1:</b>
1333      *     If {@code lookc} is not present, or if its class loader is not
1334      *     the same as or an ancestor of the class loader of {@code refc},
1335      *     then {@link SecurityManager#checkPackageAccess
1336      *     smgr.checkPackageAccess(refcPkg)} is called,
1337      *     where {@code refcPkg} is the package of {@code refc}.
1338      * <li><b>Step 2a:</b>
1339      *     If the retrieved member is not public and
1340      *     {@code lookc} is not present, then
1341      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1342      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1343      * <li><b>Step 2b:</b>
1344      *     If the retrieved class has a {@code null} class loader,
1345      *     and {@code lookc} is not present, then
1346      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1347      *     with {@code RuntimePermission("getClassLoader")} is called.
1348      * <li><b>Step 3:</b>
1349      *     If the retrieved member is not public,
1350      *     and if {@code lookc} is not present,
1351      *     and if {@code defc} and {@code refc} are different,
1352      *     then {@link SecurityManager#checkPackageAccess
1353      *     smgr.checkPackageAccess(defcPkg)} is called,
1354      *     where {@code defcPkg} is the package of {@code defc}.
1355      * </ul>
1356      * Security checks are performed after other access checks have passed.
1357      * Therefore, the above rules presuppose a member or class that is public,
1358      * or else that is being accessed from a lookup class that has
1359      * rights to access the member or class.
1360      * <p>
1361      * If a security manager is present and the current lookup object does not have
1362      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1363      * {@link #defineClass(byte[]) defineClass},
1364      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1365      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1366      * defineHiddenClassWithClassData}
1367      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1368      * with {@code RuntimePermission("defineClass")}.
1369      *
1370      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1371      * A small number of Java methods have a special property called caller sensitivity.
1372      * A <em>caller-sensitive</em> method can behave differently depending on the
1373      * identity of its immediate caller.
1374      * <p>
1375      * If a method handle for a caller-sensitive method is requested,
1376      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1377      * but they take account of the lookup class in a special way.
1378      * The resulting method handle behaves as if it were called
1379      * from an instruction contained in the lookup class,
1380      * so that the caller-sensitive method detects the lookup class.
1381      * (By contrast, the invoker of the method handle is disregarded.)
1382      * Thus, in the case of caller-sensitive methods,
1383      * different lookup classes may give rise to
1384      * differently behaving method handles.
1385      * <p>
1386      * In cases where the lookup object is
1387      * {@link MethodHandles#publicLookup() publicLookup()},
1388      * or some other lookup object without the
1389      * {@linkplain #ORIGINAL original access},
1390      * the lookup class is disregarded.
1391      * In such cases, no caller-sensitive method handle can be created,
1392      * access is forbidden, and the lookup fails with an
1393      * {@code IllegalAccessException}.
1394      * <p style="font-size:smaller;">
1395      * <em>Discussion:</em>
1396      * For example, the caller-sensitive method
1397      * {@link java.lang.Class#forName(String) Class.forName(x)}
1398      * can return varying classes or throw varying exceptions,
1399      * depending on the class loader of the class that calls it.
1400      * A public lookup of {@code Class.forName} will fail, because
1401      * there is no reasonable way to determine its bytecode behavior.
1402      * <p style="font-size:smaller;">
1403      * If an application caches method handles for broad sharing,
1404      * it should use {@code publicLookup()} to create them.
1405      * If there is a lookup of {@code Class.forName}, it will fail,
1406      * and the application must take appropriate action in that case.
1407      * It may be that a later lookup, perhaps during the invocation of a
1408      * bootstrap method, can incorporate the specific identity
1409      * of the caller, making the method accessible.
1410      * <p style="font-size:smaller;">
1411      * The function {@code MethodHandles.lookup} is caller sensitive
1412      * so that there can be a secure foundation for lookups.
1413      * Nearly all other methods in the JSR 292 API rely on lookup
1414      * objects to check access requests.
1415      *
1416      * @revised 9
1417      */
1418     public static final
1419     class Lookup {
1420         /** The class on behalf of whom the lookup is being performed. */
1421         private final Class<?> lookupClass;
1422 
1423         /** previous lookup class */
1424         private final Class<?> prevLookupClass;
1425 
1426         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1427         private final int allowedModes;
1428 
1429         static {
1430             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1431         }
1432 
1433         /** A single-bit mask representing {@code public} access,
1434          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1435          *  The value, {@code 0x01}, happens to be the same as the value of the
1436          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1437          *  <p>
1438          *  A {@code Lookup} with this lookup mode performs cross-module access check
1439          *  with respect to the {@linkplain #lookupClass() lookup class} and
1440          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1441          */
1442         public static final int PUBLIC = Modifier.PUBLIC;
1443 
1444         /** A single-bit mask representing {@code private} access,
1445          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1446          *  The value, {@code 0x02}, happens to be the same as the value of the
1447          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1448          */
1449         public static final int PRIVATE = Modifier.PRIVATE;
1450 
1451         /** A single-bit mask representing {@code protected} access,
1452          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1453          *  The value, {@code 0x04}, happens to be the same as the value of the
1454          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1455          */
1456         public static final int PROTECTED = Modifier.PROTECTED;
1457 
1458         /** A single-bit mask representing {@code package} access (default access),
1459          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1460          *  The value is {@code 0x08}, which does not correspond meaningfully to
1461          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1462          */
1463         public static final int PACKAGE = Modifier.STATIC;
1464 
1465         /** A single-bit mask representing {@code module} access,
1466          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1467          *  The value is {@code 0x10}, which does not correspond meaningfully to
1468          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1469          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1470          *  with this lookup mode can access all public types in the module of the
1471          *  lookup class and public types in packages exported by other modules
1472          *  to the module of the lookup class.
1473          *  <p>
1474          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1475          *  previous lookup class} is always {@code null}.
1476          *
1477          *  @since 9
1478          */
1479         public static final int MODULE = PACKAGE << 1;
1480 
1481         /** A single-bit mask representing {@code unconditional} access
1482          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1483          *  The value is {@code 0x20}, which does not correspond meaningfully to
1484          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1485          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1486          *  java.lang.Module#canRead(java.lang.Module) readability}.
1487          *  This lookup mode can access all public members of public types
1488          *  of all modules when the type is in a package that is {@link
1489          *  java.lang.Module#isExported(String) exported unconditionally}.
1490          *
1491          *  <p>
1492          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1493          *  previous lookup class} is always {@code null}.
1494          *
1495          *  @since 9
1496          *  @see #publicLookup()
1497          */
1498         public static final int UNCONDITIONAL = PACKAGE << 2;
1499 
1500         /** A single-bit mask representing {@code original} access
1501          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1502          *  The value is {@code 0x40}, which does not correspond meaningfully to
1503          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1504          *
1505          *  <p>
1506          *  If this lookup mode is set, the {@code Lookup} object must be
1507          *  created by the original lookup class by calling
1508          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1509          *  invoked by the VM.  The {@code Lookup} object with this lookup
1510          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1511          *
1512          *  @since 16
1513          */
1514         public static final int ORIGINAL = PACKAGE << 3;
1515 
1516         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1517         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1518         private static final int TRUSTED   = -1;
1519 
1520         /*
1521          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1522          * Adjust 0 => PACKAGE
1523          */
1524         private static int fixmods(int mods) {
1525             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1526             if (Modifier.isPublic(mods))
1527                 mods |= UNCONDITIONAL;
1528             return (mods != 0) ? mods : PACKAGE;
1529         }
1530 
1531         /** Tells which class is performing the lookup.  It is this class against
1532          *  which checks are performed for visibility and access permissions.
1533          *  <p>
1534          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1535          *  access checks are performed against both the lookup class and the previous lookup class.
1536          *  <p>
1537          *  The class implies a maximum level of access permission,
1538          *  but the permissions may be additionally limited by the bitmask
1539          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1540          *  can be accessed.
1541          *  @return the lookup class, on behalf of which this lookup object finds members
1542          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1543          */
1544         public Class<?> lookupClass() {
1545             return lookupClass;
1546         }
1547 
1548         /** Reports a lookup class in another module that this lookup object
1549          * was previously teleported from, or {@code null}.
1550          * <p>
1551          * A {@code Lookup} object produced by the factory methods, such as the
1552          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1553          * has {@code null} previous lookup class.
1554          * A {@code Lookup} object has a non-null previous lookup class
1555          * when this lookup was teleported from an old lookup class
1556          * in one module to a new lookup class in another module.
1557          *
1558          * @return the lookup class in another module that this lookup object was
1559          *         previously teleported from, or {@code null}
1560          * @since 14
1561          * @see #in(Class)
1562          * @see MethodHandles#privateLookupIn(Class, Lookup)
1563          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1564          */
1565         public Class<?> previousLookupClass() {
1566             return prevLookupClass;
1567         }
1568 
1569         // This is just for calling out to MethodHandleImpl.
1570         private Class<?> lookupClassOrNull() {
1571             return (allowedModes == TRUSTED) ? null : lookupClass;
1572         }
1573 
1574         /** Tells which access-protection classes of members this lookup object can produce.
1575          *  The result is a bit-mask of the bits
1576          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1577          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1578          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1579          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1580          *  {@linkplain #MODULE MODULE (0x10)},
1581          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1582          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1583          *  <p>
1584          *  A freshly-created lookup object
1585          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1586          *  all possible bits set, except {@code UNCONDITIONAL}.
1587          *  A lookup object on a new lookup class
1588          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1589          *  may have some mode bits set to zero.
1590          *  Mode bits can also be
1591          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1592          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1593          *  The purpose of this is to restrict access via the new lookup object,
1594          *  so that it can access only names which can be reached by the original
1595          *  lookup object, and also by the new lookup class.
1596          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1597          *  @see #in
1598          *  @see #dropLookupMode
1599          *
1600          *  @revised 9
1601          */
1602         public int lookupModes() {
1603             return allowedModes & ALL_MODES;
1604         }
1605 
1606         /** Embody the current class (the lookupClass) as a lookup class
1607          * for method handle creation.
1608          * Must be called by from a method in this package,
1609          * which in turn is called by a method not in this package.
1610          */
1611         Lookup(Class<?> lookupClass) {
1612             this(lookupClass, null, FULL_POWER_MODES);
1613         }
1614 
1615         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1616             assert lookupClass.isPrimaryType();
1617             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1618                     && prevLookupClass.getModule() != lookupClass.getModule());
1619             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1620             this.lookupClass = lookupClass;
1621             this.prevLookupClass = prevLookupClass;
1622             this.allowedModes = allowedModes;
1623         }
1624 
1625         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1626             // make sure we haven't accidentally picked up a privileged class:
1627             checkUnprivilegedlookupClass(lookupClass);
1628             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1629         }
1630 
1631         /**
1632          * Creates a lookup on the specified new lookup class.
1633          * The resulting object will report the specified
1634          * class as its own {@link #lookupClass() lookupClass}.
1635          *
1636          * <p>
1637          * However, the resulting {@code Lookup} object is guaranteed
1638          * to have no more access capabilities than the original.
1639          * In particular, access capabilities can be lost as follows:<ul>
1640          * <li>If the new lookup class is different from the old lookup class,
1641          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1642          * <li>If the new lookup class is in a different module from the old one,
1643          * i.e. {@link #MODULE MODULE} access is lost.
1644          * <li>If the new lookup class is in a different package
1645          * than the old one, protected and default (package) members will not be accessible,
1646          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1647          * <li>If the new lookup class is not within the same package member
1648          * as the old one, private members will not be accessible, and protected members
1649          * will not be accessible by virtue of inheritance,
1650          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1651          * (Protected members may continue to be accessible because of package sharing.)
1652          * <li>If the new lookup class is not
1653          * {@linkplain #accessClass(Class) accessible} to this lookup,
1654          * then no members, not even public members, will be accessible
1655          * i.e. all access modes are lost.
1656          * <li>If the new lookup class, the old lookup class and the previous lookup class
1657          * are all in different modules i.e. teleporting to a third module,
1658          * all access modes are lost.
1659          * </ul>
1660          * <p>
1661          * The new previous lookup class is chosen as follows:
1662          * <ul>
1663          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1664          * the new previous lookup class is {@code null}.
1665          * <li>If the new lookup class is in the same module as the old lookup class,
1666          * the new previous lookup class is the old previous lookup class.
1667          * <li>If the new lookup class is in a different module from the old lookup class,
1668          * the new previous lookup class is the old lookup class.
1669          *</ul>
1670          * <p>
1671          * The resulting lookup's capabilities for loading classes
1672          * (used during {@link #findClass} invocations)
1673          * are determined by the lookup class' loader,
1674          * which may change due to this operation.
1675          *
1676          * @param requestedLookupClass the desired lookup class for the new lookup object
1677          * @return a lookup object which reports the desired lookup class, or the same object
1678          * if there is no change
1679          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1680          * @throws NullPointerException if the argument is null
1681          *
1682          * @revised 9
1683          * @see #accessClass(Class)
1684          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1685          */
1686         public Lookup in(Class<?> requestedLookupClass) {
1687             Objects.requireNonNull(requestedLookupClass);
1688             if (requestedLookupClass.isPrimitive())
1689                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1690             if (requestedLookupClass.isArray())
1691                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1692 
1693             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1694                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1695             if (requestedLookupClass == this.lookupClass)
1696                 return this;  // keep same capabilities
1697             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1698             Module fromModule = this.lookupClass.getModule();
1699             Module targetModule = requestedLookupClass.getModule();
1700             Class<?> plc = this.previousLookupClass();
1701             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1702                 assert plc == null;
1703                 newModes = UNCONDITIONAL;
1704             } else if (fromModule != targetModule) {
1705                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1706                     // allow hopping back and forth between fromModule and plc's module
1707                     // but not the third module
1708                     newModes = 0;
1709                 }
1710                 // drop MODULE access
1711                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1712                 // teleport from this lookup class
1713                 plc = this.lookupClass;
1714             }
1715             if ((newModes & PACKAGE) != 0
1716                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1717                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1718             }
1719             // Allow nestmate lookups to be created without special privilege:
1720             if ((newModes & PRIVATE) != 0
1721                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1722                 newModes &= ~(PRIVATE|PROTECTED);
1723             }
1724             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1725                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1726                 // The requested class it not accessible from the lookup class.
1727                 // No permissions.
1728                 newModes = 0;
1729             }
1730             return newLookup(requestedLookupClass, plc, newModes);
1731         }
1732 
1733         /**
1734          * Creates a lookup on the same lookup class which this lookup object
1735          * finds members, but with a lookup mode that has lost the given lookup mode.
1736          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1737          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1738          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1739          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1740          *
1741          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1742          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1743          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1744          * lookup has no access.
1745          *
1746          * <p> If this lookup is not a public lookup, then the following applies
1747          * regardless of its {@linkplain #lookupModes() lookup modes}.
1748          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1749          * dropped and so the resulting lookup mode will never have these access
1750          * capabilities. When dropping {@code PACKAGE}
1751          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1752          * access. When dropping {@code MODULE} then the resulting lookup will not
1753          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1754          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1755          *
1756          * @apiNote
1757          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1758          * delegate non-public access within the package of the lookup class without
1759          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1760          * A lookup with {@code MODULE} but not
1761          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1762          * the module of the lookup class without conferring package access.
1763          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1764          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1765          * to public classes accessible to both the module of the lookup class
1766          * and the module of the previous lookup class.
1767          *
1768          * @param modeToDrop the lookup mode to drop
1769          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1770          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1771          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1772          * or {@code UNCONDITIONAL}
1773          * @see MethodHandles#privateLookupIn
1774          * @since 9
1775          */
1776         public Lookup dropLookupMode(int modeToDrop) {
1777             int oldModes = lookupModes();
1778             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1779             switch (modeToDrop) {
1780                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1781                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1782                 case PACKAGE: newModes &= ~(PRIVATE); break;
1783                 case PROTECTED:
1784                 case PRIVATE:
1785                 case ORIGINAL:
1786                 case UNCONDITIONAL: break;
1787                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1788             }
1789             if (newModes == oldModes) return this;  // return self if no change
1790             return newLookup(lookupClass(), previousLookupClass(), newModes);
1791         }
1792 
1793         /**
1794          * Creates and links a class or interface from {@code bytes}
1795          * with the same class loader and in the same runtime package and
1796          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1797          * {@linkplain #lookupClass() lookup class} as if calling
1798          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1799          * ClassLoader::defineClass}.
1800          *
1801          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1802          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1803          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1804          * that the lookup object was created by a caller in the runtime package (or derived
1805          * from a lookup originally created by suitably privileged code to a target class in
1806          * the runtime package). </p>
1807          *
1808          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1809          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1810          * same package as the lookup class. </p>
1811          *
1812          * <p> This method does not run the class initializer. The class initializer may
1813          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1814          * Specification</em>. </p>
1815          *
1816          * <p> If there is a security manager and this lookup does not have {@linkplain
1817          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1818          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1819          *
1820          * @param bytes the class bytes
1821          * @return the {@code Class} object for the class
1822          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1823          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1824          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1825          * than the lookup class or {@code bytes} is not a class or interface
1826          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1827          * @throws VerifyError if the newly created class cannot be verified
1828          * @throws LinkageError if the newly created class cannot be linked for any other reason
1829          * @throws SecurityException if a security manager is present and it
1830          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1831          * @throws NullPointerException if {@code bytes} is {@code null}
1832          * @since 9
1833          * @see Lookup#privateLookupIn
1834          * @see Lookup#dropLookupMode
1835          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1836          */
1837         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1838             ensureDefineClassPermission();
1839             if ((lookupModes() & PACKAGE) == 0)
1840                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1841             return makeClassDefiner(bytes.clone()).defineClass(false);
1842         }
1843 
1844         private void ensureDefineClassPermission() {
1845             if (allowedModes == TRUSTED)  return;
1846 
1847             if (!hasFullPrivilegeAccess()) {
1848                 @SuppressWarnings("removal")
1849                 SecurityManager sm = System.getSecurityManager();
1850                 if (sm != null)
1851                     sm.checkPermission(new RuntimePermission("defineClass"));
1852             }
1853         }
1854 
1855         /**
1856          * The set of class options that specify whether a hidden class created by
1857          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1858          * Lookup::defineHiddenClass} method is dynamically added as a new member
1859          * to the nest of a lookup class and/or whether a hidden class has
1860          * a strong relationship with the class loader marked as its defining loader.
1861          *
1862          * @since 15
1863          */
1864         public enum ClassOption {
1865             /**
1866              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1867              * of a lookup class as a nestmate.
1868              *
1869              * <p> A hidden nestmate class has access to the private members of all
1870              * classes and interfaces in the same nest.
1871              *
1872              * @see Class#getNestHost()
1873              */
1874             NESTMATE(NESTMATE_CLASS),
1875 
1876             /**
1877              * Specifies that a hidden class has a <em>strong</em>
1878              * relationship with the class loader marked as its defining loader,
1879              * as a normal class or interface has with its own defining loader.
1880              * This means that the hidden class may be unloaded if and only if
1881              * its defining loader is not reachable and thus may be reclaimed
1882              * by a garbage collector (JLS 12.7).
1883              *
1884              * <p> By default, a hidden class or interface may be unloaded
1885              * even if the class loader that is marked as its defining loader is
1886              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1887 
1888              *
1889              * @jls 12.7 Unloading of Classes and Interfaces
1890              */
1891             STRONG(STRONG_LOADER_LINK);
1892 
1893             /* the flag value is used by VM at define class time */
1894             private final int flag;
1895             ClassOption(int flag) {
1896                 this.flag = flag;
1897             }
1898 
1899             static int optionsToFlag(Set<ClassOption> options) {
1900                 int flags = 0;
1901                 for (ClassOption cp : options) {
1902                     flags |= cp.flag;
1903                 }
1904                 return flags;
1905             }
1906         }
1907 
1908         /**
1909          * Creates a <em>hidden</em> class or interface from {@code bytes},
1910          * returning a {@code Lookup} on the newly created class or interface.
1911          *
1912          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1913          * which either defines {@code C} directly or delegates to another class loader.
1914          * A class loader defines {@code C} directly by invoking
1915          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1916          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1917          * to derive {@code C} from a purported representation in {@code class} file format.
1918          * In situations where use of a class loader is undesirable, a class or interface
1919          * {@code C} can be created by this method instead. This method is capable of
1920          * defining {@code C}, and thereby creating it, without invoking
1921          * {@code ClassLoader::defineClass}.
1922          * Instead, this method defines {@code C} as if by arranging for
1923          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1924          * from a purported representation in {@code class} file format
1925          * using the following rules:
1926          *
1927          * <ol>
1928          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1929          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1930          * This level of access is needed to create {@code C} in the module
1931          * of the lookup class of this {@code Lookup}.</li>
1932          *
1933          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1934          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1935          * The major and minor version may differ from the {@code class} file version
1936          * of the lookup class of this {@code Lookup}.</li>
1937          *
1938          * <li> The value of {@code this_class} must be a valid index in the
1939          * {@code constant_pool} table, and the entry at that index must be a valid
1940          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1941          * encoded in internal form that is specified by this structure. {@code N} must
1942          * denote a class or interface in the same package as the lookup class.</li>
1943          *
1944          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1945          * where {@code <suffix>} is an unqualified name.
1946          *
1947          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1948          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1949          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1950          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1951          * refers to the new {@code CONSTANT_Utf8_info} structure.
1952          *
1953          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1954          *
1955          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1956          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1957          * with the following adjustments:
1958          * <ul>
1959          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1960          * that includes a single {@code "."} character, even though this is not a valid
1961          * binary class or interface name in internal form.</li>
1962          *
1963          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1964          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1965          *
1966          * <li> {@code C} is considered to have the same runtime
1967          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1968          * and {@linkplain java.security.ProtectionDomain protection domain}
1969          * as the lookup class of this {@code Lookup}.
1970          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1971          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1972          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1973          * <ul>
1974          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1975          *      even though this is not a valid binary class or interface name.</li>
1976          * <li> {@link Class#descriptorString()} returns the string
1977          *      {@code "L" + N + "." + <suffix> + ";"},
1978          *      even though this is not a valid type descriptor name.</li>
1979          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1980          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1981          * </ul>
1982          * </ul>
1983          * </li>
1984          * </ol>
1985          *
1986          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1987          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1988          * <ul>
1989          * <li> During verification, whenever it is necessary to load the class named
1990          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1991          * made of any class loader.</li>
1992          *
1993          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1994          * by {@code this_class}, the symbolic reference is considered to be resolved to
1995          * {@code C} and resolution always succeeds immediately.</li>
1996          * </ul>
1997          *
1998          * <p> If the {@code initialize} parameter is {@code true},
1999          * then {@code C} is initialized by the Java Virtual Machine.
2000          *
2001          * <p> The newly created class or interface {@code C} serves as the
2002          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2003          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2004          * no other class or interface can refer to {@code C} via a constant pool entry.
2005          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2006          * a method parameter type, or a method return type by any other class.
2007          * This is because a hidden class or interface does not have a binary name, so
2008          * there is no internal form available to record in any class's constant pool.
2009          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2010          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2011          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
2012          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2013          * JVM Tool Interface</a>.
2014          *
2015          * <p> A class or interface created by
2016          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2017          * a class loader} has a strong relationship with that class loader.
2018          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2019          * that {@linkplain Class#getClassLoader() defined it}.
2020          * This means that a class created by a class loader may be unloaded if and
2021          * only if its defining loader is not reachable and thus may be reclaimed
2022          * by a garbage collector (JLS 12.7).
2023          *
2024          * By default, however, a hidden class or interface may be unloaded even if
2025          * the class loader that is marked as its defining loader is
2026          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2027          * This behavior is useful when a hidden class or interface serves multiple
2028          * classes defined by arbitrary class loaders.  In other cases, a hidden
2029          * class or interface may be linked to a single class (or a small number of classes)
2030          * with the same defining loader as the hidden class or interface.
2031          * In such cases, where the hidden class or interface must be coterminous
2032          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2033          * option may be passed in {@code options}.
2034          * This arranges for a hidden class to have the same strong relationship
2035          * with the class loader marked as its defining loader,
2036          * as a normal class or interface has with its own defining loader.
2037          *
2038          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2039          * may still prevent a hidden class or interface from being
2040          * unloaded by ensuring that the {@code Class} object is reachable.
2041          *
2042          * <p> The unloading characteristics are set for each hidden class when it is
2043          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2044          * to be unloaded independently of the class loader marked as their defining loader
2045          * is that a very large number of hidden classes may be created by an application.
2046          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2047          * just as if normal classes were created by class loaders.
2048          *
2049          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2050          * their private members.  The nest relationship is determined by
2051          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2052          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2053          * By default, a hidden class belongs to a nest consisting only of itself
2054          * because a hidden class has no binary name.
2055          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2056          * to create a hidden class or interface {@code C} as a member of a nest.
2057          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2058          * in the {@code ClassFile} structure from which {@code C} was derived.
2059          * Instead, the following rules determine the nest host of {@code C}:
2060          * <ul>
2061          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2062          *     been determined, then let {@code H} be the nest host of the lookup class.
2063          *     Otherwise, the nest host of the lookup class is determined using the
2064          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2065          * <li>The nest host of {@code C} is determined to be {@code H},
2066          *     the nest host of the lookup class.</li>
2067          * </ul>
2068          *
2069          * <p> A hidden class or interface may be serializable, but this requires a custom
2070          * serialization mechanism in order to ensure that instances are properly serialized
2071          * and deserialized. The default serialization mechanism supports only classes and
2072          * interfaces that are discoverable by their class name.
2073          *
2074          * @param bytes the bytes that make up the class data,
2075          * in the format of a valid {@code class} file as defined by
2076          * <cite>The Java Virtual Machine Specification</cite>.
2077          * @param initialize if {@code true} the class will be initialized.
2078          * @param options {@linkplain ClassOption class options}
2079          * @return the {@code Lookup} object on the hidden class,
2080          * with {@linkplain #ORIGINAL original} and
2081          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2082          *
2083          * @throws IllegalAccessException if this {@code Lookup} does not have
2084          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2085          * @throws SecurityException if a security manager is present and it
2086          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2087          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2088          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2089          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2090          * than the lookup class or {@code bytes} is not a class or interface
2091          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2092          * @throws IncompatibleClassChangeError if the class or interface named as
2093          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2094          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2095          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2096          * {@code C} is {@code C} itself
2097          * @throws VerifyError if the newly created class cannot be verified
2098          * @throws LinkageError if the newly created class cannot be linked for any other reason
2099          * @throws NullPointerException if any parameter is {@code null}
2100          *
2101          * @since 15
2102          * @see Class#isHidden()
2103          * @jvms 4.2.1 Binary Class and Interface Names
2104          * @jvms 4.2.2 Unqualified Names
2105          * @jvms 4.7.28 The {@code NestHost} Attribute
2106          * @jvms 4.7.29 The {@code NestMembers} Attribute
2107          * @jvms 5.4.3.1 Class and Interface Resolution
2108          * @jvms 5.4.4 Access Control
2109          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2110          * @jvms 5.4 Linking
2111          * @jvms 5.5 Initialization
2112          * @jls 12.7 Unloading of Classes and Interfaces
2113          */
2114         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2115                 throws IllegalAccessException
2116         {
2117             Objects.requireNonNull(bytes);
2118             Objects.requireNonNull(options);
2119 
2120             ensureDefineClassPermission();
2121             if (!hasFullPrivilegeAccess()) {
2122                 throw new IllegalAccessException(this + " does not have full privilege access");
2123             }
2124 
2125             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2126         }
2127 
2128         /**
2129          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2130          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2131          * returning a {@code Lookup} on the newly created class or interface.
2132          *
2133          * <p> This method is equivalent to calling
2134          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2135          * as if the hidden class is injected with a private static final <i>unnamed</i>
2136          * field which is initialized with the given {@code classData} at
2137          * the first instruction of the class initializer.
2138          * The newly created class is linked by the Java Virtual Machine.
2139          *
2140          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2141          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2142          * methods can be used to retrieve the {@code classData}.
2143          *
2144          * @apiNote
2145          * A framework can create a hidden class with class data with one or more
2146          * objects and load the class data as dynamically-computed constant(s)
2147          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2148          * Class data} is accessible only to the lookup object created by the newly
2149          * defined hidden class but inaccessible to other members in the same nest
2150          * (unlike private static fields that are accessible to nestmates).
2151          * Care should be taken w.r.t. mutability for example when passing
2152          * an array or other mutable structure through the class data.
2153          * Changing any value stored in the class data at runtime may lead to
2154          * unpredictable behavior.
2155          * If the class data is a {@code List}, it is good practice to make it
2156          * unmodifiable for example via {@link List#of List::of}.
2157          *
2158          * @param bytes     the class bytes
2159          * @param classData pre-initialized class data
2160          * @param initialize if {@code true} the class will be initialized.
2161          * @param options   {@linkplain ClassOption class options}
2162          * @return the {@code Lookup} object on the hidden class,
2163          * with {@linkplain #ORIGINAL original} and
2164          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2165          *
2166          * @throws IllegalAccessException if this {@code Lookup} does not have
2167          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2168          * @throws SecurityException if a security manager is present and it
2169          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2170          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2171          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2172          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2173          * than the lookup class or {@code bytes} is not a class or interface
2174          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2175          * @throws IncompatibleClassChangeError if the class or interface named as
2176          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2177          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2178          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2179          * {@code C} is {@code C} itself
2180          * @throws VerifyError if the newly created class cannot be verified
2181          * @throws LinkageError if the newly created class cannot be linked for any other reason
2182          * @throws NullPointerException if any parameter is {@code null}
2183          *
2184          * @since 16
2185          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2186          * @see Class#isHidden()
2187          * @see MethodHandles#classData(Lookup, String, Class)
2188          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2189          * @jvms 4.2.1 Binary Class and Interface Names
2190          * @jvms 4.2.2 Unqualified Names
2191          * @jvms 4.7.28 The {@code NestHost} Attribute
2192          * @jvms 4.7.29 The {@code NestMembers} Attribute
2193          * @jvms 5.4.3.1 Class and Interface Resolution
2194          * @jvms 5.4.4 Access Control
2195          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2196          * @jvms 5.4 Linking
2197          * @jvms 5.5 Initialization
2198          * @jls 12.7 Unloading of Classes and Interface
2199          */
2200         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2201                 throws IllegalAccessException
2202         {
2203             Objects.requireNonNull(bytes);
2204             Objects.requireNonNull(classData);
2205             Objects.requireNonNull(options);
2206 
2207             ensureDefineClassPermission();
2208             if (!hasFullPrivilegeAccess()) {
2209                 throw new IllegalAccessException(this + " does not have full privilege access");
2210             }
2211 
2212             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2213                        .defineClassAsLookup(initialize, classData);
2214         }
2215 
2216         static class ClassFile {
2217             final String name;
2218             final int accessFlags;
2219             final byte[] bytes;
2220             ClassFile(String name, int accessFlags, byte[] bytes) {
2221                 this.name = name;
2222                 this.accessFlags = accessFlags;
2223                 this.bytes = bytes;
2224             }
2225 
2226             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2227                 return new ClassFile(name, 0, bytes);
2228             }
2229 
2230             /**
2231              * This method checks the class file version and the structure of `this_class`.
2232              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2233              * that is in the named package.
2234              *
2235              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2236              * or the class is not in the given package name.
2237              */
2238             static ClassFile newInstance(byte[] bytes, String pkgName) {
2239                 int magic = readInt(bytes, 0);
2240                 if (magic != 0xCAFEBABE) {
2241                     throw new ClassFormatError("Incompatible magic value: " + magic);
2242                 }
2243                 int minor = readUnsignedShort(bytes, 4);
2244                 int major = readUnsignedShort(bytes, 6);
2245                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2246                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2247                 }
2248 
2249                 String name;
2250                 int accessFlags;
2251                 try {
2252                     ClassReader reader = new ClassReader(bytes);
2253                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2254                     // workaround to read `this_class` using readConst and validate the value
2255                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2256                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2257                     if (!(constant instanceof Type type)) {
2258                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2259                     }
2260                     if (!type.getDescriptor().startsWith("L")) {
2261                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2262                     }
2263                     name = type.getClassName();
2264                     accessFlags = reader.readUnsignedShort(reader.header);
2265                 } catch (RuntimeException e) {
2266                     // ASM exceptions are poorly specified
2267                     ClassFormatError cfe = new ClassFormatError();
2268                     cfe.initCause(e);
2269                     throw cfe;
2270                 }
2271 
2272                 // must be a class or interface
2273                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2274                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2275                 }
2276 
2277                 // check if it's in the named package
2278                 int index = name.lastIndexOf('.');
2279                 String pn = (index == -1) ? "" : name.substring(0, index);
2280                 if (!pn.equals(pkgName)) {
2281                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2282                 }
2283 
2284                 return new ClassFile(name, accessFlags, bytes);
2285             }
2286 
2287             private static int readInt(byte[] bytes, int offset) {
2288                 if ((offset+4) > bytes.length) {
2289                     throw new ClassFormatError("Invalid ClassFile structure");
2290                 }
2291                 return ((bytes[offset] & 0xFF) << 24)
2292                         | ((bytes[offset + 1] & 0xFF) << 16)
2293                         | ((bytes[offset + 2] & 0xFF) << 8)
2294                         | (bytes[offset + 3] & 0xFF);
2295             }
2296 
2297             private static int readUnsignedShort(byte[] bytes, int offset) {
2298                 if ((offset+2) > bytes.length) {
2299                     throw new ClassFormatError("Invalid ClassFile structure");
2300                 }
2301                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2302             }
2303         }
2304 
2305         /*
2306          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2307          * from the given bytes.
2308          *
2309          * Caller should make a defensive copy of the arguments if needed
2310          * before calling this factory method.
2311          *
2312          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2313          * {@bytes} denotes a class in a different package than the lookup class
2314          */
2315         private ClassDefiner makeClassDefiner(byte[] bytes) {
2316             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2317             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2318         }
2319 
2320         /**
2321          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2322          * from the given bytes.  The name must be in the same package as the lookup class.
2323          *
2324          * Caller should make a defensive copy of the arguments if needed
2325          * before calling this factory method.
2326          *
2327          * @param bytes   class bytes
2328          * @return ClassDefiner that defines a hidden class of the given bytes.
2329          *
2330          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2331          * {@bytes} denotes a class in a different package than the lookup class
2332          */
2333         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2334             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2335             return makeHiddenClassDefiner(cf, Set.of(), false);
2336         }
2337 
2338         /**
2339          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2340          * from the given bytes and options.
2341          * The name must be in the same package as the lookup class.
2342          *
2343          * Caller should make a defensive copy of the arguments if needed
2344          * before calling this factory method.
2345          *
2346          * @param bytes   class bytes
2347          * @param options class options
2348          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2349          * @return ClassDefiner that defines a hidden class of the given bytes and options
2350          *
2351          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2352          * {@bytes} denotes a class in a different package than the lookup class
2353          */
2354         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2355                                             Set<ClassOption> options,
2356                                             boolean accessVmAnnotations) {
2357             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2358             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2359         }
2360 
2361         /**
2362          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2363          * from the given bytes.  No package name check on the given name.
2364          *
2365          * @param name    fully-qualified name that specifies the prefix of the hidden class
2366          * @param bytes   class bytes
2367          * @return ClassDefiner that defines a hidden class of the given bytes.
2368          */
2369         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
2370             // skip name and access flags validation
2371             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), Set.of(), false);
2372         }
2373 
2374         /**
2375          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2376          * from the given class file and options.
2377          *
2378          * @param cf ClassFile
2379          * @param options class options
2380          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2381          */
2382         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2383                                                     Set<ClassOption> options,
2384                                                     boolean accessVmAnnotations) {
2385             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2386             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2387                 // jdk.internal.vm.annotations are permitted for classes
2388                 // defined to boot loader and platform loader
2389                 flags |= ACCESS_VM_ANNOTATIONS;
2390             }
2391 
2392             return new ClassDefiner(this, cf, flags);
2393         }
2394 
2395         static class ClassDefiner {
2396             private final Lookup lookup;
2397             private final String name;
2398             private final byte[] bytes;
2399             private final int classFlags;
2400 
2401             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2402                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2403                 this.lookup = lookup;
2404                 this.bytes = cf.bytes;
2405                 this.name = cf.name;
2406                 this.classFlags = flags;
2407             }
2408 
2409             String className() {
2410                 return name;
2411             }
2412 
2413             Class<?> defineClass(boolean initialize) {
2414                 return defineClass(initialize, null);
2415             }
2416 
2417             Lookup defineClassAsLookup(boolean initialize) {
2418                 Class<?> c = defineClass(initialize, null);
2419                 return new Lookup(c, null, FULL_POWER_MODES);
2420             }
2421 
2422             /**
2423              * Defines the class of the given bytes and the given classData.
2424              * If {@code initialize} parameter is true, then the class will be initialized.
2425              *
2426              * @param initialize true if the class to be initialized
2427              * @param classData classData or null
2428              * @return the class
2429              *
2430              * @throws LinkageError linkage error
2431              */
2432             Class<?> defineClass(boolean initialize, Object classData) {
2433                 Class<?> lookupClass = lookup.lookupClass();
2434                 ClassLoader loader = lookupClass.getClassLoader();
2435                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2436                 Class<?> c = SharedSecrets.getJavaLangAccess()
2437                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2438                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2439                 return c;
2440             }
2441 
2442             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2443                 Class<?> c = defineClass(initialize, classData);
2444                 return new Lookup(c, null, FULL_POWER_MODES);
2445             }
2446 
2447             private boolean isNestmate() {
2448                 return (classFlags & NESTMATE_CLASS) != 0;
2449             }
2450         }
2451 
2452         private ProtectionDomain lookupClassProtectionDomain() {
2453             ProtectionDomain pd = cachedProtectionDomain;
2454             if (pd == null) {
2455                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2456             }
2457             return pd;
2458         }
2459 
2460         // cached protection domain
2461         private volatile ProtectionDomain cachedProtectionDomain;
2462 
2463         // Make sure outer class is initialized first.
2464         static { IMPL_NAMES.getClass(); }
2465 
2466         /** Package-private version of lookup which is trusted. */
2467         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2468 
2469         /** Version of lookup which is trusted minimally.
2470          *  It can only be used to create method handles to publicly accessible
2471          *  members in packages that are exported unconditionally.
2472          */
2473         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2474 
2475         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2476             String name = lookupClass.getName();
2477             if (name.startsWith("java.lang.invoke."))
2478                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2479         }
2480 
2481         /**
2482          * Displays the name of the class from which lookups are to be made,
2483          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2484          * previous lookup class} if present.
2485          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2486          * If there are restrictions on the access permitted to this lookup,
2487          * this is indicated by adding a suffix to the class name, consisting
2488          * of a slash and a keyword.  The keyword represents the strongest
2489          * allowed access, and is chosen as follows:
2490          * <ul>
2491          * <li>If no access is allowed, the suffix is "/noaccess".
2492          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2493          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2494          * <li>If only public and module access are allowed, the suffix is "/module".
2495          * <li>If public and package access are allowed, the suffix is "/package".
2496          * <li>If public, package, and private access are allowed, the suffix is "/private".
2497          * </ul>
2498          * If none of the above cases apply, it is the case that
2499          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2500          * (public, module, package, private, and protected) is allowed.
2501          * In this case, no suffix is added.
2502          * This is true only of an object obtained originally from
2503          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2504          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2505          * always have restricted access, and will display a suffix.
2506          * <p>
2507          * (It may seem strange that protected access should be
2508          * stronger than private access.  Viewed independently from
2509          * package access, protected access is the first to be lost,
2510          * because it requires a direct subclass relationship between
2511          * caller and callee.)
2512          * @see #in
2513          *
2514          * @revised 9
2515          */
2516         @Override
2517         public String toString() {
2518             String cname = lookupClass.getName();
2519             if (prevLookupClass != null)
2520                 cname += "/" + prevLookupClass.getName();
2521             switch (allowedModes) {
2522             case 0:  // no privileges
2523                 return cname + "/noaccess";
2524             case UNCONDITIONAL:
2525                 return cname + "/publicLookup";
2526             case PUBLIC:
2527                 return cname + "/public";
2528             case PUBLIC|MODULE:
2529                 return cname + "/module";
2530             case PUBLIC|PACKAGE:
2531             case PUBLIC|MODULE|PACKAGE:
2532                 return cname + "/package";
2533             case PUBLIC|PACKAGE|PRIVATE:
2534             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2535                     return cname + "/private";
2536             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2537             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2538             case FULL_POWER_MODES:
2539                     return cname;
2540             case TRUSTED:
2541                 return "/trusted";  // internal only; not exported
2542             default:  // Should not happen, but it's a bitfield...
2543                 cname = cname + "/" + Integer.toHexString(allowedModes);
2544                 assert(false) : cname;
2545                 return cname;
2546             }
2547         }
2548 
2549         /**
2550          * Produces a method handle for a static method.
2551          * The type of the method handle will be that of the method.
2552          * (Since static methods do not take receivers, there is no
2553          * additional receiver argument inserted into the method handle type,
2554          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2555          * The method and all its argument types must be accessible to the lookup object.
2556          * <p>
2557          * The returned method handle will have
2558          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2559          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2560          * <p>
2561          * If the returned method handle is invoked, the method's class will
2562          * be initialized, if it has not already been initialized.
2563          * <p><b>Example:</b>
2564          * <blockquote><pre>{@code
2565 import static java.lang.invoke.MethodHandles.*;
2566 import static java.lang.invoke.MethodType.*;
2567 ...
2568 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2569   "asList", methodType(List.class, Object[].class));
2570 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2571          * }</pre></blockquote>
2572          * @param refc the class from which the method is accessed
2573          * @param name the name of the method
2574          * @param type the type of the method
2575          * @return the desired method handle
2576          * @throws NoSuchMethodException if the method does not exist
2577          * @throws IllegalAccessException if access checking fails,
2578          *                                or if the method is not {@code static},
2579          *                                or if the method's variable arity modifier bit
2580          *                                is set and {@code asVarargsCollector} fails
2581          * @throws    SecurityException if a security manager is present and it
2582          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2583          * @throws NullPointerException if any argument is null
2584          */
2585         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2586             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2587             // resolveOrFail could return a non-static <init> method if present
2588             // detect and throw NSME before producing a MethodHandle
2589             if (!method.isStatic() && name.equals("<init>")) {
2590                 throw new NoSuchMethodException("illegal method name: " + name);
2591             }
2592 
2593             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2594         }
2595 
2596         /**
2597          * Produces a method handle for a virtual method.
2598          * The type of the method handle will be that of the method,
2599          * with the receiver type (usually {@code refc}) prepended.
2600          * The method and all its argument types must be accessible to the lookup object.
2601          * <p>
2602          * When called, the handle will treat the first argument as a receiver
2603          * and, for non-private methods, dispatch on the receiver's type to determine which method
2604          * implementation to enter.
2605          * For private methods the named method in {@code refc} will be invoked on the receiver.
2606          * (The dispatching action is identical with that performed by an
2607          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2608          * <p>
2609          * The first argument will be of type {@code refc} if the lookup
2610          * class has full privileges to access the member.  Otherwise
2611          * the member must be {@code protected} and the first argument
2612          * will be restricted in type to the lookup class.
2613          * <p>
2614          * The returned method handle will have
2615          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2616          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2617          * <p>
2618          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2619          * instructions and method handles produced by {@code findVirtual},
2620          * if the class is {@code MethodHandle} and the name string is
2621          * {@code invokeExact} or {@code invoke}, the resulting
2622          * method handle is equivalent to one produced by
2623          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2624          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2625          * with the same {@code type} argument.
2626          * <p>
2627          * If the class is {@code VarHandle} and the name string corresponds to
2628          * the name of a signature-polymorphic access mode method, the resulting
2629          * method handle is equivalent to one produced by
2630          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2631          * the access mode corresponding to the name string and with the same
2632          * {@code type} arguments.
2633          * <p>
2634          * <b>Example:</b>
2635          * <blockquote><pre>{@code
2636 import static java.lang.invoke.MethodHandles.*;
2637 import static java.lang.invoke.MethodType.*;
2638 ...
2639 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2640   "concat", methodType(String.class, String.class));
2641 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2642   "hashCode", methodType(int.class));
2643 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2644   "hashCode", methodType(int.class));
2645 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2646 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2647 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2648 // interface method:
2649 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2650   "subSequence", methodType(CharSequence.class, int.class, int.class));
2651 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2652 // constructor "internal method" must be accessed differently:
2653 MethodType MT_newString = methodType(void.class); //()V for new String()
2654 try { assertEquals("impossible", lookup()
2655         .findVirtual(String.class, "<init>", MT_newString));
2656  } catch (NoSuchMethodException ex) { } // OK
2657 MethodHandle MH_newString = publicLookup()
2658   .findConstructor(String.class, MT_newString);
2659 assertEquals("", (String) MH_newString.invokeExact());
2660          * }</pre></blockquote>
2661          *
2662          * @param refc the class or interface from which the method is accessed
2663          * @param name the name of the method
2664          * @param type the type of the method, with the receiver argument omitted
2665          * @return the desired method handle
2666          * @throws NoSuchMethodException if the method does not exist
2667          * @throws IllegalAccessException if access checking fails,
2668          *                                or if the method is {@code static},
2669          *                                or if the method's variable arity modifier bit
2670          *                                is set and {@code asVarargsCollector} fails
2671          * @throws    SecurityException if a security manager is present and it
2672          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2673          * @throws NullPointerException if any argument is null
2674          */
2675         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2676             if (refc == MethodHandle.class) {
2677                 MethodHandle mh = findVirtualForMH(name, type);
2678                 if (mh != null)  return mh;
2679             } else if (refc == VarHandle.class) {
2680                 MethodHandle mh = findVirtualForVH(name, type);
2681                 if (mh != null)  return mh;
2682             }
2683             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2684             MemberName method = resolveOrFail(refKind, refc, name, type);
2685             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2686         }
2687         private MethodHandle findVirtualForMH(String name, MethodType type) {
2688             // these names require special lookups because of the implicit MethodType argument
2689             if ("invoke".equals(name))
2690                 return invoker(type);
2691             if ("invokeExact".equals(name))
2692                 return exactInvoker(type);
2693             assert(!MemberName.isMethodHandleInvokeName(name));
2694             return null;
2695         }
2696         private MethodHandle findVirtualForVH(String name, MethodType type) {
2697             try {
2698                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2699             } catch (IllegalArgumentException e) {
2700                 return null;
2701             }
2702         }
2703 
2704         /**
2705          * Produces a method handle which creates an object and initializes it, using
2706          * the constructor of the specified type.
2707          * The parameter types of the method handle will be those of the constructor,
2708          * while the return type will be a reference to the constructor's class.
2709          * The constructor and all its argument types must be accessible to the lookup object.
2710          * <p>
2711          * The requested type must have a return type of {@code void}.
2712          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2713          * <p>
2714          * The returned method handle will have
2715          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2716          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2717          * <p>
2718          * If the returned method handle is invoked, the constructor's class will
2719          * be initialized, if it has not already been initialized.
2720          * <p><b>Example:</b>
2721          * <blockquote><pre>{@code
2722 import static java.lang.invoke.MethodHandles.*;
2723 import static java.lang.invoke.MethodType.*;
2724 ...
2725 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2726   ArrayList.class, methodType(void.class, Collection.class));
2727 Collection orig = Arrays.asList("x", "y");
2728 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2729 assert(orig != copy);
2730 assertEquals(orig, copy);
2731 // a variable-arity constructor:
2732 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2733   ProcessBuilder.class, methodType(void.class, String[].class));
2734 ProcessBuilder pb = (ProcessBuilder)
2735   MH_newProcessBuilder.invoke("x", "y", "z");
2736 assertEquals("[x, y, z]", pb.command().toString());
2737          * }</pre></blockquote>
2738          *
2739          * @apiNote
2740          * This method does not find a static {@code <init>} factory method as it is invoked
2741          * via {@code invokestatic} bytecode as opposed to {@code invokespecial} for an
2742          * object constructor.  To look up static {@code <init>} factory method, use
2743          * the {@link #findStatic(Class, String, MethodType) findStatic} method.
2744          *
2745          * @param refc the class or interface from which the method is accessed
2746          * @param type the type of the method, with the receiver argument omitted, and a void return type
2747          * @return the desired method handle
2748          * @throws NoSuchMethodException if the constructor does not exist
2749          * @throws IllegalAccessException if access checking fails
2750          *                                or if the method's variable arity modifier bit
2751          *                                is set and {@code asVarargsCollector} fails
2752          * @throws    SecurityException if a security manager is present and it
2753          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2754          * @throws NullPointerException if any argument is null
2755          */
2756         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2757             if (refc.isArray()) {
2758                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2759             }
2760             if (type.returnType() != void.class) {
2761                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2762             }
2763             String name = "<init>";
2764             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2765             return getDirectConstructor(refc, ctor);
2766         }
2767 
2768         /**
2769          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2770          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2771          * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class,
2772          * and then determines whether the class is accessible to this lookup object.
2773          * <p>
2774          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2775          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2776          *
2777          * @param targetName the fully qualified name of the class to be looked up.
2778          * @return the requested class.
2779          * @throws SecurityException if a security manager is present and it
2780          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2781          * @throws LinkageError if the linkage fails
2782          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2783          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2784          * modes.
2785          * @throws NullPointerException if {@code targetName} is null
2786          * @since 9
2787          * @jvms 5.4.3.1 Class and Interface Resolution
2788          */
2789         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2790             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2791             return accessClass(targetClass);
2792         }
2793 
2794         /**
2795          * Ensures that {@code targetClass} has been initialized. The class
2796          * to be initialized must be {@linkplain #accessClass accessible}
2797          * to this {@code Lookup} object.  This method causes {@code targetClass}
2798          * to be initialized if it has not been already initialized,
2799          * as specified in JVMS {@jvms 5.5}.
2800          *
2801          * <p>
2802          * This method returns when {@code targetClass} is fully initialized, or
2803          * when {@code targetClass} is being initialized by the current thread.
2804          *
2805          * @param targetClass the class to be initialized
2806          * @return {@code targetClass} that has been initialized, or that is being
2807          *         initialized by the current thread.
2808          *
2809          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2810          *          or array class
2811          * @throws  IllegalAccessException if {@code targetClass} is not
2812          *          {@linkplain #accessClass accessible} to this lookup
2813          * @throws  ExceptionInInitializerError if the class initialization provoked
2814          *          by this method fails
2815          * @throws  SecurityException if a security manager is present and it
2816          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2817          * @since 15
2818          * @jvms 5.5 Initialization
2819          */
2820         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2821             if (targetClass.isPrimitive())
2822                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2823             if (targetClass.isArray())
2824                 throw new IllegalArgumentException(targetClass + " is an array class");
2825 
2826             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2827                 throw makeAccessException(targetClass);
2828             }
2829             checkSecurityManager(targetClass);
2830 
2831             // ensure class initialization
2832             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2833             return targetClass;
2834         }
2835 
2836         /*
2837          * Returns IllegalAccessException due to access violation to the given targetClass.
2838          *
2839          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2840          * which verifies access to a class rather a member.
2841          */
2842         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2843             String message = "access violation: "+ targetClass;
2844             if (this == MethodHandles.publicLookup()) {
2845                 message += ", from public Lookup";
2846             } else {
2847                 Module m = lookupClass().getModule();
2848                 message += ", from " + lookupClass() + " (" + m + ")";
2849                 if (prevLookupClass != null) {
2850                     message += ", previous lookup " +
2851                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2852                 }
2853             }
2854             return new IllegalAccessException(message);
2855         }
2856 
2857         /**
2858          * Determines if a class can be accessed from the lookup context defined by
2859          * this {@code Lookup} object. The static initializer of the class is not run.
2860          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2861          * if the element type of the array class is accessible.  Otherwise,
2862          * {@code targetClass} is determined as accessible as follows.
2863          *
2864          * <p>
2865          * If {@code targetClass} is in the same module as the lookup class,
2866          * the lookup class is {@code LC} in module {@code M1} and
2867          * the previous lookup class is in module {@code M0} or
2868          * {@code null} if not present,
2869          * {@code targetClass} is accessible if and only if one of the following is true:
2870          * <ul>
2871          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2872          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2873          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2874          *     in the same runtime package of {@code LC}.</li>
2875          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2876          *     a public type in {@code M1}.</li>
2877          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2878          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2879          *     if the previous lookup class is present; otherwise, {@code targetClass}
2880          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2881          * </ul>
2882          *
2883          * <p>
2884          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2885          * can access public types in all modules when the type is in a package
2886          * that is exported unconditionally.
2887          * <p>
2888          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2889          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2890          * is inaccessible.
2891          * <p>
2892          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2893          * {@code M1} is the module containing {@code lookupClass} and
2894          * {@code M2} is the module containing {@code targetClass},
2895          * then {@code targetClass} is accessible if and only if
2896          * <ul>
2897          * <li>{@code M1} reads {@code M2}, and
2898          * <li>{@code targetClass} is public and in a package exported by
2899          *     {@code M2} at least to {@code M1}.
2900          * </ul>
2901          * <p>
2902          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2903          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2904          * containing the previous lookup class, then {@code targetClass} is accessible
2905          * if and only if one of the following is true:
2906          * <ul>
2907          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2908          *     {@linkplain Module#reads reads} {@code M0} and the type is
2909          *     in a package that is exported to at least {@code M1}.
2910          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2911          *     {@linkplain Module#reads reads} {@code M1} and the type is
2912          *     in a package that is exported to at least {@code M0}.
2913          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2914          *     and {@code M1} reads {@code M2} and the type is in a package
2915          *     that is exported to at least both {@code M0} and {@code M2}.
2916          * </ul>
2917          * <p>
2918          * Otherwise, {@code targetClass} is not accessible.
2919          *
2920          * @param targetClass the class to be access-checked
2921          * @return the class that has been access-checked
2922          * @throws IllegalAccessException if the class is not accessible from the lookup class
2923          * and previous lookup class, if present, using the allowed access modes.
2924          * @throws SecurityException if a security manager is present and it
2925          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2926          * @throws NullPointerException if {@code targetClass} is {@code null}
2927          * @since 9
2928          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2929          */
2930         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2931             if (!isClassAccessible(targetClass)) {
2932                 throw makeAccessException(targetClass);
2933             }
2934             checkSecurityManager(targetClass);
2935             return targetClass;
2936         }
2937 
2938         /**
2939          * Produces an early-bound method handle for a virtual method.
2940          * It will bypass checks for overriding methods on the receiver,
2941          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2942          * instruction from within the explicitly specified {@code specialCaller}.
2943          * The type of the method handle will be that of the method,
2944          * with a suitably restricted receiver type prepended.
2945          * (The receiver type will be {@code specialCaller} or a subtype.)
2946          * The method and all its argument types must be accessible
2947          * to the lookup object.
2948          * <p>
2949          * Before method resolution,
2950          * if the explicitly specified caller class is not identical with the
2951          * lookup class, or if this lookup object does not have
2952          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2953          * privileges, the access fails.
2954          * <p>
2955          * The returned method handle will have
2956          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2957          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2958          * <p style="font-size:smaller;">
2959          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2960          * even though the {@code invokespecial} instruction can refer to them
2961          * in special circumstances.  Use {@link #findConstructor findConstructor}
2962          * to access instance initialization methods in a safe manner.)</em>
2963          * <p><b>Example:</b>
2964          * <blockquote><pre>{@code
2965 import static java.lang.invoke.MethodHandles.*;
2966 import static java.lang.invoke.MethodType.*;
2967 ...
2968 static class Listie extends ArrayList {
2969   public String toString() { return "[wee Listie]"; }
2970   static Lookup lookup() { return MethodHandles.lookup(); }
2971 }
2972 ...
2973 // no access to constructor via invokeSpecial:
2974 MethodHandle MH_newListie = Listie.lookup()
2975   .findConstructor(Listie.class, methodType(void.class));
2976 Listie l = (Listie) MH_newListie.invokeExact();
2977 try { assertEquals("impossible", Listie.lookup().findSpecial(
2978         Listie.class, "<init>", methodType(void.class), Listie.class));
2979  } catch (NoSuchMethodException ex) { } // OK
2980 // access to super and self methods via invokeSpecial:
2981 MethodHandle MH_super = Listie.lookup().findSpecial(
2982   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2983 MethodHandle MH_this = Listie.lookup().findSpecial(
2984   Listie.class, "toString" , methodType(String.class), Listie.class);
2985 MethodHandle MH_duper = Listie.lookup().findSpecial(
2986   Object.class, "toString" , methodType(String.class), Listie.class);
2987 assertEquals("[]", (String) MH_super.invokeExact(l));
2988 assertEquals(""+l, (String) MH_this.invokeExact(l));
2989 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2990 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2991         String.class, "toString", methodType(String.class), Listie.class));
2992  } catch (IllegalAccessException ex) { } // OK
2993 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2994 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2995          * }</pre></blockquote>
2996          *
2997          * @param refc the class or interface from which the method is accessed
2998          * @param name the name of the method (which must not be "&lt;init&gt;")
2999          * @param type the type of the method, with the receiver argument omitted
3000          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3001          * @return the desired method handle
3002          * @throws NoSuchMethodException if the method does not exist
3003          * @throws IllegalAccessException if access checking fails,
3004          *                                or if the method is {@code static},
3005          *                                or if the method's variable arity modifier bit
3006          *                                is set and {@code asVarargsCollector} fails
3007          * @throws    SecurityException if a security manager is present and it
3008          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3009          * @throws NullPointerException if any argument is null
3010          */
3011         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3012                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3013             checkSpecialCaller(specialCaller, refc);
3014             Lookup specialLookup = this.in(specialCaller);
3015             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3016             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3017         }
3018 
3019         /**
3020          * Produces a method handle giving read access to a non-static field.
3021          * The type of the method handle will have a return type of the field's
3022          * value type.
3023          * The method handle's single argument will be the instance containing
3024          * the field.
3025          * Access checking is performed immediately on behalf of the lookup class.
3026          * @param refc the class or interface from which the method is accessed
3027          * @param name the field's name
3028          * @param type the field's type
3029          * @return a method handle which can load values from the field
3030          * @throws NoSuchFieldException if the field does not exist
3031          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3032          * @throws    SecurityException if a security manager is present and it
3033          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3034          * @throws NullPointerException if any argument is null
3035          * @see #findVarHandle(Class, String, Class)
3036          */
3037         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3038             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3039             return getDirectField(REF_getField, refc, field);
3040         }
3041 
3042         /**
3043          * Produces a method handle giving write access to a non-static field.
3044          * The type of the method handle will have a void return type.
3045          * The method handle will take two arguments, the instance containing
3046          * the field, and the value to be stored.
3047          * The second argument will be of the field's value type.
3048          * Access checking is performed immediately on behalf of the lookup class.
3049          * @param refc the class or interface from which the method is accessed
3050          * @param name the field's name
3051          * @param type the field's type
3052          * @return a method handle which can store values into the field
3053          * @throws NoSuchFieldException if the field does not exist
3054          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3055          *                                or {@code final}
3056          * @throws    SecurityException if a security manager is present and it
3057          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3058          * @throws NullPointerException if any argument is null
3059          * @see #findVarHandle(Class, String, Class)
3060          */
3061         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3062             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3063             return getDirectField(REF_putField, refc, field);
3064         }
3065 
3066         /**
3067          * Produces a VarHandle giving access to a non-static field {@code name}
3068          * of type {@code type} declared in a class of type {@code recv}.
3069          * The VarHandle's variable type is {@code type} and it has one
3070          * coordinate type, {@code recv}.
3071          * <p>
3072          * Access checking is performed immediately on behalf of the lookup
3073          * class.
3074          * <p>
3075          * Certain access modes of the returned VarHandle are unsupported under
3076          * the following conditions:
3077          * <ul>
3078          * <li>if the field is declared {@code final}, then the write, atomic
3079          *     update, numeric atomic update, and bitwise atomic update access
3080          *     modes are unsupported.
3081          * <li>if the field type is anything other than {@code byte},
3082          *     {@code short}, {@code char}, {@code int}, {@code long},
3083          *     {@code float}, or {@code double} then numeric atomic update
3084          *     access modes are unsupported.
3085          * <li>if the field type is anything other than {@code boolean},
3086          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3087          *     {@code long} then bitwise atomic update access modes are
3088          *     unsupported.
3089          * </ul>
3090          * <p>
3091          * If the field is declared {@code volatile} then the returned VarHandle
3092          * will override access to the field (effectively ignore the
3093          * {@code volatile} declaration) in accordance to its specified
3094          * access modes.
3095          * <p>
3096          * If the field type is {@code float} or {@code double} then numeric
3097          * and atomic update access modes compare values using their bitwise
3098          * representation (see {@link Float#floatToRawIntBits} and
3099          * {@link Double#doubleToRawLongBits}, respectively).
3100          * @apiNote
3101          * Bitwise comparison of {@code float} values or {@code double} values,
3102          * as performed by the numeric and atomic update access modes, differ
3103          * from the primitive {@code ==} operator and the {@link Float#equals}
3104          * and {@link Double#equals} methods, specifically with respect to
3105          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3106          * Care should be taken when performing a compare and set or a compare
3107          * and exchange operation with such values since the operation may
3108          * unexpectedly fail.
3109          * There are many possible NaN values that are considered to be
3110          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3111          * provided by Java can distinguish between them.  Operation failure can
3112          * occur if the expected or witness value is a NaN value and it is
3113          * transformed (perhaps in a platform specific manner) into another NaN
3114          * value, and thus has a different bitwise representation (see
3115          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3116          * details).
3117          * The values {@code -0.0} and {@code +0.0} have different bitwise
3118          * representations but are considered equal when using the primitive
3119          * {@code ==} operator.  Operation failure can occur if, for example, a
3120          * numeric algorithm computes an expected value to be say {@code -0.0}
3121          * and previously computed the witness value to be say {@code +0.0}.
3122          * @param recv the receiver class, of type {@code R}, that declares the
3123          * non-static field
3124          * @param name the field's name
3125          * @param type the field's type, of type {@code T}
3126          * @return a VarHandle giving access to non-static fields.
3127          * @throws NoSuchFieldException if the field does not exist
3128          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3129          * @throws    SecurityException if a security manager is present and it
3130          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3131          * @throws NullPointerException if any argument is null
3132          * @since 9
3133          */
3134         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3135             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3136             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3137             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3138         }
3139 
3140         /**
3141          * Produces a method handle giving read access to a static field.
3142          * The type of the method handle will have a return type of the field's
3143          * value type.
3144          * The method handle will take no arguments.
3145          * Access checking is performed immediately on behalf of the lookup class.
3146          * <p>
3147          * If the returned method handle is invoked, the field's class will
3148          * be initialized, if it has not already been initialized.
3149          * @param refc the class or interface from which the method is accessed
3150          * @param name the field's name
3151          * @param type the field's type
3152          * @return a method handle which can load values from the field
3153          * @throws NoSuchFieldException if the field does not exist
3154          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3155          * @throws    SecurityException if a security manager is present and it
3156          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3157          * @throws NullPointerException if any argument is null
3158          */
3159         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3160             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3161             return getDirectField(REF_getStatic, refc, field);
3162         }
3163 
3164         /**
3165          * Produces a method handle giving write access to a static field.
3166          * The type of the method handle will have a void return type.
3167          * The method handle will take a single
3168          * argument, of the field's value type, the value to be stored.
3169          * Access checking is performed immediately on behalf of the lookup class.
3170          * <p>
3171          * If the returned method handle is invoked, the field's class will
3172          * be initialized, if it has not already been initialized.
3173          * @param refc the class or interface from which the method is accessed
3174          * @param name the field's name
3175          * @param type the field's type
3176          * @return a method handle which can store values into the field
3177          * @throws NoSuchFieldException if the field does not exist
3178          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3179          *                                or is {@code final}
3180          * @throws    SecurityException if a security manager is present and it
3181          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3182          * @throws NullPointerException if any argument is null
3183          */
3184         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3185             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3186             return getDirectField(REF_putStatic, refc, field);
3187         }
3188 
3189         /**
3190          * Produces a VarHandle giving access to a static field {@code name} of
3191          * type {@code type} declared in a class of type {@code decl}.
3192          * The VarHandle's variable type is {@code type} and it has no
3193          * coordinate types.
3194          * <p>
3195          * Access checking is performed immediately on behalf of the lookup
3196          * class.
3197          * <p>
3198          * If the returned VarHandle is operated on, the declaring class will be
3199          * initialized, if it has not already been initialized.
3200          * <p>
3201          * Certain access modes of the returned VarHandle are unsupported under
3202          * the following conditions:
3203          * <ul>
3204          * <li>if the field is declared {@code final}, then the write, atomic
3205          *     update, numeric atomic update, and bitwise atomic update access
3206          *     modes are unsupported.
3207          * <li>if the field type is anything other than {@code byte},
3208          *     {@code short}, {@code char}, {@code int}, {@code long},
3209          *     {@code float}, or {@code double}, then numeric atomic update
3210          *     access modes are unsupported.
3211          * <li>if the field type is anything other than {@code boolean},
3212          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3213          *     {@code long} then bitwise atomic update access modes are
3214          *     unsupported.
3215          * </ul>
3216          * <p>
3217          * If the field is declared {@code volatile} then the returned VarHandle
3218          * will override access to the field (effectively ignore the
3219          * {@code volatile} declaration) in accordance to its specified
3220          * access modes.
3221          * <p>
3222          * If the field type is {@code float} or {@code double} then numeric
3223          * and atomic update access modes compare values using their bitwise
3224          * representation (see {@link Float#floatToRawIntBits} and
3225          * {@link Double#doubleToRawLongBits}, respectively).
3226          * @apiNote
3227          * Bitwise comparison of {@code float} values or {@code double} values,
3228          * as performed by the numeric and atomic update access modes, differ
3229          * from the primitive {@code ==} operator and the {@link Float#equals}
3230          * and {@link Double#equals} methods, specifically with respect to
3231          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3232          * Care should be taken when performing a compare and set or a compare
3233          * and exchange operation with such values since the operation may
3234          * unexpectedly fail.
3235          * There are many possible NaN values that are considered to be
3236          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3237          * provided by Java can distinguish between them.  Operation failure can
3238          * occur if the expected or witness value is a NaN value and it is
3239          * transformed (perhaps in a platform specific manner) into another NaN
3240          * value, and thus has a different bitwise representation (see
3241          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3242          * details).
3243          * The values {@code -0.0} and {@code +0.0} have different bitwise
3244          * representations but are considered equal when using the primitive
3245          * {@code ==} operator.  Operation failure can occur if, for example, a
3246          * numeric algorithm computes an expected value to be say {@code -0.0}
3247          * and previously computed the witness value to be say {@code +0.0}.
3248          * @param decl the class that declares the static field
3249          * @param name the field's name
3250          * @param type the field's type, of type {@code T}
3251          * @return a VarHandle giving access to a static field
3252          * @throws NoSuchFieldException if the field does not exist
3253          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3254          * @throws    SecurityException if a security manager is present and it
3255          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3256          * @throws NullPointerException if any argument is null
3257          * @since 9
3258          */
3259         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3260             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3261             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3262             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3263         }
3264 
3265         /**
3266          * Produces an early-bound method handle for a non-static method.
3267          * The receiver must have a supertype {@code defc} in which a method
3268          * of the given name and type is accessible to the lookup class.
3269          * The method and all its argument types must be accessible to the lookup object.
3270          * The type of the method handle will be that of the method,
3271          * without any insertion of an additional receiver parameter.
3272          * The given receiver will be bound into the method handle,
3273          * so that every call to the method handle will invoke the
3274          * requested method on the given receiver.
3275          * <p>
3276          * The returned method handle will have
3277          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3278          * the method's variable arity modifier bit ({@code 0x0080}) is set
3279          * <em>and</em> the trailing array argument is not the only argument.
3280          * (If the trailing array argument is the only argument,
3281          * the given receiver value will be bound to it.)
3282          * <p>
3283          * This is almost equivalent to the following code, with some differences noted below:
3284          * <blockquote><pre>{@code
3285 import static java.lang.invoke.MethodHandles.*;
3286 import static java.lang.invoke.MethodType.*;
3287 ...
3288 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3289 MethodHandle mh1 = mh0.bindTo(receiver);
3290 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3291 return mh1;
3292          * }</pre></blockquote>
3293          * where {@code defc} is either {@code receiver.getClass()} or a super
3294          * type of that class, in which the requested method is accessible
3295          * to the lookup class.
3296          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3297          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3298          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3299          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3300          * @param receiver the object from which the method is accessed
3301          * @param name the name of the method
3302          * @param type the type of the method, with the receiver argument omitted
3303          * @return the desired method handle
3304          * @throws NoSuchMethodException if the method does not exist
3305          * @throws IllegalAccessException if access checking fails
3306          *                                or if the method's variable arity modifier bit
3307          *                                is set and {@code asVarargsCollector} fails
3308          * @throws    SecurityException if a security manager is present and it
3309          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3310          * @throws NullPointerException if any argument is null
3311          * @see MethodHandle#bindTo
3312          * @see #findVirtual
3313          */
3314         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3315             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3316             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3317             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3318             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3319                 throw new IllegalAccessException("The restricted defining class " +
3320                                                  mh.type().leadingReferenceParameter().getName() +
3321                                                  " is not assignable from receiver class " +
3322                                                  receiver.getClass().getName());
3323             }
3324             return mh.bindArgumentL(0, receiver).setVarargs(method);
3325         }
3326 
3327         /**
3328          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3329          * to <i>m</i>, if the lookup class has permission.
3330          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3331          * If <i>m</i> is virtual, overriding is respected on every call.
3332          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3333          * The type of the method handle will be that of the method,
3334          * with the receiver type prepended (but only if it is non-static).
3335          * If the method's {@code accessible} flag is not set,
3336          * access checking is performed immediately on behalf of the lookup class.
3337          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3338          * <p>
3339          * The returned method handle will have
3340          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3341          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3342          * <p>
3343          * If <i>m</i> is static, and
3344          * if the returned method handle is invoked, the method's class will
3345          * be initialized, if it has not already been initialized.
3346          * @param m the reflected method
3347          * @return a method handle which can invoke the reflected method
3348          * @throws IllegalAccessException if access checking fails
3349          *                                or if the method's variable arity modifier bit
3350          *                                is set and {@code asVarargsCollector} fails
3351          * @throws NullPointerException if the argument is null
3352          */
3353         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3354             if (m.getDeclaringClass() == MethodHandle.class) {
3355                 MethodHandle mh = unreflectForMH(m);
3356                 if (mh != null)  return mh;
3357             }
3358             if (m.getDeclaringClass() == VarHandle.class) {
3359                 MethodHandle mh = unreflectForVH(m);
3360                 if (mh != null)  return mh;
3361             }
3362             MemberName method = new MemberName(m);
3363             byte refKind = method.getReferenceKind();
3364             if (refKind == REF_invokeSpecial)
3365                 refKind = REF_invokeVirtual;
3366             assert(method.isMethod());
3367             @SuppressWarnings("deprecation")
3368             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3369             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3370         }
3371         private MethodHandle unreflectForMH(Method m) {
3372             // these names require special lookups because they throw UnsupportedOperationException
3373             if (MemberName.isMethodHandleInvokeName(m.getName()))
3374                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3375             return null;
3376         }
3377         private MethodHandle unreflectForVH(Method m) {
3378             // these names require special lookups because they throw UnsupportedOperationException
3379             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3380                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3381             return null;
3382         }
3383 
3384         /**
3385          * Produces a method handle for a reflected method.
3386          * It will bypass checks for overriding methods on the receiver,
3387          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3388          * instruction from within the explicitly specified {@code specialCaller}.
3389          * The type of the method handle will be that of the method,
3390          * with a suitably restricted receiver type prepended.
3391          * (The receiver type will be {@code specialCaller} or a subtype.)
3392          * If the method's {@code accessible} flag is not set,
3393          * access checking is performed immediately on behalf of the lookup class,
3394          * as if {@code invokespecial} instruction were being linked.
3395          * <p>
3396          * Before method resolution,
3397          * if the explicitly specified caller class is not identical with the
3398          * lookup class, or if this lookup object does not have
3399          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3400          * privileges, the access fails.
3401          * <p>
3402          * The returned method handle will have
3403          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3404          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3405          * @param m the reflected method
3406          * @param specialCaller the class nominally calling the method
3407          * @return a method handle which can invoke the reflected method
3408          * @throws IllegalAccessException if access checking fails,
3409          *                                or if the method is {@code static},
3410          *                                or if the method's variable arity modifier bit
3411          *                                is set and {@code asVarargsCollector} fails
3412          * @throws NullPointerException if any argument is null
3413          */
3414         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3415             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3416             Lookup specialLookup = this.in(specialCaller);
3417             MemberName method = new MemberName(m, true);
3418             assert(method.isMethod());
3419             // ignore m.isAccessible:  this is a new kind of access
3420             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3421         }
3422 
3423         /**
3424          * Produces a method handle for a reflected constructor.
3425          * The type of the method handle will be that of the constructor,
3426          * with the return type changed to the declaring class.
3427          * The method handle will perform a {@code newInstance} operation,
3428          * creating a new instance of the constructor's class on the
3429          * arguments passed to the method handle.
3430          * <p>
3431          * If the constructor's {@code accessible} flag is not set,
3432          * access checking is performed immediately on behalf of the lookup class.
3433          * <p>
3434          * The returned method handle will have
3435          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3436          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3437          * <p>
3438          * If the returned method handle is invoked, the constructor's class will
3439          * be initialized, if it has not already been initialized.
3440          * @param c the reflected constructor
3441          * @return a method handle which can invoke the reflected constructor
3442          * @throws IllegalAccessException if access checking fails
3443          *                                or if the method's variable arity modifier bit
3444          *                                is set and {@code asVarargsCollector} fails
3445          * @throws NullPointerException if the argument is null
3446          */
3447         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3448             MemberName ctor = new MemberName(c);
3449             assert(ctor.isObjectConstructorOrStaticInitMethod());
3450             @SuppressWarnings("deprecation")
3451             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3452             Class<?> defc = c.getDeclaringClass();
3453             if (ctor.isObjectConstructor()) {
3454                 assert(ctor.getReturnType() == void.class);
3455                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3456             } else {
3457                 // static init factory is a static method
3458                 assert(ctor.isMethod() && ctor.getReturnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3459                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3460                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3461             }
3462         }
3463 
3464         /**
3465          * Produces a method handle giving read access to a reflected field.
3466          * The type of the method handle will have a return type of the field's
3467          * value type.
3468          * If the field is {@code static}, the method handle will take no arguments.
3469          * Otherwise, its single argument will be the instance containing
3470          * the field.
3471          * If the {@code Field} object's {@code accessible} flag is not set,
3472          * access checking is performed immediately on behalf of the lookup class.
3473          * <p>
3474          * If the field is static, and
3475          * if the returned method handle is invoked, the field's class will
3476          * be initialized, if it has not already been initialized.
3477          * @param f the reflected field
3478          * @return a method handle which can load values from the reflected field
3479          * @throws IllegalAccessException if access checking fails
3480          * @throws NullPointerException if the argument is null
3481          */
3482         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3483             return unreflectField(f, false);
3484         }
3485 
3486         /**
3487          * Produces a method handle giving write access to a reflected field.
3488          * The type of the method handle will have a void return type.
3489          * If the field is {@code static}, the method handle will take a single
3490          * argument, of the field's value type, the value to be stored.
3491          * Otherwise, the two arguments will be the instance containing
3492          * the field, and the value to be stored.
3493          * If the {@code Field} object's {@code accessible} flag is not set,
3494          * access checking is performed immediately on behalf of the lookup class.
3495          * <p>
3496          * If the field is {@code final}, write access will not be
3497          * allowed and access checking will fail, except under certain
3498          * narrow circumstances documented for {@link Field#set Field.set}.
3499          * A method handle is returned only if a corresponding call to
3500          * the {@code Field} object's {@code set} method could return
3501          * normally.  In particular, fields which are both {@code static}
3502          * and {@code final} may never be set.
3503          * <p>
3504          * If the field is {@code static}, and
3505          * if the returned method handle is invoked, the field's class will
3506          * be initialized, if it has not already been initialized.
3507          * @param f the reflected field
3508          * @return a method handle which can store values into the reflected field
3509          * @throws IllegalAccessException if access checking fails,
3510          *         or if the field is {@code final} and write access
3511          *         is not enabled on the {@code Field} object
3512          * @throws NullPointerException if the argument is null
3513          */
3514         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3515             return unreflectField(f, true);
3516         }
3517 
3518         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3519             MemberName field = new MemberName(f, isSetter);
3520             if (isSetter && field.isFinal()) {
3521                 if (field.isTrustedFinalField()) {
3522                     String msg = field.isStatic() ? "static final field has no write access"
3523                                                   : "final field has no write access";
3524                     throw field.makeAccessException(msg, this);
3525                 }
3526             }
3527             assert(isSetter
3528                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3529                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3530             @SuppressWarnings("deprecation")
3531             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3532             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3533         }
3534 
3535         /**
3536          * Produces a VarHandle giving access to a reflected field {@code f}
3537          * of type {@code T} declared in a class of type {@code R}.
3538          * The VarHandle's variable type is {@code T}.
3539          * If the field is non-static the VarHandle has one coordinate type,
3540          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3541          * coordinate types.
3542          * <p>
3543          * Access checking is performed immediately on behalf of the lookup
3544          * class, regardless of the value of the field's {@code accessible}
3545          * flag.
3546          * <p>
3547          * If the field is static, and if the returned VarHandle is operated
3548          * on, the field's declaring class will be initialized, if it has not
3549          * already been initialized.
3550          * <p>
3551          * Certain access modes of the returned VarHandle are unsupported under
3552          * the following conditions:
3553          * <ul>
3554          * <li>if the field is declared {@code final}, then the write, atomic
3555          *     update, numeric atomic update, and bitwise atomic update access
3556          *     modes are unsupported.
3557          * <li>if the field type is anything other than {@code byte},
3558          *     {@code short}, {@code char}, {@code int}, {@code long},
3559          *     {@code float}, or {@code double} then numeric atomic update
3560          *     access modes are unsupported.
3561          * <li>if the field type is anything other than {@code boolean},
3562          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3563          *     {@code long} then bitwise atomic update access modes are
3564          *     unsupported.
3565          * </ul>
3566          * <p>
3567          * If the field is declared {@code volatile} then the returned VarHandle
3568          * will override access to the field (effectively ignore the
3569          * {@code volatile} declaration) in accordance to its specified
3570          * access modes.
3571          * <p>
3572          * If the field type is {@code float} or {@code double} then numeric
3573          * and atomic update access modes compare values using their bitwise
3574          * representation (see {@link Float#floatToRawIntBits} and
3575          * {@link Double#doubleToRawLongBits}, respectively).
3576          * @apiNote
3577          * Bitwise comparison of {@code float} values or {@code double} values,
3578          * as performed by the numeric and atomic update access modes, differ
3579          * from the primitive {@code ==} operator and the {@link Float#equals}
3580          * and {@link Double#equals} methods, specifically with respect to
3581          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3582          * Care should be taken when performing a compare and set or a compare
3583          * and exchange operation with such values since the operation may
3584          * unexpectedly fail.
3585          * There are many possible NaN values that are considered to be
3586          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3587          * provided by Java can distinguish between them.  Operation failure can
3588          * occur if the expected or witness value is a NaN value and it is
3589          * transformed (perhaps in a platform specific manner) into another NaN
3590          * value, and thus has a different bitwise representation (see
3591          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3592          * details).
3593          * The values {@code -0.0} and {@code +0.0} have different bitwise
3594          * representations but are considered equal when using the primitive
3595          * {@code ==} operator.  Operation failure can occur if, for example, a
3596          * numeric algorithm computes an expected value to be say {@code -0.0}
3597          * and previously computed the witness value to be say {@code +0.0}.
3598          * @param f the reflected field, with a field of type {@code T}, and
3599          * a declaring class of type {@code R}
3600          * @return a VarHandle giving access to non-static fields or a static
3601          * field
3602          * @throws IllegalAccessException if access checking fails
3603          * @throws NullPointerException if the argument is null
3604          * @since 9
3605          */
3606         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3607             MemberName getField = new MemberName(f, false);
3608             MemberName putField = new MemberName(f, true);
3609             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3610                                                       f.getDeclaringClass(), getField, putField);
3611         }
3612 
3613         /**
3614          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3615          * created by this lookup object or a similar one.
3616          * Security and access checks are performed to ensure that this lookup object
3617          * is capable of reproducing the target method handle.
3618          * This means that the cracking may fail if target is a direct method handle
3619          * but was created by an unrelated lookup object.
3620          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3621          * and was created by a lookup object for a different class.
3622          * @param target a direct method handle to crack into symbolic reference components
3623          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3624          * @throws    SecurityException if a security manager is present and it
3625          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3626          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3627          * @throws    NullPointerException if the target is {@code null}
3628          * @see MethodHandleInfo
3629          * @since 1.8
3630          */
3631         public MethodHandleInfo revealDirect(MethodHandle target) {
3632             if (!target.isCrackable()) {
3633                 throw newIllegalArgumentException("not a direct method handle");
3634             }
3635             MemberName member = target.internalMemberName();
3636             Class<?> defc = member.getDeclaringClass();
3637             byte refKind = member.getReferenceKind();
3638             assert(MethodHandleNatives.refKindIsValid(refKind));
3639             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3640                 // Devirtualized method invocation is usually formally virtual.
3641                 // To avoid creating extra MemberName objects for this common case,
3642                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3643                 refKind = REF_invokeVirtual;
3644             if (refKind == REF_invokeVirtual && defc.isInterface())
3645                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3646                 refKind = REF_invokeInterface;
3647             // Check SM permissions and member access before cracking.
3648             try {
3649                 checkAccess(refKind, defc, member);
3650                 checkSecurityManager(defc, member);
3651             } catch (IllegalAccessException ex) {
3652                 throw new IllegalArgumentException(ex);
3653             }
3654             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3655                 Class<?> callerClass = target.internalCallerClass();
3656                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3657                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3658             }
3659             // Produce the handle to the results.
3660             return new InfoFromMemberName(this, member, refKind);
3661         }
3662 
3663         /// Helper methods, all package-private.
3664 
3665         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3666             checkSymbolicClass(refc);  // do this before attempting to resolve
3667             Objects.requireNonNull(name);
3668             Objects.requireNonNull(type);
3669             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3670                                             NoSuchFieldException.class);
3671         }
3672 
3673         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3674             checkSymbolicClass(refc);  // do this before attempting to resolve
3675             Objects.requireNonNull(type);
3676             checkMethodName(refKind, name);  // implicit null-check of name
3677             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3678                                             NoSuchMethodException.class);
3679         }
3680 
3681         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3682             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3683             Objects.requireNonNull(member.getName());
3684             Objects.requireNonNull(member.getType());
3685             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3686                                             ReflectiveOperationException.class);
3687         }
3688 
3689         MemberName resolveOrNull(byte refKind, MemberName member) {
3690             // do this before attempting to resolve
3691             if (!isClassAccessible(member.getDeclaringClass())) {
3692                 return null;
3693             }
3694             Objects.requireNonNull(member.getName());
3695             Objects.requireNonNull(member.getType());
3696             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3697         }
3698 
3699         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3700             // do this before attempting to resolve
3701             if (!isClassAccessible(refc)) {
3702                 return null;
3703             }
3704             Objects.requireNonNull(type);
3705             // implicit null-check of name
3706             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3707                 return null;
3708             }
3709             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3710         }
3711 
3712         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3713             if (!isClassAccessible(refc)) {
3714                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3715             }
3716         }
3717 
3718         boolean isClassAccessible(Class<?> refc) {
3719             Objects.requireNonNull(refc);
3720             Class<?> caller = lookupClassOrNull();
3721             Class<?> type = refc;
3722             while (type.isArray()) {
3723                 type = type.getComponentType();
3724             }
3725             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3726         }
3727 
3728         /** Check name for an illegal leading "&lt;" character. */
3729         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3730             // "<init>" can only be invoked via invokespecial or it's a static init factory
3731             if (name.startsWith("<") && refKind != REF_newInvokeSpecial &&
3732                     !(refKind == REF_invokeStatic && name.equals("<init>"))) {
3733                     throw new NoSuchMethodException("illegal method name: " + name);
3734             }
3735         }
3736 
3737         /**
3738          * Find my trustable caller class if m is a caller sensitive method.
3739          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3740          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3741          */
3742         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3743             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3744                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3745                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3746             }
3747             return this;
3748         }
3749 
3750         /**
3751          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3752          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3753          *
3754          * @deprecated This method was originally designed to test {@code PRIVATE} access
3755          * that implies full privilege access but {@code MODULE} access has since become
3756          * independent of {@code PRIVATE} access.  It is recommended to call
3757          * {@link #hasFullPrivilegeAccess()} instead.
3758          * @since 9
3759          */
3760         @Deprecated(since="14")
3761         public boolean hasPrivateAccess() {
3762             return hasFullPrivilegeAccess();
3763         }
3764 
3765         /**
3766          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3767          * i.e. {@code PRIVATE} and {@code MODULE} access.
3768          * A {@code Lookup} object must have full privilege access in order to
3769          * access all members that are allowed to the
3770          * {@linkplain #lookupClass() lookup class}.
3771          *
3772          * @return {@code true} if this lookup has full privilege access.
3773          * @since 14
3774          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3775          */
3776         public boolean hasFullPrivilegeAccess() {
3777             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3778         }
3779 
3780         /**
3781          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3782          * for ensureInitialzed, findClass or accessClass.
3783          */
3784         void checkSecurityManager(Class<?> refc) {
3785             if (allowedModes == TRUSTED)  return;
3786 
3787             @SuppressWarnings("removal")
3788             SecurityManager smgr = System.getSecurityManager();
3789             if (smgr == null)  return;
3790 
3791             // Step 1:
3792             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3793             if (!fullPrivilegeLookup ||
3794                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3795                 ReflectUtil.checkPackageAccess(refc);
3796             }
3797 
3798             // Step 2b:
3799             if (!fullPrivilegeLookup) {
3800                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3801             }
3802         }
3803 
3804         /**
3805          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3806          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3807          * If this lookup object has full privilege access except original access,
3808          * then the caller class is the lookupClass.
3809          *
3810          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3811          * from the same module skips the security permission check.
3812          */
3813         void checkSecurityManager(Class<?> refc, MemberName m) {
3814             Objects.requireNonNull(refc);
3815             Objects.requireNonNull(m);
3816 
3817             if (allowedModes == TRUSTED)  return;
3818 
3819             @SuppressWarnings("removal")
3820             SecurityManager smgr = System.getSecurityManager();
3821             if (smgr == null)  return;
3822 
3823             // Step 1:
3824             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3825             if (!fullPrivilegeLookup ||
3826                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3827                 ReflectUtil.checkPackageAccess(refc);
3828             }
3829 
3830             // Step 2a:
3831             if (m.isPublic()) return;
3832             if (!fullPrivilegeLookup) {
3833                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3834             }
3835 
3836             // Step 3:
3837             Class<?> defc = m.getDeclaringClass();
3838             if (!fullPrivilegeLookup && defc.asPrimaryType() != refc.asPrimaryType()) {
3839                 ReflectUtil.checkPackageAccess(defc);
3840             }
3841         }
3842 
3843         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3844             boolean wantStatic = (refKind == REF_invokeStatic);
3845             String message;
3846             if (m.isObjectConstructor())
3847                 message = "expected a method, not a constructor";
3848             else if (!m.isMethod())
3849                 message = "expected a method";
3850             else if (wantStatic != m.isStatic())
3851                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3852             else
3853                 { checkAccess(refKind, refc, m); return; }
3854             throw m.makeAccessException(message, this);
3855         }
3856 
3857         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3858             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3859             String message;
3860             if (wantStatic != m.isStatic())
3861                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3862             else
3863                 { checkAccess(refKind, refc, m); return; }
3864             throw m.makeAccessException(message, this);
3865         }
3866 
3867         /** Check public/protected/private bits on the symbolic reference class and its member. */
3868         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3869             assert(m.referenceKindIsConsistentWith(refKind) &&
3870                    MethodHandleNatives.refKindIsValid(refKind) &&
3871                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3872             int allowedModes = this.allowedModes;
3873             if (allowedModes == TRUSTED)  return;
3874             int mods = m.getModifiers();
3875             if (Modifier.isProtected(mods) &&
3876                     refKind == REF_invokeVirtual &&
3877                     m.getDeclaringClass() == Object.class &&
3878                     m.getName().equals("clone") &&
3879                     refc.isArray()) {
3880                 // The JVM does this hack also.
3881                 // (See ClassVerifier::verify_invoke_instructions
3882                 // and LinkResolver::check_method_accessability.)
3883                 // Because the JVM does not allow separate methods on array types,
3884                 // there is no separate method for int[].clone.
3885                 // All arrays simply inherit Object.clone.
3886                 // But for access checking logic, we make Object.clone
3887                 // (normally protected) appear to be public.
3888                 // Later on, when the DirectMethodHandle is created,
3889                 // its leading argument will be restricted to the
3890                 // requested array type.
3891                 // N.B. The return type is not adjusted, because
3892                 // that is *not* the bytecode behavior.
3893                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3894             }
3895             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3896                 // cannot "new" a protected ctor in a different package
3897                 mods ^= Modifier.PROTECTED;
3898             }
3899             if (Modifier.isFinal(mods) &&
3900                     MethodHandleNatives.refKindIsSetter(refKind))
3901                 throw m.makeAccessException("unexpected set of a final field", this);
3902             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3903             if ((requestedModes & allowedModes) != 0) {
3904                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3905                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3906                     return;
3907             } else {
3908                 // Protected members can also be checked as if they were package-private.
3909                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3910                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3911                     return;
3912             }
3913             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3914         }
3915 
3916         String accessFailedMessage(Class<?> refc, MemberName m) {
3917             Class<?> defc = m.getDeclaringClass();
3918             int mods = m.getModifiers();
3919             // check the class first:
3920             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3921                                (defc.asPrimaryType() == refc.asPrimaryType() ||
3922                                 Modifier.isPublic(refc.getModifiers())));
3923             if (!classOK && (allowedModes & PACKAGE) != 0) {
3924                 // ignore previous lookup class to check if default package access
3925                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3926                            (defc.asPrimaryType() == refc.asPrimaryType() ||
3927                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3928             }
3929             if (!classOK)
3930                 return "class is not public";
3931             if (Modifier.isPublic(mods))
3932                 return "access to public member failed";  // (how?, module not readable?)
3933             if (Modifier.isPrivate(mods))
3934                 return "member is private";
3935             if (Modifier.isProtected(mods))
3936                 return "member is protected";
3937             return "member is private to package";
3938         }
3939 
3940         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3941             int allowedModes = this.allowedModes;
3942             if (allowedModes == TRUSTED)  return;
3943             if ((lookupModes() & PRIVATE) == 0
3944                 || (specialCaller != lookupClass()
3945                        // ensure non-abstract methods in superinterfaces can be special-invoked
3946                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3947                 throw new MemberName(specialCaller).
3948                     makeAccessException("no private access for invokespecial", this);
3949         }
3950 
3951         private boolean restrictProtectedReceiver(MemberName method) {
3952             // The accessing class only has the right to use a protected member
3953             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3954             if (!method.isProtected() || method.isStatic()
3955                 || allowedModes == TRUSTED
3956                 || method.getDeclaringClass() == lookupClass()
3957                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3958                 return false;
3959             return true;
3960         }
3961         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3962             assert(!method.isStatic());
3963             // receiver type of mh is too wide; narrow to caller
3964             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3965                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3966             }
3967             MethodType rawType = mh.type();
3968             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3969             MethodType narrowType = rawType.changeParameterType(0, caller);
3970             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3971             assert(mh.viewAsTypeChecks(narrowType, true));
3972             return mh.copyWith(narrowType, mh.form);
3973         }
3974 
3975         /** Check access and get the requested method. */
3976         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3977             final boolean doRestrict    = true;
3978             final boolean checkSecurity = true;
3979             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3980         }
3981         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3982         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3983             final boolean doRestrict    = false;
3984             final boolean checkSecurity = true;
3985             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3986         }
3987         /** Check access and get the requested method, eliding security manager checks. */
3988         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3989             final boolean doRestrict    = true;
3990             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3991             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3992         }
3993         /** Common code for all methods; do not call directly except from immediately above. */
3994         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3995                                                    boolean checkSecurity,
3996                                                    boolean doRestrict,
3997                                                    Lookup boundCaller) throws IllegalAccessException {
3998             checkMethod(refKind, refc, method);
3999             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4000             if (checkSecurity)
4001                 checkSecurityManager(refc, method);
4002             assert(!method.isMethodHandleInvoke());
4003             if (refKind == REF_invokeSpecial &&
4004                 refc != lookupClass() &&
4005                 !refc.isInterface() &&
4006                 refc != lookupClass().getSuperclass() &&
4007                 refc.isAssignableFrom(lookupClass())) {
4008                 assert(!method.getName().equals("<init>"));  // not this code path
4009 
4010                 // Per JVMS 6.5, desc. of invokespecial instruction:
4011                 // If the method is in a superclass of the LC,
4012                 // and if our original search was above LC.super,
4013                 // repeat the search (symbolic lookup) from LC.super
4014                 // and continue with the direct superclass of that class,
4015                 // and so forth, until a match is found or no further superclasses exist.
4016                 // FIXME: MemberName.resolve should handle this instead.
4017                 Class<?> refcAsSuper = lookupClass();
4018                 MemberName m2;
4019                 do {
4020                     refcAsSuper = refcAsSuper.getSuperclass();
4021                     m2 = new MemberName(refcAsSuper,
4022                                         method.getName(),
4023                                         method.getMethodType(),
4024                                         REF_invokeSpecial);
4025                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4026                 } while (m2 == null &&         // no method is found yet
4027                          refc != refcAsSuper); // search up to refc
4028                 if (m2 == null)  throw new InternalError(method.toString());
4029                 method = m2;
4030                 refc = refcAsSuper;
4031                 // redo basic checks
4032                 checkMethod(refKind, refc, method);
4033             }
4034             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4035             MethodHandle mh = dmh;
4036             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4037             if ((doRestrict && refKind == REF_invokeSpecial) ||
4038                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4039                 mh = restrictReceiver(method, dmh, lookupClass());
4040             }
4041             mh = maybeBindCaller(method, mh, boundCaller);
4042             mh = mh.setVarargs(method);
4043             return mh;
4044         }
4045         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4046                                              throws IllegalAccessException {
4047             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4048                 return mh;
4049 
4050             // boundCaller must have full privilege access.
4051             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4052             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4053                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4054 
4055             assert boundCaller.hasFullPrivilegeAccess();
4056 
4057             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4058             // Note: caller will apply varargs after this step happens.
4059             return cbmh;
4060         }
4061 
4062         /** Check access and get the requested field. */
4063         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4064             final boolean checkSecurity = true;
4065             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4066         }
4067         /** Check access and get the requested field, eliding security manager checks. */
4068         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4069             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4070             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4071         }
4072         /** Common code for all fields; do not call directly except from immediately above. */
4073         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4074                                                   boolean checkSecurity) throws IllegalAccessException {
4075             checkField(refKind, refc, field);
4076             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4077             if (checkSecurity)
4078                 checkSecurityManager(refc, field);
4079             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4080             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4081                                     restrictProtectedReceiver(field));
4082             if (doRestrict)
4083                 return restrictReceiver(field, dmh, lookupClass());
4084             return dmh;
4085         }
4086         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4087                                             Class<?> refc, MemberName getField, MemberName putField)
4088                 throws IllegalAccessException {
4089             final boolean checkSecurity = true;
4090             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4091         }
4092         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4093                                                              Class<?> refc, MemberName getField, MemberName putField)
4094                 throws IllegalAccessException {
4095             final boolean checkSecurity = false;
4096             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4097         }
4098         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4099                                                   Class<?> refc, MemberName getField, MemberName putField,
4100                                                   boolean checkSecurity) throws IllegalAccessException {
4101             assert getField.isStatic() == putField.isStatic();
4102             assert getField.isGetter() && putField.isSetter();
4103             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4104             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4105 
4106             checkField(getRefKind, refc, getField);
4107             if (checkSecurity)
4108                 checkSecurityManager(refc, getField);
4109 
4110             if (!putField.isFinal()) {
4111                 // A VarHandle does not support updates to final fields, any
4112                 // such VarHandle to a final field will be read-only and
4113                 // therefore the following write-based accessibility checks are
4114                 // only required for non-final fields
4115                 checkField(putRefKind, refc, putField);
4116                 if (checkSecurity)
4117                     checkSecurityManager(refc, putField);
4118             }
4119 
4120             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4121                                   restrictProtectedReceiver(getField));
4122             if (doRestrict) {
4123                 assert !getField.isStatic();
4124                 // receiver type of VarHandle is too wide; narrow to caller
4125                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4126                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4127                 }
4128                 refc = lookupClass();
4129             }
4130             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4131                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4132         }
4133         /** Check access and get the requested constructor. */
4134         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4135             final boolean checkSecurity = true;
4136             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4137         }
4138         /** Check access and get the requested constructor, eliding security manager checks. */
4139         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4140             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4141             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4142         }
4143         /** Common code for all constructors; do not call directly except from immediately above. */
4144         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4145                                                   boolean checkSecurity) throws IllegalAccessException {
4146             assert(ctor.isObjectConstructor());
4147             checkAccess(REF_newInvokeSpecial, refc, ctor);
4148             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4149             if (checkSecurity)
4150                 checkSecurityManager(refc, ctor);
4151             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4152             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4153         }
4154 
4155         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4156          */
4157         /*non-public*/
4158         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4159                 throws ReflectiveOperationException {
4160             if (!(type instanceof Class || type instanceof MethodType))
4161                 throw new InternalError("unresolved MemberName");
4162             MemberName member = new MemberName(refKind, defc, name, type);
4163             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4164             if (mh != null) {
4165                 checkSymbolicClass(defc);
4166                 return mh;
4167             }
4168             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4169                 // Treat MethodHandle.invoke and invokeExact specially.
4170                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4171                 if (mh != null) {
4172                     return mh;
4173                 }
4174             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4175                 // Treat signature-polymorphic methods on VarHandle specially.
4176                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4177                 if (mh != null) {
4178                     return mh;
4179                 }
4180             }
4181             MemberName resolved = resolveOrFail(refKind, member);
4182             mh = getDirectMethodForConstant(refKind, defc, resolved);
4183             if (mh instanceof DirectMethodHandle
4184                     && canBeCached(refKind, defc, resolved)) {
4185                 MemberName key = mh.internalMemberName();
4186                 if (key != null) {
4187                     key = key.asNormalOriginal();
4188                 }
4189                 if (member.equals(key)) {  // better safe than sorry
4190                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4191                 }
4192             }
4193             return mh;
4194         }
4195         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4196             if (refKind == REF_invokeSpecial) {
4197                 return false;
4198             }
4199             if (!Modifier.isPublic(defc.getModifiers()) ||
4200                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4201                     !member.isPublic() ||
4202                     member.isCallerSensitive()) {
4203                 return false;
4204             }
4205             ClassLoader loader = defc.getClassLoader();
4206             if (loader != null) {
4207                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4208                 boolean found = false;
4209                 while (sysl != null) {
4210                     if (loader == sysl) { found = true; break; }
4211                     sysl = sysl.getParent();
4212                 }
4213                 if (!found) {
4214                     return false;
4215                 }
4216             }
4217             try {
4218                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4219                     new MemberName(refKind, defc, member.getName(), member.getType()));
4220                 if (resolved2 == null) {
4221                     return false;
4222                 }
4223                 checkSecurityManager(defc, resolved2);
4224             } catch (SecurityException ex) {
4225                 return false;
4226             }
4227             return true;
4228         }
4229         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4230                 throws ReflectiveOperationException {
4231             if (MethodHandleNatives.refKindIsField(refKind)) {
4232                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4233             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4234                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4235             } else if (refKind == REF_newInvokeSpecial) {
4236                 return getDirectConstructorNoSecurityManager(defc, member);
4237             }
4238             // oops
4239             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4240         }
4241 
4242         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4243     }
4244 
4245     /**
4246      * Produces a method handle constructing arrays of a desired type,
4247      * as if by the {@code anewarray} bytecode.
4248      * The return type of the method handle will be the array type.
4249      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4250      *
4251      * <p> If the returned method handle is invoked with a negative
4252      * array size, a {@code NegativeArraySizeException} will be thrown.
4253      *
4254      * @param arrayClass an array type
4255      * @return a method handle which can create arrays of the given type
4256      * @throws NullPointerException if the argument is {@code null}
4257      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4258      * @see java.lang.reflect.Array#newInstance(Class, int)
4259      * @jvms 6.5 {@code anewarray} Instruction
4260      * @since 9
4261      */
4262     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4263         if (!arrayClass.isArray()) {
4264             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4265         }
4266         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4267                 bindTo(arrayClass.getComponentType());
4268         return ani.asType(ani.type().changeReturnType(arrayClass));
4269     }
4270 
4271     /**
4272      * Produces a method handle returning the length of an array,
4273      * as if by the {@code arraylength} bytecode.
4274      * The type of the method handle will have {@code int} as return type,
4275      * and its sole argument will be the array type.
4276      *
4277      * <p> If the returned method handle is invoked with a {@code null}
4278      * array reference, a {@code NullPointerException} will be thrown.
4279      *
4280      * @param arrayClass an array type
4281      * @return a method handle which can retrieve the length of an array of the given array type
4282      * @throws NullPointerException if the argument is {@code null}
4283      * @throws IllegalArgumentException if arrayClass is not an array type
4284      * @jvms 6.5 {@code arraylength} Instruction
4285      * @since 9
4286      */
4287     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4288         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4289     }
4290 
4291     /**
4292      * Produces a method handle giving read access to elements of an array,
4293      * as if by the {@code aaload} bytecode.
4294      * The type of the method handle will have a return type of the array's
4295      * element type.  Its first argument will be the array type,
4296      * and the second will be {@code int}.
4297      *
4298      * <p> When the returned method handle is invoked,
4299      * the array reference and array index are checked.
4300      * A {@code NullPointerException} will be thrown if the array reference
4301      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4302      * thrown if the index is negative or if it is greater than or equal to
4303      * the length of the array.
4304      *
4305      * @param arrayClass an array type
4306      * @return a method handle which can load values from the given array type
4307      * @throws NullPointerException if the argument is null
4308      * @throws  IllegalArgumentException if arrayClass is not an array type
4309      * @jvms 6.5 {@code aaload} Instruction
4310      */
4311     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4312         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4313     }
4314 
4315     /**
4316      * Produces a method handle giving write access to elements of an array,
4317      * as if by the {@code astore} bytecode.
4318      * The type of the method handle will have a void return type.
4319      * Its last argument will be the array's element type.
4320      * The first and second arguments will be the array type and int.
4321      *
4322      * <p> When the returned method handle is invoked,
4323      * the array reference and array index are checked.
4324      * A {@code NullPointerException} will be thrown if the array reference
4325      * is {@code null} or if the array's element type is a {@link Class#isValueType()
4326      * a primitive value type} and attempts to set {@code null} in the
4327      * array element.  An {@code ArrayIndexOutOfBoundsException} will be
4328      * thrown if the index is negative or if it is greater than or equal to
4329      * the length of the array.
4330      *
4331      * @param arrayClass the class of an array
4332      * @return a method handle which can store values into the array type
4333      * @throws NullPointerException if the argument is null
4334      * @throws IllegalArgumentException if arrayClass is not an array type
4335      * @jvms 6.5 {@code aastore} Instruction
4336      */
4337     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4338         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4339     }
4340 
4341     /**
4342      * Produces a VarHandle giving access to elements of an array of type
4343      * {@code arrayClass}.  The VarHandle's variable type is the component type
4344      * of {@code arrayClass} and the list of coordinate types is
4345      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4346      * corresponds to an argument that is an index into an array.
4347      * <p>
4348      * Certain access modes of the returned VarHandle are unsupported under
4349      * the following conditions:
4350      * <ul>
4351      * <li>if the component type is anything other than {@code byte},
4352      *     {@code short}, {@code char}, {@code int}, {@code long},
4353      *     {@code float}, or {@code double} then numeric atomic update access
4354      *     modes are unsupported.
4355      * <li>if the component type is anything other than {@code boolean},
4356      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4357      *     {@code long} then bitwise atomic update access modes are
4358      *     unsupported.
4359      * </ul>
4360      * <p>
4361      * If the component type is {@code float} or {@code double} then numeric
4362      * and atomic update access modes compare values using their bitwise
4363      * representation (see {@link Float#floatToRawIntBits} and
4364      * {@link Double#doubleToRawLongBits}, respectively).
4365      *
4366      * <p> When the returned {@code VarHandle} is invoked,
4367      * the array reference and array index are checked.
4368      * A {@code NullPointerException} will be thrown if the array reference
4369      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4370      * thrown if the index is negative or if it is greater than or equal to
4371      * the length of the array.
4372      *
4373      * @apiNote
4374      * Bitwise comparison of {@code float} values or {@code double} values,
4375      * as performed by the numeric and atomic update access modes, differ
4376      * from the primitive {@code ==} operator and the {@link Float#equals}
4377      * and {@link Double#equals} methods, specifically with respect to
4378      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4379      * Care should be taken when performing a compare and set or a compare
4380      * and exchange operation with such values since the operation may
4381      * unexpectedly fail.
4382      * There are many possible NaN values that are considered to be
4383      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4384      * provided by Java can distinguish between them.  Operation failure can
4385      * occur if the expected or witness value is a NaN value and it is
4386      * transformed (perhaps in a platform specific manner) into another NaN
4387      * value, and thus has a different bitwise representation (see
4388      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4389      * details).
4390      * The values {@code -0.0} and {@code +0.0} have different bitwise
4391      * representations but are considered equal when using the primitive
4392      * {@code ==} operator.  Operation failure can occur if, for example, a
4393      * numeric algorithm computes an expected value to be say {@code -0.0}
4394      * and previously computed the witness value to be say {@code +0.0}.
4395      * @param arrayClass the class of an array, of type {@code T[]}
4396      * @return a VarHandle giving access to elements of an array
4397      * @throws NullPointerException if the arrayClass is null
4398      * @throws IllegalArgumentException if arrayClass is not an array type
4399      * @since 9
4400      */
4401     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4402         return VarHandles.makeArrayElementHandle(arrayClass);
4403     }
4404 
4405     /**
4406      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4407      * viewed as if it were a different primitive array type, such as
4408      * {@code int[]} or {@code long[]}.
4409      * The VarHandle's variable type is the component type of
4410      * {@code viewArrayClass} and the list of coordinate types is
4411      * {@code (byte[], int)}, where the {@code int} coordinate type
4412      * corresponds to an argument that is an index into a {@code byte[]} array.
4413      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4414      * array, composing bytes to or from a value of the component type of
4415      * {@code viewArrayClass} according to the given endianness.
4416      * <p>
4417      * The supported component types (variables types) are {@code short},
4418      * {@code char}, {@code int}, {@code long}, {@code float} and
4419      * {@code double}.
4420      * <p>
4421      * Access of bytes at a given index will result in an
4422      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4423      * or greater than the {@code byte[]} array length minus the size (in bytes)
4424      * of {@code T}.
4425      * <p>
4426      * Access of bytes at an index may be aligned or misaligned for {@code T},
4427      * with respect to the underlying memory address, {@code A} say, associated
4428      * with the array and index.
4429      * If access is misaligned then access for anything other than the
4430      * {@code get} and {@code set} access modes will result in an
4431      * {@code IllegalStateException}.  In such cases atomic access is only
4432      * guaranteed with respect to the largest power of two that divides the GCD
4433      * of {@code A} and the size (in bytes) of {@code T}.
4434      * If access is aligned then following access modes are supported and are
4435      * guaranteed to support atomic access:
4436      * <ul>
4437      * <li>read write access modes for all {@code T}, with the exception of
4438      *     access modes {@code get} and {@code set} for {@code long} and
4439      *     {@code double} on 32-bit platforms.
4440      * <li>atomic update access modes for {@code int}, {@code long},
4441      *     {@code float} or {@code double}.
4442      *     (Future major platform releases of the JDK may support additional
4443      *     types for certain currently unsupported access modes.)
4444      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4445      *     (Future major platform releases of the JDK may support additional
4446      *     numeric types for certain currently unsupported access modes.)
4447      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4448      *     (Future major platform releases of the JDK may support additional
4449      *     numeric types for certain currently unsupported access modes.)
4450      * </ul>
4451      * <p>
4452      * Misaligned access, and therefore atomicity guarantees, may be determined
4453      * for {@code byte[]} arrays without operating on a specific array.  Given
4454      * an {@code index}, {@code T} and its corresponding boxed type,
4455      * {@code T_BOX}, misalignment may be determined as follows:
4456      * <pre>{@code
4457      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4458      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4459      *     alignmentOffset(0, sizeOfT);
4460      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4461      * boolean isMisaligned = misalignedAtIndex != 0;
4462      * }</pre>
4463      * <p>
4464      * If the variable type is {@code float} or {@code double} then atomic
4465      * update access modes compare values using their bitwise representation
4466      * (see {@link Float#floatToRawIntBits} and
4467      * {@link Double#doubleToRawLongBits}, respectively).
4468      * @param viewArrayClass the view array class, with a component type of
4469      * type {@code T}
4470      * @param byteOrder the endianness of the view array elements, as
4471      * stored in the underlying {@code byte} array
4472      * @return a VarHandle giving access to elements of a {@code byte[]} array
4473      * viewed as if elements corresponding to the components type of the view
4474      * array class
4475      * @throws NullPointerException if viewArrayClass or byteOrder is null
4476      * @throws IllegalArgumentException if viewArrayClass is not an array type
4477      * @throws UnsupportedOperationException if the component type of
4478      * viewArrayClass is not supported as a variable type
4479      * @since 9
4480      */
4481     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4482                                      ByteOrder byteOrder) throws IllegalArgumentException {
4483         Objects.requireNonNull(byteOrder);
4484         return VarHandles.byteArrayViewHandle(viewArrayClass,
4485                                               byteOrder == ByteOrder.BIG_ENDIAN);
4486     }
4487 
4488     /**
4489      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4490      * viewed as if it were an array of elements of a different primitive
4491      * component type to that of {@code byte}, such as {@code int[]} or
4492      * {@code long[]}.
4493      * The VarHandle's variable type is the component type of
4494      * {@code viewArrayClass} and the list of coordinate types is
4495      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4496      * corresponds to an argument that is an index into a {@code byte[]} array.
4497      * The returned VarHandle accesses bytes at an index in a
4498      * {@code ByteBuffer}, composing bytes to or from a value of the component
4499      * type of {@code viewArrayClass} according to the given endianness.
4500      * <p>
4501      * The supported component types (variables types) are {@code short},
4502      * {@code char}, {@code int}, {@code long}, {@code float} and
4503      * {@code double}.
4504      * <p>
4505      * Access will result in a {@code ReadOnlyBufferException} for anything
4506      * other than the read access modes if the {@code ByteBuffer} is read-only.
4507      * <p>
4508      * Access of bytes at a given index will result in an
4509      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4510      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4511      * {@code T}.
4512      * <p>
4513      * Access of bytes at an index may be aligned or misaligned for {@code T},
4514      * with respect to the underlying memory address, {@code A} say, associated
4515      * with the {@code ByteBuffer} and index.
4516      * If access is misaligned then access for anything other than the
4517      * {@code get} and {@code set} access modes will result in an
4518      * {@code IllegalStateException}.  In such cases atomic access is only
4519      * guaranteed with respect to the largest power of two that divides the GCD
4520      * of {@code A} and the size (in bytes) of {@code T}.
4521      * If access is aligned then following access modes are supported and are
4522      * guaranteed to support atomic access:
4523      * <ul>
4524      * <li>read write access modes for all {@code T}, with the exception of
4525      *     access modes {@code get} and {@code set} for {@code long} and
4526      *     {@code double} on 32-bit platforms.
4527      * <li>atomic update access modes for {@code int}, {@code long},
4528      *     {@code float} or {@code double}.
4529      *     (Future major platform releases of the JDK may support additional
4530      *     types for certain currently unsupported access modes.)
4531      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4532      *     (Future major platform releases of the JDK may support additional
4533      *     numeric types for certain currently unsupported access modes.)
4534      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4535      *     (Future major platform releases of the JDK may support additional
4536      *     numeric types for certain currently unsupported access modes.)
4537      * </ul>
4538      * <p>
4539      * Misaligned access, and therefore atomicity guarantees, may be determined
4540      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4541      * {@code index}, {@code T} and its corresponding boxed type,
4542      * {@code T_BOX}, as follows:
4543      * <pre>{@code
4544      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4545      * ByteBuffer bb = ...
4546      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4547      * boolean isMisaligned = misalignedAtIndex != 0;
4548      * }</pre>
4549      * <p>
4550      * If the variable type is {@code float} or {@code double} then atomic
4551      * update access modes compare values using their bitwise representation
4552      * (see {@link Float#floatToRawIntBits} and
4553      * {@link Double#doubleToRawLongBits}, respectively).
4554      * @param viewArrayClass the view array class, with a component type of
4555      * type {@code T}
4556      * @param byteOrder the endianness of the view array elements, as
4557      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4558      * endianness of a {@code ByteBuffer})
4559      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4560      * viewed as if elements corresponding to the components type of the view
4561      * array class
4562      * @throws NullPointerException if viewArrayClass or byteOrder is null
4563      * @throws IllegalArgumentException if viewArrayClass is not an array type
4564      * @throws UnsupportedOperationException if the component type of
4565      * viewArrayClass is not supported as a variable type
4566      * @since 9
4567      */
4568     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4569                                       ByteOrder byteOrder) throws IllegalArgumentException {
4570         Objects.requireNonNull(byteOrder);
4571         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4572                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4573     }
4574 
4575 
4576     /// method handle invocation (reflective style)
4577 
4578     /**
4579      * Produces a method handle which will invoke any method handle of the
4580      * given {@code type}, with a given number of trailing arguments replaced by
4581      * a single trailing {@code Object[]} array.
4582      * The resulting invoker will be a method handle with the following
4583      * arguments:
4584      * <ul>
4585      * <li>a single {@code MethodHandle} target
4586      * <li>zero or more leading values (counted by {@code leadingArgCount})
4587      * <li>an {@code Object[]} array containing trailing arguments
4588      * </ul>
4589      * <p>
4590      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4591      * the indicated {@code type}.
4592      * That is, if the target is exactly of the given {@code type}, it will behave
4593      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4594      * is used to convert the target to the required {@code type}.
4595      * <p>
4596      * The type of the returned invoker will not be the given {@code type}, but rather
4597      * will have all parameters except the first {@code leadingArgCount}
4598      * replaced by a single array of type {@code Object[]}, which will be
4599      * the final parameter.
4600      * <p>
4601      * Before invoking its target, the invoker will spread the final array, apply
4602      * reference casts as necessary, and unbox and widen primitive arguments.
4603      * If, when the invoker is called, the supplied array argument does
4604      * not have the correct number of elements, the invoker will throw
4605      * an {@link IllegalArgumentException} instead of invoking the target.
4606      * <p>
4607      * This method is equivalent to the following code (though it may be more efficient):
4608      * <blockquote><pre>{@code
4609 MethodHandle invoker = MethodHandles.invoker(type);
4610 int spreadArgCount = type.parameterCount() - leadingArgCount;
4611 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4612 return invoker;
4613      * }</pre></blockquote>
4614      * This method throws no reflective or security exceptions.
4615      * @param type the desired target type
4616      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4617      * @return a method handle suitable for invoking any method handle of the given type
4618      * @throws NullPointerException if {@code type} is null
4619      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4620      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4621      *                  or if the resulting method handle's type would have
4622      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4623      */
4624     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4625         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4626             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4627         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4628         return type.invokers().spreadInvoker(leadingArgCount);
4629     }
4630 
4631     /**
4632      * Produces a special <em>invoker method handle</em> which can be used to
4633      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4634      * The resulting invoker will have a type which is
4635      * exactly equal to the desired type, except that it will accept
4636      * an additional leading argument of type {@code MethodHandle}.
4637      * <p>
4638      * This method is equivalent to the following code (though it may be more efficient):
4639      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4640      *
4641      * <p style="font-size:smaller;">
4642      * <em>Discussion:</em>
4643      * Invoker method handles can be useful when working with variable method handles
4644      * of unknown types.
4645      * For example, to emulate an {@code invokeExact} call to a variable method
4646      * handle {@code M}, extract its type {@code T},
4647      * look up the invoker method {@code X} for {@code T},
4648      * and call the invoker method, as {@code X.invoke(T, A...)}.
4649      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4650      * is unknown.)
4651      * If spreading, collecting, or other argument transformations are required,
4652      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4653      * method handle values, as long as they are compatible with the type of {@code X}.
4654      * <p style="font-size:smaller;">
4655      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4656      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4657      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4658      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4659      * <p>
4660      * This method throws no reflective or security exceptions.
4661      * @param type the desired target type
4662      * @return a method handle suitable for invoking any method handle of the given type
4663      * @throws IllegalArgumentException if the resulting method handle's type would have
4664      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4665      */
4666     public static MethodHandle exactInvoker(MethodType type) {
4667         return type.invokers().exactInvoker();
4668     }
4669 
4670     /**
4671      * Produces a special <em>invoker method handle</em> which can be used to
4672      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4673      * The resulting invoker will have a type which is
4674      * exactly equal to the desired type, except that it will accept
4675      * an additional leading argument of type {@code MethodHandle}.
4676      * <p>
4677      * Before invoking its target, if the target differs from the expected type,
4678      * the invoker will apply reference casts as
4679      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4680      * Similarly, the return value will be converted as necessary.
4681      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4682      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4683      * <p>
4684      * This method is equivalent to the following code (though it may be more efficient):
4685      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4686      * <p style="font-size:smaller;">
4687      * <em>Discussion:</em>
4688      * A {@linkplain MethodType#genericMethodType general method type} is one which
4689      * mentions only {@code Object} arguments and return values.
4690      * An invoker for such a type is capable of calling any method handle
4691      * of the same arity as the general type.
4692      * <p style="font-size:smaller;">
4693      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4694      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4695      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4696      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4697      * <p>
4698      * This method throws no reflective or security exceptions.
4699      * @param type the desired target type
4700      * @return a method handle suitable for invoking any method handle convertible to the given type
4701      * @throws IllegalArgumentException if the resulting method handle's type would have
4702      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4703      */
4704     public static MethodHandle invoker(MethodType type) {
4705         return type.invokers().genericInvoker();
4706     }
4707 
4708     /**
4709      * Produces a special <em>invoker method handle</em> which can be used to
4710      * invoke a signature-polymorphic access mode method on any VarHandle whose
4711      * associated access mode type is compatible with the given type.
4712      * The resulting invoker will have a type which is exactly equal to the
4713      * desired given type, except that it will accept an additional leading
4714      * argument of type {@code VarHandle}.
4715      *
4716      * @param accessMode the VarHandle access mode
4717      * @param type the desired target type
4718      * @return a method handle suitable for invoking an access mode method of
4719      *         any VarHandle whose access mode type is of the given type.
4720      * @since 9
4721      */
4722     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4723         return type.invokers().varHandleMethodExactInvoker(accessMode);
4724     }
4725 
4726     /**
4727      * Produces a special <em>invoker method handle</em> which can be used to
4728      * invoke a signature-polymorphic access mode method on any VarHandle whose
4729      * associated access mode type is compatible with the given type.
4730      * The resulting invoker will have a type which is exactly equal to the
4731      * desired given type, except that it will accept an additional leading
4732      * argument of type {@code VarHandle}.
4733      * <p>
4734      * Before invoking its target, if the access mode type differs from the
4735      * desired given type, the invoker will apply reference casts as necessary
4736      * and box, unbox, or widen primitive values, as if by
4737      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4738      * converted as necessary.
4739      * <p>
4740      * This method is equivalent to the following code (though it may be more
4741      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4742      *
4743      * @param accessMode the VarHandle access mode
4744      * @param type the desired target type
4745      * @return a method handle suitable for invoking an access mode method of
4746      *         any VarHandle whose access mode type is convertible to the given
4747      *         type.
4748      * @since 9
4749      */
4750     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4751         return type.invokers().varHandleMethodInvoker(accessMode);
4752     }
4753 
4754     /*non-public*/
4755     static MethodHandle basicInvoker(MethodType type) {
4756         return type.invokers().basicInvoker();
4757     }
4758 
4759      /// method handle modification (creation from other method handles)
4760 
4761     /**
4762      * Produces a method handle which adapts the type of the
4763      * given method handle to a new type by pairwise argument and return type conversion.
4764      * The original type and new type must have the same number of arguments.
4765      * The resulting method handle is guaranteed to report a type
4766      * which is equal to the desired new type.
4767      * <p>
4768      * If the original type and new type are equal, returns target.
4769      * <p>
4770      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4771      * and some additional conversions are also applied if those conversions fail.
4772      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4773      * if possible, before or instead of any conversions done by {@code asType}:
4774      * <ul>
4775      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4776      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4777      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4778      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4779      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4780      *     (This treatment follows the usage of the bytecode verifier.)
4781      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4782      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
4783      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4784      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4785      *     then a Java casting conversion (JLS 5.5) is applied.
4786      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4787      *     widening and/or narrowing.)
4788      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4789      *     conversion will be applied at runtime, possibly followed
4790      *     by a Java casting conversion (JLS 5.5) on the primitive value,
4791      *     possibly followed by a conversion from byte to boolean by testing
4792      *     the low-order bit.
4793      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4794      *     and if the reference is null at runtime, a zero value is introduced.
4795      * </ul>
4796      * @param target the method handle to invoke after arguments are retyped
4797      * @param newType the expected type of the new method handle
4798      * @return a method handle which delegates to the target after performing
4799      *           any necessary argument conversions, and arranges for any
4800      *           necessary return value conversions
4801      * @throws NullPointerException if either argument is null
4802      * @throws WrongMethodTypeException if the conversion cannot be made
4803      * @see MethodHandle#asType
4804      */
4805     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4806         explicitCastArgumentsChecks(target, newType);
4807         // use the asTypeCache when possible:
4808         MethodType oldType = target.type();
4809         if (oldType == newType)  return target;
4810         if (oldType.explicitCastEquivalentToAsType(newType)) {
4811             return target.asFixedArity().asType(newType);
4812         }
4813         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4814     }
4815 
4816     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4817         if (target.type().parameterCount() != newType.parameterCount()) {
4818             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4819         }
4820     }
4821 
4822     /**
4823      * Produces a method handle which adapts the calling sequence of the
4824      * given method handle to a new type, by reordering the arguments.
4825      * The resulting method handle is guaranteed to report a type
4826      * which is equal to the desired new type.
4827      * <p>
4828      * The given array controls the reordering.
4829      * Call {@code #I} the number of incoming parameters (the value
4830      * {@code newType.parameterCount()}, and call {@code #O} the number
4831      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4832      * Then the length of the reordering array must be {@code #O},
4833      * and each element must be a non-negative number less than {@code #I}.
4834      * For every {@code N} less than {@code #O}, the {@code N}-th
4835      * outgoing argument will be taken from the {@code I}-th incoming
4836      * argument, where {@code I} is {@code reorder[N]}.
4837      * <p>
4838      * No argument or return value conversions are applied.
4839      * The type of each incoming argument, as determined by {@code newType},
4840      * must be identical to the type of the corresponding outgoing parameter
4841      * or parameters in the target method handle.
4842      * The return type of {@code newType} must be identical to the return
4843      * type of the original target.
4844      * <p>
4845      * The reordering array need not specify an actual permutation.
4846      * An incoming argument will be duplicated if its index appears
4847      * more than once in the array, and an incoming argument will be dropped
4848      * if its index does not appear in the array.
4849      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4850      * incoming arguments which are not mentioned in the reordering array
4851      * may be of any type, as determined only by {@code newType}.
4852      * <blockquote><pre>{@code
4853 import static java.lang.invoke.MethodHandles.*;
4854 import static java.lang.invoke.MethodType.*;
4855 ...
4856 MethodType intfn1 = methodType(int.class, int.class);
4857 MethodType intfn2 = methodType(int.class, int.class, int.class);
4858 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4859 assert(sub.type().equals(intfn2));
4860 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4861 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4862 assert((int)rsub.invokeExact(1, 100) == 99);
4863 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4864 assert(add.type().equals(intfn2));
4865 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4866 assert(twice.type().equals(intfn1));
4867 assert((int)twice.invokeExact(21) == 42);
4868      * }</pre></blockquote>
4869      * <p>
4870      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4871      * variable-arity method handle}, even if the original target method handle was.
4872      * @param target the method handle to invoke after arguments are reordered
4873      * @param newType the expected type of the new method handle
4874      * @param reorder an index array which controls the reordering
4875      * @return a method handle which delegates to the target after it
4876      *           drops unused arguments and moves and/or duplicates the other arguments
4877      * @throws NullPointerException if any argument is null
4878      * @throws IllegalArgumentException if the index array length is not equal to
4879      *                  the arity of the target, or if any index array element
4880      *                  not a valid index for a parameter of {@code newType},
4881      *                  or if two corresponding parameter types in
4882      *                  {@code target.type()} and {@code newType} are not identical,
4883      */
4884     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4885         reorder = reorder.clone();  // get a private copy
4886         MethodType oldType = target.type();
4887         permuteArgumentChecks(reorder, newType, oldType);
4888         // first detect dropped arguments and handle them separately
4889         int[] originalReorder = reorder;
4890         BoundMethodHandle result = target.rebind();
4891         LambdaForm form = result.form;
4892         int newArity = newType.parameterCount();
4893         // Normalize the reordering into a real permutation,
4894         // by removing duplicates and adding dropped elements.
4895         // This somewhat improves lambda form caching, as well
4896         // as simplifying the transform by breaking it up into steps.
4897         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4898             if (ddIdx > 0) {
4899                 // We found a duplicated entry at reorder[ddIdx].
4900                 // Example:  (x,y,z)->asList(x,y,z)
4901                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4902                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4903                 // The starred element corresponds to the argument
4904                 // deleted by the dupArgumentForm transform.
4905                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4906                 boolean killFirst = false;
4907                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4908                     // Set killFirst if the dup is larger than an intervening position.
4909                     // This will remove at least one inversion from the permutation.
4910                     if (dupVal > val) killFirst = true;
4911                 }
4912                 if (!killFirst) {
4913                     srcPos = dstPos;
4914                     dstPos = ddIdx;
4915                 }
4916                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4917                 assert (reorder[srcPos] == reorder[dstPos]);
4918                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4919                 // contract the reordering by removing the element at dstPos
4920                 int tailPos = dstPos + 1;
4921                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4922                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4923             } else {
4924                 int dropVal = ~ddIdx, insPos = 0;
4925                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4926                     // Find first element of reorder larger than dropVal.
4927                     // This is where we will insert the dropVal.
4928                     insPos += 1;
4929                 }
4930                 Class<?> ptype = newType.parameterType(dropVal);
4931                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4932                 oldType = oldType.insertParameterTypes(insPos, ptype);
4933                 // expand the reordering by inserting an element at insPos
4934                 int tailPos = insPos + 1;
4935                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4936                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4937                 reorder[insPos] = dropVal;
4938             }
4939             assert (permuteArgumentChecks(reorder, newType, oldType));
4940         }
4941         assert (reorder.length == newArity);  // a perfect permutation
4942         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4943         form = form.editor().permuteArgumentsForm(1, reorder);
4944         if (newType == result.type() && form == result.internalForm())
4945             return result;
4946         return result.copyWith(newType, form);
4947     }
4948 
4949     /**
4950      * Return an indication of any duplicate or omission in reorder.
4951      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4952      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4953      * Otherwise, return zero.
4954      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4955      */
4956     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4957         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4958         if (newArity < BIT_LIMIT) {
4959             long mask = 0;
4960             for (int i = 0; i < reorder.length; i++) {
4961                 int arg = reorder[i];
4962                 if (arg >= newArity) {
4963                     return reorder.length;
4964                 }
4965                 long bit = 1L << arg;
4966                 if ((mask & bit) != 0) {
4967                     return i;  // >0 indicates a dup
4968                 }
4969                 mask |= bit;
4970             }
4971             if (mask == (1L << newArity) - 1) {
4972                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4973                 return 0;
4974             }
4975             // find first zero
4976             long zeroBit = Long.lowestOneBit(~mask);
4977             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4978             assert(zeroPos <= newArity);
4979             if (zeroPos == newArity) {
4980                 return 0;
4981             }
4982             return ~zeroPos;
4983         } else {
4984             // same algorithm, different bit set
4985             BitSet mask = new BitSet(newArity);
4986             for (int i = 0; i < reorder.length; i++) {
4987                 int arg = reorder[i];
4988                 if (arg >= newArity) {
4989                     return reorder.length;
4990                 }
4991                 if (mask.get(arg)) {
4992                     return i;  // >0 indicates a dup
4993                 }
4994                 mask.set(arg);
4995             }
4996             int zeroPos = mask.nextClearBit(0);
4997             assert(zeroPos <= newArity);
4998             if (zeroPos == newArity) {
4999                 return 0;
5000             }
5001             return ~zeroPos;
5002         }
5003     }
5004 
5005     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5006         if (newType.returnType() != oldType.returnType())
5007             throw newIllegalArgumentException("return types do not match",
5008                     oldType, newType);
5009         if (reorder.length != oldType.parameterCount())
5010             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5011                     oldType, Arrays.toString(reorder));
5012 
5013         int limit = newType.parameterCount();
5014         for (int j = 0; j < reorder.length; j++) {
5015             int i = reorder[j];
5016             if (i < 0 || i >= limit) {
5017                 throw newIllegalArgumentException("index is out of bounds for new type",
5018                         i, newType);
5019             }
5020             Class<?> src = newType.parameterType(i);
5021             Class<?> dst = oldType.parameterType(j);
5022             if (src != dst)
5023                 throw newIllegalArgumentException("parameter types do not match after reorder",
5024                         oldType, newType);
5025         }
5026         return true;
5027     }
5028 
5029     /**
5030      * Produces a method handle of the requested return type which returns the given
5031      * constant value every time it is invoked.
5032      * <p>
5033      * Before the method handle is returned, the passed-in value is converted to the requested type.
5034      * If the requested type is primitive, widening primitive conversions are attempted,
5035      * else reference conversions are attempted.
5036      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5037      * @param type the return type of the desired method handle
5038      * @param value the value to return
5039      * @return a method handle of the given return type and no arguments, which always returns the given value
5040      * @throws NullPointerException if the {@code type} argument is null
5041      * @throws ClassCastException if the value cannot be converted to the required return type
5042      * @throws IllegalArgumentException if the given type is {@code void.class}
5043      */
5044     public static MethodHandle constant(Class<?> type, Object value) {
5045         if (type.isPrimitive()) {
5046             if (type == void.class)
5047                 throw newIllegalArgumentException("void type");
5048             Wrapper w = Wrapper.forPrimitiveType(type);
5049             value = w.convert(value, type);
5050             if (w.zero().equals(value))
5051                 return zero(w, type);
5052             return insertArguments(identity(type), 0, value);
5053         } else {
5054             if (value == null)
5055                 return zero(Wrapper.OBJECT, type);
5056             return identity(type).bindTo(value);
5057         }
5058     }
5059 
5060     /**
5061      * Produces a method handle which returns its sole argument when invoked.
5062      * @param type the type of the sole parameter and return value of the desired method handle
5063      * @return a unary method handle which accepts and returns the given type
5064      * @throws NullPointerException if the argument is null
5065      * @throws IllegalArgumentException if the given type is {@code void.class}
5066      */
5067     public static MethodHandle identity(Class<?> type) {
5068         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5069         int pos = btw.ordinal();
5070         MethodHandle ident = IDENTITY_MHS[pos];
5071         if (ident == null) {
5072             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5073         }
5074         if (ident.type().returnType() == type)
5075             return ident;
5076         // something like identity(Foo.class); do not bother to intern these
5077         assert (btw == Wrapper.OBJECT);
5078         return makeIdentity(type);
5079     }
5080 
5081     /**
5082      * Produces a constant method handle of the requested return type which
5083      * returns the default value for that type every time it is invoked.
5084      * The resulting constant method handle will have no side effects.
5085      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5086      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5087      * since {@code explicitCastArguments} converts {@code null} to default values.
5088      * @param type the expected return type of the desired method handle
5089      * @return a constant method handle that takes no arguments
5090      *         and returns the default value of the given type (or void, if the type is void)
5091      * @throws NullPointerException if the argument is null
5092      * @see MethodHandles#constant
5093      * @see MethodHandles#empty
5094      * @see MethodHandles#explicitCastArguments
5095      * @since 9
5096      */
5097     public static MethodHandle zero(Class<?> type) {
5098         Objects.requireNonNull(type);
5099         if (type.isPrimitive()) {
5100             return zero(Wrapper.forPrimitiveType(type), type);
5101         } else if (type.isPrimitiveClass()) {
5102             throw new UnsupportedOperationException();
5103         } else {
5104             return zero(Wrapper.OBJECT, type);
5105         }
5106     }
5107 
5108     private static MethodHandle identityOrVoid(Class<?> type) {
5109         return type == void.class ? zero(type) : identity(type);
5110     }
5111 
5112     /**
5113      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5114      * and returns a suitable default depending on the return type.
5115      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5116      * <p>The returned method handle is equivalent to
5117      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5118      *
5119      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5120      * {@code guardWithTest(pred, target, empty(target.type())}.
5121      * @param type the type of the desired method handle
5122      * @return a constant method handle of the given type, which returns a default value of the given return type
5123      * @throws NullPointerException if the argument is null
5124      * @see MethodHandles#zero
5125      * @see MethodHandles#constant
5126      * @since 9
5127      */
5128     public static  MethodHandle empty(MethodType type) {
5129         Objects.requireNonNull(type);
5130         return dropArguments(zero(type.returnType()), 0, type.parameterList());
5131     }
5132 
5133     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5134     private static MethodHandle makeIdentity(Class<?> ptype) {
5135         MethodType mtype = MethodType.methodType(ptype, ptype);
5136         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5137         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5138     }
5139 
5140     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5141         int pos = btw.ordinal();
5142         MethodHandle zero = ZERO_MHS[pos];
5143         if (zero == null) {
5144             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5145         }
5146         if (zero.type().returnType() == rtype)
5147             return zero;
5148         assert(btw == Wrapper.OBJECT);
5149         return makeZero(rtype);
5150     }
5151     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5152     private static MethodHandle makeZero(Class<?> rtype) {
5153         MethodType mtype = methodType(rtype);
5154         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5155         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5156     }
5157 
5158     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5159         // Simulate a CAS, to avoid racy duplication of results.
5160         MethodHandle prev = cache[pos];
5161         if (prev != null) return prev;
5162         return cache[pos] = value;
5163     }
5164 
5165     /**
5166      * Provides a target method handle with one or more <em>bound arguments</em>
5167      * in advance of the method handle's invocation.
5168      * The formal parameters to the target corresponding to the bound
5169      * arguments are called <em>bound parameters</em>.
5170      * Returns a new method handle which saves away the bound arguments.
5171      * When it is invoked, it receives arguments for any non-bound parameters,
5172      * binds the saved arguments to their corresponding parameters,
5173      * and calls the original target.
5174      * <p>
5175      * The type of the new method handle will drop the types for the bound
5176      * parameters from the original target type, since the new method handle
5177      * will no longer require those arguments to be supplied by its callers.
5178      * <p>
5179      * Each given argument object must match the corresponding bound parameter type.
5180      * If a bound parameter type is a primitive, the argument object
5181      * must be a wrapper, and will be unboxed to produce the primitive value.
5182      * <p>
5183      * The {@code pos} argument selects which parameters are to be bound.
5184      * It may range between zero and <i>N-L</i> (inclusively),
5185      * where <i>N</i> is the arity of the target method handle
5186      * and <i>L</i> is the length of the values array.
5187      * <p>
5188      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5189      * variable-arity method handle}, even if the original target method handle was.
5190      * @param target the method handle to invoke after the argument is inserted
5191      * @param pos where to insert the argument (zero for the first)
5192      * @param values the series of arguments to insert
5193      * @return a method handle which inserts an additional argument,
5194      *         before calling the original method handle
5195      * @throws NullPointerException if the target or the {@code values} array is null
5196      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5197      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5198      *         is the length of the values array.
5199      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5200      *         type.
5201      * @see MethodHandle#bindTo
5202      */
5203     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5204         int insCount = values.length;
5205         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5206         if (insCount == 0)  return target;
5207         BoundMethodHandle result = target.rebind();
5208         for (int i = 0; i < insCount; i++) {
5209             Object value = values[i];
5210             Class<?> ptype = ptypes[pos+i];
5211             if (ptype.isPrimitive()) {
5212                 result = insertArgumentPrimitive(result, pos, ptype, value);
5213             } else {
5214                 value = ptype.cast(value);  // throw CCE if needed
5215                 result = result.bindArgumentL(pos, value);
5216             }
5217         }
5218         return result;
5219     }
5220 
5221     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5222                                                              Class<?> ptype, Object value) {
5223         Wrapper w = Wrapper.forPrimitiveType(ptype);
5224         // perform unboxing and/or primitive conversion
5225         value = w.convert(value, ptype);
5226         return switch (w) {
5227             case INT    -> result.bindArgumentI(pos, (int) value);
5228             case LONG   -> result.bindArgumentJ(pos, (long) value);
5229             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5230             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5231             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5232         };
5233     }
5234 
5235     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5236         MethodType oldType = target.type();
5237         int outargs = oldType.parameterCount();
5238         int inargs  = outargs - insCount;
5239         if (inargs < 0)
5240             throw newIllegalArgumentException("too many values to insert");
5241         if (pos < 0 || pos > inargs)
5242             throw newIllegalArgumentException("no argument type to append");
5243         return oldType.ptypes();
5244     }
5245 
5246     /**
5247      * Produces a method handle which will discard some dummy arguments
5248      * before calling some other specified <i>target</i> method handle.
5249      * The type of the new method handle will be the same as the target's type,
5250      * except it will also include the dummy argument types,
5251      * at some given position.
5252      * <p>
5253      * The {@code pos} argument may range between zero and <i>N</i>,
5254      * where <i>N</i> is the arity of the target.
5255      * If {@code pos} is zero, the dummy arguments will precede
5256      * the target's real arguments; if {@code pos} is <i>N</i>
5257      * they will come after.
5258      * <p>
5259      * <b>Example:</b>
5260      * <blockquote><pre>{@code
5261 import static java.lang.invoke.MethodHandles.*;
5262 import static java.lang.invoke.MethodType.*;
5263 ...
5264 MethodHandle cat = lookup().findVirtual(String.class,
5265   "concat", methodType(String.class, String.class));
5266 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5267 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5268 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5269 assertEquals(bigType, d0.type());
5270 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5271      * }</pre></blockquote>
5272      * <p>
5273      * This method is also equivalent to the following code:
5274      * <blockquote><pre>
5275      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5276      * </pre></blockquote>
5277      * @param target the method handle to invoke after the arguments are dropped
5278      * @param pos position of first argument to drop (zero for the leftmost)
5279      * @param valueTypes the type(s) of the argument(s) to drop
5280      * @return a method handle which drops arguments of the given types,
5281      *         before calling the original method handle
5282      * @throws NullPointerException if the target is null,
5283      *                              or if the {@code valueTypes} list or any of its elements is null
5284      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5285      *                  or if {@code pos} is negative or greater than the arity of the target,
5286      *                  or if the new method handle's type would have too many parameters
5287      */
5288     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5289         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
5290     }
5291 
5292     private static List<Class<?>> copyTypes(Object[] array) {
5293         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
5294     }
5295 
5296     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5297         MethodType oldType = target.type();  // get NPE
5298         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5299         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5300         if (dropped == 0)  return target;
5301         BoundMethodHandle result = target.rebind();
5302         LambdaForm lform = result.form;
5303         int insertFormArg = 1 + pos;
5304         for (Class<?> ptype : valueTypes) {
5305             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5306         }
5307         result = result.copyWith(newType, lform);
5308         return result;
5309     }
5310 
5311     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
5312         int dropped = valueTypes.size();
5313         MethodType.checkSlotCount(dropped);
5314         int outargs = oldType.parameterCount();
5315         int inargs  = outargs + dropped;
5316         if (pos < 0 || pos > outargs)
5317             throw newIllegalArgumentException("no argument type to remove"
5318                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5319                     );
5320         return dropped;
5321     }
5322 
5323     /**
5324      * Produces a method handle which will discard some dummy arguments
5325      * before calling some other specified <i>target</i> method handle.
5326      * The type of the new method handle will be the same as the target's type,
5327      * except it will also include the dummy argument types,
5328      * at some given position.
5329      * <p>
5330      * The {@code pos} argument may range between zero and <i>N</i>,
5331      * where <i>N</i> is the arity of the target.
5332      * If {@code pos} is zero, the dummy arguments will precede
5333      * the target's real arguments; if {@code pos} is <i>N</i>
5334      * they will come after.
5335      * @apiNote
5336      * <blockquote><pre>{@code
5337 import static java.lang.invoke.MethodHandles.*;
5338 import static java.lang.invoke.MethodType.*;
5339 ...
5340 MethodHandle cat = lookup().findVirtual(String.class,
5341   "concat", methodType(String.class, String.class));
5342 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5343 MethodHandle d0 = dropArguments(cat, 0, String.class);
5344 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5345 MethodHandle d1 = dropArguments(cat, 1, String.class);
5346 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5347 MethodHandle d2 = dropArguments(cat, 2, String.class);
5348 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5349 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5350 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5351      * }</pre></blockquote>
5352      * <p>
5353      * This method is also equivalent to the following code:
5354      * <blockquote><pre>
5355      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5356      * </pre></blockquote>
5357      * @param target the method handle to invoke after the arguments are dropped
5358      * @param pos position of first argument to drop (zero for the leftmost)
5359      * @param valueTypes the type(s) of the argument(s) to drop
5360      * @return a method handle which drops arguments of the given types,
5361      *         before calling the original method handle
5362      * @throws NullPointerException if the target is null,
5363      *                              or if the {@code valueTypes} array or any of its elements is null
5364      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5365      *                  or if {@code pos} is negative or greater than the arity of the target,
5366      *                  or if the new method handle's type would have
5367      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5368      */
5369     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5370         return dropArguments0(target, pos, copyTypes(valueTypes));
5371     }
5372 
5373     // private version which allows caller some freedom with error handling
5374     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
5375                                       boolean nullOnFailure) {
5376         newTypes = copyTypes(newTypes.toArray());
5377         List<Class<?>> oldTypes = target.type().parameterList();
5378         int match = oldTypes.size();
5379         if (skip != 0) {
5380             if (skip < 0 || skip > match) {
5381                 throw newIllegalArgumentException("illegal skip", skip, target);
5382             }
5383             oldTypes = oldTypes.subList(skip, match);
5384             match -= skip;
5385         }
5386         List<Class<?>> addTypes = newTypes;
5387         int add = addTypes.size();
5388         if (pos != 0) {
5389             if (pos < 0 || pos > add) {
5390                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
5391             }
5392             addTypes = addTypes.subList(pos, add);
5393             add -= pos;
5394             assert(addTypes.size() == add);
5395         }
5396         // Do not add types which already match the existing arguments.
5397         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
5398             if (nullOnFailure) {
5399                 return null;
5400             }
5401             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5402         }
5403         addTypes = addTypes.subList(match, add);
5404         add -= match;
5405         assert(addTypes.size() == add);
5406         // newTypes:     (   P*[pos], M*[match], A*[add] )
5407         // target: ( S*[skip],        M*[match]  )
5408         MethodHandle adapter = target;
5409         if (add > 0) {
5410             adapter = dropArguments0(adapter, skip+ match, addTypes);
5411         }
5412         // adapter: (S*[skip],        M*[match], A*[add] )
5413         if (pos > 0) {
5414             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5415         }
5416         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5417         return adapter;
5418     }
5419 
5420     /**
5421      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5422      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5423      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5424      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5425      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5426      * {@link #dropArguments(MethodHandle, int, Class[])}.
5427      * <p>
5428      * The resulting handle will have the same return type as the target handle.
5429      * <p>
5430      * In more formal terms, assume these two type lists:<ul>
5431      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5432      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5433      * {@code newTypes}.
5434      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5435      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5436      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5437      * sub-list.
5438      * </ul>
5439      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5440      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5441      * {@link #dropArguments(MethodHandle, int, Class[])}.
5442      *
5443      * @apiNote
5444      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5445      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5446      * <blockquote><pre>{@code
5447 import static java.lang.invoke.MethodHandles.*;
5448 import static java.lang.invoke.MethodType.*;
5449 ...
5450 ...
5451 MethodHandle h0 = constant(boolean.class, true);
5452 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5453 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5454 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5455 if (h1.type().parameterCount() < h2.type().parameterCount())
5456     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5457 else
5458     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5459 MethodHandle h3 = guardWithTest(h0, h1, h2);
5460 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5461      * }</pre></blockquote>
5462      * @param target the method handle to adapt
5463      * @param skip number of targets parameters to disregard (they will be unchanged)
5464      * @param newTypes the list of types to match {@code target}'s parameter type list to
5465      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5466      * @return a possibly adapted method handle
5467      * @throws NullPointerException if either argument is null
5468      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5469      *         or if {@code skip} is negative or greater than the arity of the target,
5470      *         or if {@code pos} is negative or greater than the newTypes list size,
5471      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5472      *         {@code pos}.
5473      * @since 9
5474      */
5475     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5476         Objects.requireNonNull(target);
5477         Objects.requireNonNull(newTypes);
5478         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5479     }
5480 
5481     /**
5482      * Drop the return value of the target handle (if any).
5483      * The returned method handle will have a {@code void} return type.
5484      *
5485      * @param target the method handle to adapt
5486      * @return a possibly adapted method handle
5487      * @throws NullPointerException if {@code target} is null
5488      * @since 16
5489      */
5490     public static MethodHandle dropReturn(MethodHandle target) {
5491         Objects.requireNonNull(target);
5492         MethodType oldType = target.type();
5493         Class<?> oldReturnType = oldType.returnType();
5494         if (oldReturnType == void.class)
5495             return target;
5496         MethodType newType = oldType.changeReturnType(void.class);
5497         BoundMethodHandle result = target.rebind();
5498         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5499         result = result.copyWith(newType, lform);
5500         return result;
5501     }
5502 
5503     /**
5504      * Adapts a target method handle by pre-processing
5505      * one or more of its arguments, each with its own unary filter function,
5506      * and then calling the target with each pre-processed argument
5507      * replaced by the result of its corresponding filter function.
5508      * <p>
5509      * The pre-processing is performed by one or more method handles,
5510      * specified in the elements of the {@code filters} array.
5511      * The first element of the filter array corresponds to the {@code pos}
5512      * argument of the target, and so on in sequence.
5513      * The filter functions are invoked in left to right order.
5514      * <p>
5515      * Null arguments in the array are treated as identity functions,
5516      * and the corresponding arguments left unchanged.
5517      * (If there are no non-null elements in the array, the original target is returned.)
5518      * Each filter is applied to the corresponding argument of the adapter.
5519      * <p>
5520      * If a filter {@code F} applies to the {@code N}th argument of
5521      * the target, then {@code F} must be a method handle which
5522      * takes exactly one argument.  The type of {@code F}'s sole argument
5523      * replaces the corresponding argument type of the target
5524      * in the resulting adapted method handle.
5525      * The return type of {@code F} must be identical to the corresponding
5526      * parameter type of the target.
5527      * <p>
5528      * It is an error if there are elements of {@code filters}
5529      * (null or not)
5530      * which do not correspond to argument positions in the target.
5531      * <p><b>Example:</b>
5532      * <blockquote><pre>{@code
5533 import static java.lang.invoke.MethodHandles.*;
5534 import static java.lang.invoke.MethodType.*;
5535 ...
5536 MethodHandle cat = lookup().findVirtual(String.class,
5537   "concat", methodType(String.class, String.class));
5538 MethodHandle upcase = lookup().findVirtual(String.class,
5539   "toUpperCase", methodType(String.class));
5540 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5541 MethodHandle f0 = filterArguments(cat, 0, upcase);
5542 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5543 MethodHandle f1 = filterArguments(cat, 1, upcase);
5544 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5545 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5546 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5547      * }</pre></blockquote>
5548      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5549      * denotes the return type of both the {@code target} and resulting adapter.
5550      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5551      * of the parameters and arguments that precede and follow the filter position
5552      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5553      * values of the filtered parameters and arguments; they also represent the
5554      * return types of the {@code filter[i]} handles. The latter accept arguments
5555      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5556      * the resulting adapter.
5557      * <blockquote><pre>{@code
5558      * T target(P... p, A[i]... a[i], B... b);
5559      * A[i] filter[i](V[i]);
5560      * T adapter(P... p, V[i]... v[i], B... b) {
5561      *   return target(p..., filter[i](v[i])..., b...);
5562      * }
5563      * }</pre></blockquote>
5564      * <p>
5565      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5566      * variable-arity method handle}, even if the original target method handle was.
5567      *
5568      * @param target the method handle to invoke after arguments are filtered
5569      * @param pos the position of the first argument to filter
5570      * @param filters method handles to call initially on filtered arguments
5571      * @return method handle which incorporates the specified argument filtering logic
5572      * @throws NullPointerException if the target is null
5573      *                              or if the {@code filters} array is null
5574      * @throws IllegalArgumentException if a non-null element of {@code filters}
5575      *          does not match a corresponding argument type of target as described above,
5576      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5577      *          or if the resulting method handle's type would have
5578      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5579      */
5580     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5581         // In method types arguments start at index 0, while the LF
5582         // editor have the MH receiver at position 0 - adjust appropriately.
5583         final int MH_RECEIVER_OFFSET = 1;
5584         filterArgumentsCheckArity(target, pos, filters);
5585         MethodHandle adapter = target;
5586 
5587         // keep track of currently matched filters, as to optimize repeated filters
5588         int index = 0;
5589         int[] positions = new int[filters.length];
5590         MethodHandle filter = null;
5591 
5592         // process filters in reverse order so that the invocation of
5593         // the resulting adapter will invoke the filters in left-to-right order
5594         for (int i = filters.length - 1; i >= 0; --i) {
5595             MethodHandle newFilter = filters[i];
5596             if (newFilter == null) continue;  // ignore null elements of filters
5597 
5598             // flush changes on update
5599             if (filter != newFilter) {
5600                 if (filter != null) {
5601                     if (index > 1) {
5602                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5603                     } else {
5604                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5605                     }
5606                 }
5607                 filter = newFilter;
5608                 index = 0;
5609             }
5610 
5611             filterArgumentChecks(target, pos + i, newFilter);
5612             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5613         }
5614         if (index > 1) {
5615             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5616         } else if (index == 1) {
5617             adapter = filterArgument(adapter, positions[0] - 1, filter);
5618         }
5619         return adapter;
5620     }
5621 
5622     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5623         MethodType targetType = adapter.type();
5624         MethodType filterType = filter.type();
5625         BoundMethodHandle result = adapter.rebind();
5626         Class<?> newParamType = filterType.parameterType(0);
5627 
5628         Class<?>[] ptypes = targetType.ptypes().clone();
5629         for (int pos : positions) {
5630             ptypes[pos - 1] = newParamType;
5631         }
5632         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5633 
5634         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5635         return result.copyWithExtendL(newType, lform, filter);
5636     }
5637 
5638     /*non-public*/
5639     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5640         filterArgumentChecks(target, pos, filter);
5641         MethodType targetType = target.type();
5642         MethodType filterType = filter.type();
5643         BoundMethodHandle result = target.rebind();
5644         Class<?> newParamType = filterType.parameterType(0);
5645         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5646         MethodType newType = targetType.changeParameterType(pos, newParamType);
5647         result = result.copyWithExtendL(newType, lform, filter);
5648         return result;
5649     }
5650 
5651     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5652         MethodType targetType = target.type();
5653         int maxPos = targetType.parameterCount();
5654         if (pos + filters.length > maxPos)
5655             throw newIllegalArgumentException("too many filters");
5656     }
5657 
5658     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5659         MethodType targetType = target.type();
5660         MethodType filterType = filter.type();
5661         if (filterType.parameterCount() != 1
5662             || filterType.returnType() != targetType.parameterType(pos))
5663             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5664     }
5665 
5666     /**
5667      * Adapts a target method handle by pre-processing
5668      * a sub-sequence of its arguments with a filter (another method handle).
5669      * The pre-processed arguments are replaced by the result (if any) of the
5670      * filter function.
5671      * The target is then called on the modified (usually shortened) argument list.
5672      * <p>
5673      * If the filter returns a value, the target must accept that value as
5674      * its argument in position {@code pos}, preceded and/or followed by
5675      * any arguments not passed to the filter.
5676      * If the filter returns void, the target must accept all arguments
5677      * not passed to the filter.
5678      * No arguments are reordered, and a result returned from the filter
5679      * replaces (in order) the whole subsequence of arguments originally
5680      * passed to the adapter.
5681      * <p>
5682      * The argument types (if any) of the filter
5683      * replace zero or one argument types of the target, at position {@code pos},
5684      * in the resulting adapted method handle.
5685      * The return type of the filter (if any) must be identical to the
5686      * argument type of the target at position {@code pos}, and that target argument
5687      * is supplied by the return value of the filter.
5688      * <p>
5689      * In all cases, {@code pos} must be greater than or equal to zero, and
5690      * {@code pos} must also be less than or equal to the target's arity.
5691      * <p><b>Example:</b>
5692      * <blockquote><pre>{@code
5693 import static java.lang.invoke.MethodHandles.*;
5694 import static java.lang.invoke.MethodType.*;
5695 ...
5696 MethodHandle deepToString = publicLookup()
5697   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5698 
5699 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5700 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5701 
5702 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5703 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5704 
5705 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5706 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5707 assertEquals("[top, [up, down], strange]",
5708              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5709 
5710 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5711 assertEquals("[top, [up, down], [strange]]",
5712              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5713 
5714 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5715 assertEquals("[top, [[up, down, strange], charm], bottom]",
5716              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5717      * }</pre></blockquote>
5718      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5719      * represents the return type of the {@code target} and resulting adapter.
5720      * {@code V}/{@code v} stand for the return type and value of the
5721      * {@code filter}, which are also found in the signature and arguments of
5722      * the {@code target}, respectively, unless {@code V} is {@code void}.
5723      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5724      * and values preceding and following the collection position, {@code pos},
5725      * in the {@code target}'s signature. They also turn up in the resulting
5726      * adapter's signature and arguments, where they surround
5727      * {@code B}/{@code b}, which represent the parameter types and arguments
5728      * to the {@code filter} (if any).
5729      * <blockquote><pre>{@code
5730      * T target(A...,V,C...);
5731      * V filter(B...);
5732      * T adapter(A... a,B... b,C... c) {
5733      *   V v = filter(b...);
5734      *   return target(a...,v,c...);
5735      * }
5736      * // and if the filter has no arguments:
5737      * T target2(A...,V,C...);
5738      * V filter2();
5739      * T adapter2(A... a,C... c) {
5740      *   V v = filter2();
5741      *   return target2(a...,v,c...);
5742      * }
5743      * // and if the filter has a void return:
5744      * T target3(A...,C...);
5745      * void filter3(B...);
5746      * T adapter3(A... a,B... b,C... c) {
5747      *   filter3(b...);
5748      *   return target3(a...,c...);
5749      * }
5750      * }</pre></blockquote>
5751      * <p>
5752      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5753      * one which first "folds" the affected arguments, and then drops them, in separate
5754      * steps as follows:
5755      * <blockquote><pre>{@code
5756      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5757      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5758      * }</pre></blockquote>
5759      * If the target method handle consumes no arguments besides than the result
5760      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5761      * is equivalent to {@code filterReturnValue(coll, mh)}.
5762      * If the filter method handle {@code coll} consumes one argument and produces
5763      * a non-void result, then {@code collectArguments(mh, N, coll)}
5764      * is equivalent to {@code filterArguments(mh, N, coll)}.
5765      * Other equivalences are possible but would require argument permutation.
5766      * <p>
5767      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5768      * variable-arity method handle}, even if the original target method handle was.
5769      *
5770      * @param target the method handle to invoke after filtering the subsequence of arguments
5771      * @param pos the position of the first adapter argument to pass to the filter,
5772      *            and/or the target argument which receives the result of the filter
5773      * @param filter method handle to call on the subsequence of arguments
5774      * @return method handle which incorporates the specified argument subsequence filtering logic
5775      * @throws NullPointerException if either argument is null
5776      * @throws IllegalArgumentException if the return type of {@code filter}
5777      *          is non-void and is not the same as the {@code pos} argument of the target,
5778      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5779      *          or if the resulting method handle's type would have
5780      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5781      * @see MethodHandles#foldArguments
5782      * @see MethodHandles#filterArguments
5783      * @see MethodHandles#filterReturnValue
5784      */
5785     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5786         MethodType newType = collectArgumentsChecks(target, pos, filter);
5787         MethodType collectorType = filter.type();
5788         BoundMethodHandle result = target.rebind();
5789         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5790         return result.copyWithExtendL(newType, lform, filter);
5791     }
5792 
5793     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5794         MethodType targetType = target.type();
5795         MethodType filterType = filter.type();
5796         Class<?> rtype = filterType.returnType();
5797         List<Class<?>> filterArgs = filterType.parameterList();
5798         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5799                        (rtype != void.class && pos >= targetType.parameterCount())) {
5800             throw newIllegalArgumentException("position is out of range for target", target, pos);
5801         }
5802         if (rtype == void.class) {
5803             return targetType.insertParameterTypes(pos, filterArgs);
5804         }
5805         if (rtype != targetType.parameterType(pos)) {
5806             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5807         }
5808         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5809     }
5810 
5811     /**
5812      * Adapts a target method handle by post-processing
5813      * its return value (if any) with a filter (another method handle).
5814      * The result of the filter is returned from the adapter.
5815      * <p>
5816      * If the target returns a value, the filter must accept that value as
5817      * its only argument.
5818      * If the target returns void, the filter must accept no arguments.
5819      * <p>
5820      * The return type of the filter
5821      * replaces the return type of the target
5822      * in the resulting adapted method handle.
5823      * The argument type of the filter (if any) must be identical to the
5824      * return type of the target.
5825      * <p><b>Example:</b>
5826      * <blockquote><pre>{@code
5827 import static java.lang.invoke.MethodHandles.*;
5828 import static java.lang.invoke.MethodType.*;
5829 ...
5830 MethodHandle cat = lookup().findVirtual(String.class,
5831   "concat", methodType(String.class, String.class));
5832 MethodHandle length = lookup().findVirtual(String.class,
5833   "length", methodType(int.class));
5834 System.out.println((String) cat.invokeExact("x", "y")); // xy
5835 MethodHandle f0 = filterReturnValue(cat, length);
5836 System.out.println((int) f0.invokeExact("x", "y")); // 2
5837      * }</pre></blockquote>
5838      * <p>Here is pseudocode for the resulting adapter. In the code,
5839      * {@code T}/{@code t} represent the result type and value of the
5840      * {@code target}; {@code V}, the result type of the {@code filter}; and
5841      * {@code A}/{@code a}, the types and values of the parameters and arguments
5842      * of the {@code target} as well as the resulting adapter.
5843      * <blockquote><pre>{@code
5844      * T target(A...);
5845      * V filter(T);
5846      * V adapter(A... a) {
5847      *   T t = target(a...);
5848      *   return filter(t);
5849      * }
5850      * // and if the target has a void return:
5851      * void target2(A...);
5852      * V filter2();
5853      * V adapter2(A... a) {
5854      *   target2(a...);
5855      *   return filter2();
5856      * }
5857      * // and if the filter has a void return:
5858      * T target3(A...);
5859      * void filter3(V);
5860      * void adapter3(A... a) {
5861      *   T t = target3(a...);
5862      *   filter3(t);
5863      * }
5864      * }</pre></blockquote>
5865      * <p>
5866      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5867      * variable-arity method handle}, even if the original target method handle was.
5868      * @param target the method handle to invoke before filtering the return value
5869      * @param filter method handle to call on the return value
5870      * @return method handle which incorporates the specified return value filtering logic
5871      * @throws NullPointerException if either argument is null
5872      * @throws IllegalArgumentException if the argument list of {@code filter}
5873      *          does not match the return type of target as described above
5874      */
5875     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5876         MethodType targetType = target.type();
5877         MethodType filterType = filter.type();
5878         filterReturnValueChecks(targetType, filterType);
5879         BoundMethodHandle result = target.rebind();
5880         BasicType rtype = BasicType.basicType(filterType.returnType());
5881         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5882         MethodType newType = targetType.changeReturnType(filterType.returnType());
5883         result = result.copyWithExtendL(newType, lform, filter);
5884         return result;
5885     }
5886 
5887     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5888         Class<?> rtype = targetType.returnType();
5889         int filterValues = filterType.parameterCount();
5890         if (filterValues == 0
5891                 ? (rtype != void.class)
5892                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5893             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5894     }
5895 
5896     /**
5897      * Filter the return value of a target method handle with a filter function. The filter function is
5898      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5899      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5900      * as follows:
5901      * <blockquote><pre>{@code
5902      * T target(A...)
5903      * V filter(B... , T)
5904      * V adapter(A... a, B... b) {
5905      *     T t = target(a...);
5906      *     return filter(b..., t);
5907      * }</pre></blockquote>
5908      * <p>
5909      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5910      *
5911      * @param target the target method handle
5912      * @param filter the filter method handle
5913      * @return the adapter method handle
5914      */
5915     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5916         MethodType targetType = target.type();
5917         MethodType filterType = filter.type();
5918         BoundMethodHandle result = target.rebind();
5919         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5920         MethodType newType = targetType.changeReturnType(filterType.returnType());
5921         if (filterType.parameterCount() > 1) {
5922             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5923                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5924             }
5925         }
5926         result = result.copyWithExtendL(newType, lform, filter);
5927         return result;
5928     }
5929 
5930     /**
5931      * Adapts a target method handle by pre-processing
5932      * some of its arguments, and then calling the target with
5933      * the result of the pre-processing, inserted into the original
5934      * sequence of arguments.
5935      * <p>
5936      * The pre-processing is performed by {@code combiner}, a second method handle.
5937      * Of the arguments passed to the adapter, the first {@code N} arguments
5938      * are copied to the combiner, which is then called.
5939      * (Here, {@code N} is defined as the parameter count of the combiner.)
5940      * After this, control passes to the target, with any result
5941      * from the combiner inserted before the original {@code N} incoming
5942      * arguments.
5943      * <p>
5944      * If the combiner returns a value, the first parameter type of the target
5945      * must be identical with the return type of the combiner, and the next
5946      * {@code N} parameter types of the target must exactly match the parameters
5947      * of the combiner.
5948      * <p>
5949      * If the combiner has a void return, no result will be inserted,
5950      * and the first {@code N} parameter types of the target
5951      * must exactly match the parameters of the combiner.
5952      * <p>
5953      * The resulting adapter is the same type as the target, except that the
5954      * first parameter type is dropped,
5955      * if it corresponds to the result of the combiner.
5956      * <p>
5957      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5958      * that either the combiner or the target does not wish to receive.
5959      * If some of the incoming arguments are destined only for the combiner,
5960      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5961      * arguments will not need to be live on the stack on entry to the
5962      * target.)
5963      * <p><b>Example:</b>
5964      * <blockquote><pre>{@code
5965 import static java.lang.invoke.MethodHandles.*;
5966 import static java.lang.invoke.MethodType.*;
5967 ...
5968 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5969   "println", methodType(void.class, String.class))
5970     .bindTo(System.out);
5971 MethodHandle cat = lookup().findVirtual(String.class,
5972   "concat", methodType(String.class, String.class));
5973 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5974 MethodHandle catTrace = foldArguments(cat, trace);
5975 // also prints "boo":
5976 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5977      * }</pre></blockquote>
5978      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5979      * represents the result type of the {@code target} and resulting adapter.
5980      * {@code V}/{@code v} represent the type and value of the parameter and argument
5981      * of {@code target} that precedes the folding position; {@code V} also is
5982      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5983      * types and values of the {@code N} parameters and arguments at the folding
5984      * position. {@code B}/{@code b} represent the types and values of the
5985      * {@code target} parameters and arguments that follow the folded parameters
5986      * and arguments.
5987      * <blockquote><pre>{@code
5988      * // there are N arguments in A...
5989      * T target(V, A[N]..., B...);
5990      * V combiner(A...);
5991      * T adapter(A... a, B... b) {
5992      *   V v = combiner(a...);
5993      *   return target(v, a..., b...);
5994      * }
5995      * // and if the combiner has a void return:
5996      * T target2(A[N]..., B...);
5997      * void combiner2(A...);
5998      * T adapter2(A... a, B... b) {
5999      *   combiner2(a...);
6000      *   return target2(a..., b...);
6001      * }
6002      * }</pre></blockquote>
6003      * <p>
6004      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6005      * variable-arity method handle}, even if the original target method handle was.
6006      * @param target the method handle to invoke after arguments are combined
6007      * @param combiner method handle to call initially on the incoming arguments
6008      * @return method handle which incorporates the specified argument folding logic
6009      * @throws NullPointerException if either argument is null
6010      * @throws IllegalArgumentException if {@code combiner}'s return type
6011      *          is non-void and not the same as the first argument type of
6012      *          the target, or if the initial {@code N} argument types
6013      *          of the target
6014      *          (skipping one matching the {@code combiner}'s return type)
6015      *          are not identical with the argument types of {@code combiner}
6016      */
6017     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6018         return foldArguments(target, 0, combiner);
6019     }
6020 
6021     /**
6022      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6023      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6024      * before the folded arguments.
6025      * <p>
6026      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6027      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6028      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6029      * 0.
6030      *
6031      * @apiNote Example:
6032      * <blockquote><pre>{@code
6033     import static java.lang.invoke.MethodHandles.*;
6034     import static java.lang.invoke.MethodType.*;
6035     ...
6036     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6037     "println", methodType(void.class, String.class))
6038     .bindTo(System.out);
6039     MethodHandle cat = lookup().findVirtual(String.class,
6040     "concat", methodType(String.class, String.class));
6041     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6042     MethodHandle catTrace = foldArguments(cat, 1, trace);
6043     // also prints "jum":
6044     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6045      * }</pre></blockquote>
6046      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6047      * represents the result type of the {@code target} and resulting adapter.
6048      * {@code V}/{@code v} represent the type and value of the parameter and argument
6049      * of {@code target} that precedes the folding position; {@code V} also is
6050      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6051      * types and values of the {@code N} parameters and arguments at the folding
6052      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6053      * and values of the {@code target} parameters and arguments that precede and
6054      * follow the folded parameters and arguments starting at {@code pos},
6055      * respectively.
6056      * <blockquote><pre>{@code
6057      * // there are N arguments in A...
6058      * T target(Z..., V, A[N]..., B...);
6059      * V combiner(A...);
6060      * T adapter(Z... z, A... a, B... b) {
6061      *   V v = combiner(a...);
6062      *   return target(z..., v, a..., b...);
6063      * }
6064      * // and if the combiner has a void return:
6065      * T target2(Z..., A[N]..., B...);
6066      * void combiner2(A...);
6067      * T adapter2(Z... z, A... a, B... b) {
6068      *   combiner2(a...);
6069      *   return target2(z..., a..., b...);
6070      * }
6071      * }</pre></blockquote>
6072      * <p>
6073      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6074      * variable-arity method handle}, even if the original target method handle was.
6075      *
6076      * @param target the method handle to invoke after arguments are combined
6077      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6078      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6079      * @param combiner method handle to call initially on the incoming arguments
6080      * @return method handle which incorporates the specified argument folding logic
6081      * @throws NullPointerException if either argument is null
6082      * @throws IllegalArgumentException if either of the following two conditions holds:
6083      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6084      *              {@code pos} of the target signature;
6085      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6086      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6087      *
6088      * @see #foldArguments(MethodHandle, MethodHandle)
6089      * @since 9
6090      */
6091     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6092         MethodType targetType = target.type();
6093         MethodType combinerType = combiner.type();
6094         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6095         BoundMethodHandle result = target.rebind();
6096         boolean dropResult = rtype == void.class;
6097         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6098         MethodType newType = targetType;
6099         if (!dropResult) {
6100             newType = newType.dropParameterTypes(pos, pos + 1);
6101         }
6102         result = result.copyWithExtendL(newType, lform, combiner);
6103         return result;
6104     }
6105 
6106     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6107         int foldArgs   = combinerType.parameterCount();
6108         Class<?> rtype = combinerType.returnType();
6109         int foldVals = rtype == void.class ? 0 : 1;
6110         int afterInsertPos = foldPos + foldVals;
6111         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6112         if (ok) {
6113             for (int i = 0; i < foldArgs; i++) {
6114                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6115                     ok = false;
6116                     break;
6117                 }
6118             }
6119         }
6120         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6121             ok = false;
6122         if (!ok)
6123             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6124         return rtype;
6125     }
6126 
6127     /**
6128      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6129      * of the pre-processing replacing the argument at the given position.
6130      *
6131      * @param target the method handle to invoke after arguments are combined
6132      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6133      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6134      * @param combiner method handle to call initially on the incoming arguments
6135      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6136      * @return method handle which incorporates the specified argument folding logic
6137      * @throws NullPointerException if either argument is null
6138      * @throws IllegalArgumentException if either of the following two conditions holds:
6139      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6140      *              {@code pos} of the target signature;
6141      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6142      *              not identical with the argument types of {@code combiner}.
6143      */
6144     /*non-public*/
6145     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6146         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6147     }
6148 
6149     /**
6150      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6151      * the pre-processing inserted into the original sequence of arguments at the given position.
6152      *
6153      * @param target the method handle to invoke after arguments are combined
6154      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6155      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6156      * @param combiner method handle to call initially on the incoming arguments
6157      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6158      * @return method handle which incorporates the specified argument folding logic
6159      * @throws NullPointerException if either argument is null
6160      * @throws IllegalArgumentException if either of the following two conditions holds:
6161      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6162      *              {@code pos} of the target signature;
6163      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6164      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6165      *              with the argument types of {@code combiner}.
6166      */
6167     /*non-public*/
6168     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6169         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6170     }
6171 
6172     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6173         MethodType targetType = target.type();
6174         MethodType combinerType = combiner.type();
6175         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6176         BoundMethodHandle result = target.rebind();
6177 
6178         MethodType newType = targetType;
6179         LambdaForm lform;
6180         if (filter) {
6181             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6182         } else {
6183             boolean dropResult = rtype == void.class;
6184             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6185             if (!dropResult) {
6186                 newType = newType.dropParameterTypes(position, position + 1);
6187             }
6188         }
6189         result = result.copyWithExtendL(newType, lform, combiner);
6190         return result;
6191     }
6192 
6193     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6194         int combinerArgs = combinerType.parameterCount();
6195         if (argPos.length != combinerArgs) {
6196             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6197         }
6198         Class<?> rtype = combinerType.returnType();
6199 
6200         for (int i = 0; i < combinerArgs; i++) {
6201             int arg = argPos[i];
6202             if (arg < 0 || arg > targetType.parameterCount()) {
6203                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6204             }
6205             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6206                 throw newIllegalArgumentException("target argument type at position " + arg
6207                         + " must match combiner argument type at index " + i + ": " + targetType
6208                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6209             }
6210         }
6211         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6212             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6213         }
6214         return rtype;
6215     }
6216 
6217     /**
6218      * Makes a method handle which adapts a target method handle,
6219      * by guarding it with a test, a boolean-valued method handle.
6220      * If the guard fails, a fallback handle is called instead.
6221      * All three method handles must have the same corresponding
6222      * argument and return types, except that the return type
6223      * of the test must be boolean, and the test is allowed
6224      * to have fewer arguments than the other two method handles.
6225      * <p>
6226      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6227      * represents the uniform result type of the three involved handles;
6228      * {@code A}/{@code a}, the types and values of the {@code target}
6229      * parameters and arguments that are consumed by the {@code test}; and
6230      * {@code B}/{@code b}, those types and values of the {@code target}
6231      * parameters and arguments that are not consumed by the {@code test}.
6232      * <blockquote><pre>{@code
6233      * boolean test(A...);
6234      * T target(A...,B...);
6235      * T fallback(A...,B...);
6236      * T adapter(A... a,B... b) {
6237      *   if (test(a...))
6238      *     return target(a..., b...);
6239      *   else
6240      *     return fallback(a..., b...);
6241      * }
6242      * }</pre></blockquote>
6243      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6244      * be modified by execution of the test, and so are passed unchanged
6245      * from the caller to the target or fallback as appropriate.
6246      * @param test method handle used for test, must return boolean
6247      * @param target method handle to call if test passes
6248      * @param fallback method handle to call if test fails
6249      * @return method handle which incorporates the specified if/then/else logic
6250      * @throws NullPointerException if any argument is null
6251      * @throws IllegalArgumentException if {@code test} does not return boolean,
6252      *          or if all three method types do not match (with the return
6253      *          type of {@code test} changed to match that of the target).
6254      */
6255     public static MethodHandle guardWithTest(MethodHandle test,
6256                                MethodHandle target,
6257                                MethodHandle fallback) {
6258         MethodType gtype = test.type();
6259         MethodType ttype = target.type();
6260         MethodType ftype = fallback.type();
6261         if (!ttype.equals(ftype))
6262             throw misMatchedTypes("target and fallback types", ttype, ftype);
6263         if (gtype.returnType() != boolean.class)
6264             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6265         List<Class<?>> targs = ttype.parameterList();
6266         test = dropArgumentsToMatch(test, 0, targs, 0, true);
6267         if (test == null) {
6268             throw misMatchedTypes("target and test types", ttype, gtype);
6269         }
6270         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6271     }
6272 
6273     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6274         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6275     }
6276 
6277     /**
6278      * Makes a method handle which adapts a target method handle,
6279      * by running it inside an exception handler.
6280      * If the target returns normally, the adapter returns that value.
6281      * If an exception matching the specified type is thrown, the fallback
6282      * handle is called instead on the exception, plus the original arguments.
6283      * <p>
6284      * The target and handler must have the same corresponding
6285      * argument and return types, except that handler may omit trailing arguments
6286      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6287      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6288      * <p>
6289      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6290      * represents the return type of the {@code target} and {@code handler},
6291      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6292      * the types and values of arguments to the resulting handle consumed by
6293      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6294      * resulting handle discarded by {@code handler}.
6295      * <blockquote><pre>{@code
6296      * T target(A..., B...);
6297      * T handler(ExType, A...);
6298      * T adapter(A... a, B... b) {
6299      *   try {
6300      *     return target(a..., b...);
6301      *   } catch (ExType ex) {
6302      *     return handler(ex, a...);
6303      *   }
6304      * }
6305      * }</pre></blockquote>
6306      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6307      * be modified by execution of the target, and so are passed unchanged
6308      * from the caller to the handler, if the handler is invoked.
6309      * <p>
6310      * The target and handler must return the same type, even if the handler
6311      * always throws.  (This might happen, for instance, because the handler
6312      * is simulating a {@code finally} clause).
6313      * To create such a throwing handler, compose the handler creation logic
6314      * with {@link #throwException throwException},
6315      * in order to create a method handle of the correct return type.
6316      * @param target method handle to call
6317      * @param exType the type of exception which the handler will catch
6318      * @param handler method handle to call if a matching exception is thrown
6319      * @return method handle which incorporates the specified try/catch logic
6320      * @throws NullPointerException if any argument is null
6321      * @throws IllegalArgumentException if {@code handler} does not accept
6322      *          the given exception type, or if the method handle types do
6323      *          not match in their return types and their
6324      *          corresponding parameters
6325      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6326      */
6327     public static MethodHandle catchException(MethodHandle target,
6328                                 Class<? extends Throwable> exType,
6329                                 MethodHandle handler) {
6330         MethodType ttype = target.type();
6331         MethodType htype = handler.type();
6332         if (!Throwable.class.isAssignableFrom(exType))
6333             throw new ClassCastException(exType.getName());
6334         if (htype.parameterCount() < 1 ||
6335             !htype.parameterType(0).isAssignableFrom(exType))
6336             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6337         if (htype.returnType() != ttype.returnType())
6338             throw misMatchedTypes("target and handler return types", ttype, htype);
6339         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
6340         if (handler == null) {
6341             throw misMatchedTypes("target and handler types", ttype, htype);
6342         }
6343         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6344     }
6345 
6346     /**
6347      * Produces a method handle which will throw exceptions of the given {@code exType}.
6348      * The method handle will accept a single argument of {@code exType},
6349      * and immediately throw it as an exception.
6350      * The method type will nominally specify a return of {@code returnType}.
6351      * The return type may be anything convenient:  It doesn't matter to the
6352      * method handle's behavior, since it will never return normally.
6353      * @param returnType the return type of the desired method handle
6354      * @param exType the parameter type of the desired method handle
6355      * @return method handle which can throw the given exceptions
6356      * @throws NullPointerException if either argument is null
6357      */
6358     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6359         if (!Throwable.class.isAssignableFrom(exType))
6360             throw new ClassCastException(exType.getName());
6361         return MethodHandleImpl.throwException(methodType(returnType, exType));
6362     }
6363 
6364     /**
6365      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6366      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6367      * delivers the loop's result, which is the return value of the resulting handle.
6368      * <p>
6369      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6370      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6371      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6372      * terms of method handles, each clause will specify up to four independent actions:<ul>
6373      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6374      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6375      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6376      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6377      * </ul>
6378      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6379      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6380      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6381      * <p>
6382      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6383      * this case. See below for a detailed description.
6384      * <p>
6385      * <em>Parameters optional everywhere:</em>
6386      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6387      * As an exception, the init functions cannot take any {@code v} parameters,
6388      * because those values are not yet computed when the init functions are executed.
6389      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6390      * In fact, any clause function may take no arguments at all.
6391      * <p>
6392      * <em>Loop parameters:</em>
6393      * A clause function may take all the iteration variable values it is entitled to, in which case
6394      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6395      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6396      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6397      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6398      * init function is automatically a loop parameter {@code a}.)
6399      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6400      * These loop parameters act as loop-invariant values visible across the whole loop.
6401      * <p>
6402      * <em>Parameters visible everywhere:</em>
6403      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6404      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6405      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6406      * Most clause functions will not need all of this information, but they will be formally connected to it
6407      * as if by {@link #dropArguments}.
6408      * <a id="astar"></a>
6409      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6410      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6411      * In that notation, the general form of an init function parameter list
6412      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6413      * <p>
6414      * <em>Checking clause structure:</em>
6415      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6416      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6417      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6418      * met by the inputs to the loop combinator.
6419      * <p>
6420      * <em>Effectively identical sequences:</em>
6421      * <a id="effid"></a>
6422      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6423      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6424      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6425      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6426      * that longest list.
6427      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6428      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6429      * <p>
6430      * <em>Step 0: Determine clause structure.</em><ol type="a">
6431      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6432      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6433      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6434      * four. Padding takes place by appending elements to the array.
6435      * <li>Clauses with all {@code null}s are disregarded.
6436      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6437      * </ol>
6438      * <p>
6439      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6440      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6441      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6442      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6443      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6444      * iteration variable type.
6445      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6446      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6447      * </ol>
6448      * <p>
6449      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6450      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6451      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6452      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6453      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6454      * (These types will be checked in step 2, along with all the clause function types.)
6455      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6456      * <li>All of the collected parameter lists must be effectively identical.
6457      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6458      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6459      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6460      * the "internal parameter list".
6461      * </ul>
6462      * <p>
6463      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6464      * <li>Examine fini function return types, disregarding omitted fini functions.
6465      * <li>If there are no fini functions, the loop return type is {@code void}.
6466      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6467      * type.
6468      * </ol>
6469      * <p>
6470      * <em>Step 1D: Check other types.</em><ol type="a">
6471      * <li>There must be at least one non-omitted pred function.
6472      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6473      * </ol>
6474      * <p>
6475      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6476      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6477      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6478      * (Note that their parameter lists are already effectively identical to this list.)
6479      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6480      * effectively identical to the internal parameter list {@code (V... A...)}.
6481      * </ol>
6482      * <p>
6483      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6484      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6485      * type.
6486      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6487      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6488      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6489      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6490      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6491      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6492      * loop return type.
6493      * </ol>
6494      * <p>
6495      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6496      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6497      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6498      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6499      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6500      * pad out the end of the list.
6501      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6502      * </ol>
6503      * <p>
6504      * <em>Final observations.</em><ol type="a">
6505      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6506      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6507      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6508      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6509      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6510      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6511      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6512      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6513      * </ol>
6514      * <p>
6515      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6516      * <ul>
6517      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6518      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6519      * (Only one {@code Pn} has to be non-{@code null}.)
6520      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6521      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6522      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6523      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6524      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6525      * the resulting loop handle's parameter types {@code (A...)}.
6526      * </ul>
6527      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6528      * which is natural if most of the loop computation happens in the steps.  For some loops,
6529      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6530      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6531      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6532      * where the init functions will need the extra parameters.  For such reasons, the rules for
6533      * determining these parameters are as symmetric as possible, across all clause parts.
6534      * In general, the loop parameters function as common invariant values across the whole
6535      * loop, while the iteration variables function as common variant values, or (if there is
6536      * no step function) as internal loop invariant temporaries.
6537      * <p>
6538      * <em>Loop execution.</em><ol type="a">
6539      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6540      * every clause function. These locals are loop invariant.
6541      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6542      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6543      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6544      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6545      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6546      * (in argument order).
6547      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6548      * returns {@code false}.
6549      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6550      * sequence {@code (v...)} of loop variables.
6551      * The updated value is immediately visible to all subsequent function calls.
6552      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6553      * (of type {@code R}) is returned from the loop as a whole.
6554      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6555      * except by throwing an exception.
6556      * </ol>
6557      * <p>
6558      * <em>Usage tips.</em>
6559      * <ul>
6560      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6561      * sometimes a step function only needs to observe the current value of its own variable.
6562      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6563      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6564      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6565      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6566      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6567      * <li>If some of the clause functions are virtual methods on an instance, the instance
6568      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6569      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6570      * will be the first iteration variable value, and it will be easy to use virtual
6571      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6572      * </ul>
6573      * <p>
6574      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6575      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6576      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6577      * <blockquote><pre>{@code
6578      * V... init...(A...);
6579      * boolean pred...(V..., A...);
6580      * V... step...(V..., A...);
6581      * R fini...(V..., A...);
6582      * R loop(A... a) {
6583      *   V... v... = init...(a...);
6584      *   for (;;) {
6585      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6586      *       v = s(v..., a...);
6587      *       if (!p(v..., a...)) {
6588      *         return f(v..., a...);
6589      *       }
6590      *     }
6591      *   }
6592      * }
6593      * }</pre></blockquote>
6594      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6595      * to their full length, even though individual clause functions may neglect to take them all.
6596      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6597      *
6598      * @apiNote Example:
6599      * <blockquote><pre>{@code
6600      * // iterative implementation of the factorial function as a loop handle
6601      * static int one(int k) { return 1; }
6602      * static int inc(int i, int acc, int k) { return i + 1; }
6603      * static int mult(int i, int acc, int k) { return i * acc; }
6604      * static boolean pred(int i, int acc, int k) { return i < k; }
6605      * static int fin(int i, int acc, int k) { return acc; }
6606      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6607      * // null initializer for counter, should initialize to 0
6608      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6609      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6610      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6611      * assertEquals(120, loop.invoke(5));
6612      * }</pre></blockquote>
6613      * The same example, dropping arguments and using combinators:
6614      * <blockquote><pre>{@code
6615      * // simplified implementation of the factorial function as a loop handle
6616      * static int inc(int i) { return i + 1; } // drop acc, k
6617      * static int mult(int i, int acc) { return i * acc; } //drop k
6618      * static boolean cmp(int i, int k) { return i < k; }
6619      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6620      * // null initializer for counter, should initialize to 0
6621      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6622      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6623      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6624      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6625      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6626      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6627      * assertEquals(720, loop.invoke(6));
6628      * }</pre></blockquote>
6629      * A similar example, using a helper object to hold a loop parameter:
6630      * <blockquote><pre>{@code
6631      * // instance-based implementation of the factorial function as a loop handle
6632      * static class FacLoop {
6633      *   final int k;
6634      *   FacLoop(int k) { this.k = k; }
6635      *   int inc(int i) { return i + 1; }
6636      *   int mult(int i, int acc) { return i * acc; }
6637      *   boolean pred(int i) { return i < k; }
6638      *   int fin(int i, int acc) { return acc; }
6639      * }
6640      * // assume MH_FacLoop is a handle to the constructor
6641      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6642      * // null initializer for counter, should initialize to 0
6643      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6644      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6645      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6646      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6647      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6648      * assertEquals(5040, loop.invoke(7));
6649      * }</pre></blockquote>
6650      *
6651      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6652      *
6653      * @return a method handle embodying the looping behavior as defined by the arguments.
6654      *
6655      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6656      *
6657      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6658      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6659      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6660      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6661      * @since 9
6662      */
6663     public static MethodHandle loop(MethodHandle[]... clauses) {
6664         // Step 0: determine clause structure.
6665         loopChecks0(clauses);
6666 
6667         List<MethodHandle> init = new ArrayList<>();
6668         List<MethodHandle> step = new ArrayList<>();
6669         List<MethodHandle> pred = new ArrayList<>();
6670         List<MethodHandle> fini = new ArrayList<>();
6671 
6672         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6673             init.add(clause[0]); // all clauses have at least length 1
6674             step.add(clause.length <= 1 ? null : clause[1]);
6675             pred.add(clause.length <= 2 ? null : clause[2]);
6676             fini.add(clause.length <= 3 ? null : clause[3]);
6677         });
6678 
6679         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6680         final int nclauses = init.size();
6681 
6682         // Step 1A: determine iteration variables (V...).
6683         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6684         for (int i = 0; i < nclauses; ++i) {
6685             MethodHandle in = init.get(i);
6686             MethodHandle st = step.get(i);
6687             if (in == null && st == null) {
6688                 iterationVariableTypes.add(void.class);
6689             } else if (in != null && st != null) {
6690                 loopChecks1a(i, in, st);
6691                 iterationVariableTypes.add(in.type().returnType());
6692             } else {
6693                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6694             }
6695         }
6696         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6697 
6698         // Step 1B: determine loop parameters (A...).
6699         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6700         loopChecks1b(init, commonSuffix);
6701 
6702         // Step 1C: determine loop return type.
6703         // Step 1D: check other types.
6704         // local variable required here; see JDK-8223553
6705         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6706                 .map(MethodType::returnType);
6707         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6708         loopChecks1cd(pred, fini, loopReturnType);
6709 
6710         // Step 2: determine parameter lists.
6711         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6712         commonParameterSequence.addAll(commonSuffix);
6713         loopChecks2(step, pred, fini, commonParameterSequence);
6714 
6715         // Step 3: fill in omitted functions.
6716         for (int i = 0; i < nclauses; ++i) {
6717             Class<?> t = iterationVariableTypes.get(i);
6718             if (init.get(i) == null) {
6719                 init.set(i, empty(methodType(t, commonSuffix)));
6720             }
6721             if (step.get(i) == null) {
6722                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6723             }
6724             if (pred.get(i) == null) {
6725                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6726             }
6727             if (fini.get(i) == null) {
6728                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6729             }
6730         }
6731 
6732         // Step 4: fill in missing parameter types.
6733         // Also convert all handles to fixed-arity handles.
6734         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6735         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6736         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6737         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6738 
6739         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6740                 allMatch(pl -> pl.equals(commonSuffix));
6741         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6742                 allMatch(pl -> pl.equals(commonParameterSequence));
6743 
6744         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6745     }
6746 
6747     private static void loopChecks0(MethodHandle[][] clauses) {
6748         if (clauses == null || clauses.length == 0) {
6749             throw newIllegalArgumentException("null or no clauses passed");
6750         }
6751         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6752             throw newIllegalArgumentException("null clauses are not allowed");
6753         }
6754         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6755             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6756         }
6757     }
6758 
6759     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6760         if (in.type().returnType() != st.type().returnType()) {
6761             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6762                     st.type().returnType());
6763         }
6764     }
6765 
6766     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6767         final List<Class<?>> empty = List.of();
6768         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6769                 // take only those that can contribute to a common suffix because they are longer than the prefix
6770                         map(MethodHandle::type).
6771                         filter(t -> t.parameterCount() > skipSize).
6772                         map(MethodType::parameterList).
6773                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6774         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6775     }
6776 
6777     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6778         final List<Class<?>> empty = List.of();
6779         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6780     }
6781 
6782     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6783         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6784         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6785         return longestParameterList(Arrays.asList(longest1, longest2));
6786     }
6787 
6788     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6789         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6790                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6791             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6792                     " (common suffix: " + commonSuffix + ")");
6793         }
6794     }
6795 
6796     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6797         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6798                 anyMatch(t -> t != loopReturnType)) {
6799             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6800                     loopReturnType + ")");
6801         }
6802 
6803         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6804             throw newIllegalArgumentException("no predicate found", pred);
6805         }
6806         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6807                 anyMatch(t -> t != boolean.class)) {
6808             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6809         }
6810     }
6811 
6812     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6813         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6814                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6815             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6816                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6817         }
6818     }
6819 
6820     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6821         return hs.stream().map(h -> {
6822             int pc = h.type().parameterCount();
6823             int tpsize = targetParams.size();
6824             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6825         }).toList();
6826     }
6827 
6828     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6829         return hs.stream().map(MethodHandle::asFixedArity).toList();
6830     }
6831 
6832     /**
6833      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6834      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6835      * <p>
6836      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6837      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6838      * evaluates to {@code true}).
6839      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6840      * <p>
6841      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6842      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6843      * and updated with the value returned from its invocation. The result of loop execution will be
6844      * the final value of the additional loop-local variable (if present).
6845      * <p>
6846      * The following rules hold for these argument handles:<ul>
6847      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6848      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6849      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6850      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6851      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6852      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6853      * It will constrain the parameter lists of the other loop parts.
6854      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6855      * list {@code (A...)} is called the <em>external parameter list</em>.
6856      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6857      * additional state variable of the loop.
6858      * The body must both accept and return a value of this type {@code V}.
6859      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6860      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6861      * <a href="MethodHandles.html#effid">effectively identical</a>
6862      * to the external parameter list {@code (A...)}.
6863      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6864      * {@linkplain #empty default value}.
6865      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6866      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6867      * effectively identical to the internal parameter list.
6868      * </ul>
6869      * <p>
6870      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6871      * <li>The loop handle's result type is the result type {@code V} of the body.
6872      * <li>The loop handle's parameter types are the types {@code (A...)},
6873      * from the external parameter list.
6874      * </ul>
6875      * <p>
6876      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6877      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6878      * passed to the loop.
6879      * <blockquote><pre>{@code
6880      * V init(A...);
6881      * boolean pred(V, A...);
6882      * V body(V, A...);
6883      * V whileLoop(A... a...) {
6884      *   V v = init(a...);
6885      *   while (pred(v, a...)) {
6886      *     v = body(v, a...);
6887      *   }
6888      *   return v;
6889      * }
6890      * }</pre></blockquote>
6891      *
6892      * @apiNote Example:
6893      * <blockquote><pre>{@code
6894      * // implement the zip function for lists as a loop handle
6895      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6896      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6897      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6898      *   zip.add(a.next());
6899      *   zip.add(b.next());
6900      *   return zip;
6901      * }
6902      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6903      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6904      * List<String> a = Arrays.asList("a", "b", "c", "d");
6905      * List<String> b = Arrays.asList("e", "f", "g", "h");
6906      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6907      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6908      * }</pre></blockquote>
6909      *
6910      *
6911      * @apiNote The implementation of this method can be expressed as follows:
6912      * <blockquote><pre>{@code
6913      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6914      *     MethodHandle fini = (body.type().returnType() == void.class
6915      *                         ? null : identity(body.type().returnType()));
6916      *     MethodHandle[]
6917      *         checkExit = { null, null, pred, fini },
6918      *         varBody   = { init, body };
6919      *     return loop(checkExit, varBody);
6920      * }
6921      * }</pre></blockquote>
6922      *
6923      * @param init optional initializer, providing the initial value of the loop variable.
6924      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6925      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6926      *             above for other constraints.
6927      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6928      *             See above for other constraints.
6929      *
6930      * @return a method handle implementing the {@code while} loop as described by the arguments.
6931      * @throws IllegalArgumentException if the rules for the arguments are violated.
6932      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6933      *
6934      * @see #loop(MethodHandle[][])
6935      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6936      * @since 9
6937      */
6938     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6939         whileLoopChecks(init, pred, body);
6940         MethodHandle fini = identityOrVoid(body.type().returnType());
6941         MethodHandle[] checkExit = { null, null, pred, fini };
6942         MethodHandle[] varBody = { init, body };
6943         return loop(checkExit, varBody);
6944     }
6945 
6946     /**
6947      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6948      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6949      * <p>
6950      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6951      * method will, in each iteration, first execute its body and then evaluate the predicate.
6952      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6953      * <p>
6954      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6955      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6956      * and updated with the value returned from its invocation. The result of loop execution will be
6957      * the final value of the additional loop-local variable (if present).
6958      * <p>
6959      * The following rules hold for these argument handles:<ul>
6960      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6961      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6962      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6963      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6964      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6965      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6966      * It will constrain the parameter lists of the other loop parts.
6967      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6968      * list {@code (A...)} is called the <em>external parameter list</em>.
6969      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6970      * additional state variable of the loop.
6971      * The body must both accept and return a value of this type {@code V}.
6972      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6973      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6974      * <a href="MethodHandles.html#effid">effectively identical</a>
6975      * to the external parameter list {@code (A...)}.
6976      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6977      * {@linkplain #empty default value}.
6978      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6979      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6980      * effectively identical to the internal parameter list.
6981      * </ul>
6982      * <p>
6983      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6984      * <li>The loop handle's result type is the result type {@code V} of the body.
6985      * <li>The loop handle's parameter types are the types {@code (A...)},
6986      * from the external parameter list.
6987      * </ul>
6988      * <p>
6989      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6990      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6991      * passed to the loop.
6992      * <blockquote><pre>{@code
6993      * V init(A...);
6994      * boolean pred(V, A...);
6995      * V body(V, A...);
6996      * V doWhileLoop(A... a...) {
6997      *   V v = init(a...);
6998      *   do {
6999      *     v = body(v, a...);
7000      *   } while (pred(v, a...));
7001      *   return v;
7002      * }
7003      * }</pre></blockquote>
7004      *
7005      * @apiNote Example:
7006      * <blockquote><pre>{@code
7007      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7008      * static int zero(int limit) { return 0; }
7009      * static int step(int i, int limit) { return i + 1; }
7010      * static boolean pred(int i, int limit) { return i < limit; }
7011      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7012      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7013      * assertEquals(23, loop.invoke(23));
7014      * }</pre></blockquote>
7015      *
7016      *
7017      * @apiNote The implementation of this method can be expressed as follows:
7018      * <blockquote><pre>{@code
7019      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7020      *     MethodHandle fini = (body.type().returnType() == void.class
7021      *                         ? null : identity(body.type().returnType()));
7022      *     MethodHandle[] clause = { init, body, pred, fini };
7023      *     return loop(clause);
7024      * }
7025      * }</pre></blockquote>
7026      *
7027      * @param init optional initializer, providing the initial value of the loop variable.
7028      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7029      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7030      *             See above for other constraints.
7031      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7032      *             above for other constraints.
7033      *
7034      * @return a method handle implementing the {@code while} loop as described by the arguments.
7035      * @throws IllegalArgumentException if the rules for the arguments are violated.
7036      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7037      *
7038      * @see #loop(MethodHandle[][])
7039      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7040      * @since 9
7041      */
7042     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7043         whileLoopChecks(init, pred, body);
7044         MethodHandle fini = identityOrVoid(body.type().returnType());
7045         MethodHandle[] clause = {init, body, pred, fini };
7046         return loop(clause);
7047     }
7048 
7049     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7050         Objects.requireNonNull(pred);
7051         Objects.requireNonNull(body);
7052         MethodType bodyType = body.type();
7053         Class<?> returnType = bodyType.returnType();
7054         List<Class<?>> innerList = bodyType.parameterList();
7055         List<Class<?>> outerList = innerList;
7056         if (returnType == void.class) {
7057             // OK
7058         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7059             // leading V argument missing => error
7060             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7061             throw misMatchedTypes("body function", bodyType, expected);
7062         } else {
7063             outerList = innerList.subList(1, innerList.size());
7064         }
7065         MethodType predType = pred.type();
7066         if (predType.returnType() != boolean.class ||
7067                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7068             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7069         }
7070         if (init != null) {
7071             MethodType initType = init.type();
7072             if (initType.returnType() != returnType ||
7073                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7074                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7075             }
7076         }
7077     }
7078 
7079     /**
7080      * Constructs a loop that runs a given number of iterations.
7081      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7082      * <p>
7083      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7084      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7085      * It will be initialized to 0 and incremented by 1 in each iteration.
7086      * <p>
7087      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7088      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7089      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7090      * <p>
7091      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7092      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7093      * iteration variable.
7094      * The result of the loop handle execution will be the final {@code V} value of that variable
7095      * (or {@code void} if there is no {@code V} variable).
7096      * <p>
7097      * The following rules hold for the argument handles:<ul>
7098      * <li>The {@code iterations} handle must not be {@code null}, and must return
7099      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7100      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7101      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7102      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7103      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7104      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7105      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7106      * of types called the <em>internal parameter list</em>.
7107      * It will constrain the parameter lists of the other loop parts.
7108      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7109      * with no additional {@code A} types, then the internal parameter list is extended by
7110      * the argument types {@code A...} of the {@code iterations} handle.
7111      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7112      * list {@code (A...)} is called the <em>external parameter list</em>.
7113      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7114      * additional state variable of the loop.
7115      * The body must both accept a leading parameter and return a value of this type {@code V}.
7116      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7117      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7118      * <a href="MethodHandles.html#effid">effectively identical</a>
7119      * to the external parameter list {@code (A...)}.
7120      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7121      * {@linkplain #empty default value}.
7122      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7123      * effectively identical to the external parameter list {@code (A...)}.
7124      * </ul>
7125      * <p>
7126      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7127      * <li>The loop handle's result type is the result type {@code V} of the body.
7128      * <li>The loop handle's parameter types are the types {@code (A...)},
7129      * from the external parameter list.
7130      * </ul>
7131      * <p>
7132      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7133      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7134      * arguments passed to the loop.
7135      * <blockquote><pre>{@code
7136      * int iterations(A...);
7137      * V init(A...);
7138      * V body(V, int, A...);
7139      * V countedLoop(A... a...) {
7140      *   int end = iterations(a...);
7141      *   V v = init(a...);
7142      *   for (int i = 0; i < end; ++i) {
7143      *     v = body(v, i, a...);
7144      *   }
7145      *   return v;
7146      * }
7147      * }</pre></blockquote>
7148      *
7149      * @apiNote Example with a fully conformant body method:
7150      * <blockquote><pre>{@code
7151      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7152      * // => a variation on a well known theme
7153      * static String step(String v, int counter, String init) { return "na " + v; }
7154      * // assume MH_step is a handle to the method above
7155      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7156      * MethodHandle start = MethodHandles.identity(String.class);
7157      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7158      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7159      * }</pre></blockquote>
7160      *
7161      * @apiNote Example with the simplest possible body method type,
7162      * and passing the number of iterations to the loop invocation:
7163      * <blockquote><pre>{@code
7164      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7165      * // => a variation on a well known theme
7166      * static String step(String v, int counter ) { return "na " + v; }
7167      * // assume MH_step is a handle to the method above
7168      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7169      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7170      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7171      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7172      * }</pre></blockquote>
7173      *
7174      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7175      * as loop parameters:
7176      * <blockquote><pre>{@code
7177      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7178      * // => a variation on a well known theme
7179      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7180      * // assume MH_step is a handle to the method above
7181      * MethodHandle count = MethodHandles.identity(int.class);
7182      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7183      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7184      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7185      * }</pre></blockquote>
7186      *
7187      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7188      * to enforce a loop type:
7189      * <blockquote><pre>{@code
7190      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7191      * // => a variation on a well known theme
7192      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7193      * // assume MH_step is a handle to the method above
7194      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7195      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7196      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7197      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7198      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7199      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7200      * }</pre></blockquote>
7201      *
7202      * @apiNote The implementation of this method can be expressed as follows:
7203      * <blockquote><pre>{@code
7204      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7205      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7206      * }
7207      * }</pre></blockquote>
7208      *
7209      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7210      *                   result type must be {@code int}. See above for other constraints.
7211      * @param init optional initializer, providing the initial value of the loop variable.
7212      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7213      * @param body body of the loop, which may not be {@code null}.
7214      *             It controls the loop parameters and result type in the standard case (see above for details).
7215      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7216      *             and may accept any number of additional types.
7217      *             See above for other constraints.
7218      *
7219      * @return a method handle representing the loop.
7220      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7221      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7222      *
7223      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7224      * @since 9
7225      */
7226     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7227         return countedLoop(empty(iterations.type()), iterations, init, body);
7228     }
7229 
7230     /**
7231      * Constructs a loop that counts over a range of numbers.
7232      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7233      * <p>
7234      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7235      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7236      * values of the loop counter.
7237      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7238      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7239      * <p>
7240      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7241      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7242      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7243      * <p>
7244      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7245      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7246      * iteration variable.
7247      * The result of the loop handle execution will be the final {@code V} value of that variable
7248      * (or {@code void} if there is no {@code V} variable).
7249      * <p>
7250      * The following rules hold for the argument handles:<ul>
7251      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7252      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7253      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7254      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7255      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7256      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7257      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7258      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7259      * of types called the <em>internal parameter list</em>.
7260      * It will constrain the parameter lists of the other loop parts.
7261      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7262      * with no additional {@code A} types, then the internal parameter list is extended by
7263      * the argument types {@code A...} of the {@code end} handle.
7264      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7265      * list {@code (A...)} is called the <em>external parameter list</em>.
7266      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7267      * additional state variable of the loop.
7268      * The body must both accept a leading parameter and return a value of this type {@code V}.
7269      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7270      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7271      * <a href="MethodHandles.html#effid">effectively identical</a>
7272      * to the external parameter list {@code (A...)}.
7273      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7274      * {@linkplain #empty default value}.
7275      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7276      * effectively identical to the external parameter list {@code (A...)}.
7277      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7278      * to the external parameter list.
7279      * </ul>
7280      * <p>
7281      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7282      * <li>The loop handle's result type is the result type {@code V} of the body.
7283      * <li>The loop handle's parameter types are the types {@code (A...)},
7284      * from the external parameter list.
7285      * </ul>
7286      * <p>
7287      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7288      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7289      * arguments passed to the loop.
7290      * <blockquote><pre>{@code
7291      * int start(A...);
7292      * int end(A...);
7293      * V init(A...);
7294      * V body(V, int, A...);
7295      * V countedLoop(A... a...) {
7296      *   int e = end(a...);
7297      *   int s = start(a...);
7298      *   V v = init(a...);
7299      *   for (int i = s; i < e; ++i) {
7300      *     v = body(v, i, a...);
7301      *   }
7302      *   return v;
7303      * }
7304      * }</pre></blockquote>
7305      *
7306      * @apiNote The implementation of this method can be expressed as follows:
7307      * <blockquote><pre>{@code
7308      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7309      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7310      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7311      *     // the following semantics:
7312      *     // MH_increment: (int limit, int counter) -> counter + 1
7313      *     // MH_predicate: (int limit, int counter) -> counter < limit
7314      *     Class<?> counterType = start.type().returnType();  // int
7315      *     Class<?> returnType = body.type().returnType();
7316      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7317      *     if (returnType != void.class) {  // ignore the V variable
7318      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7319      *         pred = dropArguments(pred, 1, returnType);  // ditto
7320      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7321      *     }
7322      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7323      *     MethodHandle[]
7324      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7325      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7326      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7327      *     return loop(loopLimit, bodyClause, indexVar);
7328      * }
7329      * }</pre></blockquote>
7330      *
7331      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7332      *              See above for other constraints.
7333      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7334      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7335      * @param init optional initializer, providing the initial value of the loop variable.
7336      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7337      * @param body body of the loop, which may not be {@code null}.
7338      *             It controls the loop parameters and result type in the standard case (see above for details).
7339      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7340      *             and may accept any number of additional types.
7341      *             See above for other constraints.
7342      *
7343      * @return a method handle representing the loop.
7344      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7345      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7346      *
7347      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7348      * @since 9
7349      */
7350     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7351         countedLoopChecks(start, end, init, body);
7352         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7353         Class<?> limitType   = end.type().returnType();    // yes, int again
7354         Class<?> returnType  = body.type().returnType();
7355         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7356         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7357         MethodHandle retv = null;
7358         if (returnType != void.class) {
7359             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7360             pred = dropArguments(pred, 1, returnType);  // ditto
7361             retv = dropArguments(identity(returnType), 0, counterType);
7362         }
7363         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7364         MethodHandle[]
7365             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7366             bodyClause = { init, body },            // v = init(); v = body(v, i)
7367             indexVar   = { start, incr };           // i = start(); i = i + 1
7368         return loop(loopLimit, bodyClause, indexVar);
7369     }
7370 
7371     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7372         Objects.requireNonNull(start);
7373         Objects.requireNonNull(end);
7374         Objects.requireNonNull(body);
7375         Class<?> counterType = start.type().returnType();
7376         if (counterType != int.class) {
7377             MethodType expected = start.type().changeReturnType(int.class);
7378             throw misMatchedTypes("start function", start.type(), expected);
7379         } else if (end.type().returnType() != counterType) {
7380             MethodType expected = end.type().changeReturnType(counterType);
7381             throw misMatchedTypes("end function", end.type(), expected);
7382         }
7383         MethodType bodyType = body.type();
7384         Class<?> returnType = bodyType.returnType();
7385         List<Class<?>> innerList = bodyType.parameterList();
7386         // strip leading V value if present
7387         int vsize = (returnType == void.class ? 0 : 1);
7388         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7389             // argument list has no "V" => error
7390             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7391             throw misMatchedTypes("body function", bodyType, expected);
7392         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7393             // missing I type => error
7394             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7395             throw misMatchedTypes("body function", bodyType, expected);
7396         }
7397         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7398         if (outerList.isEmpty()) {
7399             // special case; take lists from end handle
7400             outerList = end.type().parameterList();
7401             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7402         }
7403         MethodType expected = methodType(counterType, outerList);
7404         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7405             throw misMatchedTypes("start parameter types", start.type(), expected);
7406         }
7407         if (end.type() != start.type() &&
7408             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7409             throw misMatchedTypes("end parameter types", end.type(), expected);
7410         }
7411         if (init != null) {
7412             MethodType initType = init.type();
7413             if (initType.returnType() != returnType ||
7414                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7415                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7416             }
7417         }
7418     }
7419 
7420     /**
7421      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7422      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7423      * <p>
7424      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7425      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7426      * <p>
7427      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7428      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7429      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7430      * <p>
7431      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7432      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7433      * iteration variable.
7434      * The result of the loop handle execution will be the final {@code V} value of that variable
7435      * (or {@code void} if there is no {@code V} variable).
7436      * <p>
7437      * The following rules hold for the argument handles:<ul>
7438      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7439      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7440      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7441      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7442      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7443      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7444      * of types called the <em>internal parameter list</em>.
7445      * It will constrain the parameter lists of the other loop parts.
7446      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7447      * with no additional {@code A} types, then the internal parameter list is extended by
7448      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7449      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7450      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7451      * list {@code (A...)} is called the <em>external parameter list</em>.
7452      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7453      * additional state variable of the loop.
7454      * The body must both accept a leading parameter and return a value of this type {@code V}.
7455      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7456      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7457      * <a href="MethodHandles.html#effid">effectively identical</a>
7458      * to the external parameter list {@code (A...)}.
7459      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7460      * {@linkplain #empty default value}.
7461      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7462      * type {@code java.util.Iterator} or a subtype thereof.
7463      * The iterator it produces when the loop is executed will be assumed
7464      * to yield values which can be converted to type {@code T}.
7465      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7466      * effectively identical to the external parameter list {@code (A...)}.
7467      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7468      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7469      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7470      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7471      * the {@link MethodHandle#asType asType} conversion method.
7472      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7473      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7474      * </ul>
7475      * <p>
7476      * The type {@code T} may be either a primitive or reference.
7477      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7478      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7479      * as if by the {@link MethodHandle#asType asType} conversion method.
7480      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7481      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7482      * <p>
7483      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7484      * <li>The loop handle's result type is the result type {@code V} of the body.
7485      * <li>The loop handle's parameter types are the types {@code (A...)},
7486      * from the external parameter list.
7487      * </ul>
7488      * <p>
7489      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7490      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7491      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7492      * <blockquote><pre>{@code
7493      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7494      * V init(A...);
7495      * V body(V,T,A...);
7496      * V iteratedLoop(A... a...) {
7497      *   Iterator<T> it = iterator(a...);
7498      *   V v = init(a...);
7499      *   while (it.hasNext()) {
7500      *     T t = it.next();
7501      *     v = body(v, t, a...);
7502      *   }
7503      *   return v;
7504      * }
7505      * }</pre></blockquote>
7506      *
7507      * @apiNote Example:
7508      * <blockquote><pre>{@code
7509      * // get an iterator from a list
7510      * static List<String> reverseStep(List<String> r, String e) {
7511      *   r.add(0, e);
7512      *   return r;
7513      * }
7514      * static List<String> newArrayList() { return new ArrayList<>(); }
7515      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7516      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7517      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7518      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7519      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7520      * }</pre></blockquote>
7521      *
7522      * @apiNote The implementation of this method can be expressed approximately as follows:
7523      * <blockquote><pre>{@code
7524      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7525      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7526      *     Class<?> returnType = body.type().returnType();
7527      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7528      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7529      *     MethodHandle retv = null, step = body, startIter = iterator;
7530      *     if (returnType != void.class) {
7531      *         // the simple thing first:  in (I V A...), drop the I to get V
7532      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7533      *         // body type signature (V T A...), internal loop types (I V A...)
7534      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7535      *     }
7536      *     if (startIter == null)  startIter = MH_getIter;
7537      *     MethodHandle[]
7538      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7539      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7540      *     return loop(iterVar, bodyClause);
7541      * }
7542      * }</pre></blockquote>
7543      *
7544      * @param iterator an optional handle to return the iterator to start the loop.
7545      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7546      *                 See above for other constraints.
7547      * @param init optional initializer, providing the initial value of the loop variable.
7548      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7549      * @param body body of the loop, which may not be {@code null}.
7550      *             It controls the loop parameters and result type in the standard case (see above for details).
7551      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7552      *             and may accept any number of additional types.
7553      *             See above for other constraints.
7554      *
7555      * @return a method handle embodying the iteration loop functionality.
7556      * @throws NullPointerException if the {@code body} handle is {@code null}.
7557      * @throws IllegalArgumentException if any argument violates the above requirements.
7558      *
7559      * @since 9
7560      */
7561     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7562         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7563         Class<?> returnType = body.type().returnType();
7564         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7565         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7566         MethodHandle startIter;
7567         MethodHandle nextVal;
7568         {
7569             MethodType iteratorType;
7570             if (iterator == null) {
7571                 // derive argument type from body, if available, else use Iterable
7572                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7573                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7574             } else {
7575                 // force return type to the internal iterator class
7576                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7577                 startIter = iterator;
7578             }
7579             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7580             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7581 
7582             // perform the asType transforms under an exception transformer, as per spec.:
7583             try {
7584                 startIter = startIter.asType(iteratorType);
7585                 nextVal = nextRaw.asType(nextValType);
7586             } catch (WrongMethodTypeException ex) {
7587                 throw new IllegalArgumentException(ex);
7588             }
7589         }
7590 
7591         MethodHandle retv = null, step = body;
7592         if (returnType != void.class) {
7593             // the simple thing first:  in (I V A...), drop the I to get V
7594             retv = dropArguments(identity(returnType), 0, Iterator.class);
7595             // body type signature (V T A...), internal loop types (I V A...)
7596             step = swapArguments(body, 0, 1);  // swap V <-> T
7597         }
7598 
7599         MethodHandle[]
7600             iterVar    = { startIter, null, hasNext, retv },
7601             bodyClause = { init, filterArgument(step, 0, nextVal) };
7602         return loop(iterVar, bodyClause);
7603     }
7604 
7605     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7606         Objects.requireNonNull(body);
7607         MethodType bodyType = body.type();
7608         Class<?> returnType = bodyType.returnType();
7609         List<Class<?>> internalParamList = bodyType.parameterList();
7610         // strip leading V value if present
7611         int vsize = (returnType == void.class ? 0 : 1);
7612         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7613             // argument list has no "V" => error
7614             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7615             throw misMatchedTypes("body function", bodyType, expected);
7616         } else if (internalParamList.size() <= vsize) {
7617             // missing T type => error
7618             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7619             throw misMatchedTypes("body function", bodyType, expected);
7620         }
7621         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7622         Class<?> iterableType = null;
7623         if (iterator != null) {
7624             // special case; if the body handle only declares V and T then
7625             // the external parameter list is obtained from iterator handle
7626             if (externalParamList.isEmpty()) {
7627                 externalParamList = iterator.type().parameterList();
7628             }
7629             MethodType itype = iterator.type();
7630             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7631                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7632             }
7633             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7634                 MethodType expected = methodType(itype.returnType(), externalParamList);
7635                 throw misMatchedTypes("iterator parameters", itype, expected);
7636             }
7637         } else {
7638             if (externalParamList.isEmpty()) {
7639                 // special case; if the iterator handle is null and the body handle
7640                 // only declares V and T then the external parameter list consists
7641                 // of Iterable
7642                 externalParamList = Arrays.asList(Iterable.class);
7643                 iterableType = Iterable.class;
7644             } else {
7645                 // special case; if the iterator handle is null and the external
7646                 // parameter list is not empty then the first parameter must be
7647                 // assignable to Iterable
7648                 iterableType = externalParamList.get(0);
7649                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7650                     throw newIllegalArgumentException(
7651                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7652                 }
7653             }
7654         }
7655         if (init != null) {
7656             MethodType initType = init.type();
7657             if (initType.returnType() != returnType ||
7658                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7659                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7660             }
7661         }
7662         return iterableType;  // help the caller a bit
7663     }
7664 
7665     /*non-public*/
7666     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7667         // there should be a better way to uncross my wires
7668         int arity = mh.type().parameterCount();
7669         int[] order = new int[arity];
7670         for (int k = 0; k < arity; k++)  order[k] = k;
7671         order[i] = j; order[j] = i;
7672         Class<?>[] types = mh.type().parameterArray();
7673         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7674         MethodType swapType = methodType(mh.type().returnType(), types);
7675         return permuteArguments(mh, swapType, order);
7676     }
7677 
7678     /**
7679      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7680      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7681      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7682      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7683      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7684      * {@code try-finally} handle.
7685      * <p>
7686      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7687      * The first is the exception thrown during the
7688      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7689      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7690      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7691      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7692      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7693      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7694      * <p>
7695      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7696      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7697      * two extra leading parameters:<ul>
7698      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7699      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7700      * the result from the execution of the {@code target} handle.
7701      * This parameter is not present if the {@code target} returns {@code void}.
7702      * </ul>
7703      * <p>
7704      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7705      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7706      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7707      * the cleanup.
7708      * <blockquote><pre>{@code
7709      * V target(A..., B...);
7710      * V cleanup(Throwable, V, A...);
7711      * V adapter(A... a, B... b) {
7712      *   V result = (zero value for V);
7713      *   Throwable throwable = null;
7714      *   try {
7715      *     result = target(a..., b...);
7716      *   } catch (Throwable t) {
7717      *     throwable = t;
7718      *     throw t;
7719      *   } finally {
7720      *     result = cleanup(throwable, result, a...);
7721      *   }
7722      *   return result;
7723      * }
7724      * }</pre></blockquote>
7725      * <p>
7726      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7727      * be modified by execution of the target, and so are passed unchanged
7728      * from the caller to the cleanup, if it is invoked.
7729      * <p>
7730      * The target and cleanup must return the same type, even if the cleanup
7731      * always throws.
7732      * To create such a throwing cleanup, compose the cleanup logic
7733      * with {@link #throwException throwException},
7734      * in order to create a method handle of the correct return type.
7735      * <p>
7736      * Note that {@code tryFinally} never converts exceptions into normal returns.
7737      * In rare cases where exceptions must be converted in that way, first wrap
7738      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7739      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7740      * <p>
7741      * It is recommended that the first parameter type of {@code cleanup} be
7742      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7743      * {@code cleanup} will always be invoked with whatever exception that
7744      * {@code target} throws.  Declaring a narrower type may result in a
7745      * {@code ClassCastException} being thrown by the {@code try-finally}
7746      * handle if the type of the exception thrown by {@code target} is not
7747      * assignable to the first parameter type of {@code cleanup}.  Note that
7748      * various exception types of {@code VirtualMachineError},
7749      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7750      * thrown by almost any kind of Java code, and a finally clause that
7751      * catches (say) only {@code IOException} would mask any of the others
7752      * behind a {@code ClassCastException}.
7753      *
7754      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7755      * @param cleanup the handle that is invoked in the finally block.
7756      *
7757      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7758      * @throws NullPointerException if any argument is null
7759      * @throws IllegalArgumentException if {@code cleanup} does not accept
7760      *          the required leading arguments, or if the method handle types do
7761      *          not match in their return types and their
7762      *          corresponding trailing parameters
7763      *
7764      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7765      * @since 9
7766      */
7767     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7768         List<Class<?>> targetParamTypes = target.type().parameterList();
7769         Class<?> rtype = target.type().returnType();
7770 
7771         tryFinallyChecks(target, cleanup);
7772 
7773         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7774         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7775         // target parameter list.
7776         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7777 
7778         // Ensure that the intrinsic type checks the instance thrown by the
7779         // target against the first parameter of cleanup
7780         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7781 
7782         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7783         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7784     }
7785 
7786     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7787         Class<?> rtype = target.type().returnType();
7788         if (rtype != cleanup.type().returnType()) {
7789             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7790         }
7791         MethodType cleanupType = cleanup.type();
7792         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7793             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7794         }
7795         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7796             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7797         }
7798         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7799         // target parameter list.
7800         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7801         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7802             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7803                     cleanup.type(), target.type());
7804         }
7805     }
7806 
7807     /**
7808      * Creates a table switch method handle, which can be used to switch over a set of target
7809      * method handles, based on a given target index, called selector.
7810      * <p>
7811      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7812      * and where {@code N} is the number of target method handles, the table switch method
7813      * handle will invoke the n-th target method handle from the list of target method handles.
7814      * <p>
7815      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7816      * method handle will invoke the given fallback method handle.
7817      * <p>
7818      * All method handles passed to this method must have the same type, with the additional
7819      * requirement that the leading parameter be of type {@code int}. The leading parameter
7820      * represents the selector.
7821      * <p>
7822      * Any trailing parameters present in the type will appear on the returned table switch
7823      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7824      * together with the selector value, to the selected method handle when invoking it.
7825      *
7826      * @apiNote Example:
7827      * The cases each drop the {@code selector} value they are given, and take an additional
7828      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7829      * to a specific constant label string for each case:
7830      * <blockquote><pre>{@code
7831      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7832      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7833      *         MethodType.methodType(String.class, String.class));
7834      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7835      *
7836      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7837      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7838      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7839      *
7840      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7841      *     caseDefault,
7842      *     case0,
7843      *     case1
7844      * );
7845      *
7846      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7847      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7848      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7849      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7850      * }</pre></blockquote>
7851      *
7852      * @param fallback the fallback method handle that is called when the selector is not
7853      *                 within the range {@code [0, N)}.
7854      * @param targets array of target method handles.
7855      * @return the table switch method handle.
7856      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7857      *                              any of the elements of the {@code targets} array are
7858      *                              {@code null}.
7859      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7860      *                                  parameter of the fallback handle or any of the target
7861      *                                  handles is not {@code int}, or if the types of
7862      *                                  the fallback handle and all of target handles are
7863      *                                  not the same.
7864      */
7865     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7866         Objects.requireNonNull(fallback);
7867         Objects.requireNonNull(targets);
7868         targets = targets.clone();
7869         MethodType type = tableSwitchChecks(fallback, targets);
7870         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7871     }
7872 
7873     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7874         if (caseActions.length == 0)
7875             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7876 
7877         MethodType expectedType = defaultCase.type();
7878 
7879         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7880             throw new IllegalArgumentException(
7881                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7882 
7883         for (MethodHandle mh : caseActions) {
7884             Objects.requireNonNull(mh);
7885             if (mh.type() != expectedType)
7886                 throw new IllegalArgumentException(
7887                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7888         }
7889 
7890         return expectedType;
7891     }
7892 
7893 }