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.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.vm.annotation.ForceInline;
  38 import sun.invoke.util.ValueConversions;
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.Wrapper;
  41 import sun.reflect.misc.ReflectUtil;
  42 import sun.security.util.SecurityConstants;
  43 
  44 import java.lang.constant.ConstantDescs;
  45 import java.lang.invoke.LambdaForm.BasicType;
  46 import java.lang.reflect.Constructor;
  47 import java.lang.reflect.Field;
  48 import java.lang.reflect.Member;
  49 import java.lang.reflect.Method;
  50 import java.lang.reflect.Modifier;
  51 import java.lang.reflect.ReflectPermission;
  52 import java.nio.ByteOrder;
  53 import java.security.ProtectionDomain;
  54 import java.util.ArrayList;
  55 import java.util.Arrays;
  56 import java.util.BitSet;
  57 import java.util.Iterator;
  58 import java.util.List;
  59 import java.util.Objects;
  60 import java.util.Set;
  61 import java.util.concurrent.ConcurrentHashMap;
  62 import java.util.stream.Stream;
  63 
  64 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  65 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  66 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  67 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  68 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  69 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  70 import static java.lang.invoke.MethodType.methodType;
  71 
  72 /**
  73  * This class consists exclusively of static methods that operate on or return
  74  * method handles. They fall into several categories:
  75  * <ul>
  76  * <li>Lookup methods which help create method handles for methods and fields.
  77  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  78  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  79  * </ul>
  80  * A lookup, combinator, or factory method will fail and throw an
  81  * {@code IllegalArgumentException} if the created method handle's type
  82  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  83  *
  84  * @author John Rose, JSR 292 EG
  85  * @since 1.7
  86  */
  87 public class MethodHandles {
  88 
  89     private MethodHandles() { }  // do not instantiate
  90 
  91     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  92 
  93     // See IMPL_LOOKUP below.
  94 
  95     //// Method handle creation from ordinary methods.
  96 
  97     /**
  98      * Returns a {@link Lookup lookup object} with
  99      * full capabilities to emulate all supported bytecode behaviors of the caller.
 100      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 101      * Factory methods on the lookup object can create
 102      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 103      * for any member that the caller has access to via bytecodes,
 104      * including protected and private fields and methods.
 105      * This lookup object is created by the original lookup class
 106      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 107      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 108      * Do not store it in place where untrusted code can access it.
 109      * <p>
 110      * This method is caller sensitive, which means that it may return different
 111      * values to different callers.
 112      * @return a lookup object for the caller of this method, with
 113      * {@linkplain Lookup#ORIGINAL original} and
 114      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 115      */
 116     @CallerSensitive
 117     @ForceInline // to ensure Reflection.getCallerClass optimization
 118     public static Lookup lookup() {
 119         return new Lookup(Reflection.getCallerClass());
 120     }
 121 
 122     /**
 123      * This lookup method is the alternate implementation of
 124      * the lookup method with a leading caller class argument which is
 125      * non-caller-sensitive.  This method is only invoked by reflection
 126      * and method handle.
 127      */
 128     @CallerSensitiveAdapter
 129     private static Lookup lookup(Class<?> caller) {
 130         if (caller.getClassLoader() == null) {
 131             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 132         }
 133         return new Lookup(caller);
 134     }
 135 
 136     /**
 137      * Returns a {@link Lookup lookup object} which is trusted minimally.
 138      * The lookup has the {@code UNCONDITIONAL} mode.
 139      * It can only be used to create method handles to public members of
 140      * public classes in packages that are exported unconditionally.
 141      * <p>
 142      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 143      * of this lookup object will be {@link java.lang.Object}.
 144      *
 145      * @apiNote The use of Object is conventional, and because the lookup modes are
 146      * limited, there is no special access provided to the internals of Object, its package
 147      * or its module.  This public lookup object or other lookup object with
 148      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 149      * is not used to determine the lookup context.
 150      *
 151      * <p style="font-size:smaller;">
 152      * <em>Discussion:</em>
 153      * The lookup class can be changed to any other class {@code C} using an expression of the form
 154      * {@link Lookup#in publicLookup().in(C.class)}.
 155      * A public lookup object is always subject to
 156      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 157      * Also, it cannot access
 158      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 159      * @return a lookup object which is trusted minimally
 160      *
 161      * @revised 9
 162      */
 163     public static Lookup publicLookup() {
 164         return Lookup.PUBLIC_LOOKUP;
 165     }
 166 
 167     /**
 168      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 169      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 170      * The returned lookup object can provide access to classes in modules and packages,
 171      * and members of those classes, outside the normal rules of Java access control,
 172      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 173      * <p>
 174      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 175      * allowed to do deep reflection on module {@code M2} and package of the target class
 176      * if and only if all of the following conditions are {@code true}:
 177      * <ul>
 178      * <li>If there is a security manager, its {@code checkPermission} method is
 179      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 180      * that must return normally.
 181      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 182      * full privilege access}.  Specifically:
 183      *   <ul>
 184      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 185      *         (This is because otherwise there would be no way to ensure the original lookup
 186      *         creator was a member of any particular module, and so any subsequent checks
 187      *         for readability and qualified exports would become ineffective.)
 188      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 189      *         (This is because an application intending to share intra-module access
 190      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 191      *         deep reflection to its own module.)
 192      *   </ul>
 193      * <li>The target class must be a proper class, not a primitive or array class.
 194      * (Thus, {@code M2} is well-defined.)
 195      * <li>If the caller module {@code M1} differs from
 196      * the target module {@code M2} then both of the following must be true:
 197      *   <ul>
 198      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 199      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 200      *         containing the target class to at least {@code M1}.</li>
 201      *   </ul>
 202      * </ul>
 203      * <p>
 204      * If any of the above checks is violated, this method fails with an
 205      * exception.
 206      * <p>
 207      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 208      * returns a {@code Lookup} on {@code targetClass} with
 209      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 210      * with {@code null} previous lookup class.
 211      * <p>
 212      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 213      * returns a {@code Lookup} on {@code targetClass} that records
 214      * the lookup class of the caller as the new previous lookup class with
 215      * {@code PRIVATE} access but no {@code MODULE} access.
 216      * <p>
 217      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 218      *
 219      * @param targetClass the target class
 220      * @param caller the caller lookup object
 221      * @return a lookup object for the target class, with private access
 222      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 223      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 224      * @throws SecurityException if denied by the security manager
 225      * @throws IllegalAccessException if any of the other access checks specified above fails
 226      * @since 9
 227      * @see Lookup#dropLookupMode
 228      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 229      */
 230     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 231         if (caller.allowedModes == Lookup.TRUSTED) {
 232             return new Lookup(targetClass);
 233         }
 234 
 235         @SuppressWarnings("removal")
 236         SecurityManager sm = System.getSecurityManager();
 237         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 238         if (targetClass.isPrimitive())
 239             throw new IllegalArgumentException(targetClass + " is a primitive class");
 240         if (targetClass.isArray())
 241             throw new IllegalArgumentException(targetClass + " is an array class");
 242         // Ensure that we can reason accurately about private and module access.
 243         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 244         if ((caller.lookupModes() & requireAccess) != requireAccess)
 245             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 246 
 247         // previous lookup class is never set if it has MODULE access
 248         assert caller.previousLookupClass() == null;
 249 
 250         Class<?> callerClass = caller.lookupClass();
 251         Module callerModule = callerClass.getModule();  // M1
 252         Module targetModule = targetClass.getModule();  // M2
 253         Class<?> newPreviousClass = null;
 254         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 255 
 256         if (targetModule != callerModule) {
 257             if (!callerModule.canRead(targetModule))
 258                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 259             if (targetModule.isNamed()) {
 260                 String pn = targetClass.getPackageName();
 261                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 262                 if (!targetModule.isOpen(pn, callerModule))
 263                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 264             }
 265 
 266             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 267             newPreviousClass = callerClass;
 268             newModes &= ~Lookup.MODULE;
 269         }
 270         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 271     }
 272 
 273     /**
 274      * Returns the <em>class data</em> associated with the lookup class
 275      * of the given {@code caller} lookup object, or {@code null}.
 276      *
 277      * <p> A hidden class with class data can be created by calling
 278      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 279      * Lookup::defineHiddenClassWithClassData}.
 280      * This method will cause the static class initializer of the lookup
 281      * class of the given {@code caller} lookup object be executed if
 282      * it has not been initialized.
 283      *
 284      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 285      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 286      * {@code null} is returned if this method is called on the lookup object
 287      * on these classes.
 288      *
 289      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 290      * must have {@linkplain Lookup#ORIGINAL original access}
 291      * in order to retrieve the class data.
 292      *
 293      * @apiNote
 294      * This method can be called as a bootstrap method for a dynamically computed
 295      * constant.  A framework can create a hidden class with class data, for
 296      * example that can be {@code Class} or {@code MethodHandle} object.
 297      * The class data is accessible only to the lookup object
 298      * created by the original caller but inaccessible to other members
 299      * in the same nest.  If a framework passes security sensitive objects
 300      * to a hidden class via class data, it is recommended to load the value
 301      * of class data as a dynamically computed constant instead of storing
 302      * the class data in private static field(s) which are accessible to
 303      * other nestmates.
 304      *
 305      * @param <T> the type to cast the class data object to
 306      * @param caller the lookup context describing the class performing the
 307      * operation (normally stacked by the JVM)
 308      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 309      *             ({@code "_"})
 310      * @param type the type of the class data
 311      * @return the value of the class data if present in the lookup class;
 312      * otherwise {@code null}
 313      * @throws IllegalArgumentException if name is not {@code "_"}
 314      * @throws IllegalAccessException if the lookup context does not have
 315      * {@linkplain Lookup#ORIGINAL original} access
 316      * @throws ClassCastException if the class data cannot be converted to
 317      * the given {@code type}
 318      * @throws NullPointerException if {@code caller} or {@code type} argument
 319      * is {@code null}
 320      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 321      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 322      * @since 16
 323      * @jvms 5.5 Initialization
 324      */
 325      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 326          Objects.requireNonNull(caller);
 327          Objects.requireNonNull(type);
 328          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 329              throw new IllegalArgumentException("name must be \"_\": " + name);
 330          }
 331 
 332          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 333              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 334          }
 335 
 336          Object classdata = classData(caller.lookupClass());
 337          if (classdata == null) return null;
 338 
 339          try {
 340              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 341          } catch (RuntimeException|Error e) {
 342              throw e; // let CCE and other runtime exceptions through
 343          } catch (Throwable e) {
 344              throw new InternalError(e);
 345          }
 346     }
 347 
 348     /*
 349      * Returns the class data set by the VM in the Class::classData field.
 350      *
 351      * This is also invoked by LambdaForms as it cannot use condy via
 352      * MethodHandles::classData due to bootstrapping issue.
 353      */
 354     static Object classData(Class<?> c) {
 355         UNSAFE.ensureClassInitialized(c);
 356         return SharedSecrets.getJavaLangAccess().classData(c);
 357     }
 358 
 359     /**
 360      * Returns the element at the specified index in the
 361      * {@linkplain #classData(Lookup, String, Class) class data},
 362      * if the class data associated with the lookup class
 363      * of the given {@code caller} lookup object is a {@code List}.
 364      * If the class data is not present in this lookup class, this method
 365      * returns {@code null}.
 366      *
 367      * <p> A hidden class with class data can be created by calling
 368      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 369      * Lookup::defineHiddenClassWithClassData}.
 370      * This method will cause the static class initializer of the lookup
 371      * class of the given {@code caller} lookup object be executed if
 372      * it has not been initialized.
 373      *
 374      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 375      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 376      * {@code null} is returned if this method is called on the lookup object
 377      * on these classes.
 378      *
 379      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 380      * must have {@linkplain Lookup#ORIGINAL original access}
 381      * in order to retrieve the class data.
 382      *
 383      * @apiNote
 384      * This method can be called as a bootstrap method for a dynamically computed
 385      * constant.  A framework can create a hidden class with class data, for
 386      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 387      * one object and use this method to load one element at a specific index.
 388      * The class data is accessible only to the lookup object
 389      * created by the original caller but inaccessible to other members
 390      * in the same nest.  If a framework passes security sensitive objects
 391      * to a hidden class via class data, it is recommended to load the value
 392      * of class data as a dynamically computed constant instead of storing
 393      * the class data in private static field(s) which are accessible to other
 394      * nestmates.
 395      *
 396      * @param <T> the type to cast the result object to
 397      * @param caller the lookup context describing the class performing the
 398      * operation (normally stacked by the JVM)
 399      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 400      *             ({@code "_"})
 401      * @param type the type of the element at the given index in the class data
 402      * @param index index of the element in the class data
 403      * @return the element at the given index in the class data
 404      * if the class data is present; otherwise {@code null}
 405      * @throws IllegalArgumentException if name is not {@code "_"}
 406      * @throws IllegalAccessException if the lookup context does not have
 407      * {@linkplain Lookup#ORIGINAL original} access
 408      * @throws ClassCastException if the class data cannot be converted to {@code List}
 409      * or the element at the specified index cannot be converted to the given type
 410      * @throws IndexOutOfBoundsException if the index is out of range
 411      * @throws NullPointerException if {@code caller} or {@code type} argument is
 412      * {@code null}; or if unboxing operation fails because
 413      * the element at the given index is {@code null}
 414      *
 415      * @since 16
 416      * @see #classData(Lookup, String, Class)
 417      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 418      */
 419     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 420             throws IllegalAccessException
 421     {
 422         @SuppressWarnings("unchecked")
 423         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 424         if (classdata == null) return null;
 425 
 426         try {
 427             Object element = classdata.get(index);
 428             return BootstrapMethodInvoker.widenAndCast(element, type);
 429         } catch (RuntimeException|Error e) {
 430             throw e; // let specified exceptions and other runtime exceptions/errors through
 431         } catch (Throwable e) {
 432             throw new InternalError(e);
 433         }
 434     }
 435 
 436     /**
 437      * Performs an unchecked "crack" of a
 438      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 439      * The result is as if the user had obtained a lookup object capable enough
 440      * to crack the target method handle, called
 441      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 442      * on the target to obtain its symbolic reference, and then called
 443      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 444      * to resolve the symbolic reference to a member.
 445      * <p>
 446      * If there is a security manager, its {@code checkPermission} method
 447      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 448      * @param <T> the desired type of the result, either {@link Member} or a subtype
 449      * @param target a direct method handle to crack into symbolic reference components
 450      * @param expected a class object representing the desired result type {@code T}
 451      * @return a reference to the method, constructor, or field object
 452      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 453      * @throws    NullPointerException if either argument is {@code null}
 454      * @throws    IllegalArgumentException if the target is not a direct method handle
 455      * @throws    ClassCastException if the member is not of the expected type
 456      * @since 1.8
 457      */
 458     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 459         @SuppressWarnings("removal")
 460         SecurityManager smgr = System.getSecurityManager();
 461         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 462         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 463         return lookup.revealDirect(target).reflectAs(expected, lookup);
 464     }
 465 
 466     /**
 467      * A <em>lookup object</em> is a factory for creating method handles,
 468      * when the creation requires access checking.
 469      * Method handles do not perform
 470      * access checks when they are called, but rather when they are created.
 471      * Therefore, method handle access
 472      * restrictions must be enforced when a method handle is created.
 473      * The caller class against which those restrictions are enforced
 474      * is known as the {@linkplain #lookupClass() lookup class}.
 475      * <p>
 476      * A lookup class which needs to create method handles will call
 477      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 478      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 479      * determined, and securely stored in the {@code Lookup} object.
 480      * The lookup class (or its delegates) may then use factory methods
 481      * on the {@code Lookup} object to create method handles for access-checked members.
 482      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 483      * even private ones.
 484      *
 485      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 486      * The factory methods on a {@code Lookup} object correspond to all major
 487      * use cases for methods, constructors, and fields.
 488      * Each method handle created by a factory method is the functional
 489      * equivalent of a particular <em>bytecode behavior</em>.
 490      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 491      * the Java Virtual Machine Specification.)
 492      * Here is a summary of the correspondence between these factory methods and
 493      * the behavior of the resulting method handles:
 494      * <table class="striped">
 495      * <caption style="display:none">lookup method behaviors</caption>
 496      * <thead>
 497      * <tr>
 498      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 499      *     <th scope="col">member</th>
 500      *     <th scope="col">bytecode behavior</th>
 501      * </tr>
 502      * </thead>
 503      * <tbody>
 504      * <tr>
 505      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 506      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 507      * </tr>
 508      * <tr>
 509      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 510      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 511      * </tr>
 512      * <tr>
 513      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 514      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 515      * </tr>
 516      * <tr>
 517      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 518      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 519      * </tr>
 520      * <tr>
 521      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 522      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 523      * </tr>
 524      * <tr>
 525      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 526      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 527      * </tr>
 528      * <tr>
 529      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 530      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 531      * </tr>
 532      * <tr>
 533      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 534      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 535      * </tr>
 536      * <tr>
 537      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 538      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 539      * </tr>
 540      * <tr>
 541      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 542      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 543      * </tr>
 544      * <tr>
 545      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 546      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 547      * </tr>
 548      * <tr>
 549      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 550      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 551      * </tr>
 552      * <tr>
 553      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 554      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 555      * </tr>
 556      * <tr>
 557      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 558      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 559      * </tr>
 560      * </tbody>
 561      * </table>
 562      *
 563      * Here, the type {@code C} is the class or interface being searched for a member,
 564      * documented as a parameter named {@code refc} in the lookup methods.
 565      * The method type {@code MT} is composed from the return type {@code T}
 566      * and the sequence of argument types {@code A*}.
 567      * The constructor also has a sequence of argument types {@code A*} and
 568      * is deemed to return the newly-created object of type {@code C}.
 569      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 570      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 571      * if it is present, it is always the leading argument to the method handle invocation.
 572      * (In the case of some {@code protected} members, {@code this} may be
 573      * restricted in type to the lookup class; see below.)
 574      * The name {@code arg} stands for all the other method handle arguments.
 575      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 576      * stands for a null reference if the accessed method or field is static,
 577      * and {@code this} otherwise.
 578      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 579      * for reflective objects corresponding to the given members declared in type {@code C}.
 580      * <p>
 581      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 582      * as if by {@code ldc CONSTANT_Class}.
 583      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 584      * <p>
 585      * In cases where the given member is of variable arity (i.e., a method or constructor)
 586      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 587      * In all other cases, the returned method handle will be of fixed arity.
 588      * <p style="font-size:smaller;">
 589      * <em>Discussion:</em>
 590      * The equivalence between looked-up method handles and underlying
 591      * class members and bytecode behaviors
 592      * can break down in a few ways:
 593      * <ul style="font-size:smaller;">
 594      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 595      * the lookup can still succeed, even when there is no equivalent
 596      * Java expression or bytecoded constant.
 597      * <li>Likewise, if {@code T} or {@code MT}
 598      * is not symbolically accessible from the lookup class's loader,
 599      * the lookup can still succeed.
 600      * For example, lookups for {@code MethodHandle.invokeExact} and
 601      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 602      * <li>If there is a security manager installed, it can forbid the lookup
 603      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 604      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 605      * constant is not subject to security manager checks.
 606      * <li>If the looked-up method has a
 607      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 608      * the method handle creation may fail with an
 609      * {@code IllegalArgumentException}, due to the method handle type having
 610      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 611      * </ul>
 612      *
 613      * <h2><a id="access"></a>Access checking</h2>
 614      * Access checks are applied in the factory methods of {@code Lookup},
 615      * when a method handle is created.
 616      * This is a key difference from the Core Reflection API, since
 617      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 618      * performs access checking against every caller, on every call.
 619      * <p>
 620      * All access checks start from a {@code Lookup} object, which
 621      * compares its recorded lookup class against all requests to
 622      * create method handles.
 623      * A single {@code Lookup} object can be used to create any number
 624      * of access-checked method handles, all checked against a single
 625      * lookup class.
 626      * <p>
 627      * A {@code Lookup} object can be shared with other trusted code,
 628      * such as a metaobject protocol.
 629      * A shared {@code Lookup} object delegates the capability
 630      * to create method handles on private members of the lookup class.
 631      * Even if privileged code uses the {@code Lookup} object,
 632      * the access checking is confined to the privileges of the
 633      * original lookup class.
 634      * <p>
 635      * A lookup can fail, because
 636      * the containing class is not accessible to the lookup class, or
 637      * because the desired class member is missing, or because the
 638      * desired class member is not accessible to the lookup class, or
 639      * because the lookup object is not trusted enough to access the member.
 640      * In the case of a field setter function on a {@code final} field,
 641      * finality enforcement is treated as a kind of access control,
 642      * and the lookup will fail, except in special cases of
 643      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 644      * In any of these cases, a {@code ReflectiveOperationException} will be
 645      * thrown from the attempted lookup.  The exact class will be one of
 646      * the following:
 647      * <ul>
 648      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 649      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 650      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 651      * </ul>
 652      * <p>
 653      * In general, the conditions under which a method handle may be
 654      * looked up for a method {@code M} are no more restrictive than the conditions
 655      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 656      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 657      * a method handle lookup will generally raise a corresponding
 658      * checked exception, such as {@code NoSuchMethodException}.
 659      * And the effect of invoking the method handle resulting from the lookup
 660      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 661      * to executing the compiled, verified, and resolved call to {@code M}.
 662      * The same point is true of fields and constructors.
 663      * <p style="font-size:smaller;">
 664      * <em>Discussion:</em>
 665      * Access checks only apply to named and reflected methods,
 666      * constructors, and fields.
 667      * Other method handle creation methods, such as
 668      * {@link MethodHandle#asType MethodHandle.asType},
 669      * do not require any access checks, and are used
 670      * independently of any {@code Lookup} object.
 671      * <p>
 672      * If the desired member is {@code protected}, the usual JVM rules apply,
 673      * including the requirement that the lookup class must either be in the
 674      * same package as the desired member, or must inherit that member.
 675      * (See the Java Virtual Machine Specification, sections {@jvms
 676      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 677      * In addition, if the desired member is a non-static field or method
 678      * in a different package, the resulting method handle may only be applied
 679      * to objects of the lookup class or one of its subclasses.
 680      * This requirement is enforced by narrowing the type of the leading
 681      * {@code this} parameter from {@code C}
 682      * (which will necessarily be a superclass of the lookup class)
 683      * to the lookup class itself.
 684      * <p>
 685      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 686      * that the receiver argument must match both the resolved method <em>and</em>
 687      * the current class.  Again, this requirement is enforced by narrowing the
 688      * type of the leading parameter to the resulting method handle.
 689      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 690      * <p>
 691      * The JVM represents constructors and static initializer blocks as internal methods
 692      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 693      * The internal syntax of invocation instructions allows them to refer to such internal
 694      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 695      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 696      * <p>
 697      * If the relationship between nested types is expressed directly through the
 698      * {@code NestHost} and {@code NestMembers} attributes
 699      * (see the Java Virtual Machine Specification, sections {@jvms
 700      * 4.7.28} and {@jvms 4.7.29}),
 701      * then the associated {@code Lookup} object provides direct access to
 702      * the lookup class and all of its nestmates
 703      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 704      * Otherwise, access between nested classes is obtained by the Java compiler creating
 705      * a wrapper method to access a private method of another class in the same nest.
 706      * For example, a nested class {@code C.D}
 707      * can access private members within other related classes such as
 708      * {@code C}, {@code C.D.E}, or {@code C.B},
 709      * but the Java compiler may need to generate wrapper methods in
 710      * those related classes.  In such cases, a {@code Lookup} object on
 711      * {@code C.E} would be unable to access those private members.
 712      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 713      * which can transform a lookup on {@code C.E} into one on any of those other
 714      * classes, without special elevation of privilege.
 715      * <p>
 716      * The accesses permitted to a given lookup object may be limited,
 717      * according to its set of {@link #lookupModes lookupModes},
 718      * to a subset of members normally accessible to the lookup class.
 719      * For example, the {@link MethodHandles#publicLookup publicLookup}
 720      * method produces a lookup object which is only allowed to access
 721      * public members in public classes of exported packages.
 722      * The caller sensitive method {@link MethodHandles#lookup lookup}
 723      * produces a lookup object with full capabilities relative to
 724      * its caller class, to emulate all supported bytecode behaviors.
 725      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 726      * with fewer access modes than the original lookup object.
 727      *
 728      * <p style="font-size:smaller;">
 729      * <a id="privacc"></a>
 730      * <em>Discussion of private and module access:</em>
 731      * We say that a lookup has <em>private access</em>
 732      * if its {@linkplain #lookupModes lookup modes}
 733      * include the possibility of accessing {@code private} members
 734      * (which includes the private members of nestmates).
 735      * As documented in the relevant methods elsewhere,
 736      * only lookups with private access possess the following capabilities:
 737      * <ul style="font-size:smaller;">
 738      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 739      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 740      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 741      *     for classes accessible to the lookup class
 742      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 743      *     within the same package member
 744      * </ul>
 745      * <p style="font-size:smaller;">
 746      * Similarly, a lookup with module access ensures that the original lookup creator was
 747      * a member in the same module as the lookup class.
 748      * <p style="font-size:smaller;">
 749      * Private and module access are independently determined modes; a lookup may have
 750      * either or both or neither.  A lookup which possesses both access modes is said to
 751      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 752      * <p style="font-size:smaller;">
 753      * A lookup with <em>original access</em> ensures that this lookup is created by
 754      * the original lookup class and the bootstrap method invoked by the VM.
 755      * Such a lookup with original access also has private and module access
 756      * which has the following additional capability:
 757      * <ul style="font-size:smaller;">
 758      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 759      *     such as {@code Class.forName}
 760      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 761      * class data} associated with the lookup class</li>
 762      * </ul>
 763      * <p style="font-size:smaller;">
 764      * Each of these permissions is a consequence of the fact that a lookup object
 765      * with private access can be securely traced back to an originating class,
 766      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 767      * can be reliably determined and emulated by method handles.
 768      *
 769      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 770      * When a lookup class in one module {@code M1} accesses a class in another module
 771      * {@code M2}, extra access checking is performed beyond the access mode bits.
 772      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 773      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 774      * and when the type is in a package of {@code M2} that is exported to
 775      * at least {@code M1}.
 776      * <p>
 777      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 778      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 779      * MethodHandles.privateLookupIn} methods.
 780      * Teleporting across modules will always record the original lookup class as
 781      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 782      * and drops {@link Lookup#MODULE MODULE} access.
 783      * If the target class is in the same module as the lookup class {@code C},
 784      * then the target class becomes the new lookup class
 785      * and there is no change to the previous lookup class.
 786      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 787      * {@code C} becomes the new previous lookup class
 788      * and the target class becomes the new lookup class.
 789      * In that case, if there was already a previous lookup class in {@code M0},
 790      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 791      * drops all privileges.
 792      * For example,
 793      * <blockquote><pre>
 794      * {@code
 795      * Lookup lookup = MethodHandles.lookup();   // in class C
 796      * Lookup lookup2 = lookup.in(D.class);
 797      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 798      * }</pre></blockquote>
 799      * <p>
 800      * The {@link #lookup()} factory method produces a {@code Lookup} object
 801      * with {@code null} previous lookup class.
 802      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 803      * to class {@code D} without elevation of privileges.
 804      * If {@code C} and {@code D} are in the same module,
 805      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 806      * same previous lookup class as the original {@code lookup}, or
 807      * {@code null} if not present.
 808      * <p>
 809      * When a {@code Lookup} teleports from a class
 810      * in one nest to another nest, {@code PRIVATE} access is dropped.
 811      * When a {@code Lookup} teleports from a class in one package to
 812      * another package, {@code PACKAGE} access is dropped.
 813      * When a {@code Lookup} teleports from a class in one module to another module,
 814      * {@code MODULE} access is dropped.
 815      * Teleporting across modules drops the ability to access non-exported classes
 816      * in both the module of the new lookup class and the module of the old lookup class
 817      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 818      * A {@code Lookup} can teleport back and forth to a class in the module of
 819      * the lookup class and the module of the previous class lookup.
 820      * Teleporting across modules can only decrease access but cannot increase it.
 821      * Teleporting to some third module drops all accesses.
 822      * <p>
 823      * In the above example, if {@code C} and {@code D} are in different modules,
 824      * {@code lookup2} records {@code D} as its lookup class and
 825      * {@code C} as its previous lookup class and {@code lookup2} has only
 826      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 827      * {@code C}'s module and {@code D}'s module.
 828      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 829      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 830      * class {@code D} is recorded as its previous lookup class.
 831      * <p>
 832      * Teleporting across modules restricts access to the public types that
 833      * both the lookup class and the previous lookup class can equally access
 834      * (see below).
 835      * <p>
 836      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 837      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 838      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 839      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 840      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 841      * to call {@code privateLookupIn}.
 842      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 843      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 844      * produces a new {@code Lookup} on {@code T} with full capabilities.
 845      * A {@code lookup} on {@code C} is also allowed
 846      * to do deep reflection on {@code T} in another module {@code M2} if
 847      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 848      * the package containing {@code T} to at least {@code M1}.
 849      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 850      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 851      * The resulting {@code Lookup} can be used to do member lookup or teleport
 852      * to another lookup class by calling {@link #in Lookup::in}.  But
 853      * it cannot be used to obtain another private {@code Lookup} by calling
 854      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 855      * because it has no {@code MODULE} access.
 856      *
 857      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 858      *
 859      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 860      * allows cross-module access. The access checking is performed with respect
 861      * to both the lookup class and the previous lookup class if present.
 862      * <p>
 863      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 864      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 865      * exported unconditionally}.
 866      * <p>
 867      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 868      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 869      * that are readable to {@code M1} and the type is in a package that is exported
 870      * at least to {@code M1}.
 871      * <p>
 872      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 873      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 874      * the intersection of all public types that are accessible to {@code M1}
 875      * with all public types that are accessible to {@code M0}. {@code M0}
 876      * reads {@code M1} and hence the set of accessible types includes:
 877      *
 878      * <ul>
 879      * <li>unconditional-exported packages from {@code M1}</li>
 880      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 881      * <li>
 882      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 883      *     and {@code M1} read {@code M2}
 884      * </li>
 885      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 886      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 887      * <li>
 888      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 889      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 890      * </li>
 891      * </ul>
 892      *
 893      * <h2><a id="access-modes"></a>Access modes</h2>
 894      *
 895      * The table below shows the access modes of a {@code Lookup} produced by
 896      * any of the following factory or transformation methods:
 897      * <ul>
 898      * <li>{@link #lookup() MethodHandles::lookup}</li>
 899      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 900      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 901      * <li>{@link Lookup#in Lookup::in}</li>
 902      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 903      * </ul>
 904      *
 905      * <table class="striped">
 906      * <caption style="display:none">
 907      * Access mode summary
 908      * </caption>
 909      * <thead>
 910      * <tr>
 911      * <th scope="col">Lookup object</th>
 912      * <th style="text-align:center">original</th>
 913      * <th style="text-align:center">protected</th>
 914      * <th style="text-align:center">private</th>
 915      * <th style="text-align:center">package</th>
 916      * <th style="text-align:center">module</th>
 917      * <th style="text-align:center">public</th>
 918      * </tr>
 919      * </thead>
 920      * <tbody>
 921      * <tr>
 922      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 923      * <td style="text-align:center">ORI</td>
 924      * <td style="text-align:center">PRO</td>
 925      * <td style="text-align:center">PRI</td>
 926      * <td style="text-align:center">PAC</td>
 927      * <td style="text-align:center">MOD</td>
 928      * <td style="text-align:center">1R</td>
 929      * </tr>
 930      * <tr>
 931      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 932      * <td></td>
 933      * <td></td>
 934      * <td></td>
 935      * <td style="text-align:center">PAC</td>
 936      * <td style="text-align:center">MOD</td>
 937      * <td style="text-align:center">1R</td>
 938      * </tr>
 939      * <tr>
 940      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 941      * <td></td>
 942      * <td></td>
 943      * <td></td>
 944      * <td></td>
 945      * <td style="text-align:center">MOD</td>
 946      * <td style="text-align:center">1R</td>
 947      * </tr>
 948      * <tr>
 949      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 950      * <td></td>
 951      * <td></td>
 952      * <td></td>
 953      * <td></td>
 954      * <td></td>
 955      * <td style="text-align:center">2R</td>
 956      * </tr>
 957      * <tr>
 958      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 959      * <td></td>
 960      * <td></td>
 961      * <td></td>
 962      * <td></td>
 963      * <td></td>
 964      * <td style="text-align:center">2R</td>
 965      * </tr>
 966      * <tr>
 967      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 968      * <td></td>
 969      * <td style="text-align:center">PRO</td>
 970      * <td style="text-align:center">PRI</td>
 971      * <td style="text-align:center">PAC</td>
 972      * <td style="text-align:center">MOD</td>
 973      * <td style="text-align:center">1R</td>
 974      * </tr>
 975      * <tr>
 976      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 977      * <td></td>
 978      * <td style="text-align:center">PRO</td>
 979      * <td style="text-align:center">PRI</td>
 980      * <td style="text-align:center">PAC</td>
 981      * <td style="text-align:center">MOD</td>
 982      * <td style="text-align:center">1R</td>
 983      * </tr>
 984      * <tr>
 985      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
 986      * <td></td>
 987      * <td></td>
 988      * <td></td>
 989      * <td style="text-align:center">PAC</td>
 990      * <td style="text-align:center">MOD</td>
 991      * <td style="text-align:center">1R</td>
 992      * </tr>
 993      * <tr>
 994      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
 995      * <td></td>
 996      * <td></td>
 997      * <td></td>
 998      * <td></td>
 999      * <td style="text-align:center">MOD</td>
1000      * <td style="text-align:center">1R</td>
1001      * </tr>
1002      * <tr>
1003      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1004      * <td></td>
1005      * <td></td>
1006      * <td></td>
1007      * <td></td>
1008      * <td></td>
1009      * <td style="text-align:center">2R</td>
1010      * </tr>
1011      * <tr>
1012      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1013      * <td></td>
1014      * <td></td>
1015      * <td style="text-align:center">PRI</td>
1016      * <td style="text-align:center">PAC</td>
1017      * <td style="text-align:center">MOD</td>
1018      * <td style="text-align:center">1R</td>
1019      * </tr>
1020      * <tr>
1021      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1022      * <td></td>
1023      * <td></td>
1024      * <td></td>
1025      * <td style="text-align:center">PAC</td>
1026      * <td style="text-align:center">MOD</td>
1027      * <td style="text-align:center">1R</td>
1028      * </tr>
1029      * <tr>
1030      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1031      * <td></td>
1032      * <td></td>
1033      * <td></td>
1034      * <td></td>
1035      * <td style="text-align:center">MOD</td>
1036      * <td style="text-align:center">1R</td>
1037      * </tr>
1038      * <tr>
1039      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1040      * <td></td>
1041      * <td></td>
1042      * <td></td>
1043      * <td></td>
1044      * <td></td>
1045      * <td style="text-align:center">1R</td>
1046      * </tr>
1047      * <tr>
1048      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1049      * <td></td>
1050      * <td></td>
1051      * <td></td>
1052      * <td></td>
1053      * <td></td>
1054      * <td style="text-align:center">none</td>
1055      * <tr>
1056      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1057      * <td></td>
1058      * <td style="text-align:center">PRO</td>
1059      * <td style="text-align:center">PRI</td>
1060      * <td style="text-align:center">PAC</td>
1061      * <td></td>
1062      * <td style="text-align:center">2R</td>
1063      * </tr>
1064      * <tr>
1065      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1066      * <td></td>
1067      * <td style="text-align:center">PRO</td>
1068      * <td style="text-align:center">PRI</td>
1069      * <td style="text-align:center">PAC</td>
1070      * <td></td>
1071      * <td style="text-align:center">2R</td>
1072      * </tr>
1073      * <tr>
1074      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1075      * <td></td>
1076      * <td></td>
1077      * <td></td>
1078      * <td></td>
1079      * <td></td>
1080      * <td style="text-align:center">IAE</td>
1081      * </tr>
1082      * <tr>
1083      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1084      * <td></td>
1085      * <td></td>
1086      * <td></td>
1087      * <td style="text-align:center">PAC</td>
1088      * <td></td>
1089      * <td style="text-align:center">2R</td>
1090      * </tr>
1091      * <tr>
1092      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1093      * <td></td>
1094      * <td></td>
1095      * <td></td>
1096      * <td></td>
1097      * <td></td>
1098      * <td style="text-align:center">2R</td>
1099      * </tr>
1100      * <tr>
1101      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1102      * <td></td>
1103      * <td></td>
1104      * <td></td>
1105      * <td></td>
1106      * <td></td>
1107      * <td style="text-align:center">2R</td>
1108      * </tr>
1109      * <tr>
1110      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1111      * <td></td>
1112      * <td></td>
1113      * <td></td>
1114      * <td></td>
1115      * <td></td>
1116      * <td style="text-align:center">none</td>
1117      * </tr>
1118      * <tr>
1119      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1120      * <td></td>
1121      * <td></td>
1122      * <td style="text-align:center">PRI</td>
1123      * <td style="text-align:center">PAC</td>
1124      * <td></td>
1125      * <td style="text-align:center">2R</td>
1126      * </tr>
1127      * <tr>
1128      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1129      * <td></td>
1130      * <td></td>
1131      * <td></td>
1132      * <td style="text-align:center">PAC</td>
1133      * <td></td>
1134      * <td style="text-align:center">2R</td>
1135      * </tr>
1136      * <tr>
1137      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1138      * <td></td>
1139      * <td></td>
1140      * <td></td>
1141      * <td></td>
1142      * <td></td>
1143      * <td style="text-align:center">2R</td>
1144      * </tr>
1145      * <tr>
1146      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1147      * <td></td>
1148      * <td></td>
1149      * <td></td>
1150      * <td></td>
1151      * <td></td>
1152      * <td style="text-align:center">2R</td>
1153      * </tr>
1154      * <tr>
1155      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1156      * <td></td>
1157      * <td></td>
1158      * <td></td>
1159      * <td></td>
1160      * <td></td>
1161      * <td style="text-align:center">none</td>
1162      * </tr>
1163      * <tr>
1164      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1165      * <td></td>
1166      * <td></td>
1167      * <td style="text-align:center">PRI</td>
1168      * <td style="text-align:center">PAC</td>
1169      * <td style="text-align:center">MOD</td>
1170      * <td style="text-align:center">1R</td>
1171      * </tr>
1172      * <tr>
1173      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1174      * <td></td>
1175      * <td></td>
1176      * <td></td>
1177      * <td style="text-align:center">PAC</td>
1178      * <td style="text-align:center">MOD</td>
1179      * <td style="text-align:center">1R</td>
1180      * </tr>
1181      * <tr>
1182      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1183      * <td></td>
1184      * <td></td>
1185      * <td></td>
1186      * <td></td>
1187      * <td style="text-align:center">MOD</td>
1188      * <td style="text-align:center">1R</td>
1189      * </tr>
1190      * <tr>
1191      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1192      * <td></td>
1193      * <td></td>
1194      * <td></td>
1195      * <td></td>
1196      * <td></td>
1197      * <td style="text-align:center">1R</td>
1198      * </tr>
1199      * <tr>
1200      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1201      * <td></td>
1202      * <td></td>
1203      * <td></td>
1204      * <td></td>
1205      * <td></td>
1206      * <td style="text-align:center">none</td>
1207      * </tr>
1208      * <tr>
1209      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1210      * <td></td>
1211      * <td></td>
1212      * <td></td>
1213      * <td></td>
1214      * <td></td>
1215      * <td style="text-align:center">U</td>
1216      * </tr>
1217      * <tr>
1218      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1219      * <td></td>
1220      * <td></td>
1221      * <td></td>
1222      * <td></td>
1223      * <td></td>
1224      * <td style="text-align:center">U</td>
1225      * </tr>
1226      * <tr>
1227      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1228      * <td></td>
1229      * <td></td>
1230      * <td></td>
1231      * <td></td>
1232      * <td></td>
1233      * <td style="text-align:center">U</td>
1234      * </tr>
1235      * <tr>
1236      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1237      * <td></td>
1238      * <td></td>
1239      * <td></td>
1240      * <td></td>
1241      * <td></td>
1242      * <td style="text-align:center">none</td>
1243      * </tr>
1244      * <tr>
1245      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1246      * <td></td>
1247      * <td></td>
1248      * <td></td>
1249      * <td></td>
1250      * <td></td>
1251      * <td style="text-align:center">IAE</td>
1252      * </tr>
1253      * <tr>
1254      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1255      * <td></td>
1256      * <td></td>
1257      * <td></td>
1258      * <td></td>
1259      * <td></td>
1260      * <td style="text-align:center">none</td>
1261      * </tr>
1262      * </tbody>
1263      * </table>
1264      *
1265      * <p>
1266      * Notes:
1267      * <ul>
1268      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1269      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1270      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1271      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1272      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1273      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1274      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1275      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1276      *     {@code MOD} indicates {@link #MODULE} bit set,
1277      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1278      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1279      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1280      * <li>Public access comes in three kinds:
1281      * <ul>
1282      * <li>unconditional ({@code U}): the lookup assumes readability.
1283      *     The lookup has {@code null} previous lookup class.
1284      * <li>one-module-reads ({@code 1R}): the module access checking is
1285      *     performed with respect to the lookup class.  The lookup has {@code null}
1286      *     previous lookup class.
1287      * <li>two-module-reads ({@code 2R}): the module access checking is
1288      *     performed with respect to the lookup class and the previous lookup class.
1289      *     The lookup has a non-null previous lookup class which is in a
1290      *     different module from the current lookup class.
1291      * </ul>
1292      * <li>Any attempt to reach a third module loses all access.</li>
1293      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1294      * all access modes are dropped.</li>
1295      * </ul>
1296      *
1297      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1298      * Although bytecode instructions can only refer to classes in
1299      * a related class loader, this API can search for methods in any
1300      * class, as long as a reference to its {@code Class} object is
1301      * available.  Such cross-loader references are also possible with the
1302      * Core Reflection API, and are impossible to bytecode instructions
1303      * such as {@code invokestatic} or {@code getfield}.
1304      * There is a {@linkplain java.lang.SecurityManager security manager API}
1305      * to allow applications to check such cross-loader references.
1306      * These checks apply to both the {@code MethodHandles.Lookup} API
1307      * and the Core Reflection API
1308      * (as found on {@link java.lang.Class Class}).
1309      * <p>
1310      * If a security manager is present, member and class lookups are subject to
1311      * additional checks.
1312      * From one to three calls are made to the security manager.
1313      * Any of these calls can refuse access by throwing a
1314      * {@link java.lang.SecurityException SecurityException}.
1315      * Define {@code smgr} as the security manager,
1316      * {@code lookc} as the lookup class of the current lookup object,
1317      * {@code refc} as the containing class in which the member
1318      * is being sought, and {@code defc} as the class in which the
1319      * member is actually defined.
1320      * (If a class or other type is being accessed,
1321      * the {@code refc} and {@code defc} values are the class itself.)
1322      * The value {@code lookc} is defined as <em>not present</em>
1323      * if the current lookup object does not have
1324      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1325      * The calls are made according to the following rules:
1326      * <ul>
1327      * <li><b>Step 1:</b>
1328      *     If {@code lookc} is not present, or if its class loader is not
1329      *     the same as or an ancestor of the class loader of {@code refc},
1330      *     then {@link SecurityManager#checkPackageAccess
1331      *     smgr.checkPackageAccess(refcPkg)} is called,
1332      *     where {@code refcPkg} is the package of {@code refc}.
1333      * <li><b>Step 2a:</b>
1334      *     If the retrieved member is not public and
1335      *     {@code lookc} is not present, then
1336      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1337      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1338      * <li><b>Step 2b:</b>
1339      *     If the retrieved class has a {@code null} class loader,
1340      *     and {@code lookc} is not present, then
1341      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1342      *     with {@code RuntimePermission("getClassLoader")} is called.
1343      * <li><b>Step 3:</b>
1344      *     If the retrieved member is not public,
1345      *     and if {@code lookc} is not present,
1346      *     and if {@code defc} and {@code refc} are different,
1347      *     then {@link SecurityManager#checkPackageAccess
1348      *     smgr.checkPackageAccess(defcPkg)} is called,
1349      *     where {@code defcPkg} is the package of {@code defc}.
1350      * </ul>
1351      * Security checks are performed after other access checks have passed.
1352      * Therefore, the above rules presuppose a member or class that is public,
1353      * or else that is being accessed from a lookup class that has
1354      * rights to access the member or class.
1355      * <p>
1356      * If a security manager is present and the current lookup object does not have
1357      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1358      * {@link #defineClass(byte[]) defineClass},
1359      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1360      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1361      * defineHiddenClassWithClassData}
1362      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1363      * with {@code RuntimePermission("defineClass")}.
1364      *
1365      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1366      * A small number of Java methods have a special property called caller sensitivity.
1367      * A <em>caller-sensitive</em> method can behave differently depending on the
1368      * identity of its immediate caller.
1369      * <p>
1370      * If a method handle for a caller-sensitive method is requested,
1371      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1372      * but they take account of the lookup class in a special way.
1373      * The resulting method handle behaves as if it were called
1374      * from an instruction contained in the lookup class,
1375      * so that the caller-sensitive method detects the lookup class.
1376      * (By contrast, the invoker of the method handle is disregarded.)
1377      * Thus, in the case of caller-sensitive methods,
1378      * different lookup classes may give rise to
1379      * differently behaving method handles.
1380      * <p>
1381      * In cases where the lookup object is
1382      * {@link MethodHandles#publicLookup() publicLookup()},
1383      * or some other lookup object without the
1384      * {@linkplain #ORIGINAL original access},
1385      * the lookup class is disregarded.
1386      * In such cases, no caller-sensitive method handle can be created,
1387      * access is forbidden, and the lookup fails with an
1388      * {@code IllegalAccessException}.
1389      * <p style="font-size:smaller;">
1390      * <em>Discussion:</em>
1391      * For example, the caller-sensitive method
1392      * {@link java.lang.Class#forName(String) Class.forName(x)}
1393      * can return varying classes or throw varying exceptions,
1394      * depending on the class loader of the class that calls it.
1395      * A public lookup of {@code Class.forName} will fail, because
1396      * there is no reasonable way to determine its bytecode behavior.
1397      * <p style="font-size:smaller;">
1398      * If an application caches method handles for broad sharing,
1399      * it should use {@code publicLookup()} to create them.
1400      * If there is a lookup of {@code Class.forName}, it will fail,
1401      * and the application must take appropriate action in that case.
1402      * It may be that a later lookup, perhaps during the invocation of a
1403      * bootstrap method, can incorporate the specific identity
1404      * of the caller, making the method accessible.
1405      * <p style="font-size:smaller;">
1406      * The function {@code MethodHandles.lookup} is caller sensitive
1407      * so that there can be a secure foundation for lookups.
1408      * Nearly all other methods in the JSR 292 API rely on lookup
1409      * objects to check access requests.
1410      *
1411      * @revised 9
1412      */
1413     public static final
1414     class Lookup {
1415         /** The class on behalf of whom the lookup is being performed. */
1416         private final Class<?> lookupClass;
1417 
1418         /** previous lookup class */
1419         private final Class<?> prevLookupClass;
1420 
1421         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1422         private final int allowedModes;
1423 
1424         static {
1425             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1426         }
1427 
1428         /** A single-bit mask representing {@code public} access,
1429          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1430          *  The value, {@code 0x01}, happens to be the same as the value of the
1431          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1432          *  <p>
1433          *  A {@code Lookup} with this lookup mode performs cross-module access check
1434          *  with respect to the {@linkplain #lookupClass() lookup class} and
1435          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1436          */
1437         public static final int PUBLIC = Modifier.PUBLIC;
1438 
1439         /** A single-bit mask representing {@code private} access,
1440          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1441          *  The value, {@code 0x02}, happens to be the same as the value of the
1442          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1443          */
1444         public static final int PRIVATE = Modifier.PRIVATE;
1445 
1446         /** A single-bit mask representing {@code protected} access,
1447          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1448          *  The value, {@code 0x04}, happens to be the same as the value of the
1449          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1450          */
1451         public static final int PROTECTED = Modifier.PROTECTED;
1452 
1453         /** A single-bit mask representing {@code package} access (default access),
1454          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1455          *  The value is {@code 0x08}, which does not correspond meaningfully to
1456          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1457          */
1458         public static final int PACKAGE = Modifier.STATIC;
1459 
1460         /** A single-bit mask representing {@code module} access,
1461          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1462          *  The value is {@code 0x10}, which does not correspond meaningfully to
1463          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1464          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1465          *  with this lookup mode can access all public types in the module of the
1466          *  lookup class and public types in packages exported by other modules
1467          *  to the module of the lookup class.
1468          *  <p>
1469          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1470          *  previous lookup class} is always {@code null}.
1471          *
1472          *  @since 9
1473          */
1474         public static final int MODULE = PACKAGE << 1;
1475 
1476         /** A single-bit mask representing {@code unconditional} access
1477          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1478          *  The value is {@code 0x20}, which does not correspond meaningfully to
1479          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1480          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1481          *  java.lang.Module#canRead(java.lang.Module) readability}.
1482          *  This lookup mode can access all public members of public types
1483          *  of all modules when the type is in a package that is {@link
1484          *  java.lang.Module#isExported(String) exported unconditionally}.
1485          *
1486          *  <p>
1487          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1488          *  previous lookup class} is always {@code null}.
1489          *
1490          *  @since 9
1491          *  @see #publicLookup()
1492          */
1493         public static final int UNCONDITIONAL = PACKAGE << 2;
1494 
1495         /** A single-bit mask representing {@code original} access
1496          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1497          *  The value is {@code 0x40}, which does not correspond meaningfully to
1498          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1499          *
1500          *  <p>
1501          *  If this lookup mode is set, the {@code Lookup} object must be
1502          *  created by the original lookup class by calling
1503          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1504          *  invoked by the VM.  The {@code Lookup} object with this lookup
1505          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1506          *
1507          *  @since 16
1508          */
1509         public static final int ORIGINAL = PACKAGE << 3;
1510 
1511         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1512         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1513         private static final int TRUSTED   = -1;
1514 
1515         /*
1516          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1517          * Adjust 0 => PACKAGE
1518          */
1519         private static int fixmods(int mods) {
1520             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1521             if (Modifier.isPublic(mods))
1522                 mods |= UNCONDITIONAL;
1523             return (mods != 0) ? mods : PACKAGE;
1524         }
1525 
1526         /** Tells which class is performing the lookup.  It is this class against
1527          *  which checks are performed for visibility and access permissions.
1528          *  <p>
1529          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1530          *  access checks are performed against both the lookup class and the previous lookup class.
1531          *  <p>
1532          *  The class implies a maximum level of access permission,
1533          *  but the permissions may be additionally limited by the bitmask
1534          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1535          *  can be accessed.
1536          *  @return the lookup class, on behalf of which this lookup object finds members
1537          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1538          */
1539         public Class<?> lookupClass() {
1540             return lookupClass;
1541         }
1542 
1543         /** Reports a lookup class in another module that this lookup object
1544          * was previously teleported from, or {@code null}.
1545          * <p>
1546          * A {@code Lookup} object produced by the factory methods, such as the
1547          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1548          * has {@code null} previous lookup class.
1549          * A {@code Lookup} object has a non-null previous lookup class
1550          * when this lookup was teleported from an old lookup class
1551          * in one module to a new lookup class in another module.
1552          *
1553          * @return the lookup class in another module that this lookup object was
1554          *         previously teleported from, or {@code null}
1555          * @since 14
1556          * @see #in(Class)
1557          * @see MethodHandles#privateLookupIn(Class, Lookup)
1558          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1559          */
1560         public Class<?> previousLookupClass() {
1561             return prevLookupClass;
1562         }
1563 
1564         // This is just for calling out to MethodHandleImpl.
1565         private Class<?> lookupClassOrNull() {
1566             return (allowedModes == TRUSTED) ? null : lookupClass;
1567         }
1568 
1569         /** Tells which access-protection classes of members this lookup object can produce.
1570          *  The result is a bit-mask of the bits
1571          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1572          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1573          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1574          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1575          *  {@linkplain #MODULE MODULE (0x10)},
1576          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1577          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1578          *  <p>
1579          *  A freshly-created lookup object
1580          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1581          *  all possible bits set, except {@code UNCONDITIONAL}.
1582          *  A lookup object on a new lookup class
1583          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1584          *  may have some mode bits set to zero.
1585          *  Mode bits can also be
1586          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1587          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1588          *  The purpose of this is to restrict access via the new lookup object,
1589          *  so that it can access only names which can be reached by the original
1590          *  lookup object, and also by the new lookup class.
1591          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1592          *  @see #in
1593          *  @see #dropLookupMode
1594          *
1595          *  @revised 9
1596          */
1597         public int lookupModes() {
1598             return allowedModes & ALL_MODES;
1599         }
1600 
1601         /** Embody the current class (the lookupClass) as a lookup class
1602          * for method handle creation.
1603          * Must be called by from a method in this package,
1604          * which in turn is called by a method not in this package.
1605          */
1606         Lookup(Class<?> lookupClass) {
1607             this(lookupClass, null, FULL_POWER_MODES);
1608         }
1609 
1610         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1611             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1612                     && prevLookupClass.getModule() != lookupClass.getModule());
1613             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1614             this.lookupClass = lookupClass;
1615             this.prevLookupClass = prevLookupClass;
1616             this.allowedModes = allowedModes;
1617         }
1618 
1619         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1620             // make sure we haven't accidentally picked up a privileged class:
1621             checkUnprivilegedlookupClass(lookupClass);
1622             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1623         }
1624 
1625         /**
1626          * Creates a lookup on the specified new lookup class.
1627          * The resulting object will report the specified
1628          * class as its own {@link #lookupClass() lookupClass}.
1629          *
1630          * <p>
1631          * However, the resulting {@code Lookup} object is guaranteed
1632          * to have no more access capabilities than the original.
1633          * In particular, access capabilities can be lost as follows:<ul>
1634          * <li>If the new lookup class is different from the old lookup class,
1635          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1636          * <li>If the new lookup class is in a different module from the old one,
1637          * i.e. {@link #MODULE MODULE} access is lost.
1638          * <li>If the new lookup class is in a different package
1639          * than the old one, protected and default (package) members will not be accessible,
1640          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1641          * <li>If the new lookup class is not within the same package member
1642          * as the old one, private members will not be accessible, and protected members
1643          * will not be accessible by virtue of inheritance,
1644          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1645          * (Protected members may continue to be accessible because of package sharing.)
1646          * <li>If the new lookup class is not
1647          * {@linkplain #accessClass(Class) accessible} to this lookup,
1648          * then no members, not even public members, will be accessible
1649          * i.e. all access modes are lost.
1650          * <li>If the new lookup class, the old lookup class and the previous lookup class
1651          * are all in different modules i.e. teleporting to a third module,
1652          * all access modes are lost.
1653          * </ul>
1654          * <p>
1655          * The new previous lookup class is chosen as follows:
1656          * <ul>
1657          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1658          * the new previous lookup class is {@code null}.
1659          * <li>If the new lookup class is in the same module as the old lookup class,
1660          * the new previous lookup class is the old previous lookup class.
1661          * <li>If the new lookup class is in a different module from the old lookup class,
1662          * the new previous lookup class is the old lookup class.
1663          *</ul>
1664          * <p>
1665          * The resulting lookup's capabilities for loading classes
1666          * (used during {@link #findClass} invocations)
1667          * are determined by the lookup class' loader,
1668          * which may change due to this operation.
1669          *
1670          * @param requestedLookupClass the desired lookup class for the new lookup object
1671          * @return a lookup object which reports the desired lookup class, or the same object
1672          * if there is no change
1673          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1674          * @throws NullPointerException if the argument is null
1675          *
1676          * @revised 9
1677          * @see #accessClass(Class)
1678          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1679          */
1680         public Lookup in(Class<?> requestedLookupClass) {
1681             Objects.requireNonNull(requestedLookupClass);
1682             if (requestedLookupClass.isPrimitive())
1683                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1684             if (requestedLookupClass.isArray())
1685                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1686 
1687             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1688                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1689             if (requestedLookupClass == this.lookupClass)
1690                 return this;  // keep same capabilities
1691             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1692             Module fromModule = this.lookupClass.getModule();
1693             Module targetModule = requestedLookupClass.getModule();
1694             Class<?> plc = this.previousLookupClass();
1695             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1696                 assert plc == null;
1697                 newModes = UNCONDITIONAL;
1698             } else if (fromModule != targetModule) {
1699                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1700                     // allow hopping back and forth between fromModule and plc's module
1701                     // but not the third module
1702                     newModes = 0;
1703                 }
1704                 // drop MODULE access
1705                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1706                 // teleport from this lookup class
1707                 plc = this.lookupClass;
1708             }
1709             if ((newModes & PACKAGE) != 0
1710                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1711                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1712             }
1713             // Allow nestmate lookups to be created without special privilege:
1714             if ((newModes & PRIVATE) != 0
1715                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1716                 newModes &= ~(PRIVATE|PROTECTED);
1717             }
1718             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1719                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1720                 // The requested class it not accessible from the lookup class.
1721                 // No permissions.
1722                 newModes = 0;
1723             }
1724             return newLookup(requestedLookupClass, plc, newModes);
1725         }
1726 
1727         /**
1728          * Creates a lookup on the same lookup class which this lookup object
1729          * finds members, but with a lookup mode that has lost the given lookup mode.
1730          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1731          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1732          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1733          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1734          *
1735          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1736          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1737          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1738          * lookup has no access.
1739          *
1740          * <p> If this lookup is not a public lookup, then the following applies
1741          * regardless of its {@linkplain #lookupModes() lookup modes}.
1742          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1743          * dropped and so the resulting lookup mode will never have these access
1744          * capabilities. When dropping {@code PACKAGE}
1745          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1746          * access. When dropping {@code MODULE} then the resulting lookup will not
1747          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1748          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1749          *
1750          * @apiNote
1751          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1752          * delegate non-public access within the package of the lookup class without
1753          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1754          * A lookup with {@code MODULE} but not
1755          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1756          * the module of the lookup class without conferring package access.
1757          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1758          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1759          * to public classes accessible to both the module of the lookup class
1760          * and the module of the previous lookup class.
1761          *
1762          * @param modeToDrop the lookup mode to drop
1763          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1764          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1765          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1766          * or {@code UNCONDITIONAL}
1767          * @see MethodHandles#privateLookupIn
1768          * @since 9
1769          */
1770         public Lookup dropLookupMode(int modeToDrop) {
1771             int oldModes = lookupModes();
1772             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1773             switch (modeToDrop) {
1774                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1775                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1776                 case PACKAGE: newModes &= ~(PRIVATE); break;
1777                 case PROTECTED:
1778                 case PRIVATE:
1779                 case ORIGINAL:
1780                 case UNCONDITIONAL: break;
1781                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1782             }
1783             if (newModes == oldModes) return this;  // return self if no change
1784             return newLookup(lookupClass(), previousLookupClass(), newModes);
1785         }
1786 
1787         /**
1788          * Creates and links a class or interface from {@code bytes}
1789          * with the same class loader and in the same runtime package and
1790          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1791          * {@linkplain #lookupClass() lookup class} as if calling
1792          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1793          * ClassLoader::defineClass}.
1794          *
1795          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1796          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1797          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1798          * that the lookup object was created by a caller in the runtime package (or derived
1799          * from a lookup originally created by suitably privileged code to a target class in
1800          * the runtime package). </p>
1801          *
1802          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1803          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1804          * same package as the lookup class. </p>
1805          *
1806          * <p> This method does not run the class initializer. The class initializer may
1807          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1808          * Specification</em>. </p>
1809          *
1810          * <p> If there is a security manager and this lookup does not have {@linkplain
1811          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1812          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1813          *
1814          * @param bytes the class bytes
1815          * @return the {@code Class} object for the class
1816          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1817          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1818          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1819          * than the lookup class or {@code bytes} is not a class or interface
1820          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1821          * @throws VerifyError if the newly created class cannot be verified
1822          * @throws LinkageError if the newly created class cannot be linked for any other reason
1823          * @throws SecurityException if a security manager is present and it
1824          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1825          * @throws NullPointerException if {@code bytes} is {@code null}
1826          * @since 9
1827          * @see Lookup#privateLookupIn
1828          * @see Lookup#dropLookupMode
1829          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1830          */
1831         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1832             ensureDefineClassPermission();
1833             if ((lookupModes() & PACKAGE) == 0)
1834                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1835             return makeClassDefiner(bytes.clone()).defineClass(false);
1836         }
1837 
1838         private void ensureDefineClassPermission() {
1839             if (allowedModes == TRUSTED)  return;
1840 
1841             if (!hasFullPrivilegeAccess()) {
1842                 @SuppressWarnings("removal")
1843                 SecurityManager sm = System.getSecurityManager();
1844                 if (sm != null)
1845                     sm.checkPermission(new RuntimePermission("defineClass"));
1846             }
1847         }
1848 
1849         /**
1850          * The set of class options that specify whether a hidden class created by
1851          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1852          * Lookup::defineHiddenClass} method is dynamically added as a new member
1853          * to the nest of a lookup class and/or whether a hidden class has
1854          * a strong relationship with the class loader marked as its defining loader.
1855          *
1856          * @since 15
1857          */
1858         public enum ClassOption {
1859             /**
1860              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1861              * of a lookup class as a nestmate.
1862              *
1863              * <p> A hidden nestmate class has access to the private members of all
1864              * classes and interfaces in the same nest.
1865              *
1866              * @see Class#getNestHost()
1867              */
1868             NESTMATE(NESTMATE_CLASS),
1869 
1870             /**
1871              * Specifies that a hidden class has a <em>strong</em>
1872              * relationship with the class loader marked as its defining loader,
1873              * as a normal class or interface has with its own defining loader.
1874              * This means that the hidden class may be unloaded if and only if
1875              * its defining loader is not reachable and thus may be reclaimed
1876              * by a garbage collector (JLS 12.7).
1877              *
1878              * <p> By default, a hidden class or interface may be unloaded
1879              * even if the class loader that is marked as its defining loader is
1880              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1881 
1882              *
1883              * @jls 12.7 Unloading of Classes and Interfaces
1884              */
1885             STRONG(STRONG_LOADER_LINK);
1886 
1887             /* the flag value is used by VM at define class time */
1888             private final int flag;
1889             ClassOption(int flag) {
1890                 this.flag = flag;
1891             }
1892 
1893             static int optionsToFlag(Set<ClassOption> options) {
1894                 int flags = 0;
1895                 for (ClassOption cp : options) {
1896                     flags |= cp.flag;
1897                 }
1898                 return flags;
1899             }
1900         }
1901 
1902         /**
1903          * Creates a <em>hidden</em> class or interface from {@code bytes},
1904          * returning a {@code Lookup} on the newly created class or interface.
1905          *
1906          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1907          * which either defines {@code C} directly or delegates to another class loader.
1908          * A class loader defines {@code C} directly by invoking
1909          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1910          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1911          * to derive {@code C} from a purported representation in {@code class} file format.
1912          * In situations where use of a class loader is undesirable, a class or interface
1913          * {@code C} can be created by this method instead. This method is capable of
1914          * defining {@code C}, and thereby creating it, without invoking
1915          * {@code ClassLoader::defineClass}.
1916          * Instead, this method defines {@code C} as if by arranging for
1917          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1918          * from a purported representation in {@code class} file format
1919          * using the following rules:
1920          *
1921          * <ol>
1922          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1923          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1924          * This level of access is needed to create {@code C} in the module
1925          * of the lookup class of this {@code Lookup}.</li>
1926          *
1927          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1928          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1929          * The major and minor version may differ from the {@code class} file version
1930          * of the lookup class of this {@code Lookup}.</li>
1931          *
1932          * <li> The value of {@code this_class} must be a valid index in the
1933          * {@code constant_pool} table, and the entry at that index must be a valid
1934          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1935          * encoded in internal form that is specified by this structure. {@code N} must
1936          * denote a class or interface in the same package as the lookup class.</li>
1937          *
1938          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1939          * where {@code <suffix>} is an unqualified name.
1940          *
1941          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1942          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1943          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1944          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1945          * refers to the new {@code CONSTANT_Utf8_info} structure.
1946          *
1947          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1948          *
1949          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1950          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1951          * with the following adjustments:
1952          * <ul>
1953          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1954          * that includes a single {@code "."} character, even though this is not a valid
1955          * binary class or interface name in internal form.</li>
1956          *
1957          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1958          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1959          *
1960          * <li> {@code C} is considered to have the same runtime
1961          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1962          * and {@linkplain java.security.ProtectionDomain protection domain}
1963          * as the lookup class of this {@code Lookup}.
1964          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1965          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1966          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1967          * <ul>
1968          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1969          *      even though this is not a valid binary class or interface name.</li>
1970          * <li> {@link Class#descriptorString()} returns the string
1971          *      {@code "L" + N + "." + <suffix> + ";"},
1972          *      even though this is not a valid type descriptor name.</li>
1973          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1974          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1975          * </ul>
1976          * </ul>
1977          * </li>
1978          * </ol>
1979          *
1980          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1981          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1982          * <ul>
1983          * <li> During verification, whenever it is necessary to load the class named
1984          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1985          * made of any class loader.</li>
1986          *
1987          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1988          * by {@code this_class}, the symbolic reference is considered to be resolved to
1989          * {@code C} and resolution always succeeds immediately.</li>
1990          * </ul>
1991          *
1992          * <p> If the {@code initialize} parameter is {@code true},
1993          * then {@code C} is initialized by the Java Virtual Machine.
1994          *
1995          * <p> The newly created class or interface {@code C} serves as the
1996          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
1997          * returned by this method. {@code C} is <em>hidden</em> in the sense that
1998          * no other class or interface can refer to {@code C} via a constant pool entry.
1999          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2000          * a method parameter type, or a method return type by any other class.
2001          * This is because a hidden class or interface does not have a binary name, so
2002          * there is no internal form available to record in any class's constant pool.
2003          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2004          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2005          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
2006          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2007          * JVM Tool Interface</a>.
2008          *
2009          * <p> A class or interface created by
2010          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2011          * a class loader} has a strong relationship with that class loader.
2012          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2013          * that {@linkplain Class#getClassLoader() defined it}.
2014          * This means that a class created by a class loader may be unloaded if and
2015          * only if its defining loader is not reachable and thus may be reclaimed
2016          * by a garbage collector (JLS 12.7).
2017          *
2018          * By default, however, a hidden class or interface may be unloaded even if
2019          * the class loader that is marked as its defining loader is
2020          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2021          * This behavior is useful when a hidden class or interface serves multiple
2022          * classes defined by arbitrary class loaders.  In other cases, a hidden
2023          * class or interface may be linked to a single class (or a small number of classes)
2024          * with the same defining loader as the hidden class or interface.
2025          * In such cases, where the hidden class or interface must be coterminous
2026          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2027          * option may be passed in {@code options}.
2028          * This arranges for a hidden class to have the same strong relationship
2029          * with the class loader marked as its defining loader,
2030          * as a normal class or interface has with its own defining loader.
2031          *
2032          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2033          * may still prevent a hidden class or interface from being
2034          * unloaded by ensuring that the {@code Class} object is reachable.
2035          *
2036          * <p> The unloading characteristics are set for each hidden class when it is
2037          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2038          * to be unloaded independently of the class loader marked as their defining loader
2039          * is that a very large number of hidden classes may be created by an application.
2040          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2041          * just as if normal classes were created by class loaders.
2042          *
2043          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2044          * their private members.  The nest relationship is determined by
2045          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2046          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2047          * By default, a hidden class belongs to a nest consisting only of itself
2048          * because a hidden class has no binary name.
2049          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2050          * to create a hidden class or interface {@code C} as a member of a nest.
2051          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2052          * in the {@code ClassFile} structure from which {@code C} was derived.
2053          * Instead, the following rules determine the nest host of {@code C}:
2054          * <ul>
2055          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2056          *     been determined, then let {@code H} be the nest host of the lookup class.
2057          *     Otherwise, the nest host of the lookup class is determined using the
2058          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2059          * <li>The nest host of {@code C} is determined to be {@code H},
2060          *     the nest host of the lookup class.</li>
2061          * </ul>
2062          *
2063          * <p> A hidden class or interface may be serializable, but this requires a custom
2064          * serialization mechanism in order to ensure that instances are properly serialized
2065          * and deserialized. The default serialization mechanism supports only classes and
2066          * interfaces that are discoverable by their class name.
2067          *
2068          * @param bytes the bytes that make up the class data,
2069          * in the format of a valid {@code class} file as defined by
2070          * <cite>The Java Virtual Machine Specification</cite>.
2071          * @param initialize if {@code true} the class will be initialized.
2072          * @param options {@linkplain ClassOption class options}
2073          * @return the {@code Lookup} object on the hidden class,
2074          * with {@linkplain #ORIGINAL original} and
2075          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2076          *
2077          * @throws IllegalAccessException if this {@code Lookup} does not have
2078          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2079          * @throws SecurityException if a security manager is present and it
2080          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2081          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2082          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2083          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2084          * than the lookup class or {@code bytes} is not a class or interface
2085          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2086          * @throws IncompatibleClassChangeError if the class or interface named as
2087          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2088          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2089          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2090          * {@code C} is {@code C} itself
2091          * @throws VerifyError if the newly created class cannot be verified
2092          * @throws LinkageError if the newly created class cannot be linked for any other reason
2093          * @throws NullPointerException if any parameter is {@code null}
2094          *
2095          * @since 15
2096          * @see Class#isHidden()
2097          * @jvms 4.2.1 Binary Class and Interface Names
2098          * @jvms 4.2.2 Unqualified Names
2099          * @jvms 4.7.28 The {@code NestHost} Attribute
2100          * @jvms 4.7.29 The {@code NestMembers} Attribute
2101          * @jvms 5.4.3.1 Class and Interface Resolution
2102          * @jvms 5.4.4 Access Control
2103          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2104          * @jvms 5.4 Linking
2105          * @jvms 5.5 Initialization
2106          * @jls 12.7 Unloading of Classes and Interfaces
2107          */
2108         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2109                 throws IllegalAccessException
2110         {
2111             Objects.requireNonNull(bytes);
2112             Objects.requireNonNull(options);
2113 
2114             ensureDefineClassPermission();
2115             if (!hasFullPrivilegeAccess()) {
2116                 throw new IllegalAccessException(this + " does not have full privilege access");
2117             }
2118 
2119             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2120         }
2121 
2122         /**
2123          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2124          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2125          * returning a {@code Lookup} on the newly created class or interface.
2126          *
2127          * <p> This method is equivalent to calling
2128          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2129          * as if the hidden class is injected with a private static final <i>unnamed</i>
2130          * field which is initialized with the given {@code classData} at
2131          * the first instruction of the class initializer.
2132          * The newly created class is linked by the Java Virtual Machine.
2133          *
2134          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2135          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2136          * methods can be used to retrieve the {@code classData}.
2137          *
2138          * @apiNote
2139          * A framework can create a hidden class with class data with one or more
2140          * objects and load the class data as dynamically-computed constant(s)
2141          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2142          * Class data} is accessible only to the lookup object created by the newly
2143          * defined hidden class but inaccessible to other members in the same nest
2144          * (unlike private static fields that are accessible to nestmates).
2145          * Care should be taken w.r.t. mutability for example when passing
2146          * an array or other mutable structure through the class data.
2147          * Changing any value stored in the class data at runtime may lead to
2148          * unpredictable behavior.
2149          * If the class data is a {@code List}, it is good practice to make it
2150          * unmodifiable for example via {@link List#of List::of}.
2151          *
2152          * @param bytes     the class bytes
2153          * @param classData pre-initialized class data
2154          * @param initialize if {@code true} the class will be initialized.
2155          * @param options   {@linkplain ClassOption class options}
2156          * @return the {@code Lookup} object on the hidden class,
2157          * with {@linkplain #ORIGINAL original} and
2158          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2159          *
2160          * @throws IllegalAccessException if this {@code Lookup} does not have
2161          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2162          * @throws SecurityException if a security manager is present and it
2163          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2164          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2165          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2166          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2167          * than the lookup class or {@code bytes} is not a class or interface
2168          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2169          * @throws IncompatibleClassChangeError if the class or interface named as
2170          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2171          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2172          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2173          * {@code C} is {@code C} itself
2174          * @throws VerifyError if the newly created class cannot be verified
2175          * @throws LinkageError if the newly created class cannot be linked for any other reason
2176          * @throws NullPointerException if any parameter is {@code null}
2177          *
2178          * @since 16
2179          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2180          * @see Class#isHidden()
2181          * @see MethodHandles#classData(Lookup, String, Class)
2182          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2183          * @jvms 4.2.1 Binary Class and Interface Names
2184          * @jvms 4.2.2 Unqualified Names
2185          * @jvms 4.7.28 The {@code NestHost} Attribute
2186          * @jvms 4.7.29 The {@code NestMembers} Attribute
2187          * @jvms 5.4.3.1 Class and Interface Resolution
2188          * @jvms 5.4.4 Access Control
2189          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2190          * @jvms 5.4 Linking
2191          * @jvms 5.5 Initialization
2192          * @jls 12.7 Unloading of Classes and Interface
2193          */
2194         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2195                 throws IllegalAccessException
2196         {
2197             Objects.requireNonNull(bytes);
2198             Objects.requireNonNull(classData);
2199             Objects.requireNonNull(options);
2200 
2201             ensureDefineClassPermission();
2202             if (!hasFullPrivilegeAccess()) {
2203                 throw new IllegalAccessException(this + " does not have full privilege access");
2204             }
2205 
2206             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2207                        .defineClassAsLookup(initialize, classData);
2208         }
2209 
2210         static class ClassFile {
2211             final String name;
2212             final int accessFlags;
2213             final byte[] bytes;
2214             ClassFile(String name, int accessFlags, byte[] bytes) {
2215                 this.name = name;
2216                 this.accessFlags = accessFlags;
2217                 this.bytes = bytes;
2218             }
2219 
2220             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2221                 return new ClassFile(name, 0, bytes);
2222             }
2223 
2224             /**
2225              * This method checks the class file version and the structure of `this_class`.
2226              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2227              * that is in the named package.
2228              *
2229              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2230              * or the class is not in the given package name.
2231              */
2232             static ClassFile newInstance(byte[] bytes, String pkgName) {
2233                 int magic = readInt(bytes, 0);
2234                 if (magic != 0xCAFEBABE) {
2235                     throw new ClassFormatError("Incompatible magic value: " + magic);
2236                 }
2237                 int minor = readUnsignedShort(bytes, 4);
2238                 int major = readUnsignedShort(bytes, 6);
2239                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2240                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2241                 }
2242 
2243                 String name;
2244                 int accessFlags;
2245                 try {
2246                     ClassReader reader = new ClassReader(bytes);
2247                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2248                     // workaround to read `this_class` using readConst and validate the value
2249                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2250                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2251                     if (!(constant instanceof Type type)) {
2252                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2253                     }
2254                     if (!type.getDescriptor().startsWith("L")) {
2255                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2256                     }
2257                     name = type.getClassName();
2258                     accessFlags = reader.readUnsignedShort(reader.header);
2259                 } catch (RuntimeException e) {
2260                     // ASM exceptions are poorly specified
2261                     ClassFormatError cfe = new ClassFormatError();
2262                     cfe.initCause(e);
2263                     throw cfe;
2264                 }
2265 
2266                 // must be a class or interface
2267                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2268                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2269                 }
2270 
2271                 // check if it's in the named package
2272                 int index = name.lastIndexOf('.');
2273                 String pn = (index == -1) ? "" : name.substring(0, index);
2274                 if (!pn.equals(pkgName)) {
2275                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2276                 }
2277 
2278                 return new ClassFile(name, accessFlags, bytes);
2279             }
2280 
2281             private static int readInt(byte[] bytes, int offset) {
2282                 if ((offset+4) > bytes.length) {
2283                     throw new ClassFormatError("Invalid ClassFile structure");
2284                 }
2285                 return ((bytes[offset] & 0xFF) << 24)
2286                         | ((bytes[offset + 1] & 0xFF) << 16)
2287                         | ((bytes[offset + 2] & 0xFF) << 8)
2288                         | (bytes[offset + 3] & 0xFF);
2289             }
2290 
2291             private static int readUnsignedShort(byte[] bytes, int offset) {
2292                 if ((offset+2) > bytes.length) {
2293                     throw new ClassFormatError("Invalid ClassFile structure");
2294                 }
2295                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2296             }
2297         }
2298 
2299         /*
2300          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2301          * from the given bytes.
2302          *
2303          * Caller should make a defensive copy of the arguments if needed
2304          * before calling this factory method.
2305          *
2306          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2307          * {@bytes} denotes a class in a different package than the lookup class
2308          */
2309         private ClassDefiner makeClassDefiner(byte[] bytes) {
2310             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2311             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2312         }
2313 
2314         /**
2315          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2316          * from the given bytes.  The name must be in the same package as the lookup class.
2317          *
2318          * Caller should make a defensive copy of the arguments if needed
2319          * before calling this factory method.
2320          *
2321          * @param bytes   class bytes
2322          * @return ClassDefiner that defines a hidden class of the given bytes.
2323          *
2324          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2325          * {@bytes} denotes a class in a different package than the lookup class
2326          */
2327         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2328             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2329             return makeHiddenClassDefiner(cf, Set.of(), false);
2330         }
2331 
2332         /**
2333          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2334          * from the given bytes and options.
2335          * The name must be in the same package as the lookup class.
2336          *
2337          * Caller should make a defensive copy of the arguments if needed
2338          * before calling this factory method.
2339          *
2340          * @param bytes   class bytes
2341          * @param options class options
2342          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2343          * @return ClassDefiner that defines a hidden class of the given bytes and options
2344          *
2345          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2346          * {@bytes} denotes a class in a different package than the lookup class
2347          */
2348         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2349                                             Set<ClassOption> options,
2350                                             boolean accessVmAnnotations) {
2351             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2352             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2353         }
2354 
2355         /**
2356          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2357          * from the given bytes and the given options.  No package name check on the given name.
2358          *
2359          * @param name    fully-qualified name that specifies the prefix of the hidden class
2360          * @param bytes   class bytes
2361          * @param options class options
2362          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2363          */
2364         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) {
2365             // skip name and access flags validation
2366             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false);
2367         }
2368 
2369         /**
2370          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2371          * from the given class file and options.
2372          *
2373          * @param cf ClassFile
2374          * @param options class options
2375          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2376          */
2377         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2378                                                     Set<ClassOption> options,
2379                                                     boolean accessVmAnnotations) {
2380             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2381             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2382                 // jdk.internal.vm.annotations are permitted for classes
2383                 // defined to boot loader and platform loader
2384                 flags |= ACCESS_VM_ANNOTATIONS;
2385             }
2386 
2387             return new ClassDefiner(this, cf, flags);
2388         }
2389 
2390         static class ClassDefiner {
2391             private final Lookup lookup;
2392             private final String name;
2393             private final byte[] bytes;
2394             private final int classFlags;
2395 
2396             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2397                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2398                 this.lookup = lookup;
2399                 this.bytes = cf.bytes;
2400                 this.name = cf.name;
2401                 this.classFlags = flags;
2402             }
2403 
2404             String className() {
2405                 return name;
2406             }
2407 
2408             Class<?> defineClass(boolean initialize) {
2409                 return defineClass(initialize, null);
2410             }
2411 
2412             Lookup defineClassAsLookup(boolean initialize) {
2413                 Class<?> c = defineClass(initialize, null);
2414                 return new Lookup(c, null, FULL_POWER_MODES);
2415             }
2416 
2417             /**
2418              * Defines the class of the given bytes and the given classData.
2419              * If {@code initialize} parameter is true, then the class will be initialized.
2420              *
2421              * @param initialize true if the class to be initialized
2422              * @param classData classData or null
2423              * @return the class
2424              *
2425              * @throws LinkageError linkage error
2426              */
2427             Class<?> defineClass(boolean initialize, Object classData) {
2428                 Class<?> lookupClass = lookup.lookupClass();
2429                 ClassLoader loader = lookupClass.getClassLoader();
2430                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2431                 Class<?> c = SharedSecrets.getJavaLangAccess()
2432                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2433                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2434                 return c;
2435             }
2436 
2437             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2438                 Class<?> c = defineClass(initialize, classData);
2439                 return new Lookup(c, null, FULL_POWER_MODES);
2440             }
2441 
2442             private boolean isNestmate() {
2443                 return (classFlags & NESTMATE_CLASS) != 0;
2444             }
2445         }
2446 
2447         private ProtectionDomain lookupClassProtectionDomain() {
2448             ProtectionDomain pd = cachedProtectionDomain;
2449             if (pd == null) {
2450                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2451             }
2452             return pd;
2453         }
2454 
2455         // cached protection domain
2456         private volatile ProtectionDomain cachedProtectionDomain;
2457 
2458         // Make sure outer class is initialized first.
2459         static { IMPL_NAMES.getClass(); }
2460 
2461         /** Package-private version of lookup which is trusted. */
2462         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2463 
2464         /** Version of lookup which is trusted minimally.
2465          *  It can only be used to create method handles to publicly accessible
2466          *  members in packages that are exported unconditionally.
2467          */
2468         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2469 
2470         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2471             String name = lookupClass.getName();
2472             if (name.startsWith("java.lang.invoke."))
2473                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2474         }
2475 
2476         /**
2477          * Displays the name of the class from which lookups are to be made,
2478          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2479          * previous lookup class} if present.
2480          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2481          * If there are restrictions on the access permitted to this lookup,
2482          * this is indicated by adding a suffix to the class name, consisting
2483          * of a slash and a keyword.  The keyword represents the strongest
2484          * allowed access, and is chosen as follows:
2485          * <ul>
2486          * <li>If no access is allowed, the suffix is "/noaccess".
2487          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2488          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2489          * <li>If only public and module access are allowed, the suffix is "/module".
2490          * <li>If public and package access are allowed, the suffix is "/package".
2491          * <li>If public, package, and private access are allowed, the suffix is "/private".
2492          * </ul>
2493          * If none of the above cases apply, it is the case that
2494          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2495          * (public, module, package, private, and protected) is allowed.
2496          * In this case, no suffix is added.
2497          * This is true only of an object obtained originally from
2498          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2499          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2500          * always have restricted access, and will display a suffix.
2501          * <p>
2502          * (It may seem strange that protected access should be
2503          * stronger than private access.  Viewed independently from
2504          * package access, protected access is the first to be lost,
2505          * because it requires a direct subclass relationship between
2506          * caller and callee.)
2507          * @see #in
2508          *
2509          * @revised 9
2510          */
2511         @Override
2512         public String toString() {
2513             String cname = lookupClass.getName();
2514             if (prevLookupClass != null)
2515                 cname += "/" + prevLookupClass.getName();
2516             switch (allowedModes) {
2517             case 0:  // no privileges
2518                 return cname + "/noaccess";
2519             case UNCONDITIONAL:
2520                 return cname + "/publicLookup";
2521             case PUBLIC:
2522                 return cname + "/public";
2523             case PUBLIC|MODULE:
2524                 return cname + "/module";
2525             case PUBLIC|PACKAGE:
2526             case PUBLIC|MODULE|PACKAGE:
2527                 return cname + "/package";
2528             case PUBLIC|PACKAGE|PRIVATE:
2529             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2530                     return cname + "/private";
2531             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2532             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2533             case FULL_POWER_MODES:
2534                     return cname;
2535             case TRUSTED:
2536                 return "/trusted";  // internal only; not exported
2537             default:  // Should not happen, but it's a bitfield...
2538                 cname = cname + "/" + Integer.toHexString(allowedModes);
2539                 assert(false) : cname;
2540                 return cname;
2541             }
2542         }
2543 
2544         /**
2545          * Produces a method handle for a static method.
2546          * The type of the method handle will be that of the method.
2547          * (Since static methods do not take receivers, there is no
2548          * additional receiver argument inserted into the method handle type,
2549          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2550          * The method and all its argument types must be accessible to the lookup object.
2551          * <p>
2552          * The returned method handle will have
2553          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2554          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2555          * <p>
2556          * If the returned method handle is invoked, the method's class will
2557          * be initialized, if it has not already been initialized.
2558          * <p><b>Example:</b>
2559          * <blockquote><pre>{@code
2560 import static java.lang.invoke.MethodHandles.*;
2561 import static java.lang.invoke.MethodType.*;
2562 ...
2563 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2564   "asList", methodType(List.class, Object[].class));
2565 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2566          * }</pre></blockquote>
2567          * @param refc the class from which the method is accessed
2568          * @param name the name of the method
2569          * @param type the type of the method
2570          * @return the desired method handle
2571          * @throws NoSuchMethodException if the method does not exist
2572          * @throws IllegalAccessException if access checking fails,
2573          *                                or if the method is not {@code static},
2574          *                                or if the method's variable arity modifier bit
2575          *                                is set and {@code asVarargsCollector} fails
2576          * @throws    SecurityException if a security manager is present and it
2577          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2578          * @throws NullPointerException if any argument is null
2579          */
2580         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2581             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2582             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2583         }
2584 
2585         /**
2586          * Produces a method handle for a virtual method.
2587          * The type of the method handle will be that of the method,
2588          * with the receiver type (usually {@code refc}) prepended.
2589          * The method and all its argument types must be accessible to the lookup object.
2590          * <p>
2591          * When called, the handle will treat the first argument as a receiver
2592          * and, for non-private methods, dispatch on the receiver's type to determine which method
2593          * implementation to enter.
2594          * For private methods the named method in {@code refc} will be invoked on the receiver.
2595          * (The dispatching action is identical with that performed by an
2596          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2597          * <p>
2598          * The first argument will be of type {@code refc} if the lookup
2599          * class has full privileges to access the member.  Otherwise
2600          * the member must be {@code protected} and the first argument
2601          * will be restricted in type to the lookup class.
2602          * <p>
2603          * The returned method handle will have
2604          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2605          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2606          * <p>
2607          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2608          * instructions and method handles produced by {@code findVirtual},
2609          * if the class is {@code MethodHandle} and the name string is
2610          * {@code invokeExact} or {@code invoke}, the resulting
2611          * method handle is equivalent to one produced by
2612          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2613          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2614          * with the same {@code type} argument.
2615          * <p>
2616          * If the class is {@code VarHandle} and the name string corresponds to
2617          * the name of a signature-polymorphic access mode method, the resulting
2618          * method handle is equivalent to one produced by
2619          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2620          * the access mode corresponding to the name string and with the same
2621          * {@code type} arguments.
2622          * <p>
2623          * <b>Example:</b>
2624          * <blockquote><pre>{@code
2625 import static java.lang.invoke.MethodHandles.*;
2626 import static java.lang.invoke.MethodType.*;
2627 ...
2628 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2629   "concat", methodType(String.class, String.class));
2630 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2631   "hashCode", methodType(int.class));
2632 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2633   "hashCode", methodType(int.class));
2634 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2635 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2636 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2637 // interface method:
2638 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2639   "subSequence", methodType(CharSequence.class, int.class, int.class));
2640 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2641 // constructor "internal method" must be accessed differently:
2642 MethodType MT_newString = methodType(void.class); //()V for new String()
2643 try { assertEquals("impossible", lookup()
2644         .findVirtual(String.class, "<init>", MT_newString));
2645  } catch (NoSuchMethodException ex) { } // OK
2646 MethodHandle MH_newString = publicLookup()
2647   .findConstructor(String.class, MT_newString);
2648 assertEquals("", (String) MH_newString.invokeExact());
2649          * }</pre></blockquote>
2650          *
2651          * @param refc the class or interface from which the method is accessed
2652          * @param name the name of the method
2653          * @param type the type of the method, with the receiver argument omitted
2654          * @return the desired method handle
2655          * @throws NoSuchMethodException if the method does not exist
2656          * @throws IllegalAccessException if access checking fails,
2657          *                                or if the method is {@code static},
2658          *                                or if the method's variable arity modifier bit
2659          *                                is set and {@code asVarargsCollector} fails
2660          * @throws    SecurityException if a security manager is present and it
2661          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2662          * @throws NullPointerException if any argument is null
2663          */
2664         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2665             if (refc == MethodHandle.class) {
2666                 MethodHandle mh = findVirtualForMH(name, type);
2667                 if (mh != null)  return mh;
2668             } else if (refc == VarHandle.class) {
2669                 MethodHandle mh = findVirtualForVH(name, type);
2670                 if (mh != null)  return mh;
2671             }
2672             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2673             MemberName method = resolveOrFail(refKind, refc, name, type);
2674             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2675         }
2676         private MethodHandle findVirtualForMH(String name, MethodType type) {
2677             // these names require special lookups because of the implicit MethodType argument
2678             if ("invoke".equals(name))
2679                 return invoker(type);
2680             if ("invokeExact".equals(name))
2681                 return exactInvoker(type);
2682             assert(!MemberName.isMethodHandleInvokeName(name));
2683             return null;
2684         }
2685         private MethodHandle findVirtualForVH(String name, MethodType type) {
2686             try {
2687                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2688             } catch (IllegalArgumentException e) {
2689                 return null;
2690             }
2691         }
2692 
2693         /**
2694          * Produces a method handle which creates an object and initializes it, using
2695          * the constructor of the specified type.
2696          * The parameter types of the method handle will be those of the constructor,
2697          * while the return type will be a reference to the constructor's class.
2698          * The constructor and all its argument types must be accessible to the lookup object.
2699          * <p>
2700          * The requested type must have a return type of {@code void}.
2701          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2702          * <p>
2703          * The returned method handle will have
2704          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2705          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2706          * <p>
2707          * If the returned method handle is invoked, the constructor's class will
2708          * be initialized, if it has not already been initialized.
2709          * <p><b>Example:</b>
2710          * <blockquote><pre>{@code
2711 import static java.lang.invoke.MethodHandles.*;
2712 import static java.lang.invoke.MethodType.*;
2713 ...
2714 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2715   ArrayList.class, methodType(void.class, Collection.class));
2716 Collection orig = Arrays.asList("x", "y");
2717 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2718 assert(orig != copy);
2719 assertEquals(orig, copy);
2720 // a variable-arity constructor:
2721 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2722   ProcessBuilder.class, methodType(void.class, String[].class));
2723 ProcessBuilder pb = (ProcessBuilder)
2724   MH_newProcessBuilder.invoke("x", "y", "z");
2725 assertEquals("[x, y, z]", pb.command().toString());
2726          * }</pre></blockquote>
2727          * @param refc the class or interface from which the method is accessed
2728          * @param type the type of the method, with the receiver argument omitted, and a void return type
2729          * @return the desired method handle
2730          * @throws NoSuchMethodException if the constructor does not exist
2731          * @throws IllegalAccessException if access checking fails
2732          *                                or if the method's variable arity modifier bit
2733          *                                is set and {@code asVarargsCollector} fails
2734          * @throws    SecurityException if a security manager is present and it
2735          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2736          * @throws NullPointerException if any argument is null
2737          */
2738         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2739             if (refc.isArray()) {
2740                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2741             }
2742             String name = "<init>";
2743             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2744             return getDirectConstructor(refc, ctor);
2745         }
2746 
2747         /**
2748          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2749          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2750          * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class,
2751          * and then determines whether the class is accessible to this lookup object.
2752          * <p>
2753          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2754          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2755          *
2756          * @param targetName the fully qualified name of the class to be looked up.
2757          * @return the requested class.
2758          * @throws SecurityException if a security manager is present and it
2759          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2760          * @throws LinkageError if the linkage fails
2761          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2762          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2763          * modes.
2764          * @throws NullPointerException if {@code targetName} is null
2765          * @since 9
2766          * @jvms 5.4.3.1 Class and Interface Resolution
2767          */
2768         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2769             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2770             return accessClass(targetClass);
2771         }
2772 
2773         /**
2774          * Ensures that {@code targetClass} has been initialized. The class
2775          * to be initialized must be {@linkplain #accessClass accessible}
2776          * to this {@code Lookup} object.  This method causes {@code targetClass}
2777          * to be initialized if it has not been already initialized,
2778          * as specified in JVMS {@jvms 5.5}.
2779          *
2780          * <p>
2781          * This method returns when {@code targetClass} is fully initialized, or
2782          * when {@code targetClass} is being initialized by the current thread.
2783          *
2784          * @param targetClass the class to be initialized
2785          * @return {@code targetClass} that has been initialized, or that is being
2786          *         initialized by the current thread.
2787          *
2788          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2789          *          or array class
2790          * @throws  IllegalAccessException if {@code targetClass} is not
2791          *          {@linkplain #accessClass accessible} to this lookup
2792          * @throws  ExceptionInInitializerError if the class initialization provoked
2793          *          by this method fails
2794          * @throws  SecurityException if a security manager is present and it
2795          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2796          * @since 15
2797          * @jvms 5.5 Initialization
2798          */
2799         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2800             if (targetClass.isPrimitive())
2801                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2802             if (targetClass.isArray())
2803                 throw new IllegalArgumentException(targetClass + " is an array class");
2804 
2805             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2806                 throw makeAccessException(targetClass);
2807             }
2808             checkSecurityManager(targetClass);
2809 
2810             // ensure class initialization
2811             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2812             return targetClass;
2813         }
2814 
2815         /*
2816          * Returns IllegalAccessException due to access violation to the given targetClass.
2817          *
2818          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2819          * which verifies access to a class rather a member.
2820          */
2821         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2822             String message = "access violation: "+ targetClass;
2823             if (this == MethodHandles.publicLookup()) {
2824                 message += ", from public Lookup";
2825             } else {
2826                 Module m = lookupClass().getModule();
2827                 message += ", from " + lookupClass() + " (" + m + ")";
2828                 if (prevLookupClass != null) {
2829                     message += ", previous lookup " +
2830                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2831                 }
2832             }
2833             return new IllegalAccessException(message);
2834         }
2835 
2836         /**
2837          * Determines if a class can be accessed from the lookup context defined by
2838          * this {@code Lookup} object. The static initializer of the class is not run.
2839          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2840          * if the element type of the array class is accessible.  Otherwise,
2841          * {@code targetClass} is determined as accessible as follows.
2842          *
2843          * <p>
2844          * If {@code targetClass} is in the same module as the lookup class,
2845          * the lookup class is {@code LC} in module {@code M1} and
2846          * the previous lookup class is in module {@code M0} or
2847          * {@code null} if not present,
2848          * {@code targetClass} is accessible if and only if one of the following is true:
2849          * <ul>
2850          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2851          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2852          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2853          *     in the same runtime package of {@code LC}.</li>
2854          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2855          *     a public type in {@code M1}.</li>
2856          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2857          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2858          *     if the previous lookup class is present; otherwise, {@code targetClass}
2859          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2860          * </ul>
2861          *
2862          * <p>
2863          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2864          * can access public types in all modules when the type is in a package
2865          * that is exported unconditionally.
2866          * <p>
2867          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2868          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2869          * is inaccessible.
2870          * <p>
2871          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2872          * {@code M1} is the module containing {@code lookupClass} and
2873          * {@code M2} is the module containing {@code targetClass},
2874          * then {@code targetClass} is accessible if and only if
2875          * <ul>
2876          * <li>{@code M1} reads {@code M2}, and
2877          * <li>{@code targetClass} is public and in a package exported by
2878          *     {@code M2} at least to {@code M1}.
2879          * </ul>
2880          * <p>
2881          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2882          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2883          * containing the previous lookup class, then {@code targetClass} is accessible
2884          * if and only if one of the following is true:
2885          * <ul>
2886          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2887          *     {@linkplain Module#reads reads} {@code M0} and the type is
2888          *     in a package that is exported to at least {@code M1}.
2889          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2890          *     {@linkplain Module#reads reads} {@code M1} and the type is
2891          *     in a package that is exported to at least {@code M0}.
2892          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2893          *     and {@code M1} reads {@code M2} and the type is in a package
2894          *     that is exported to at least both {@code M0} and {@code M2}.
2895          * </ul>
2896          * <p>
2897          * Otherwise, {@code targetClass} is not accessible.
2898          *
2899          * @param targetClass the class to be access-checked
2900          * @return the class that has been access-checked
2901          * @throws IllegalAccessException if the class is not accessible from the lookup class
2902          * and previous lookup class, if present, using the allowed access modes.
2903          * @throws SecurityException if a security manager is present and it
2904          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2905          * @throws NullPointerException if {@code targetClass} is {@code null}
2906          * @since 9
2907          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2908          */
2909         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2910             if (!isClassAccessible(targetClass)) {
2911                 throw makeAccessException(targetClass);
2912             }
2913             checkSecurityManager(targetClass);
2914             return targetClass;
2915         }
2916 
2917         /**
2918          * Produces an early-bound method handle for a virtual method.
2919          * It will bypass checks for overriding methods on the receiver,
2920          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2921          * instruction from within the explicitly specified {@code specialCaller}.
2922          * The type of the method handle will be that of the method,
2923          * with a suitably restricted receiver type prepended.
2924          * (The receiver type will be {@code specialCaller} or a subtype.)
2925          * The method and all its argument types must be accessible
2926          * to the lookup object.
2927          * <p>
2928          * Before method resolution,
2929          * if the explicitly specified caller class is not identical with the
2930          * lookup class, or if this lookup object does not have
2931          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2932          * privileges, the access fails.
2933          * <p>
2934          * The returned method handle will have
2935          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2936          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2937          * <p style="font-size:smaller;">
2938          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2939          * even though the {@code invokespecial} instruction can refer to them
2940          * in special circumstances.  Use {@link #findConstructor findConstructor}
2941          * to access instance initialization methods in a safe manner.)</em>
2942          * <p><b>Example:</b>
2943          * <blockquote><pre>{@code
2944 import static java.lang.invoke.MethodHandles.*;
2945 import static java.lang.invoke.MethodType.*;
2946 ...
2947 static class Listie extends ArrayList {
2948   public String toString() { return "[wee Listie]"; }
2949   static Lookup lookup() { return MethodHandles.lookup(); }
2950 }
2951 ...
2952 // no access to constructor via invokeSpecial:
2953 MethodHandle MH_newListie = Listie.lookup()
2954   .findConstructor(Listie.class, methodType(void.class));
2955 Listie l = (Listie) MH_newListie.invokeExact();
2956 try { assertEquals("impossible", Listie.lookup().findSpecial(
2957         Listie.class, "<init>", methodType(void.class), Listie.class));
2958  } catch (NoSuchMethodException ex) { } // OK
2959 // access to super and self methods via invokeSpecial:
2960 MethodHandle MH_super = Listie.lookup().findSpecial(
2961   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2962 MethodHandle MH_this = Listie.lookup().findSpecial(
2963   Listie.class, "toString" , methodType(String.class), Listie.class);
2964 MethodHandle MH_duper = Listie.lookup().findSpecial(
2965   Object.class, "toString" , methodType(String.class), Listie.class);
2966 assertEquals("[]", (String) MH_super.invokeExact(l));
2967 assertEquals(""+l, (String) MH_this.invokeExact(l));
2968 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2969 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2970         String.class, "toString", methodType(String.class), Listie.class));
2971  } catch (IllegalAccessException ex) { } // OK
2972 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2973 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2974          * }</pre></blockquote>
2975          *
2976          * @param refc the class or interface from which the method is accessed
2977          * @param name the name of the method (which must not be "&lt;init&gt;")
2978          * @param type the type of the method, with the receiver argument omitted
2979          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2980          * @return the desired method handle
2981          * @throws NoSuchMethodException if the method does not exist
2982          * @throws IllegalAccessException if access checking fails,
2983          *                                or if the method is {@code static},
2984          *                                or if the method's variable arity modifier bit
2985          *                                is set and {@code asVarargsCollector} fails
2986          * @throws    SecurityException if a security manager is present and it
2987          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2988          * @throws NullPointerException if any argument is null
2989          */
2990         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2991                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2992             checkSpecialCaller(specialCaller, refc);
2993             Lookup specialLookup = this.in(specialCaller);
2994             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2995             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
2996         }
2997 
2998         /**
2999          * Produces a method handle giving read access to a non-static field.
3000          * The type of the method handle will have a return type of the field's
3001          * value type.
3002          * The method handle's single argument will be the instance containing
3003          * the field.
3004          * Access checking is performed immediately on behalf of the lookup class.
3005          * @param refc the class or interface from which the method is accessed
3006          * @param name the field's name
3007          * @param type the field's type
3008          * @return a method handle which can load values from the field
3009          * @throws NoSuchFieldException if the field does not exist
3010          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3011          * @throws    SecurityException if a security manager is present and it
3012          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3013          * @throws NullPointerException if any argument is null
3014          * @see #findVarHandle(Class, String, Class)
3015          */
3016         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3017             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3018             return getDirectField(REF_getField, refc, field);
3019         }
3020 
3021         /**
3022          * Produces a method handle giving write access to a non-static field.
3023          * The type of the method handle will have a void return type.
3024          * The method handle will take two arguments, the instance containing
3025          * the field, and the value to be stored.
3026          * The second argument will be of the field's value type.
3027          * Access checking is performed immediately on behalf of the lookup class.
3028          * @param refc the class or interface from which the method is accessed
3029          * @param name the field's name
3030          * @param type the field's type
3031          * @return a method handle which can store values into the field
3032          * @throws NoSuchFieldException if the field does not exist
3033          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3034          *                                or {@code final}
3035          * @throws    SecurityException if a security manager is present and it
3036          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3037          * @throws NullPointerException if any argument is null
3038          * @see #findVarHandle(Class, String, Class)
3039          */
3040         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3041             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3042             return getDirectField(REF_putField, refc, field);
3043         }
3044 
3045         /**
3046          * Produces a VarHandle giving access to a non-static field {@code name}
3047          * of type {@code type} declared in a class of type {@code recv}.
3048          * The VarHandle's variable type is {@code type} and it has one
3049          * coordinate type, {@code recv}.
3050          * <p>
3051          * Access checking is performed immediately on behalf of the lookup
3052          * class.
3053          * <p>
3054          * Certain access modes of the returned VarHandle are unsupported under
3055          * the following conditions:
3056          * <ul>
3057          * <li>if the field is declared {@code final}, then the write, atomic
3058          *     update, numeric atomic update, and bitwise atomic update access
3059          *     modes are unsupported.
3060          * <li>if the field type is anything other than {@code byte},
3061          *     {@code short}, {@code char}, {@code int}, {@code long},
3062          *     {@code float}, or {@code double} then numeric atomic update
3063          *     access modes are unsupported.
3064          * <li>if the field type is anything other than {@code boolean},
3065          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3066          *     {@code long} then bitwise atomic update access modes are
3067          *     unsupported.
3068          * </ul>
3069          * <p>
3070          * If the field is declared {@code volatile} then the returned VarHandle
3071          * will override access to the field (effectively ignore the
3072          * {@code volatile} declaration) in accordance to its specified
3073          * access modes.
3074          * <p>
3075          * If the field type is {@code float} or {@code double} then numeric
3076          * and atomic update access modes compare values using their bitwise
3077          * representation (see {@link Float#floatToRawIntBits} and
3078          * {@link Double#doubleToRawLongBits}, respectively).
3079          * @apiNote
3080          * Bitwise comparison of {@code float} values or {@code double} values,
3081          * as performed by the numeric and atomic update access modes, differ
3082          * from the primitive {@code ==} operator and the {@link Float#equals}
3083          * and {@link Double#equals} methods, specifically with respect to
3084          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3085          * Care should be taken when performing a compare and set or a compare
3086          * and exchange operation with such values since the operation may
3087          * unexpectedly fail.
3088          * There are many possible NaN values that are considered to be
3089          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3090          * provided by Java can distinguish between them.  Operation failure can
3091          * occur if the expected or witness value is a NaN value and it is
3092          * transformed (perhaps in a platform specific manner) into another NaN
3093          * value, and thus has a different bitwise representation (see
3094          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3095          * details).
3096          * The values {@code -0.0} and {@code +0.0} have different bitwise
3097          * representations but are considered equal when using the primitive
3098          * {@code ==} operator.  Operation failure can occur if, for example, a
3099          * numeric algorithm computes an expected value to be say {@code -0.0}
3100          * and previously computed the witness value to be say {@code +0.0}.
3101          * @param recv the receiver class, of type {@code R}, that declares the
3102          * non-static field
3103          * @param name the field's name
3104          * @param type the field's type, of type {@code T}
3105          * @return a VarHandle giving access to non-static fields.
3106          * @throws NoSuchFieldException if the field does not exist
3107          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3108          * @throws    SecurityException if a security manager is present and it
3109          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3110          * @throws NullPointerException if any argument is null
3111          * @since 9
3112          */
3113         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3114             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3115             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3116             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3117         }
3118 
3119         /**
3120          * Produces a method handle giving read access to a static field.
3121          * The type of the method handle will have a return type of the field's
3122          * value type.
3123          * The method handle will take no arguments.
3124          * Access checking is performed immediately on behalf of the lookup class.
3125          * <p>
3126          * If the returned method handle is invoked, the field's class will
3127          * be initialized, if it has not already been initialized.
3128          * @param refc the class or interface from which the method is accessed
3129          * @param name the field's name
3130          * @param type the field's type
3131          * @return a method handle which can load values from the field
3132          * @throws NoSuchFieldException if the field does not exist
3133          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3134          * @throws    SecurityException if a security manager is present and it
3135          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3136          * @throws NullPointerException if any argument is null
3137          */
3138         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3139             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3140             return getDirectField(REF_getStatic, refc, field);
3141         }
3142 
3143         /**
3144          * Produces a method handle giving write access to a static field.
3145          * The type of the method handle will have a void return type.
3146          * The method handle will take a single
3147          * argument, of the field's value type, the value to be stored.
3148          * Access checking is performed immediately on behalf of the lookup class.
3149          * <p>
3150          * If the returned method handle is invoked, the field's class will
3151          * be initialized, if it has not already been initialized.
3152          * @param refc the class or interface from which the method is accessed
3153          * @param name the field's name
3154          * @param type the field's type
3155          * @return a method handle which can store values into the field
3156          * @throws NoSuchFieldException if the field does not exist
3157          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3158          *                                or is {@code final}
3159          * @throws    SecurityException if a security manager is present and it
3160          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3161          * @throws NullPointerException if any argument is null
3162          */
3163         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3164             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3165             return getDirectField(REF_putStatic, refc, field);
3166         }
3167 
3168         /**
3169          * Produces a VarHandle giving access to a static field {@code name} of
3170          * type {@code type} declared in a class of type {@code decl}.
3171          * The VarHandle's variable type is {@code type} and it has no
3172          * coordinate types.
3173          * <p>
3174          * Access checking is performed immediately on behalf of the lookup
3175          * class.
3176          * <p>
3177          * If the returned VarHandle is operated on, the declaring class will be
3178          * initialized, if it has not already been initialized.
3179          * <p>
3180          * Certain access modes of the returned VarHandle are unsupported under
3181          * the following conditions:
3182          * <ul>
3183          * <li>if the field is declared {@code final}, then the write, atomic
3184          *     update, numeric atomic update, and bitwise atomic update access
3185          *     modes are unsupported.
3186          * <li>if the field type is anything other than {@code byte},
3187          *     {@code short}, {@code char}, {@code int}, {@code long},
3188          *     {@code float}, or {@code double}, then numeric atomic update
3189          *     access modes are unsupported.
3190          * <li>if the field type is anything other than {@code boolean},
3191          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3192          *     {@code long} then bitwise atomic update access modes are
3193          *     unsupported.
3194          * </ul>
3195          * <p>
3196          * If the field is declared {@code volatile} then the returned VarHandle
3197          * will override access to the field (effectively ignore the
3198          * {@code volatile} declaration) in accordance to its specified
3199          * access modes.
3200          * <p>
3201          * If the field type is {@code float} or {@code double} then numeric
3202          * and atomic update access modes compare values using their bitwise
3203          * representation (see {@link Float#floatToRawIntBits} and
3204          * {@link Double#doubleToRawLongBits}, respectively).
3205          * @apiNote
3206          * Bitwise comparison of {@code float} values or {@code double} values,
3207          * as performed by the numeric and atomic update access modes, differ
3208          * from the primitive {@code ==} operator and the {@link Float#equals}
3209          * and {@link Double#equals} methods, specifically with respect to
3210          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3211          * Care should be taken when performing a compare and set or a compare
3212          * and exchange operation with such values since the operation may
3213          * unexpectedly fail.
3214          * There are many possible NaN values that are considered to be
3215          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3216          * provided by Java can distinguish between them.  Operation failure can
3217          * occur if the expected or witness value is a NaN value and it is
3218          * transformed (perhaps in a platform specific manner) into another NaN
3219          * value, and thus has a different bitwise representation (see
3220          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3221          * details).
3222          * The values {@code -0.0} and {@code +0.0} have different bitwise
3223          * representations but are considered equal when using the primitive
3224          * {@code ==} operator.  Operation failure can occur if, for example, a
3225          * numeric algorithm computes an expected value to be say {@code -0.0}
3226          * and previously computed the witness value to be say {@code +0.0}.
3227          * @param decl the class that declares the static field
3228          * @param name the field's name
3229          * @param type the field's type, of type {@code T}
3230          * @return a VarHandle giving access to a static field
3231          * @throws NoSuchFieldException if the field does not exist
3232          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3233          * @throws    SecurityException if a security manager is present and it
3234          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3235          * @throws NullPointerException if any argument is null
3236          * @since 9
3237          */
3238         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3239             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3240             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3241             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3242         }
3243 
3244         /**
3245          * Produces an early-bound method handle for a non-static method.
3246          * The receiver must have a supertype {@code defc} in which a method
3247          * of the given name and type is accessible to the lookup class.
3248          * The method and all its argument types must be accessible to the lookup object.
3249          * The type of the method handle will be that of the method,
3250          * without any insertion of an additional receiver parameter.
3251          * The given receiver will be bound into the method handle,
3252          * so that every call to the method handle will invoke the
3253          * requested method on the given receiver.
3254          * <p>
3255          * The returned method handle will have
3256          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3257          * the method's variable arity modifier bit ({@code 0x0080}) is set
3258          * <em>and</em> the trailing array argument is not the only argument.
3259          * (If the trailing array argument is the only argument,
3260          * the given receiver value will be bound to it.)
3261          * <p>
3262          * This is almost equivalent to the following code, with some differences noted below:
3263          * <blockquote><pre>{@code
3264 import static java.lang.invoke.MethodHandles.*;
3265 import static java.lang.invoke.MethodType.*;
3266 ...
3267 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3268 MethodHandle mh1 = mh0.bindTo(receiver);
3269 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3270 return mh1;
3271          * }</pre></blockquote>
3272          * where {@code defc} is either {@code receiver.getClass()} or a super
3273          * type of that class, in which the requested method is accessible
3274          * to the lookup class.
3275          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3276          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3277          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3278          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3279          * @param receiver the object from which the method is accessed
3280          * @param name the name of the method
3281          * @param type the type of the method, with the receiver argument omitted
3282          * @return the desired method handle
3283          * @throws NoSuchMethodException if the method does not exist
3284          * @throws IllegalAccessException if access checking fails
3285          *                                or if the method's variable arity modifier bit
3286          *                                is set and {@code asVarargsCollector} fails
3287          * @throws    SecurityException if a security manager is present and it
3288          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3289          * @throws NullPointerException if any argument is null
3290          * @see MethodHandle#bindTo
3291          * @see #findVirtual
3292          */
3293         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3294             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3295             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3296             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3297             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3298                 throw new IllegalAccessException("The restricted defining class " +
3299                                                  mh.type().leadingReferenceParameter().getName() +
3300                                                  " is not assignable from receiver class " +
3301                                                  receiver.getClass().getName());
3302             }
3303             return mh.bindArgumentL(0, receiver).setVarargs(method);
3304         }
3305 
3306         /**
3307          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3308          * to <i>m</i>, if the lookup class has permission.
3309          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3310          * If <i>m</i> is virtual, overriding is respected on every call.
3311          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3312          * The type of the method handle will be that of the method,
3313          * with the receiver type prepended (but only if it is non-static).
3314          * If the method's {@code accessible} flag is not set,
3315          * access checking is performed immediately on behalf of the lookup class.
3316          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3317          * <p>
3318          * The returned method handle will have
3319          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3320          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3321          * <p>
3322          * If <i>m</i> is static, and
3323          * if the returned method handle is invoked, the method's class will
3324          * be initialized, if it has not already been initialized.
3325          * @param m the reflected method
3326          * @return a method handle which can invoke the reflected method
3327          * @throws IllegalAccessException if access checking fails
3328          *                                or if the method's variable arity modifier bit
3329          *                                is set and {@code asVarargsCollector} fails
3330          * @throws NullPointerException if the argument is null
3331          */
3332         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3333             if (m.getDeclaringClass() == MethodHandle.class) {
3334                 MethodHandle mh = unreflectForMH(m);
3335                 if (mh != null)  return mh;
3336             }
3337             if (m.getDeclaringClass() == VarHandle.class) {
3338                 MethodHandle mh = unreflectForVH(m);
3339                 if (mh != null)  return mh;
3340             }
3341             MemberName method = new MemberName(m);
3342             byte refKind = method.getReferenceKind();
3343             if (refKind == REF_invokeSpecial)
3344                 refKind = REF_invokeVirtual;
3345             assert(method.isMethod());
3346             @SuppressWarnings("deprecation")
3347             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3348             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3349         }
3350         private MethodHandle unreflectForMH(Method m) {
3351             // these names require special lookups because they throw UnsupportedOperationException
3352             if (MemberName.isMethodHandleInvokeName(m.getName()))
3353                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3354             return null;
3355         }
3356         private MethodHandle unreflectForVH(Method m) {
3357             // these names require special lookups because they throw UnsupportedOperationException
3358             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3359                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3360             return null;
3361         }
3362 
3363         /**
3364          * Produces a method handle for a reflected method.
3365          * It will bypass checks for overriding methods on the receiver,
3366          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3367          * instruction from within the explicitly specified {@code specialCaller}.
3368          * The type of the method handle will be that of the method,
3369          * with a suitably restricted receiver type prepended.
3370          * (The receiver type will be {@code specialCaller} or a subtype.)
3371          * If the method's {@code accessible} flag is not set,
3372          * access checking is performed immediately on behalf of the lookup class,
3373          * as if {@code invokespecial} instruction were being linked.
3374          * <p>
3375          * Before method resolution,
3376          * if the explicitly specified caller class is not identical with the
3377          * lookup class, or if this lookup object does not have
3378          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3379          * privileges, the access fails.
3380          * <p>
3381          * The returned method handle will have
3382          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3383          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3384          * @param m the reflected method
3385          * @param specialCaller the class nominally calling the method
3386          * @return a method handle which can invoke the reflected method
3387          * @throws IllegalAccessException if access checking fails,
3388          *                                or if the method is {@code static},
3389          *                                or if the method's variable arity modifier bit
3390          *                                is set and {@code asVarargsCollector} fails
3391          * @throws NullPointerException if any argument is null
3392          */
3393         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3394             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3395             Lookup specialLookup = this.in(specialCaller);
3396             MemberName method = new MemberName(m, true);
3397             assert(method.isMethod());
3398             // ignore m.isAccessible:  this is a new kind of access
3399             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3400         }
3401 
3402         /**
3403          * Produces a method handle for a reflected constructor.
3404          * The type of the method handle will be that of the constructor,
3405          * with the return type changed to the declaring class.
3406          * The method handle will perform a {@code newInstance} operation,
3407          * creating a new instance of the constructor's class on the
3408          * arguments passed to the method handle.
3409          * <p>
3410          * If the constructor's {@code accessible} flag is not set,
3411          * access checking is performed immediately on behalf of the lookup class.
3412          * <p>
3413          * The returned method handle will have
3414          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3415          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3416          * <p>
3417          * If the returned method handle is invoked, the constructor's class will
3418          * be initialized, if it has not already been initialized.
3419          * @param c the reflected constructor
3420          * @return a method handle which can invoke the reflected constructor
3421          * @throws IllegalAccessException if access checking fails
3422          *                                or if the method's variable arity modifier bit
3423          *                                is set and {@code asVarargsCollector} fails
3424          * @throws NullPointerException if the argument is null
3425          */
3426         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3427             MemberName ctor = new MemberName(c);
3428             assert(ctor.isConstructor());
3429             @SuppressWarnings("deprecation")
3430             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3431             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3432         }
3433 
3434         /**
3435          * Produces a method handle giving read access to a reflected field.
3436          * The type of the method handle will have a return type of the field's
3437          * value type.
3438          * If the field is {@code static}, the method handle will take no arguments.
3439          * Otherwise, its single argument will be the instance containing
3440          * the field.
3441          * If the {@code Field} object's {@code accessible} flag is not set,
3442          * access checking is performed immediately on behalf of the lookup class.
3443          * <p>
3444          * If the field is static, and
3445          * if the returned method handle is invoked, the field's class will
3446          * be initialized, if it has not already been initialized.
3447          * @param f the reflected field
3448          * @return a method handle which can load values from the reflected field
3449          * @throws IllegalAccessException if access checking fails
3450          * @throws NullPointerException if the argument is null
3451          */
3452         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3453             return unreflectField(f, false);
3454         }
3455 
3456         /**
3457          * Produces a method handle giving write access to a reflected field.
3458          * The type of the method handle will have a void return type.
3459          * If the field is {@code static}, the method handle will take a single
3460          * argument, of the field's value type, the value to be stored.
3461          * Otherwise, the two arguments will be the instance containing
3462          * the field, and the value to be stored.
3463          * If the {@code Field} object's {@code accessible} flag is not set,
3464          * access checking is performed immediately on behalf of the lookup class.
3465          * <p>
3466          * If the field is {@code final}, write access will not be
3467          * allowed and access checking will fail, except under certain
3468          * narrow circumstances documented for {@link Field#set Field.set}.
3469          * A method handle is returned only if a corresponding call to
3470          * the {@code Field} object's {@code set} method could return
3471          * normally.  In particular, fields which are both {@code static}
3472          * and {@code final} may never be set.
3473          * <p>
3474          * If the field is {@code 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 store values into the reflected field
3479          * @throws IllegalAccessException if access checking fails,
3480          *         or if the field is {@code final} and write access
3481          *         is not enabled on the {@code Field} object
3482          * @throws NullPointerException if the argument is null
3483          */
3484         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3485             return unreflectField(f, true);
3486         }
3487 
3488         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3489             MemberName field = new MemberName(f, isSetter);
3490             if (isSetter && field.isFinal()) {
3491                 if (field.isTrustedFinalField()) {
3492                     String msg = field.isStatic() ? "static final field has no write access"
3493                                                   : "final field has no write access";
3494                     throw field.makeAccessException(msg, this);
3495                 }
3496             }
3497             assert(isSetter
3498                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3499                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3500             @SuppressWarnings("deprecation")
3501             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3502             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3503         }
3504 
3505         /**
3506          * Produces a VarHandle giving access to a reflected field {@code f}
3507          * of type {@code T} declared in a class of type {@code R}.
3508          * The VarHandle's variable type is {@code T}.
3509          * If the field is non-static the VarHandle has one coordinate type,
3510          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3511          * coordinate types.
3512          * <p>
3513          * Access checking is performed immediately on behalf of the lookup
3514          * class, regardless of the value of the field's {@code accessible}
3515          * flag.
3516          * <p>
3517          * If the field is static, and if the returned VarHandle is operated
3518          * on, the field's declaring class will be initialized, if it has not
3519          * already been initialized.
3520          * <p>
3521          * Certain access modes of the returned VarHandle are unsupported under
3522          * the following conditions:
3523          * <ul>
3524          * <li>if the field is declared {@code final}, then the write, atomic
3525          *     update, numeric atomic update, and bitwise atomic update access
3526          *     modes are unsupported.
3527          * <li>if the field type is anything other than {@code byte},
3528          *     {@code short}, {@code char}, {@code int}, {@code long},
3529          *     {@code float}, or {@code double} then numeric atomic update
3530          *     access modes are unsupported.
3531          * <li>if the field type is anything other than {@code boolean},
3532          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3533          *     {@code long} then bitwise atomic update access modes are
3534          *     unsupported.
3535          * </ul>
3536          * <p>
3537          * If the field is declared {@code volatile} then the returned VarHandle
3538          * will override access to the field (effectively ignore the
3539          * {@code volatile} declaration) in accordance to its specified
3540          * access modes.
3541          * <p>
3542          * If the field type is {@code float} or {@code double} then numeric
3543          * and atomic update access modes compare values using their bitwise
3544          * representation (see {@link Float#floatToRawIntBits} and
3545          * {@link Double#doubleToRawLongBits}, respectively).
3546          * @apiNote
3547          * Bitwise comparison of {@code float} values or {@code double} values,
3548          * as performed by the numeric and atomic update access modes, differ
3549          * from the primitive {@code ==} operator and the {@link Float#equals}
3550          * and {@link Double#equals} methods, specifically with respect to
3551          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3552          * Care should be taken when performing a compare and set or a compare
3553          * and exchange operation with such values since the operation may
3554          * unexpectedly fail.
3555          * There are many possible NaN values that are considered to be
3556          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3557          * provided by Java can distinguish between them.  Operation failure can
3558          * occur if the expected or witness value is a NaN value and it is
3559          * transformed (perhaps in a platform specific manner) into another NaN
3560          * value, and thus has a different bitwise representation (see
3561          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3562          * details).
3563          * The values {@code -0.0} and {@code +0.0} have different bitwise
3564          * representations but are considered equal when using the primitive
3565          * {@code ==} operator.  Operation failure can occur if, for example, a
3566          * numeric algorithm computes an expected value to be say {@code -0.0}
3567          * and previously computed the witness value to be say {@code +0.0}.
3568          * @param f the reflected field, with a field of type {@code T}, and
3569          * a declaring class of type {@code R}
3570          * @return a VarHandle giving access to non-static fields or a static
3571          * field
3572          * @throws IllegalAccessException if access checking fails
3573          * @throws NullPointerException if the argument is null
3574          * @since 9
3575          */
3576         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3577             MemberName getField = new MemberName(f, false);
3578             MemberName putField = new MemberName(f, true);
3579             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3580                                                       f.getDeclaringClass(), getField, putField);
3581         }
3582 
3583         /**
3584          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3585          * created by this lookup object or a similar one.
3586          * Security and access checks are performed to ensure that this lookup object
3587          * is capable of reproducing the target method handle.
3588          * This means that the cracking may fail if target is a direct method handle
3589          * but was created by an unrelated lookup object.
3590          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3591          * and was created by a lookup object for a different class.
3592          * @param target a direct method handle to crack into symbolic reference components
3593          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3594          * @throws    SecurityException if a security manager is present and it
3595          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3596          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3597          * @throws    NullPointerException if the target is {@code null}
3598          * @see MethodHandleInfo
3599          * @since 1.8
3600          */
3601         public MethodHandleInfo revealDirect(MethodHandle target) {
3602             if (!target.isCrackable()) {
3603                 throw newIllegalArgumentException("not a direct method handle");
3604             }
3605             MemberName member = target.internalMemberName();
3606             Class<?> defc = member.getDeclaringClass();
3607             byte refKind = member.getReferenceKind();
3608             assert(MethodHandleNatives.refKindIsValid(refKind));
3609             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3610                 // Devirtualized method invocation is usually formally virtual.
3611                 // To avoid creating extra MemberName objects for this common case,
3612                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3613                 refKind = REF_invokeVirtual;
3614             if (refKind == REF_invokeVirtual && defc.isInterface())
3615                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3616                 refKind = REF_invokeInterface;
3617             // Check SM permissions and member access before cracking.
3618             try {
3619                 checkAccess(refKind, defc, member);
3620                 checkSecurityManager(defc, member);
3621             } catch (IllegalAccessException ex) {
3622                 throw new IllegalArgumentException(ex);
3623             }
3624             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3625                 Class<?> callerClass = target.internalCallerClass();
3626                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3627                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3628             }
3629             // Produce the handle to the results.
3630             return new InfoFromMemberName(this, member, refKind);
3631         }
3632 
3633         /// Helper methods, all package-private.
3634 
3635         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3636             checkSymbolicClass(refc);  // do this before attempting to resolve
3637             Objects.requireNonNull(name);
3638             Objects.requireNonNull(type);
3639             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3640                                             NoSuchFieldException.class);
3641         }
3642 
3643         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3644             checkSymbolicClass(refc);  // do this before attempting to resolve
3645             Objects.requireNonNull(type);
3646             checkMethodName(refKind, name);  // implicit null-check of name
3647             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3648                                             NoSuchMethodException.class);
3649         }
3650 
3651         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3652             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3653             Objects.requireNonNull(member.getName());
3654             Objects.requireNonNull(member.getType());
3655             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3656                                             ReflectiveOperationException.class);
3657         }
3658 
3659         MemberName resolveOrNull(byte refKind, MemberName member) {
3660             // do this before attempting to resolve
3661             if (!isClassAccessible(member.getDeclaringClass())) {
3662                 return null;
3663             }
3664             Objects.requireNonNull(member.getName());
3665             Objects.requireNonNull(member.getType());
3666             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3667         }
3668 
3669         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3670             // do this before attempting to resolve
3671             if (!isClassAccessible(refc)) {
3672                 return null;
3673             }
3674             Objects.requireNonNull(type);
3675             // implicit null-check of name
3676             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3677                 return null;
3678             }
3679             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3680         }
3681 
3682         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3683             if (!isClassAccessible(refc)) {
3684                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3685             }
3686         }
3687 
3688         boolean isClassAccessible(Class<?> refc) {
3689             Objects.requireNonNull(refc);
3690             Class<?> caller = lookupClassOrNull();
3691             Class<?> type = refc;
3692             while (type.isArray()) {
3693                 type = type.getComponentType();
3694             }
3695             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3696         }
3697 
3698         /** Check name for an illegal leading "&lt;" character. */
3699         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3700             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3701                 throw new NoSuchMethodException("illegal method name: "+name);
3702         }
3703 
3704         /**
3705          * Find my trustable caller class if m is a caller sensitive method.
3706          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3707          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3708          */
3709         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3710             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3711                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3712                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3713             }
3714             return this;
3715         }
3716 
3717         /**
3718          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3719          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3720          *
3721          * @deprecated This method was originally designed to test {@code PRIVATE} access
3722          * that implies full privilege access but {@code MODULE} access has since become
3723          * independent of {@code PRIVATE} access.  It is recommended to call
3724          * {@link #hasFullPrivilegeAccess()} instead.
3725          * @since 9
3726          */
3727         @Deprecated(since="14")
3728         public boolean hasPrivateAccess() {
3729             return hasFullPrivilegeAccess();
3730         }
3731 
3732         /**
3733          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3734          * i.e. {@code PRIVATE} and {@code MODULE} access.
3735          * A {@code Lookup} object must have full privilege access in order to
3736          * access all members that are allowed to the
3737          * {@linkplain #lookupClass() lookup class}.
3738          *
3739          * @return {@code true} if this lookup has full privilege access.
3740          * @since 14
3741          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3742          */
3743         public boolean hasFullPrivilegeAccess() {
3744             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3745         }
3746 
3747         /**
3748          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3749          * for ensureInitialzed, findClass or accessClass.
3750          */
3751         void checkSecurityManager(Class<?> refc) {
3752             if (allowedModes == TRUSTED)  return;
3753 
3754             @SuppressWarnings("removal")
3755             SecurityManager smgr = System.getSecurityManager();
3756             if (smgr == null)  return;
3757 
3758             // Step 1:
3759             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3760             if (!fullPrivilegeLookup ||
3761                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3762                 ReflectUtil.checkPackageAccess(refc);
3763             }
3764 
3765             // Step 2b:
3766             if (!fullPrivilegeLookup) {
3767                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3768             }
3769         }
3770 
3771         /**
3772          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3773          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3774          * If this lookup object has full privilege access except original access,
3775          * then the caller class is the lookupClass.
3776          *
3777          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3778          * from the same module skips the security permission check.
3779          */
3780         void checkSecurityManager(Class<?> refc, MemberName m) {
3781             Objects.requireNonNull(refc);
3782             Objects.requireNonNull(m);
3783 
3784             if (allowedModes == TRUSTED)  return;
3785 
3786             @SuppressWarnings("removal")
3787             SecurityManager smgr = System.getSecurityManager();
3788             if (smgr == null)  return;
3789 
3790             // Step 1:
3791             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3792             if (!fullPrivilegeLookup ||
3793                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3794                 ReflectUtil.checkPackageAccess(refc);
3795             }
3796 
3797             // Step 2a:
3798             if (m.isPublic()) return;
3799             if (!fullPrivilegeLookup) {
3800                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3801             }
3802 
3803             // Step 3:
3804             Class<?> defc = m.getDeclaringClass();
3805             if (!fullPrivilegeLookup && defc != refc) {
3806                 ReflectUtil.checkPackageAccess(defc);
3807             }
3808         }
3809 
3810         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3811             boolean wantStatic = (refKind == REF_invokeStatic);
3812             String message;
3813             if (m.isConstructor())
3814                 message = "expected a method, not a constructor";
3815             else if (!m.isMethod())
3816                 message = "expected a method";
3817             else if (wantStatic != m.isStatic())
3818                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3819             else
3820                 { checkAccess(refKind, refc, m); return; }
3821             throw m.makeAccessException(message, this);
3822         }
3823 
3824         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3825             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3826             String message;
3827             if (wantStatic != m.isStatic())
3828                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3829             else
3830                 { checkAccess(refKind, refc, m); return; }
3831             throw m.makeAccessException(message, this);
3832         }
3833 
3834         /** Check public/protected/private bits on the symbolic reference class and its member. */
3835         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3836             assert(m.referenceKindIsConsistentWith(refKind) &&
3837                    MethodHandleNatives.refKindIsValid(refKind) &&
3838                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3839             int allowedModes = this.allowedModes;
3840             if (allowedModes == TRUSTED)  return;
3841             int mods = m.getModifiers();
3842             if (Modifier.isProtected(mods) &&
3843                     refKind == REF_invokeVirtual &&
3844                     m.getDeclaringClass() == Object.class &&
3845                     m.getName().equals("clone") &&
3846                     refc.isArray()) {
3847                 // The JVM does this hack also.
3848                 // (See ClassVerifier::verify_invoke_instructions
3849                 // and LinkResolver::check_method_accessability.)
3850                 // Because the JVM does not allow separate methods on array types,
3851                 // there is no separate method for int[].clone.
3852                 // All arrays simply inherit Object.clone.
3853                 // But for access checking logic, we make Object.clone
3854                 // (normally protected) appear to be public.
3855                 // Later on, when the DirectMethodHandle is created,
3856                 // its leading argument will be restricted to the
3857                 // requested array type.
3858                 // N.B. The return type is not adjusted, because
3859                 // that is *not* the bytecode behavior.
3860                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3861             }
3862             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3863                 // cannot "new" a protected ctor in a different package
3864                 mods ^= Modifier.PROTECTED;
3865             }
3866             if (Modifier.isFinal(mods) &&
3867                     MethodHandleNatives.refKindIsSetter(refKind))
3868                 throw m.makeAccessException("unexpected set of a final field", this);
3869             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3870             if ((requestedModes & allowedModes) != 0) {
3871                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3872                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3873                     return;
3874             } else {
3875                 // Protected members can also be checked as if they were package-private.
3876                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3877                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3878                     return;
3879             }
3880             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3881         }
3882 
3883         String accessFailedMessage(Class<?> refc, MemberName m) {
3884             Class<?> defc = m.getDeclaringClass();
3885             int mods = m.getModifiers();
3886             // check the class first:
3887             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3888                                (defc == refc ||
3889                                 Modifier.isPublic(refc.getModifiers())));
3890             if (!classOK && (allowedModes & PACKAGE) != 0) {
3891                 // ignore previous lookup class to check if default package access
3892                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3893                            (defc == refc ||
3894                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3895             }
3896             if (!classOK)
3897                 return "class is not public";
3898             if (Modifier.isPublic(mods))
3899                 return "access to public member failed";  // (how?, module not readable?)
3900             if (Modifier.isPrivate(mods))
3901                 return "member is private";
3902             if (Modifier.isProtected(mods))
3903                 return "member is protected";
3904             return "member is private to package";
3905         }
3906 
3907         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3908             int allowedModes = this.allowedModes;
3909             if (allowedModes == TRUSTED)  return;
3910             if ((lookupModes() & PRIVATE) == 0
3911                 || (specialCaller != lookupClass()
3912                        // ensure non-abstract methods in superinterfaces can be special-invoked
3913                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3914                 throw new MemberName(specialCaller).
3915                     makeAccessException("no private access for invokespecial", this);
3916         }
3917 
3918         private boolean restrictProtectedReceiver(MemberName method) {
3919             // The accessing class only has the right to use a protected member
3920             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3921             if (!method.isProtected() || method.isStatic()
3922                 || allowedModes == TRUSTED
3923                 || method.getDeclaringClass() == lookupClass()
3924                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3925                 return false;
3926             return true;
3927         }
3928         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3929             assert(!method.isStatic());
3930             // receiver type of mh is too wide; narrow to caller
3931             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3932                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3933             }
3934             MethodType rawType = mh.type();
3935             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3936             MethodType narrowType = rawType.changeParameterType(0, caller);
3937             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3938             assert(mh.viewAsTypeChecks(narrowType, true));
3939             return mh.copyWith(narrowType, mh.form);
3940         }
3941 
3942         /** Check access and get the requested method. */
3943         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3944             final boolean doRestrict    = true;
3945             final boolean checkSecurity = true;
3946             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3947         }
3948         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3949         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3950             final boolean doRestrict    = false;
3951             final boolean checkSecurity = true;
3952             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3953         }
3954         /** Check access and get the requested method, eliding security manager checks. */
3955         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3956             final boolean doRestrict    = true;
3957             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3958             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3959         }
3960         /** Common code for all methods; do not call directly except from immediately above. */
3961         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3962                                                    boolean checkSecurity,
3963                                                    boolean doRestrict,
3964                                                    Lookup boundCaller) throws IllegalAccessException {
3965             checkMethod(refKind, refc, method);
3966             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3967             if (checkSecurity)
3968                 checkSecurityManager(refc, method);
3969             assert(!method.isMethodHandleInvoke());
3970 
3971             if (refKind == REF_invokeSpecial &&
3972                 refc != lookupClass() &&
3973                 !refc.isInterface() &&
3974                 refc != lookupClass().getSuperclass() &&
3975                 refc.isAssignableFrom(lookupClass())) {
3976                 assert(!method.getName().equals("<init>"));  // not this code path
3977 
3978                 // Per JVMS 6.5, desc. of invokespecial instruction:
3979                 // If the method is in a superclass of the LC,
3980                 // and if our original search was above LC.super,
3981                 // repeat the search (symbolic lookup) from LC.super
3982                 // and continue with the direct superclass of that class,
3983                 // and so forth, until a match is found or no further superclasses exist.
3984                 // FIXME: MemberName.resolve should handle this instead.
3985                 Class<?> refcAsSuper = lookupClass();
3986                 MemberName m2;
3987                 do {
3988                     refcAsSuper = refcAsSuper.getSuperclass();
3989                     m2 = new MemberName(refcAsSuper,
3990                                         method.getName(),
3991                                         method.getMethodType(),
3992                                         REF_invokeSpecial);
3993                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
3994                 } while (m2 == null &&         // no method is found yet
3995                          refc != refcAsSuper); // search up to refc
3996                 if (m2 == null)  throw new InternalError(method.toString());
3997                 method = m2;
3998                 refc = refcAsSuper;
3999                 // redo basic checks
4000                 checkMethod(refKind, refc, method);
4001             }
4002             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4003             MethodHandle mh = dmh;
4004             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4005             if ((doRestrict && refKind == REF_invokeSpecial) ||
4006                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4007                 mh = restrictReceiver(method, dmh, lookupClass());
4008             }
4009             mh = maybeBindCaller(method, mh, boundCaller);
4010             mh = mh.setVarargs(method);
4011             return mh;
4012         }
4013         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4014                                              throws IllegalAccessException {
4015             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4016                 return mh;
4017 
4018             // boundCaller must have full privilege access.
4019             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4020             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4021                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4022 
4023             assert boundCaller.hasFullPrivilegeAccess();
4024 
4025             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4026             // Note: caller will apply varargs after this step happens.
4027             return cbmh;
4028         }
4029 
4030         /** Check access and get the requested field. */
4031         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4032             final boolean checkSecurity = true;
4033             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4034         }
4035         /** Check access and get the requested field, eliding security manager checks. */
4036         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4037             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4038             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4039         }
4040         /** Common code for all fields; do not call directly except from immediately above. */
4041         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4042                                                   boolean checkSecurity) throws IllegalAccessException {
4043             checkField(refKind, refc, field);
4044             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4045             if (checkSecurity)
4046                 checkSecurityManager(refc, field);
4047             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4048             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4049                                     restrictProtectedReceiver(field));
4050             if (doRestrict)
4051                 return restrictReceiver(field, dmh, lookupClass());
4052             return dmh;
4053         }
4054         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4055                                             Class<?> refc, MemberName getField, MemberName putField)
4056                 throws IllegalAccessException {
4057             final boolean checkSecurity = true;
4058             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4059         }
4060         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4061                                                              Class<?> refc, MemberName getField, MemberName putField)
4062                 throws IllegalAccessException {
4063             final boolean checkSecurity = false;
4064             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4065         }
4066         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4067                                                   Class<?> refc, MemberName getField, MemberName putField,
4068                                                   boolean checkSecurity) throws IllegalAccessException {
4069             assert getField.isStatic() == putField.isStatic();
4070             assert getField.isGetter() && putField.isSetter();
4071             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4072             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4073 
4074             checkField(getRefKind, refc, getField);
4075             if (checkSecurity)
4076                 checkSecurityManager(refc, getField);
4077 
4078             if (!putField.isFinal()) {
4079                 // A VarHandle does not support updates to final fields, any
4080                 // such VarHandle to a final field will be read-only and
4081                 // therefore the following write-based accessibility checks are
4082                 // only required for non-final fields
4083                 checkField(putRefKind, refc, putField);
4084                 if (checkSecurity)
4085                     checkSecurityManager(refc, putField);
4086             }
4087 
4088             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4089                                   restrictProtectedReceiver(getField));
4090             if (doRestrict) {
4091                 assert !getField.isStatic();
4092                 // receiver type of VarHandle is too wide; narrow to caller
4093                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4094                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4095                 }
4096                 refc = lookupClass();
4097             }
4098             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4099                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4100         }
4101         /** Check access and get the requested constructor. */
4102         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4103             final boolean checkSecurity = true;
4104             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4105         }
4106         /** Check access and get the requested constructor, eliding security manager checks. */
4107         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4108             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4109             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4110         }
4111         /** Common code for all constructors; do not call directly except from immediately above. */
4112         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4113                                                   boolean checkSecurity) throws IllegalAccessException {
4114             assert(ctor.isConstructor());
4115             checkAccess(REF_newInvokeSpecial, refc, ctor);
4116             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4117             if (checkSecurity)
4118                 checkSecurityManager(refc, ctor);
4119             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4120             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4121         }
4122 
4123         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4124          */
4125         /*non-public*/
4126         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4127                 throws ReflectiveOperationException {
4128             if (!(type instanceof Class || type instanceof MethodType))
4129                 throw new InternalError("unresolved MemberName");
4130             MemberName member = new MemberName(refKind, defc, name, type);
4131             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4132             if (mh != null) {
4133                 checkSymbolicClass(defc);
4134                 return mh;
4135             }
4136             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4137                 // Treat MethodHandle.invoke and invokeExact specially.
4138                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4139                 if (mh != null) {
4140                     return mh;
4141                 }
4142             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4143                 // Treat signature-polymorphic methods on VarHandle specially.
4144                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4145                 if (mh != null) {
4146                     return mh;
4147                 }
4148             }
4149             MemberName resolved = resolveOrFail(refKind, member);
4150             mh = getDirectMethodForConstant(refKind, defc, resolved);
4151             if (mh instanceof DirectMethodHandle
4152                     && canBeCached(refKind, defc, resolved)) {
4153                 MemberName key = mh.internalMemberName();
4154                 if (key != null) {
4155                     key = key.asNormalOriginal();
4156                 }
4157                 if (member.equals(key)) {  // better safe than sorry
4158                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4159                 }
4160             }
4161             return mh;
4162         }
4163         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4164             if (refKind == REF_invokeSpecial) {
4165                 return false;
4166             }
4167             if (!Modifier.isPublic(defc.getModifiers()) ||
4168                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4169                     !member.isPublic() ||
4170                     member.isCallerSensitive()) {
4171                 return false;
4172             }
4173             ClassLoader loader = defc.getClassLoader();
4174             if (loader != null) {
4175                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4176                 boolean found = false;
4177                 while (sysl != null) {
4178                     if (loader == sysl) { found = true; break; }
4179                     sysl = sysl.getParent();
4180                 }
4181                 if (!found) {
4182                     return false;
4183                 }
4184             }
4185             try {
4186                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4187                     new MemberName(refKind, defc, member.getName(), member.getType()));
4188                 if (resolved2 == null) {
4189                     return false;
4190                 }
4191                 checkSecurityManager(defc, resolved2);
4192             } catch (SecurityException ex) {
4193                 return false;
4194             }
4195             return true;
4196         }
4197         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4198                 throws ReflectiveOperationException {
4199             if (MethodHandleNatives.refKindIsField(refKind)) {
4200                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4201             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4202                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4203             } else if (refKind == REF_newInvokeSpecial) {
4204                 return getDirectConstructorNoSecurityManager(defc, member);
4205             }
4206             // oops
4207             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4208         }
4209 
4210         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4211     }
4212 
4213     /**
4214      * Produces a method handle constructing arrays of a desired type,
4215      * as if by the {@code anewarray} bytecode.
4216      * The return type of the method handle will be the array type.
4217      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4218      *
4219      * <p> If the returned method handle is invoked with a negative
4220      * array size, a {@code NegativeArraySizeException} will be thrown.
4221      *
4222      * @param arrayClass an array type
4223      * @return a method handle which can create arrays of the given type
4224      * @throws NullPointerException if the argument is {@code null}
4225      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4226      * @see java.lang.reflect.Array#newInstance(Class, int)
4227      * @jvms 6.5 {@code anewarray} Instruction
4228      * @since 9
4229      */
4230     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4231         if (!arrayClass.isArray()) {
4232             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4233         }
4234         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4235                 bindTo(arrayClass.getComponentType());
4236         return ani.asType(ani.type().changeReturnType(arrayClass));
4237     }
4238 
4239     /**
4240      * Produces a method handle returning the length of an array,
4241      * as if by the {@code arraylength} bytecode.
4242      * The type of the method handle will have {@code int} as return type,
4243      * and its sole argument will be the array type.
4244      *
4245      * <p> If the returned method handle is invoked with a {@code null}
4246      * array reference, a {@code NullPointerException} will be thrown.
4247      *
4248      * @param arrayClass an array type
4249      * @return a method handle which can retrieve the length of an array of the given array type
4250      * @throws NullPointerException if the argument is {@code null}
4251      * @throws IllegalArgumentException if arrayClass is not an array type
4252      * @jvms 6.5 {@code arraylength} Instruction
4253      * @since 9
4254      */
4255     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4256         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4257     }
4258 
4259     /**
4260      * Produces a method handle giving read access to elements of an array,
4261      * as if by the {@code aaload} bytecode.
4262      * The type of the method handle will have a return type of the array's
4263      * element type.  Its first argument will be the array type,
4264      * and the second will be {@code int}.
4265      *
4266      * <p> When the returned method handle is invoked,
4267      * the array reference and array index are checked.
4268      * A {@code NullPointerException} will be thrown if the array reference
4269      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4270      * thrown if the index is negative or if it is greater than or equal to
4271      * the length of the array.
4272      *
4273      * @param arrayClass an array type
4274      * @return a method handle which can load values from the given array type
4275      * @throws NullPointerException if the argument is null
4276      * @throws  IllegalArgumentException if arrayClass is not an array type
4277      * @jvms 6.5 {@code aaload} Instruction
4278      */
4279     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4280         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4281     }
4282 
4283     /**
4284      * Produces a method handle giving write access to elements of an array,
4285      * as if by the {@code astore} bytecode.
4286      * The type of the method handle will have a void return type.
4287      * Its last argument will be the array's element type.
4288      * The first and second arguments will be the array type and int.
4289      *
4290      * <p> When the returned method handle is invoked,
4291      * the array reference and array index are checked.
4292      * A {@code NullPointerException} will be thrown if the array reference
4293      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4294      * thrown if the index is negative or if it is greater than or equal to
4295      * the length of the array.
4296      *
4297      * @param arrayClass the class of an array
4298      * @return a method handle which can store values into the array type
4299      * @throws NullPointerException if the argument is null
4300      * @throws IllegalArgumentException if arrayClass is not an array type
4301      * @jvms 6.5 {@code aastore} Instruction
4302      */
4303     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4304         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4305     }
4306 
4307     /**
4308      * Produces a VarHandle giving access to elements of an array of type
4309      * {@code arrayClass}.  The VarHandle's variable type is the component type
4310      * of {@code arrayClass} and the list of coordinate types is
4311      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4312      * corresponds to an argument that is an index into an array.
4313      * <p>
4314      * Certain access modes of the returned VarHandle are unsupported under
4315      * the following conditions:
4316      * <ul>
4317      * <li>if the component type is anything other than {@code byte},
4318      *     {@code short}, {@code char}, {@code int}, {@code long},
4319      *     {@code float}, or {@code double} then numeric atomic update access
4320      *     modes are unsupported.
4321      * <li>if the component type is anything other than {@code boolean},
4322      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4323      *     {@code long} then bitwise atomic update access modes are
4324      *     unsupported.
4325      * </ul>
4326      * <p>
4327      * If the component type is {@code float} or {@code double} then numeric
4328      * and atomic update access modes compare values using their bitwise
4329      * representation (see {@link Float#floatToRawIntBits} and
4330      * {@link Double#doubleToRawLongBits}, respectively).
4331      *
4332      * <p> When the returned {@code VarHandle} is invoked,
4333      * the array reference and array index are checked.
4334      * A {@code NullPointerException} will be thrown if the array reference
4335      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4336      * thrown if the index is negative or if it is greater than or equal to
4337      * the length of the array.
4338      *
4339      * @apiNote
4340      * Bitwise comparison of {@code float} values or {@code double} values,
4341      * as performed by the numeric and atomic update access modes, differ
4342      * from the primitive {@code ==} operator and the {@link Float#equals}
4343      * and {@link Double#equals} methods, specifically with respect to
4344      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4345      * Care should be taken when performing a compare and set or a compare
4346      * and exchange operation with such values since the operation may
4347      * unexpectedly fail.
4348      * There are many possible NaN values that are considered to be
4349      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4350      * provided by Java can distinguish between them.  Operation failure can
4351      * occur if the expected or witness value is a NaN value and it is
4352      * transformed (perhaps in a platform specific manner) into another NaN
4353      * value, and thus has a different bitwise representation (see
4354      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4355      * details).
4356      * The values {@code -0.0} and {@code +0.0} have different bitwise
4357      * representations but are considered equal when using the primitive
4358      * {@code ==} operator.  Operation failure can occur if, for example, a
4359      * numeric algorithm computes an expected value to be say {@code -0.0}
4360      * and previously computed the witness value to be say {@code +0.0}.
4361      * @param arrayClass the class of an array, of type {@code T[]}
4362      * @return a VarHandle giving access to elements of an array
4363      * @throws NullPointerException if the arrayClass is null
4364      * @throws IllegalArgumentException if arrayClass is not an array type
4365      * @since 9
4366      */
4367     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4368         return VarHandles.makeArrayElementHandle(arrayClass);
4369     }
4370 
4371     /**
4372      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4373      * viewed as if it were a different primitive array type, such as
4374      * {@code int[]} or {@code long[]}.
4375      * The VarHandle's variable type is the component type of
4376      * {@code viewArrayClass} and the list of coordinate types is
4377      * {@code (byte[], int)}, where the {@code int} coordinate type
4378      * corresponds to an argument that is an index into a {@code byte[]} array.
4379      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4380      * array, composing bytes to or from a value of the component type of
4381      * {@code viewArrayClass} according to the given endianness.
4382      * <p>
4383      * The supported component types (variables types) are {@code short},
4384      * {@code char}, {@code int}, {@code long}, {@code float} and
4385      * {@code double}.
4386      * <p>
4387      * Access of bytes at a given index will result in an
4388      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4389      * or greater than the {@code byte[]} array length minus the size (in bytes)
4390      * of {@code T}.
4391      * <p>
4392      * Access of bytes at an index may be aligned or misaligned for {@code T},
4393      * with respect to the underlying memory address, {@code A} say, associated
4394      * with the array and index.
4395      * If access is misaligned then access for anything other than the
4396      * {@code get} and {@code set} access modes will result in an
4397      * {@code IllegalStateException}.  In such cases atomic access is only
4398      * guaranteed with respect to the largest power of two that divides the GCD
4399      * of {@code A} and the size (in bytes) of {@code T}.
4400      * If access is aligned then following access modes are supported and are
4401      * guaranteed to support atomic access:
4402      * <ul>
4403      * <li>read write access modes for all {@code T}, with the exception of
4404      *     access modes {@code get} and {@code set} for {@code long} and
4405      *     {@code double} on 32-bit platforms.
4406      * <li>atomic update access modes for {@code int}, {@code long},
4407      *     {@code float} or {@code double}.
4408      *     (Future major platform releases of the JDK may support additional
4409      *     types for certain currently unsupported access modes.)
4410      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4411      *     (Future major platform releases of the JDK may support additional
4412      *     numeric types for certain currently unsupported access modes.)
4413      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4414      *     (Future major platform releases of the JDK may support additional
4415      *     numeric types for certain currently unsupported access modes.)
4416      * </ul>
4417      * <p>
4418      * Misaligned access, and therefore atomicity guarantees, may be determined
4419      * for {@code byte[]} arrays without operating on a specific array.  Given
4420      * an {@code index}, {@code T} and its corresponding boxed type,
4421      * {@code T_BOX}, misalignment may be determined as follows:
4422      * <pre>{@code
4423      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4424      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4425      *     alignmentOffset(0, sizeOfT);
4426      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4427      * boolean isMisaligned = misalignedAtIndex != 0;
4428      * }</pre>
4429      * <p>
4430      * If the variable type is {@code float} or {@code double} then atomic
4431      * update access modes compare values using their bitwise representation
4432      * (see {@link Float#floatToRawIntBits} and
4433      * {@link Double#doubleToRawLongBits}, respectively).
4434      * @param viewArrayClass the view array class, with a component type of
4435      * type {@code T}
4436      * @param byteOrder the endianness of the view array elements, as
4437      * stored in the underlying {@code byte} array
4438      * @return a VarHandle giving access to elements of a {@code byte[]} array
4439      * viewed as if elements corresponding to the components type of the view
4440      * array class
4441      * @throws NullPointerException if viewArrayClass or byteOrder is null
4442      * @throws IllegalArgumentException if viewArrayClass is not an array type
4443      * @throws UnsupportedOperationException if the component type of
4444      * viewArrayClass is not supported as a variable type
4445      * @since 9
4446      */
4447     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4448                                      ByteOrder byteOrder) throws IllegalArgumentException {
4449         Objects.requireNonNull(byteOrder);
4450         return VarHandles.byteArrayViewHandle(viewArrayClass,
4451                                               byteOrder == ByteOrder.BIG_ENDIAN);
4452     }
4453 
4454     /**
4455      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4456      * viewed as if it were an array of elements of a different primitive
4457      * component type to that of {@code byte}, such as {@code int[]} or
4458      * {@code long[]}.
4459      * The VarHandle's variable type is the component type of
4460      * {@code viewArrayClass} and the list of coordinate types is
4461      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4462      * corresponds to an argument that is an index into a {@code byte[]} array.
4463      * The returned VarHandle accesses bytes at an index in a
4464      * {@code ByteBuffer}, composing bytes to or from a value of the component
4465      * type of {@code viewArrayClass} according to the given endianness.
4466      * <p>
4467      * The supported component types (variables types) are {@code short},
4468      * {@code char}, {@code int}, {@code long}, {@code float} and
4469      * {@code double}.
4470      * <p>
4471      * Access will result in a {@code ReadOnlyBufferException} for anything
4472      * other than the read access modes if the {@code ByteBuffer} is read-only.
4473      * <p>
4474      * Access of bytes at a given index will result in an
4475      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4476      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4477      * {@code T}.
4478      * <p>
4479      * Access of bytes at an index may be aligned or misaligned for {@code T},
4480      * with respect to the underlying memory address, {@code A} say, associated
4481      * with the {@code ByteBuffer} and index.
4482      * If access is misaligned then access for anything other than the
4483      * {@code get} and {@code set} access modes will result in an
4484      * {@code IllegalStateException}.  In such cases atomic access is only
4485      * guaranteed with respect to the largest power of two that divides the GCD
4486      * of {@code A} and the size (in bytes) of {@code T}.
4487      * If access is aligned then following access modes are supported and are
4488      * guaranteed to support atomic access:
4489      * <ul>
4490      * <li>read write access modes for all {@code T}, with the exception of
4491      *     access modes {@code get} and {@code set} for {@code long} and
4492      *     {@code double} on 32-bit platforms.
4493      * <li>atomic update access modes for {@code int}, {@code long},
4494      *     {@code float} or {@code double}.
4495      *     (Future major platform releases of the JDK may support additional
4496      *     types for certain currently unsupported access modes.)
4497      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4498      *     (Future major platform releases of the JDK may support additional
4499      *     numeric types for certain currently unsupported access modes.)
4500      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4501      *     (Future major platform releases of the JDK may support additional
4502      *     numeric types for certain currently unsupported access modes.)
4503      * </ul>
4504      * <p>
4505      * Misaligned access, and therefore atomicity guarantees, may be determined
4506      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4507      * {@code index}, {@code T} and its corresponding boxed type,
4508      * {@code T_BOX}, as follows:
4509      * <pre>{@code
4510      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4511      * ByteBuffer bb = ...
4512      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4513      * boolean isMisaligned = misalignedAtIndex != 0;
4514      * }</pre>
4515      * <p>
4516      * If the variable type is {@code float} or {@code double} then atomic
4517      * update access modes compare values using their bitwise representation
4518      * (see {@link Float#floatToRawIntBits} and
4519      * {@link Double#doubleToRawLongBits}, respectively).
4520      * @param viewArrayClass the view array class, with a component type of
4521      * type {@code T}
4522      * @param byteOrder the endianness of the view array elements, as
4523      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4524      * endianness of a {@code ByteBuffer})
4525      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4526      * viewed as if elements corresponding to the components type of the view
4527      * array class
4528      * @throws NullPointerException if viewArrayClass or byteOrder is null
4529      * @throws IllegalArgumentException if viewArrayClass is not an array type
4530      * @throws UnsupportedOperationException if the component type of
4531      * viewArrayClass is not supported as a variable type
4532      * @since 9
4533      */
4534     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4535                                       ByteOrder byteOrder) throws IllegalArgumentException {
4536         Objects.requireNonNull(byteOrder);
4537         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4538                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4539     }
4540 
4541 
4542     /// method handle invocation (reflective style)
4543 
4544     /**
4545      * Produces a method handle which will invoke any method handle of the
4546      * given {@code type}, with a given number of trailing arguments replaced by
4547      * a single trailing {@code Object[]} array.
4548      * The resulting invoker will be a method handle with the following
4549      * arguments:
4550      * <ul>
4551      * <li>a single {@code MethodHandle} target
4552      * <li>zero or more leading values (counted by {@code leadingArgCount})
4553      * <li>an {@code Object[]} array containing trailing arguments
4554      * </ul>
4555      * <p>
4556      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4557      * the indicated {@code type}.
4558      * That is, if the target is exactly of the given {@code type}, it will behave
4559      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4560      * is used to convert the target to the required {@code type}.
4561      * <p>
4562      * The type of the returned invoker will not be the given {@code type}, but rather
4563      * will have all parameters except the first {@code leadingArgCount}
4564      * replaced by a single array of type {@code Object[]}, which will be
4565      * the final parameter.
4566      * <p>
4567      * Before invoking its target, the invoker will spread the final array, apply
4568      * reference casts as necessary, and unbox and widen primitive arguments.
4569      * If, when the invoker is called, the supplied array argument does
4570      * not have the correct number of elements, the invoker will throw
4571      * an {@link IllegalArgumentException} instead of invoking the target.
4572      * <p>
4573      * This method is equivalent to the following code (though it may be more efficient):
4574      * <blockquote><pre>{@code
4575 MethodHandle invoker = MethodHandles.invoker(type);
4576 int spreadArgCount = type.parameterCount() - leadingArgCount;
4577 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4578 return invoker;
4579      * }</pre></blockquote>
4580      * This method throws no reflective or security exceptions.
4581      * @param type the desired target type
4582      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4583      * @return a method handle suitable for invoking any method handle of the given type
4584      * @throws NullPointerException if {@code type} is null
4585      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4586      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4587      *                  or if the resulting method handle's type would have
4588      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4589      */
4590     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4591         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4592             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4593         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4594         return type.invokers().spreadInvoker(leadingArgCount);
4595     }
4596 
4597     /**
4598      * Produces a special <em>invoker method handle</em> which can be used to
4599      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4600      * The resulting invoker will have a type which is
4601      * exactly equal to the desired type, except that it will accept
4602      * an additional leading argument of type {@code MethodHandle}.
4603      * <p>
4604      * This method is equivalent to the following code (though it may be more efficient):
4605      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4606      *
4607      * <p style="font-size:smaller;">
4608      * <em>Discussion:</em>
4609      * Invoker method handles can be useful when working with variable method handles
4610      * of unknown types.
4611      * For example, to emulate an {@code invokeExact} call to a variable method
4612      * handle {@code M}, extract its type {@code T},
4613      * look up the invoker method {@code X} for {@code T},
4614      * and call the invoker method, as {@code X.invoke(T, A...)}.
4615      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4616      * is unknown.)
4617      * If spreading, collecting, or other argument transformations are required,
4618      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4619      * method handle values, as long as they are compatible with the type of {@code X}.
4620      * <p style="font-size:smaller;">
4621      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4622      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4623      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4624      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4625      * <p>
4626      * This method throws no reflective or security exceptions.
4627      * @param type the desired target type
4628      * @return a method handle suitable for invoking any method handle of the given type
4629      * @throws IllegalArgumentException if the resulting method handle's type would have
4630      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4631      */
4632     public static MethodHandle exactInvoker(MethodType type) {
4633         return type.invokers().exactInvoker();
4634     }
4635 
4636     /**
4637      * Produces a special <em>invoker method handle</em> which can be used to
4638      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4639      * The resulting invoker will have a type which is
4640      * exactly equal to the desired type, except that it will accept
4641      * an additional leading argument of type {@code MethodHandle}.
4642      * <p>
4643      * Before invoking its target, if the target differs from the expected type,
4644      * the invoker will apply reference casts as
4645      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4646      * Similarly, the return value will be converted as necessary.
4647      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4648      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4649      * <p>
4650      * This method is equivalent to the following code (though it may be more efficient):
4651      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4652      * <p style="font-size:smaller;">
4653      * <em>Discussion:</em>
4654      * A {@linkplain MethodType#genericMethodType general method type} is one which
4655      * mentions only {@code Object} arguments and return values.
4656      * An invoker for such a type is capable of calling any method handle
4657      * of the same arity as the general type.
4658      * <p style="font-size:smaller;">
4659      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4660      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4661      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4662      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4663      * <p>
4664      * This method throws no reflective or security exceptions.
4665      * @param type the desired target type
4666      * @return a method handle suitable for invoking any method handle convertible to the given type
4667      * @throws IllegalArgumentException if the resulting method handle's type would have
4668      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4669      */
4670     public static MethodHandle invoker(MethodType type) {
4671         return type.invokers().genericInvoker();
4672     }
4673 
4674     /**
4675      * Produces a special <em>invoker method handle</em> which can be used to
4676      * invoke a signature-polymorphic access mode method on any VarHandle whose
4677      * associated access mode type is compatible with the given type.
4678      * The resulting invoker will have a type which is exactly equal to the
4679      * desired given type, except that it will accept an additional leading
4680      * argument of type {@code VarHandle}.
4681      *
4682      * @param accessMode the VarHandle access mode
4683      * @param type the desired target type
4684      * @return a method handle suitable for invoking an access mode method of
4685      *         any VarHandle whose access mode type is of the given type.
4686      * @since 9
4687      */
4688     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4689         return type.invokers().varHandleMethodExactInvoker(accessMode);
4690     }
4691 
4692     /**
4693      * Produces a special <em>invoker method handle</em> which can be used to
4694      * invoke a signature-polymorphic access mode method on any VarHandle whose
4695      * associated access mode type is compatible with the given type.
4696      * The resulting invoker will have a type which is exactly equal to the
4697      * desired given type, except that it will accept an additional leading
4698      * argument of type {@code VarHandle}.
4699      * <p>
4700      * Before invoking its target, if the access mode type differs from the
4701      * desired given type, the invoker will apply reference casts as necessary
4702      * and box, unbox, or widen primitive values, as if by
4703      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4704      * converted as necessary.
4705      * <p>
4706      * This method is equivalent to the following code (though it may be more
4707      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4708      *
4709      * @param accessMode the VarHandle access mode
4710      * @param type the desired target type
4711      * @return a method handle suitable for invoking an access mode method of
4712      *         any VarHandle whose access mode type is convertible to the given
4713      *         type.
4714      * @since 9
4715      */
4716     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4717         return type.invokers().varHandleMethodInvoker(accessMode);
4718     }
4719 
4720     /*non-public*/
4721     static MethodHandle basicInvoker(MethodType type) {
4722         return type.invokers().basicInvoker();
4723     }
4724 
4725      /// method handle modification (creation from other method handles)
4726 
4727     /**
4728      * Produces a method handle which adapts the type of the
4729      * given method handle to a new type by pairwise argument and return type conversion.
4730      * The original type and new type must have the same number of arguments.
4731      * The resulting method handle is guaranteed to report a type
4732      * which is equal to the desired new type.
4733      * <p>
4734      * If the original type and new type are equal, returns target.
4735      * <p>
4736      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4737      * and some additional conversions are also applied if those conversions fail.
4738      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4739      * if possible, before or instead of any conversions done by {@code asType}:
4740      * <ul>
4741      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4742      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4743      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4744      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4745      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4746      *     (This treatment follows the usage of the bytecode verifier.)
4747      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4748      *     <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
4749      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4750      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4751      *     then a Java casting conversion (JLS 5.5) is applied.
4752      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4753      *     widening and/or narrowing.)
4754      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4755      *     conversion will be applied at runtime, possibly followed
4756      *     by a Java casting conversion (JLS 5.5) on the primitive value,
4757      *     possibly followed by a conversion from byte to boolean by testing
4758      *     the low-order bit.
4759      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4760      *     and if the reference is null at runtime, a zero value is introduced.
4761      * </ul>
4762      * @param target the method handle to invoke after arguments are retyped
4763      * @param newType the expected type of the new method handle
4764      * @return a method handle which delegates to the target after performing
4765      *           any necessary argument conversions, and arranges for any
4766      *           necessary return value conversions
4767      * @throws NullPointerException if either argument is null
4768      * @throws WrongMethodTypeException if the conversion cannot be made
4769      * @see MethodHandle#asType
4770      */
4771     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4772         explicitCastArgumentsChecks(target, newType);
4773         // use the asTypeCache when possible:
4774         MethodType oldType = target.type();
4775         if (oldType == newType)  return target;
4776         if (oldType.explicitCastEquivalentToAsType(newType)) {
4777             return target.asFixedArity().asType(newType);
4778         }
4779         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4780     }
4781 
4782     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4783         if (target.type().parameterCount() != newType.parameterCount()) {
4784             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4785         }
4786     }
4787 
4788     /**
4789      * Produces a method handle which adapts the calling sequence of the
4790      * given method handle to a new type, by reordering the arguments.
4791      * The resulting method handle is guaranteed to report a type
4792      * which is equal to the desired new type.
4793      * <p>
4794      * The given array controls the reordering.
4795      * Call {@code #I} the number of incoming parameters (the value
4796      * {@code newType.parameterCount()}, and call {@code #O} the number
4797      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4798      * Then the length of the reordering array must be {@code #O},
4799      * and each element must be a non-negative number less than {@code #I}.
4800      * For every {@code N} less than {@code #O}, the {@code N}-th
4801      * outgoing argument will be taken from the {@code I}-th incoming
4802      * argument, where {@code I} is {@code reorder[N]}.
4803      * <p>
4804      * No argument or return value conversions are applied.
4805      * The type of each incoming argument, as determined by {@code newType},
4806      * must be identical to the type of the corresponding outgoing parameter
4807      * or parameters in the target method handle.
4808      * The return type of {@code newType} must be identical to the return
4809      * type of the original target.
4810      * <p>
4811      * The reordering array need not specify an actual permutation.
4812      * An incoming argument will be duplicated if its index appears
4813      * more than once in the array, and an incoming argument will be dropped
4814      * if its index does not appear in the array.
4815      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4816      * incoming arguments which are not mentioned in the reordering array
4817      * may be of any type, as determined only by {@code newType}.
4818      * <blockquote><pre>{@code
4819 import static java.lang.invoke.MethodHandles.*;
4820 import static java.lang.invoke.MethodType.*;
4821 ...
4822 MethodType intfn1 = methodType(int.class, int.class);
4823 MethodType intfn2 = methodType(int.class, int.class, int.class);
4824 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4825 assert(sub.type().equals(intfn2));
4826 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4827 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4828 assert((int)rsub.invokeExact(1, 100) == 99);
4829 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4830 assert(add.type().equals(intfn2));
4831 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4832 assert(twice.type().equals(intfn1));
4833 assert((int)twice.invokeExact(21) == 42);
4834      * }</pre></blockquote>
4835      * <p>
4836      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4837      * variable-arity method handle}, even if the original target method handle was.
4838      * @param target the method handle to invoke after arguments are reordered
4839      * @param newType the expected type of the new method handle
4840      * @param reorder an index array which controls the reordering
4841      * @return a method handle which delegates to the target after it
4842      *           drops unused arguments and moves and/or duplicates the other arguments
4843      * @throws NullPointerException if any argument is null
4844      * @throws IllegalArgumentException if the index array length is not equal to
4845      *                  the arity of the target, or if any index array element
4846      *                  not a valid index for a parameter of {@code newType},
4847      *                  or if two corresponding parameter types in
4848      *                  {@code target.type()} and {@code newType} are not identical,
4849      */
4850     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4851         reorder = reorder.clone();  // get a private copy
4852         MethodType oldType = target.type();
4853         permuteArgumentChecks(reorder, newType, oldType);
4854         // first detect dropped arguments and handle them separately
4855         int[] originalReorder = reorder;
4856         BoundMethodHandle result = target.rebind();
4857         LambdaForm form = result.form;
4858         int newArity = newType.parameterCount();
4859         // Normalize the reordering into a real permutation,
4860         // by removing duplicates and adding dropped elements.
4861         // This somewhat improves lambda form caching, as well
4862         // as simplifying the transform by breaking it up into steps.
4863         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4864             if (ddIdx > 0) {
4865                 // We found a duplicated entry at reorder[ddIdx].
4866                 // Example:  (x,y,z)->asList(x,y,z)
4867                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4868                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4869                 // The starred element corresponds to the argument
4870                 // deleted by the dupArgumentForm transform.
4871                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4872                 boolean killFirst = false;
4873                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4874                     // Set killFirst if the dup is larger than an intervening position.
4875                     // This will remove at least one inversion from the permutation.
4876                     if (dupVal > val) killFirst = true;
4877                 }
4878                 if (!killFirst) {
4879                     srcPos = dstPos;
4880                     dstPos = ddIdx;
4881                 }
4882                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4883                 assert (reorder[srcPos] == reorder[dstPos]);
4884                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4885                 // contract the reordering by removing the element at dstPos
4886                 int tailPos = dstPos + 1;
4887                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4888                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4889             } else {
4890                 int dropVal = ~ddIdx, insPos = 0;
4891                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4892                     // Find first element of reorder larger than dropVal.
4893                     // This is where we will insert the dropVal.
4894                     insPos += 1;
4895                 }
4896                 Class<?> ptype = newType.parameterType(dropVal);
4897                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4898                 oldType = oldType.insertParameterTypes(insPos, ptype);
4899                 // expand the reordering by inserting an element at insPos
4900                 int tailPos = insPos + 1;
4901                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4902                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4903                 reorder[insPos] = dropVal;
4904             }
4905             assert (permuteArgumentChecks(reorder, newType, oldType));
4906         }
4907         assert (reorder.length == newArity);  // a perfect permutation
4908         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4909         form = form.editor().permuteArgumentsForm(1, reorder);
4910         if (newType == result.type() && form == result.internalForm())
4911             return result;
4912         return result.copyWith(newType, form);
4913     }
4914 
4915     /**
4916      * Return an indication of any duplicate or omission in reorder.
4917      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4918      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4919      * Otherwise, return zero.
4920      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4921      */
4922     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4923         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4924         if (newArity < BIT_LIMIT) {
4925             long mask = 0;
4926             for (int i = 0; i < reorder.length; i++) {
4927                 int arg = reorder[i];
4928                 if (arg >= newArity) {
4929                     return reorder.length;
4930                 }
4931                 long bit = 1L << arg;
4932                 if ((mask & bit) != 0) {
4933                     return i;  // >0 indicates a dup
4934                 }
4935                 mask |= bit;
4936             }
4937             if (mask == (1L << newArity) - 1) {
4938                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4939                 return 0;
4940             }
4941             // find first zero
4942             long zeroBit = Long.lowestOneBit(~mask);
4943             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4944             assert(zeroPos <= newArity);
4945             if (zeroPos == newArity) {
4946                 return 0;
4947             }
4948             return ~zeroPos;
4949         } else {
4950             // same algorithm, different bit set
4951             BitSet mask = new BitSet(newArity);
4952             for (int i = 0; i < reorder.length; i++) {
4953                 int arg = reorder[i];
4954                 if (arg >= newArity) {
4955                     return reorder.length;
4956                 }
4957                 if (mask.get(arg)) {
4958                     return i;  // >0 indicates a dup
4959                 }
4960                 mask.set(arg);
4961             }
4962             int zeroPos = mask.nextClearBit(0);
4963             assert(zeroPos <= newArity);
4964             if (zeroPos == newArity) {
4965                 return 0;
4966             }
4967             return ~zeroPos;
4968         }
4969     }
4970 
4971     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4972         if (newType.returnType() != oldType.returnType())
4973             throw newIllegalArgumentException("return types do not match",
4974                     oldType, newType);
4975         if (reorder.length != oldType.parameterCount())
4976             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4977                     oldType, Arrays.toString(reorder));
4978 
4979         int limit = newType.parameterCount();
4980         for (int j = 0; j < reorder.length; j++) {
4981             int i = reorder[j];
4982             if (i < 0 || i >= limit) {
4983                 throw newIllegalArgumentException("index is out of bounds for new type",
4984                         i, newType);
4985             }
4986             Class<?> src = newType.parameterType(i);
4987             Class<?> dst = oldType.parameterType(j);
4988             if (src != dst)
4989                 throw newIllegalArgumentException("parameter types do not match after reorder",
4990                         oldType, newType);
4991         }
4992         return true;
4993     }
4994 
4995     /**
4996      * Produces a method handle of the requested return type which returns the given
4997      * constant value every time it is invoked.
4998      * <p>
4999      * Before the method handle is returned, the passed-in value is converted to the requested type.
5000      * If the requested type is primitive, widening primitive conversions are attempted,
5001      * else reference conversions are attempted.
5002      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5003      * @param type the return type of the desired method handle
5004      * @param value the value to return
5005      * @return a method handle of the given return type and no arguments, which always returns the given value
5006      * @throws NullPointerException if the {@code type} argument is null
5007      * @throws ClassCastException if the value cannot be converted to the required return type
5008      * @throws IllegalArgumentException if the given type is {@code void.class}
5009      */
5010     public static MethodHandle constant(Class<?> type, Object value) {
5011         if (type.isPrimitive()) {
5012             if (type == void.class)
5013                 throw newIllegalArgumentException("void type");
5014             Wrapper w = Wrapper.forPrimitiveType(type);
5015             value = w.convert(value, type);
5016             if (w.zero().equals(value))
5017                 return zero(w, type);
5018             return insertArguments(identity(type), 0, value);
5019         } else {
5020             if (value == null)
5021                 return zero(Wrapper.OBJECT, type);
5022             return identity(type).bindTo(value);
5023         }
5024     }
5025 
5026     /**
5027      * Produces a method handle which returns its sole argument when invoked.
5028      * @param type the type of the sole parameter and return value of the desired method handle
5029      * @return a unary method handle which accepts and returns the given type
5030      * @throws NullPointerException if the argument is null
5031      * @throws IllegalArgumentException if the given type is {@code void.class}
5032      */
5033     public static MethodHandle identity(Class<?> type) {
5034         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5035         int pos = btw.ordinal();
5036         MethodHandle ident = IDENTITY_MHS[pos];
5037         if (ident == null) {
5038             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5039         }
5040         if (ident.type().returnType() == type)
5041             return ident;
5042         // something like identity(Foo.class); do not bother to intern these
5043         assert (btw == Wrapper.OBJECT);
5044         return makeIdentity(type);
5045     }
5046 
5047     /**
5048      * Produces a constant method handle of the requested return type which
5049      * returns the default value for that type every time it is invoked.
5050      * The resulting constant method handle will have no side effects.
5051      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5052      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5053      * since {@code explicitCastArguments} converts {@code null} to default values.
5054      * @param type the expected return type of the desired method handle
5055      * @return a constant method handle that takes no arguments
5056      *         and returns the default value of the given type (or void, if the type is void)
5057      * @throws NullPointerException if the argument is null
5058      * @see MethodHandles#constant
5059      * @see MethodHandles#empty
5060      * @see MethodHandles#explicitCastArguments
5061      * @since 9
5062      */
5063     public static MethodHandle zero(Class<?> type) {
5064         Objects.requireNonNull(type);
5065         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
5066     }
5067 
5068     private static MethodHandle identityOrVoid(Class<?> type) {
5069         return type == void.class ? zero(type) : identity(type);
5070     }
5071 
5072     /**
5073      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5074      * and returns a suitable default depending on the return type.
5075      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5076      * <p>The returned method handle is equivalent to
5077      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5078      *
5079      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5080      * {@code guardWithTest(pred, target, empty(target.type())}.
5081      * @param type the type of the desired method handle
5082      * @return a constant method handle of the given type, which returns a default value of the given return type
5083      * @throws NullPointerException if the argument is null
5084      * @see MethodHandles#zero
5085      * @see MethodHandles#constant
5086      * @since 9
5087      */
5088     public static  MethodHandle empty(MethodType type) {
5089         Objects.requireNonNull(type);
5090         return dropArguments(zero(type.returnType()), 0, type.parameterList());
5091     }
5092 
5093     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5094     private static MethodHandle makeIdentity(Class<?> ptype) {
5095         MethodType mtype = methodType(ptype, ptype);
5096         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5097         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5098     }
5099 
5100     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5101         int pos = btw.ordinal();
5102         MethodHandle zero = ZERO_MHS[pos];
5103         if (zero == null) {
5104             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5105         }
5106         if (zero.type().returnType() == rtype)
5107             return zero;
5108         assert(btw == Wrapper.OBJECT);
5109         return makeZero(rtype);
5110     }
5111     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5112     private static MethodHandle makeZero(Class<?> rtype) {
5113         MethodType mtype = methodType(rtype);
5114         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5115         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5116     }
5117 
5118     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5119         // Simulate a CAS, to avoid racy duplication of results.
5120         MethodHandle prev = cache[pos];
5121         if (prev != null) return prev;
5122         return cache[pos] = value;
5123     }
5124 
5125     /**
5126      * Provides a target method handle with one or more <em>bound arguments</em>
5127      * in advance of the method handle's invocation.
5128      * The formal parameters to the target corresponding to the bound
5129      * arguments are called <em>bound parameters</em>.
5130      * Returns a new method handle which saves away the bound arguments.
5131      * When it is invoked, it receives arguments for any non-bound parameters,
5132      * binds the saved arguments to their corresponding parameters,
5133      * and calls the original target.
5134      * <p>
5135      * The type of the new method handle will drop the types for the bound
5136      * parameters from the original target type, since the new method handle
5137      * will no longer require those arguments to be supplied by its callers.
5138      * <p>
5139      * Each given argument object must match the corresponding bound parameter type.
5140      * If a bound parameter type is a primitive, the argument object
5141      * must be a wrapper, and will be unboxed to produce the primitive value.
5142      * <p>
5143      * The {@code pos} argument selects which parameters are to be bound.
5144      * It may range between zero and <i>N-L</i> (inclusively),
5145      * where <i>N</i> is the arity of the target method handle
5146      * and <i>L</i> is the length of the values array.
5147      * <p>
5148      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5149      * variable-arity method handle}, even if the original target method handle was.
5150      * @param target the method handle to invoke after the argument is inserted
5151      * @param pos where to insert the argument (zero for the first)
5152      * @param values the series of arguments to insert
5153      * @return a method handle which inserts an additional argument,
5154      *         before calling the original method handle
5155      * @throws NullPointerException if the target or the {@code values} array is null
5156      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5157      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5158      *         is the length of the values array.
5159      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5160      *         type.
5161      * @see MethodHandle#bindTo
5162      */
5163     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5164         int insCount = values.length;
5165         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5166         if (insCount == 0)  return target;
5167         BoundMethodHandle result = target.rebind();
5168         for (int i = 0; i < insCount; i++) {
5169             Object value = values[i];
5170             Class<?> ptype = ptypes[pos+i];
5171             if (ptype.isPrimitive()) {
5172                 result = insertArgumentPrimitive(result, pos, ptype, value);
5173             } else {
5174                 value = ptype.cast(value);  // throw CCE if needed
5175                 result = result.bindArgumentL(pos, value);
5176             }
5177         }
5178         return result;
5179     }
5180 
5181     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5182                                                              Class<?> ptype, Object value) {
5183         Wrapper w = Wrapper.forPrimitiveType(ptype);
5184         // perform unboxing and/or primitive conversion
5185         value = w.convert(value, ptype);
5186         return switch (w) {
5187             case INT    -> result.bindArgumentI(pos, (int) value);
5188             case LONG   -> result.bindArgumentJ(pos, (long) value);
5189             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5190             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5191             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5192         };
5193     }
5194 
5195     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5196         MethodType oldType = target.type();
5197         int outargs = oldType.parameterCount();
5198         int inargs  = outargs - insCount;
5199         if (inargs < 0)
5200             throw newIllegalArgumentException("too many values to insert");
5201         if (pos < 0 || pos > inargs)
5202             throw newIllegalArgumentException("no argument type to append");
5203         return oldType.ptypes();
5204     }
5205 
5206     /**
5207      * Produces a method handle which will discard some dummy arguments
5208      * before calling some other specified <i>target</i> method handle.
5209      * The type of the new method handle will be the same as the target's type,
5210      * except it will also include the dummy argument types,
5211      * at some given position.
5212      * <p>
5213      * The {@code pos} argument may range between zero and <i>N</i>,
5214      * where <i>N</i> is the arity of the target.
5215      * If {@code pos} is zero, the dummy arguments will precede
5216      * the target's real arguments; if {@code pos} is <i>N</i>
5217      * they will come after.
5218      * <p>
5219      * <b>Example:</b>
5220      * <blockquote><pre>{@code
5221 import static java.lang.invoke.MethodHandles.*;
5222 import static java.lang.invoke.MethodType.*;
5223 ...
5224 MethodHandle cat = lookup().findVirtual(String.class,
5225   "concat", methodType(String.class, String.class));
5226 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5227 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5228 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5229 assertEquals(bigType, d0.type());
5230 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5231      * }</pre></blockquote>
5232      * <p>
5233      * This method is also equivalent to the following code:
5234      * <blockquote><pre>
5235      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5236      * </pre></blockquote>
5237      * @param target the method handle to invoke after the arguments are dropped
5238      * @param pos position of first argument to drop (zero for the leftmost)
5239      * @param valueTypes the type(s) of the argument(s) to drop
5240      * @return a method handle which drops arguments of the given types,
5241      *         before calling the original method handle
5242      * @throws NullPointerException if the target is null,
5243      *                              or if the {@code valueTypes} list or any of its elements is null
5244      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5245      *                  or if {@code pos} is negative or greater than the arity of the target,
5246      *                  or if the new method handle's type would have too many parameters
5247      */
5248     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5249         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
5250     }
5251 
5252     private static List<Class<?>> copyTypes(Object[] array) {
5253         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
5254     }
5255 
5256     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5257         MethodType oldType = target.type();  // get NPE
5258         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5259         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5260         if (dropped == 0)  return target;
5261         BoundMethodHandle result = target.rebind();
5262         LambdaForm lform = result.form;
5263         int insertFormArg = 1 + pos;
5264         for (Class<?> ptype : valueTypes) {
5265             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5266         }
5267         result = result.copyWith(newType, lform);
5268         return result;
5269     }
5270 
5271     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
5272         int dropped = valueTypes.size();
5273         MethodType.checkSlotCount(dropped);
5274         int outargs = oldType.parameterCount();
5275         int inargs  = outargs + dropped;
5276         if (pos < 0 || pos > outargs)
5277             throw newIllegalArgumentException("no argument type to remove"
5278                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5279                     );
5280         return dropped;
5281     }
5282 
5283     /**
5284      * Produces a method handle which will discard some dummy arguments
5285      * before calling some other specified <i>target</i> method handle.
5286      * The type of the new method handle will be the same as the target's type,
5287      * except it will also include the dummy argument types,
5288      * at some given position.
5289      * <p>
5290      * The {@code pos} argument may range between zero and <i>N</i>,
5291      * where <i>N</i> is the arity of the target.
5292      * If {@code pos} is zero, the dummy arguments will precede
5293      * the target's real arguments; if {@code pos} is <i>N</i>
5294      * they will come after.
5295      * @apiNote
5296      * <blockquote><pre>{@code
5297 import static java.lang.invoke.MethodHandles.*;
5298 import static java.lang.invoke.MethodType.*;
5299 ...
5300 MethodHandle cat = lookup().findVirtual(String.class,
5301   "concat", methodType(String.class, String.class));
5302 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5303 MethodHandle d0 = dropArguments(cat, 0, String.class);
5304 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5305 MethodHandle d1 = dropArguments(cat, 1, String.class);
5306 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5307 MethodHandle d2 = dropArguments(cat, 2, String.class);
5308 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5309 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5310 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5311      * }</pre></blockquote>
5312      * <p>
5313      * This method is also equivalent to the following code:
5314      * <blockquote><pre>
5315      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5316      * </pre></blockquote>
5317      * @param target the method handle to invoke after the arguments are dropped
5318      * @param pos position of first argument to drop (zero for the leftmost)
5319      * @param valueTypes the type(s) of the argument(s) to drop
5320      * @return a method handle which drops arguments of the given types,
5321      *         before calling the original method handle
5322      * @throws NullPointerException if the target is null,
5323      *                              or if the {@code valueTypes} array or any of its elements is null
5324      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5325      *                  or if {@code pos} is negative or greater than the arity of the target,
5326      *                  or if the new method handle's type would have
5327      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5328      */
5329     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5330         return dropArguments0(target, pos, copyTypes(valueTypes));
5331     }
5332 
5333     // private version which allows caller some freedom with error handling
5334     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
5335                                       boolean nullOnFailure) {
5336         newTypes = copyTypes(newTypes.toArray());
5337         List<Class<?>> oldTypes = target.type().parameterList();
5338         int match = oldTypes.size();
5339         if (skip != 0) {
5340             if (skip < 0 || skip > match) {
5341                 throw newIllegalArgumentException("illegal skip", skip, target);
5342             }
5343             oldTypes = oldTypes.subList(skip, match);
5344             match -= skip;
5345         }
5346         List<Class<?>> addTypes = newTypes;
5347         int add = addTypes.size();
5348         if (pos != 0) {
5349             if (pos < 0 || pos > add) {
5350                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
5351             }
5352             addTypes = addTypes.subList(pos, add);
5353             add -= pos;
5354             assert(addTypes.size() == add);
5355         }
5356         // Do not add types which already match the existing arguments.
5357         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
5358             if (nullOnFailure) {
5359                 return null;
5360             }
5361             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5362         }
5363         addTypes = addTypes.subList(match, add);
5364         add -= match;
5365         assert(addTypes.size() == add);
5366         // newTypes:     (   P*[pos], M*[match], A*[add] )
5367         // target: ( S*[skip],        M*[match]  )
5368         MethodHandle adapter = target;
5369         if (add > 0) {
5370             adapter = dropArguments0(adapter, skip+ match, addTypes);
5371         }
5372         // adapter: (S*[skip],        M*[match], A*[add] )
5373         if (pos > 0) {
5374             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5375         }
5376         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5377         return adapter;
5378     }
5379 
5380     /**
5381      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5382      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5383      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5384      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5385      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5386      * {@link #dropArguments(MethodHandle, int, Class[])}.
5387      * <p>
5388      * The resulting handle will have the same return type as the target handle.
5389      * <p>
5390      * In more formal terms, assume these two type lists:<ul>
5391      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5392      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5393      * {@code newTypes}.
5394      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5395      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5396      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5397      * sub-list.
5398      * </ul>
5399      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5400      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5401      * {@link #dropArguments(MethodHandle, int, Class[])}.
5402      *
5403      * @apiNote
5404      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5405      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5406      * <blockquote><pre>{@code
5407 import static java.lang.invoke.MethodHandles.*;
5408 import static java.lang.invoke.MethodType.*;
5409 ...
5410 ...
5411 MethodHandle h0 = constant(boolean.class, true);
5412 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5413 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5414 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5415 if (h1.type().parameterCount() < h2.type().parameterCount())
5416     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5417 else
5418     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5419 MethodHandle h3 = guardWithTest(h0, h1, h2);
5420 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5421      * }</pre></blockquote>
5422      * @param target the method handle to adapt
5423      * @param skip number of targets parameters to disregard (they will be unchanged)
5424      * @param newTypes the list of types to match {@code target}'s parameter type list to
5425      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5426      * @return a possibly adapted method handle
5427      * @throws NullPointerException if either argument is null
5428      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5429      *         or if {@code skip} is negative or greater than the arity of the target,
5430      *         or if {@code pos} is negative or greater than the newTypes list size,
5431      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5432      *         {@code pos}.
5433      * @since 9
5434      */
5435     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5436         Objects.requireNonNull(target);
5437         Objects.requireNonNull(newTypes);
5438         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5439     }
5440 
5441     /**
5442      * Drop the return value of the target handle (if any).
5443      * The returned method handle will have a {@code void} return type.
5444      *
5445      * @param target the method handle to adapt
5446      * @return a possibly adapted method handle
5447      * @throws NullPointerException if {@code target} is null
5448      * @since 16
5449      */
5450     public static MethodHandle dropReturn(MethodHandle target) {
5451         Objects.requireNonNull(target);
5452         MethodType oldType = target.type();
5453         Class<?> oldReturnType = oldType.returnType();
5454         if (oldReturnType == void.class)
5455             return target;
5456         MethodType newType = oldType.changeReturnType(void.class);
5457         BoundMethodHandle result = target.rebind();
5458         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5459         result = result.copyWith(newType, lform);
5460         return result;
5461     }
5462 
5463     /**
5464      * Adapts a target method handle by pre-processing
5465      * one or more of its arguments, each with its own unary filter function,
5466      * and then calling the target with each pre-processed argument
5467      * replaced by the result of its corresponding filter function.
5468      * <p>
5469      * The pre-processing is performed by one or more method handles,
5470      * specified in the elements of the {@code filters} array.
5471      * The first element of the filter array corresponds to the {@code pos}
5472      * argument of the target, and so on in sequence.
5473      * The filter functions are invoked in left to right order.
5474      * <p>
5475      * Null arguments in the array are treated as identity functions,
5476      * and the corresponding arguments left unchanged.
5477      * (If there are no non-null elements in the array, the original target is returned.)
5478      * Each filter is applied to the corresponding argument of the adapter.
5479      * <p>
5480      * If a filter {@code F} applies to the {@code N}th argument of
5481      * the target, then {@code F} must be a method handle which
5482      * takes exactly one argument.  The type of {@code F}'s sole argument
5483      * replaces the corresponding argument type of the target
5484      * in the resulting adapted method handle.
5485      * The return type of {@code F} must be identical to the corresponding
5486      * parameter type of the target.
5487      * <p>
5488      * It is an error if there are elements of {@code filters}
5489      * (null or not)
5490      * which do not correspond to argument positions in the target.
5491      * <p><b>Example:</b>
5492      * <blockquote><pre>{@code
5493 import static java.lang.invoke.MethodHandles.*;
5494 import static java.lang.invoke.MethodType.*;
5495 ...
5496 MethodHandle cat = lookup().findVirtual(String.class,
5497   "concat", methodType(String.class, String.class));
5498 MethodHandle upcase = lookup().findVirtual(String.class,
5499   "toUpperCase", methodType(String.class));
5500 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5501 MethodHandle f0 = filterArguments(cat, 0, upcase);
5502 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5503 MethodHandle f1 = filterArguments(cat, 1, upcase);
5504 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5505 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5506 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5507      * }</pre></blockquote>
5508      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5509      * denotes the return type of both the {@code target} and resulting adapter.
5510      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5511      * of the parameters and arguments that precede and follow the filter position
5512      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5513      * values of the filtered parameters and arguments; they also represent the
5514      * return types of the {@code filter[i]} handles. The latter accept arguments
5515      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5516      * the resulting adapter.
5517      * <blockquote><pre>{@code
5518      * T target(P... p, A[i]... a[i], B... b);
5519      * A[i] filter[i](V[i]);
5520      * T adapter(P... p, V[i]... v[i], B... b) {
5521      *   return target(p..., filter[i](v[i])..., b...);
5522      * }
5523      * }</pre></blockquote>
5524      * <p>
5525      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5526      * variable-arity method handle}, even if the original target method handle was.
5527      *
5528      * @param target the method handle to invoke after arguments are filtered
5529      * @param pos the position of the first argument to filter
5530      * @param filters method handles to call initially on filtered arguments
5531      * @return method handle which incorporates the specified argument filtering logic
5532      * @throws NullPointerException if the target is null
5533      *                              or if the {@code filters} array is null
5534      * @throws IllegalArgumentException if a non-null element of {@code filters}
5535      *          does not match a corresponding argument type of target as described above,
5536      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5537      *          or if the resulting method handle's type would have
5538      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5539      */
5540     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5541         // In method types arguments start at index 0, while the LF
5542         // editor have the MH receiver at position 0 - adjust appropriately.
5543         final int MH_RECEIVER_OFFSET = 1;
5544         filterArgumentsCheckArity(target, pos, filters);
5545         MethodHandle adapter = target;
5546 
5547         // keep track of currently matched filters, as to optimize repeated filters
5548         int index = 0;
5549         int[] positions = new int[filters.length];
5550         MethodHandle filter = null;
5551 
5552         // process filters in reverse order so that the invocation of
5553         // the resulting adapter will invoke the filters in left-to-right order
5554         for (int i = filters.length - 1; i >= 0; --i) {
5555             MethodHandle newFilter = filters[i];
5556             if (newFilter == null) continue;  // ignore null elements of filters
5557 
5558             // flush changes on update
5559             if (filter != newFilter) {
5560                 if (filter != null) {
5561                     if (index > 1) {
5562                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5563                     } else {
5564                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5565                     }
5566                 }
5567                 filter = newFilter;
5568                 index = 0;
5569             }
5570 
5571             filterArgumentChecks(target, pos + i, newFilter);
5572             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5573         }
5574         if (index > 1) {
5575             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5576         } else if (index == 1) {
5577             adapter = filterArgument(adapter, positions[0] - 1, filter);
5578         }
5579         return adapter;
5580     }
5581 
5582     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5583         MethodType targetType = adapter.type();
5584         MethodType filterType = filter.type();
5585         BoundMethodHandle result = adapter.rebind();
5586         Class<?> newParamType = filterType.parameterType(0);
5587 
5588         Class<?>[] ptypes = targetType.ptypes().clone();
5589         for (int pos : positions) {
5590             ptypes[pos - 1] = newParamType;
5591         }
5592         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5593 
5594         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5595         return result.copyWithExtendL(newType, lform, filter);
5596     }
5597 
5598     /*non-public*/
5599     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5600         filterArgumentChecks(target, pos, filter);
5601         MethodType targetType = target.type();
5602         MethodType filterType = filter.type();
5603         BoundMethodHandle result = target.rebind();
5604         Class<?> newParamType = filterType.parameterType(0);
5605         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5606         MethodType newType = targetType.changeParameterType(pos, newParamType);
5607         result = result.copyWithExtendL(newType, lform, filter);
5608         return result;
5609     }
5610 
5611     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5612         MethodType targetType = target.type();
5613         int maxPos = targetType.parameterCount();
5614         if (pos + filters.length > maxPos)
5615             throw newIllegalArgumentException("too many filters");
5616     }
5617 
5618     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5619         MethodType targetType = target.type();
5620         MethodType filterType = filter.type();
5621         if (filterType.parameterCount() != 1
5622             || filterType.returnType() != targetType.parameterType(pos))
5623             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5624     }
5625 
5626     /**
5627      * Adapts a target method handle by pre-processing
5628      * a sub-sequence of its arguments with a filter (another method handle).
5629      * The pre-processed arguments are replaced by the result (if any) of the
5630      * filter function.
5631      * The target is then called on the modified (usually shortened) argument list.
5632      * <p>
5633      * If the filter returns a value, the target must accept that value as
5634      * its argument in position {@code pos}, preceded and/or followed by
5635      * any arguments not passed to the filter.
5636      * If the filter returns void, the target must accept all arguments
5637      * not passed to the filter.
5638      * No arguments are reordered, and a result returned from the filter
5639      * replaces (in order) the whole subsequence of arguments originally
5640      * passed to the adapter.
5641      * <p>
5642      * The argument types (if any) of the filter
5643      * replace zero or one argument types of the target, at position {@code pos},
5644      * in the resulting adapted method handle.
5645      * The return type of the filter (if any) must be identical to the
5646      * argument type of the target at position {@code pos}, and that target argument
5647      * is supplied by the return value of the filter.
5648      * <p>
5649      * In all cases, {@code pos} must be greater than or equal to zero, and
5650      * {@code pos} must also be less than or equal to the target's arity.
5651      * <p><b>Example:</b>
5652      * <blockquote><pre>{@code
5653 import static java.lang.invoke.MethodHandles.*;
5654 import static java.lang.invoke.MethodType.*;
5655 ...
5656 MethodHandle deepToString = publicLookup()
5657   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5658 
5659 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5660 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5661 
5662 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5663 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5664 
5665 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5666 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5667 assertEquals("[top, [up, down], strange]",
5668              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5669 
5670 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5671 assertEquals("[top, [up, down], [strange]]",
5672              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5673 
5674 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5675 assertEquals("[top, [[up, down, strange], charm], bottom]",
5676              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5677      * }</pre></blockquote>
5678      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5679      * represents the return type of the {@code target} and resulting adapter.
5680      * {@code V}/{@code v} stand for the return type and value of the
5681      * {@code filter}, which are also found in the signature and arguments of
5682      * the {@code target}, respectively, unless {@code V} is {@code void}.
5683      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5684      * and values preceding and following the collection position, {@code pos},
5685      * in the {@code target}'s signature. They also turn up in the resulting
5686      * adapter's signature and arguments, where they surround
5687      * {@code B}/{@code b}, which represent the parameter types and arguments
5688      * to the {@code filter} (if any).
5689      * <blockquote><pre>{@code
5690      * T target(A...,V,C...);
5691      * V filter(B...);
5692      * T adapter(A... a,B... b,C... c) {
5693      *   V v = filter(b...);
5694      *   return target(a...,v,c...);
5695      * }
5696      * // and if the filter has no arguments:
5697      * T target2(A...,V,C...);
5698      * V filter2();
5699      * T adapter2(A... a,C... c) {
5700      *   V v = filter2();
5701      *   return target2(a...,v,c...);
5702      * }
5703      * // and if the filter has a void return:
5704      * T target3(A...,C...);
5705      * void filter3(B...);
5706      * T adapter3(A... a,B... b,C... c) {
5707      *   filter3(b...);
5708      *   return target3(a...,c...);
5709      * }
5710      * }</pre></blockquote>
5711      * <p>
5712      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5713      * one which first "folds" the affected arguments, and then drops them, in separate
5714      * steps as follows:
5715      * <blockquote><pre>{@code
5716      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5717      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5718      * }</pre></blockquote>
5719      * If the target method handle consumes no arguments besides than the result
5720      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5721      * is equivalent to {@code filterReturnValue(coll, mh)}.
5722      * If the filter method handle {@code coll} consumes one argument and produces
5723      * a non-void result, then {@code collectArguments(mh, N, coll)}
5724      * is equivalent to {@code filterArguments(mh, N, coll)}.
5725      * Other equivalences are possible but would require argument permutation.
5726      * <p>
5727      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5728      * variable-arity method handle}, even if the original target method handle was.
5729      *
5730      * @param target the method handle to invoke after filtering the subsequence of arguments
5731      * @param pos the position of the first adapter argument to pass to the filter,
5732      *            and/or the target argument which receives the result of the filter
5733      * @param filter method handle to call on the subsequence of arguments
5734      * @return method handle which incorporates the specified argument subsequence filtering logic
5735      * @throws NullPointerException if either argument is null
5736      * @throws IllegalArgumentException if the return type of {@code filter}
5737      *          is non-void and is not the same as the {@code pos} argument of the target,
5738      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5739      *          or if the resulting method handle's type would have
5740      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5741      * @see MethodHandles#foldArguments
5742      * @see MethodHandles#filterArguments
5743      * @see MethodHandles#filterReturnValue
5744      */
5745     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5746         MethodType newType = collectArgumentsChecks(target, pos, filter);
5747         MethodType collectorType = filter.type();
5748         BoundMethodHandle result = target.rebind();
5749         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5750         return result.copyWithExtendL(newType, lform, filter);
5751     }
5752 
5753     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5754         MethodType targetType = target.type();
5755         MethodType filterType = filter.type();
5756         Class<?> rtype = filterType.returnType();
5757         List<Class<?>> filterArgs = filterType.parameterList();
5758         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5759                        (rtype != void.class && pos >= targetType.parameterCount())) {
5760             throw newIllegalArgumentException("position is out of range for target", target, pos);
5761         }
5762         if (rtype == void.class) {
5763             return targetType.insertParameterTypes(pos, filterArgs);
5764         }
5765         if (rtype != targetType.parameterType(pos)) {
5766             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5767         }
5768         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5769     }
5770 
5771     /**
5772      * Adapts a target method handle by post-processing
5773      * its return value (if any) with a filter (another method handle).
5774      * The result of the filter is returned from the adapter.
5775      * <p>
5776      * If the target returns a value, the filter must accept that value as
5777      * its only argument.
5778      * If the target returns void, the filter must accept no arguments.
5779      * <p>
5780      * The return type of the filter
5781      * replaces the return type of the target
5782      * in the resulting adapted method handle.
5783      * The argument type of the filter (if any) must be identical to the
5784      * return type of the target.
5785      * <p><b>Example:</b>
5786      * <blockquote><pre>{@code
5787 import static java.lang.invoke.MethodHandles.*;
5788 import static java.lang.invoke.MethodType.*;
5789 ...
5790 MethodHandle cat = lookup().findVirtual(String.class,
5791   "concat", methodType(String.class, String.class));
5792 MethodHandle length = lookup().findVirtual(String.class,
5793   "length", methodType(int.class));
5794 System.out.println((String) cat.invokeExact("x", "y")); // xy
5795 MethodHandle f0 = filterReturnValue(cat, length);
5796 System.out.println((int) f0.invokeExact("x", "y")); // 2
5797      * }</pre></blockquote>
5798      * <p>Here is pseudocode for the resulting adapter. In the code,
5799      * {@code T}/{@code t} represent the result type and value of the
5800      * {@code target}; {@code V}, the result type of the {@code filter}; and
5801      * {@code A}/{@code a}, the types and values of the parameters and arguments
5802      * of the {@code target} as well as the resulting adapter.
5803      * <blockquote><pre>{@code
5804      * T target(A...);
5805      * V filter(T);
5806      * V adapter(A... a) {
5807      *   T t = target(a...);
5808      *   return filter(t);
5809      * }
5810      * // and if the target has a void return:
5811      * void target2(A...);
5812      * V filter2();
5813      * V adapter2(A... a) {
5814      *   target2(a...);
5815      *   return filter2();
5816      * }
5817      * // and if the filter has a void return:
5818      * T target3(A...);
5819      * void filter3(V);
5820      * void adapter3(A... a) {
5821      *   T t = target3(a...);
5822      *   filter3(t);
5823      * }
5824      * }</pre></blockquote>
5825      * <p>
5826      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5827      * variable-arity method handle}, even if the original target method handle was.
5828      * @param target the method handle to invoke before filtering the return value
5829      * @param filter method handle to call on the return value
5830      * @return method handle which incorporates the specified return value filtering logic
5831      * @throws NullPointerException if either argument is null
5832      * @throws IllegalArgumentException if the argument list of {@code filter}
5833      *          does not match the return type of target as described above
5834      */
5835     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5836         MethodType targetType = target.type();
5837         MethodType filterType = filter.type();
5838         filterReturnValueChecks(targetType, filterType);
5839         BoundMethodHandle result = target.rebind();
5840         BasicType rtype = BasicType.basicType(filterType.returnType());
5841         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5842         MethodType newType = targetType.changeReturnType(filterType.returnType());
5843         result = result.copyWithExtendL(newType, lform, filter);
5844         return result;
5845     }
5846 
5847     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5848         Class<?> rtype = targetType.returnType();
5849         int filterValues = filterType.parameterCount();
5850         if (filterValues == 0
5851                 ? (rtype != void.class)
5852                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5853             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5854     }
5855 
5856     /**
5857      * Filter the return value of a target method handle with a filter function. The filter function is
5858      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5859      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5860      * as follows:
5861      * <blockquote><pre>{@code
5862      * T target(A...)
5863      * V filter(B... , T)
5864      * V adapter(A... a, B... b) {
5865      *     T t = target(a...);
5866      *     return filter(b..., t);
5867      * }</pre></blockquote>
5868      * <p>
5869      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5870      *
5871      * @param target the target method handle
5872      * @param filter the filter method handle
5873      * @return the adapter method handle
5874      */
5875     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5876         MethodType targetType = target.type();
5877         MethodType filterType = filter.type();
5878         BoundMethodHandle result = target.rebind();
5879         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5880         MethodType newType = targetType.changeReturnType(filterType.returnType());
5881         if (filterType.parameterCount() > 1) {
5882             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5883                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5884             }
5885         }
5886         result = result.copyWithExtendL(newType, lform, filter);
5887         return result;
5888     }
5889 
5890     /**
5891      * Adapts a target method handle by pre-processing
5892      * some of its arguments, and then calling the target with
5893      * the result of the pre-processing, inserted into the original
5894      * sequence of arguments.
5895      * <p>
5896      * The pre-processing is performed by {@code combiner}, a second method handle.
5897      * Of the arguments passed to the adapter, the first {@code N} arguments
5898      * are copied to the combiner, which is then called.
5899      * (Here, {@code N} is defined as the parameter count of the combiner.)
5900      * After this, control passes to the target, with any result
5901      * from the combiner inserted before the original {@code N} incoming
5902      * arguments.
5903      * <p>
5904      * If the combiner returns a value, the first parameter type of the target
5905      * must be identical with the return type of the combiner, and the next
5906      * {@code N} parameter types of the target must exactly match the parameters
5907      * of the combiner.
5908      * <p>
5909      * If the combiner has a void return, no result will be inserted,
5910      * and the first {@code N} parameter types of the target
5911      * must exactly match the parameters of the combiner.
5912      * <p>
5913      * The resulting adapter is the same type as the target, except that the
5914      * first parameter type is dropped,
5915      * if it corresponds to the result of the combiner.
5916      * <p>
5917      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5918      * that either the combiner or the target does not wish to receive.
5919      * If some of the incoming arguments are destined only for the combiner,
5920      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5921      * arguments will not need to be live on the stack on entry to the
5922      * target.)
5923      * <p><b>Example:</b>
5924      * <blockquote><pre>{@code
5925 import static java.lang.invoke.MethodHandles.*;
5926 import static java.lang.invoke.MethodType.*;
5927 ...
5928 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5929   "println", methodType(void.class, String.class))
5930     .bindTo(System.out);
5931 MethodHandle cat = lookup().findVirtual(String.class,
5932   "concat", methodType(String.class, String.class));
5933 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5934 MethodHandle catTrace = foldArguments(cat, trace);
5935 // also prints "boo":
5936 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5937      * }</pre></blockquote>
5938      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5939      * represents the result type of the {@code target} and resulting adapter.
5940      * {@code V}/{@code v} represent the type and value of the parameter and argument
5941      * of {@code target} that precedes the folding position; {@code V} also is
5942      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5943      * types and values of the {@code N} parameters and arguments at the folding
5944      * position. {@code B}/{@code b} represent the types and values of the
5945      * {@code target} parameters and arguments that follow the folded parameters
5946      * and arguments.
5947      * <blockquote><pre>{@code
5948      * // there are N arguments in A...
5949      * T target(V, A[N]..., B...);
5950      * V combiner(A...);
5951      * T adapter(A... a, B... b) {
5952      *   V v = combiner(a...);
5953      *   return target(v, a..., b...);
5954      * }
5955      * // and if the combiner has a void return:
5956      * T target2(A[N]..., B...);
5957      * void combiner2(A...);
5958      * T adapter2(A... a, B... b) {
5959      *   combiner2(a...);
5960      *   return target2(a..., b...);
5961      * }
5962      * }</pre></blockquote>
5963      * <p>
5964      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5965      * variable-arity method handle}, even if the original target method handle was.
5966      * @param target the method handle to invoke after arguments are combined
5967      * @param combiner method handle to call initially on the incoming arguments
5968      * @return method handle which incorporates the specified argument folding logic
5969      * @throws NullPointerException if either argument is null
5970      * @throws IllegalArgumentException if {@code combiner}'s return type
5971      *          is non-void and not the same as the first argument type of
5972      *          the target, or if the initial {@code N} argument types
5973      *          of the target
5974      *          (skipping one matching the {@code combiner}'s return type)
5975      *          are not identical with the argument types of {@code combiner}
5976      */
5977     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5978         return foldArguments(target, 0, combiner);
5979     }
5980 
5981     /**
5982      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5983      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5984      * before the folded arguments.
5985      * <p>
5986      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5987      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5988      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5989      * 0.
5990      *
5991      * @apiNote Example:
5992      * <blockquote><pre>{@code
5993     import static java.lang.invoke.MethodHandles.*;
5994     import static java.lang.invoke.MethodType.*;
5995     ...
5996     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5997     "println", methodType(void.class, String.class))
5998     .bindTo(System.out);
5999     MethodHandle cat = lookup().findVirtual(String.class,
6000     "concat", methodType(String.class, String.class));
6001     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6002     MethodHandle catTrace = foldArguments(cat, 1, trace);
6003     // also prints "jum":
6004     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6005      * }</pre></blockquote>
6006      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6007      * represents the result type of the {@code target} and resulting adapter.
6008      * {@code V}/{@code v} represent the type and value of the parameter and argument
6009      * of {@code target} that precedes the folding position; {@code V} also is
6010      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6011      * types and values of the {@code N} parameters and arguments at the folding
6012      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6013      * and values of the {@code target} parameters and arguments that precede and
6014      * follow the folded parameters and arguments starting at {@code pos},
6015      * respectively.
6016      * <blockquote><pre>{@code
6017      * // there are N arguments in A...
6018      * T target(Z..., V, A[N]..., B...);
6019      * V combiner(A...);
6020      * T adapter(Z... z, A... a, B... b) {
6021      *   V v = combiner(a...);
6022      *   return target(z..., v, a..., b...);
6023      * }
6024      * // and if the combiner has a void return:
6025      * T target2(Z..., A[N]..., B...);
6026      * void combiner2(A...);
6027      * T adapter2(Z... z, A... a, B... b) {
6028      *   combiner2(a...);
6029      *   return target2(z..., a..., b...);
6030      * }
6031      * }</pre></blockquote>
6032      * <p>
6033      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6034      * variable-arity method handle}, even if the original target method handle was.
6035      *
6036      * @param target the method handle to invoke after arguments are combined
6037      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6038      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6039      * @param combiner method handle to call initially on the incoming arguments
6040      * @return method handle which incorporates the specified argument folding logic
6041      * @throws NullPointerException if either argument is null
6042      * @throws IllegalArgumentException if either of the following two conditions holds:
6043      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6044      *              {@code pos} of the target signature;
6045      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6046      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6047      *
6048      * @see #foldArguments(MethodHandle, MethodHandle)
6049      * @since 9
6050      */
6051     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6052         MethodType targetType = target.type();
6053         MethodType combinerType = combiner.type();
6054         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6055         BoundMethodHandle result = target.rebind();
6056         boolean dropResult = rtype == void.class;
6057         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6058         MethodType newType = targetType;
6059         if (!dropResult) {
6060             newType = newType.dropParameterTypes(pos, pos + 1);
6061         }
6062         result = result.copyWithExtendL(newType, lform, combiner);
6063         return result;
6064     }
6065 
6066     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6067         int foldArgs   = combinerType.parameterCount();
6068         Class<?> rtype = combinerType.returnType();
6069         int foldVals = rtype == void.class ? 0 : 1;
6070         int afterInsertPos = foldPos + foldVals;
6071         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6072         if (ok) {
6073             for (int i = 0; i < foldArgs; i++) {
6074                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6075                     ok = false;
6076                     break;
6077                 }
6078             }
6079         }
6080         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6081             ok = false;
6082         if (!ok)
6083             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6084         return rtype;
6085     }
6086 
6087     /**
6088      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6089      * of the pre-processing replacing the argument at the given position.
6090      *
6091      * @param target the method handle to invoke after arguments are combined
6092      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6093      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6094      * @param combiner method handle to call initially on the incoming arguments
6095      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6096      * @return method handle which incorporates the specified argument folding logic
6097      * @throws NullPointerException if either argument is null
6098      * @throws IllegalArgumentException if either of the following two conditions holds:
6099      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6100      *              {@code pos} of the target signature;
6101      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6102      *              not identical with the argument types of {@code combiner}.
6103      */
6104     /*non-public*/
6105     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6106         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6107     }
6108 
6109     /**
6110      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6111      * the pre-processing inserted into the original sequence of arguments at the given position.
6112      *
6113      * @param target the method handle to invoke after arguments are combined
6114      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6115      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6116      * @param combiner method handle to call initially on the incoming arguments
6117      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6118      * @return method handle which incorporates the specified argument folding logic
6119      * @throws NullPointerException if either argument is null
6120      * @throws IllegalArgumentException if either of the following two conditions holds:
6121      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6122      *              {@code pos} of the target signature;
6123      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6124      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6125      *              with the argument types of {@code combiner}.
6126      */
6127     /*non-public*/
6128     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6129         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6130     }
6131 
6132     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6133         MethodType targetType = target.type();
6134         MethodType combinerType = combiner.type();
6135         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6136         BoundMethodHandle result = target.rebind();
6137 
6138         MethodType newType = targetType;
6139         LambdaForm lform;
6140         if (filter) {
6141             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6142         } else {
6143             boolean dropResult = rtype == void.class;
6144             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6145             if (!dropResult) {
6146                 newType = newType.dropParameterTypes(position, position + 1);
6147             }
6148         }
6149         result = result.copyWithExtendL(newType, lform, combiner);
6150         return result;
6151     }
6152 
6153     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6154         int combinerArgs = combinerType.parameterCount();
6155         if (argPos.length != combinerArgs) {
6156             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6157         }
6158         Class<?> rtype = combinerType.returnType();
6159 
6160         for (int i = 0; i < combinerArgs; i++) {
6161             int arg = argPos[i];
6162             if (arg < 0 || arg > targetType.parameterCount()) {
6163                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6164             }
6165             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6166                 throw newIllegalArgumentException("target argument type at position " + arg
6167                         + " must match combiner argument type at index " + i + ": " + targetType
6168                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6169             }
6170         }
6171         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6172             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6173         }
6174         return rtype;
6175     }
6176 
6177     /**
6178      * Makes a method handle which adapts a target method handle,
6179      * by guarding it with a test, a boolean-valued method handle.
6180      * If the guard fails, a fallback handle is called instead.
6181      * All three method handles must have the same corresponding
6182      * argument and return types, except that the return type
6183      * of the test must be boolean, and the test is allowed
6184      * to have fewer arguments than the other two method handles.
6185      * <p>
6186      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6187      * represents the uniform result type of the three involved handles;
6188      * {@code A}/{@code a}, the types and values of the {@code target}
6189      * parameters and arguments that are consumed by the {@code test}; and
6190      * {@code B}/{@code b}, those types and values of the {@code target}
6191      * parameters and arguments that are not consumed by the {@code test}.
6192      * <blockquote><pre>{@code
6193      * boolean test(A...);
6194      * T target(A...,B...);
6195      * T fallback(A...,B...);
6196      * T adapter(A... a,B... b) {
6197      *   if (test(a...))
6198      *     return target(a..., b...);
6199      *   else
6200      *     return fallback(a..., b...);
6201      * }
6202      * }</pre></blockquote>
6203      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6204      * be modified by execution of the test, and so are passed unchanged
6205      * from the caller to the target or fallback as appropriate.
6206      * @param test method handle used for test, must return boolean
6207      * @param target method handle to call if test passes
6208      * @param fallback method handle to call if test fails
6209      * @return method handle which incorporates the specified if/then/else logic
6210      * @throws NullPointerException if any argument is null
6211      * @throws IllegalArgumentException if {@code test} does not return boolean,
6212      *          or if all three method types do not match (with the return
6213      *          type of {@code test} changed to match that of the target).
6214      */
6215     public static MethodHandle guardWithTest(MethodHandle test,
6216                                MethodHandle target,
6217                                MethodHandle fallback) {
6218         MethodType gtype = test.type();
6219         MethodType ttype = target.type();
6220         MethodType ftype = fallback.type();
6221         if (!ttype.equals(ftype))
6222             throw misMatchedTypes("target and fallback types", ttype, ftype);
6223         if (gtype.returnType() != boolean.class)
6224             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6225         List<Class<?>> targs = ttype.parameterList();
6226         test = dropArgumentsToMatch(test, 0, targs, 0, true);
6227         if (test == null) {
6228             throw misMatchedTypes("target and test types", ttype, gtype);
6229         }
6230         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6231     }
6232 
6233     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6234         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6235     }
6236 
6237     /**
6238      * Makes a method handle which adapts a target method handle,
6239      * by running it inside an exception handler.
6240      * If the target returns normally, the adapter returns that value.
6241      * If an exception matching the specified type is thrown, the fallback
6242      * handle is called instead on the exception, plus the original arguments.
6243      * <p>
6244      * The target and handler must have the same corresponding
6245      * argument and return types, except that handler may omit trailing arguments
6246      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6247      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6248      * <p>
6249      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6250      * represents the return type of the {@code target} and {@code handler},
6251      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6252      * the types and values of arguments to the resulting handle consumed by
6253      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6254      * resulting handle discarded by {@code handler}.
6255      * <blockquote><pre>{@code
6256      * T target(A..., B...);
6257      * T handler(ExType, A...);
6258      * T adapter(A... a, B... b) {
6259      *   try {
6260      *     return target(a..., b...);
6261      *   } catch (ExType ex) {
6262      *     return handler(ex, a...);
6263      *   }
6264      * }
6265      * }</pre></blockquote>
6266      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6267      * be modified by execution of the target, and so are passed unchanged
6268      * from the caller to the handler, if the handler is invoked.
6269      * <p>
6270      * The target and handler must return the same type, even if the handler
6271      * always throws.  (This might happen, for instance, because the handler
6272      * is simulating a {@code finally} clause).
6273      * To create such a throwing handler, compose the handler creation logic
6274      * with {@link #throwException throwException},
6275      * in order to create a method handle of the correct return type.
6276      * @param target method handle to call
6277      * @param exType the type of exception which the handler will catch
6278      * @param handler method handle to call if a matching exception is thrown
6279      * @return method handle which incorporates the specified try/catch logic
6280      * @throws NullPointerException if any argument is null
6281      * @throws IllegalArgumentException if {@code handler} does not accept
6282      *          the given exception type, or if the method handle types do
6283      *          not match in their return types and their
6284      *          corresponding parameters
6285      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6286      */
6287     public static MethodHandle catchException(MethodHandle target,
6288                                 Class<? extends Throwable> exType,
6289                                 MethodHandle handler) {
6290         MethodType ttype = target.type();
6291         MethodType htype = handler.type();
6292         if (!Throwable.class.isAssignableFrom(exType))
6293             throw new ClassCastException(exType.getName());
6294         if (htype.parameterCount() < 1 ||
6295             !htype.parameterType(0).isAssignableFrom(exType))
6296             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6297         if (htype.returnType() != ttype.returnType())
6298             throw misMatchedTypes("target and handler return types", ttype, htype);
6299         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
6300         if (handler == null) {
6301             throw misMatchedTypes("target and handler types", ttype, htype);
6302         }
6303         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6304     }
6305 
6306     /**
6307      * Produces a method handle which will throw exceptions of the given {@code exType}.
6308      * The method handle will accept a single argument of {@code exType},
6309      * and immediately throw it as an exception.
6310      * The method type will nominally specify a return of {@code returnType}.
6311      * The return type may be anything convenient:  It doesn't matter to the
6312      * method handle's behavior, since it will never return normally.
6313      * @param returnType the return type of the desired method handle
6314      * @param exType the parameter type of the desired method handle
6315      * @return method handle which can throw the given exceptions
6316      * @throws NullPointerException if either argument is null
6317      */
6318     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6319         if (!Throwable.class.isAssignableFrom(exType))
6320             throw new ClassCastException(exType.getName());
6321         return MethodHandleImpl.throwException(methodType(returnType, exType));
6322     }
6323 
6324     /**
6325      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6326      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6327      * delivers the loop's result, which is the return value of the resulting handle.
6328      * <p>
6329      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6330      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6331      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6332      * terms of method handles, each clause will specify up to four independent actions:<ul>
6333      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6334      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6335      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6336      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6337      * </ul>
6338      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6339      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6340      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6341      * <p>
6342      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6343      * this case. See below for a detailed description.
6344      * <p>
6345      * <em>Parameters optional everywhere:</em>
6346      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6347      * As an exception, the init functions cannot take any {@code v} parameters,
6348      * because those values are not yet computed when the init functions are executed.
6349      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6350      * In fact, any clause function may take no arguments at all.
6351      * <p>
6352      * <em>Loop parameters:</em>
6353      * A clause function may take all the iteration variable values it is entitled to, in which case
6354      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6355      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6356      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6357      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6358      * init function is automatically a loop parameter {@code a}.)
6359      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6360      * These loop parameters act as loop-invariant values visible across the whole loop.
6361      * <p>
6362      * <em>Parameters visible everywhere:</em>
6363      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6364      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6365      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6366      * Most clause functions will not need all of this information, but they will be formally connected to it
6367      * as if by {@link #dropArguments}.
6368      * <a id="astar"></a>
6369      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6370      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6371      * In that notation, the general form of an init function parameter list
6372      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6373      * <p>
6374      * <em>Checking clause structure:</em>
6375      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6376      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6377      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6378      * met by the inputs to the loop combinator.
6379      * <p>
6380      * <em>Effectively identical sequences:</em>
6381      * <a id="effid"></a>
6382      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6383      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6384      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6385      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6386      * that longest list.
6387      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6388      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6389      * <p>
6390      * <em>Step 0: Determine clause structure.</em><ol type="a">
6391      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6392      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6393      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6394      * four. Padding takes place by appending elements to the array.
6395      * <li>Clauses with all {@code null}s are disregarded.
6396      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6397      * </ol>
6398      * <p>
6399      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6400      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6401      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6402      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6403      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6404      * iteration variable type.
6405      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6406      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6407      * </ol>
6408      * <p>
6409      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6410      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6411      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6412      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6413      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6414      * (These types will be checked in step 2, along with all the clause function types.)
6415      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6416      * <li>All of the collected parameter lists must be effectively identical.
6417      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6418      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6419      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6420      * the "internal parameter list".
6421      * </ul>
6422      * <p>
6423      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6424      * <li>Examine fini function return types, disregarding omitted fini functions.
6425      * <li>If there are no fini functions, the loop return type is {@code void}.
6426      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6427      * type.
6428      * </ol>
6429      * <p>
6430      * <em>Step 1D: Check other types.</em><ol type="a">
6431      * <li>There must be at least one non-omitted pred function.
6432      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6433      * </ol>
6434      * <p>
6435      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6436      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6437      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6438      * (Note that their parameter lists are already effectively identical to this list.)
6439      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6440      * effectively identical to the internal parameter list {@code (V... A...)}.
6441      * </ol>
6442      * <p>
6443      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6444      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6445      * type.
6446      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6447      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6448      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6449      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6450      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6451      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6452      * loop return type.
6453      * </ol>
6454      * <p>
6455      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6456      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6457      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6458      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6459      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6460      * pad out the end of the list.
6461      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6462      * </ol>
6463      * <p>
6464      * <em>Final observations.</em><ol type="a">
6465      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6466      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6467      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6468      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6469      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6470      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6471      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6472      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6473      * </ol>
6474      * <p>
6475      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6476      * <ul>
6477      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6478      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6479      * (Only one {@code Pn} has to be non-{@code null}.)
6480      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6481      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6482      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6483      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6484      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6485      * the resulting loop handle's parameter types {@code (A...)}.
6486      * </ul>
6487      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6488      * which is natural if most of the loop computation happens in the steps.  For some loops,
6489      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6490      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6491      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6492      * where the init functions will need the extra parameters.  For such reasons, the rules for
6493      * determining these parameters are as symmetric as possible, across all clause parts.
6494      * In general, the loop parameters function as common invariant values across the whole
6495      * loop, while the iteration variables function as common variant values, or (if there is
6496      * no step function) as internal loop invariant temporaries.
6497      * <p>
6498      * <em>Loop execution.</em><ol type="a">
6499      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6500      * every clause function. These locals are loop invariant.
6501      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6502      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6503      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6504      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6505      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6506      * (in argument order).
6507      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6508      * returns {@code false}.
6509      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6510      * sequence {@code (v...)} of loop variables.
6511      * The updated value is immediately visible to all subsequent function calls.
6512      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6513      * (of type {@code R}) is returned from the loop as a whole.
6514      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6515      * except by throwing an exception.
6516      * </ol>
6517      * <p>
6518      * <em>Usage tips.</em>
6519      * <ul>
6520      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6521      * sometimes a step function only needs to observe the current value of its own variable.
6522      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6523      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6524      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6525      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6526      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6527      * <li>If some of the clause functions are virtual methods on an instance, the instance
6528      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6529      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6530      * will be the first iteration variable value, and it will be easy to use virtual
6531      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6532      * </ul>
6533      * <p>
6534      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6535      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6536      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6537      * <blockquote><pre>{@code
6538      * V... init...(A...);
6539      * boolean pred...(V..., A...);
6540      * V... step...(V..., A...);
6541      * R fini...(V..., A...);
6542      * R loop(A... a) {
6543      *   V... v... = init...(a...);
6544      *   for (;;) {
6545      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6546      *       v = s(v..., a...);
6547      *       if (!p(v..., a...)) {
6548      *         return f(v..., a...);
6549      *       }
6550      *     }
6551      *   }
6552      * }
6553      * }</pre></blockquote>
6554      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6555      * to their full length, even though individual clause functions may neglect to take them all.
6556      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6557      *
6558      * @apiNote Example:
6559      * <blockquote><pre>{@code
6560      * // iterative implementation of the factorial function as a loop handle
6561      * static int one(int k) { return 1; }
6562      * static int inc(int i, int acc, int k) { return i + 1; }
6563      * static int mult(int i, int acc, int k) { return i * acc; }
6564      * static boolean pred(int i, int acc, int k) { return i < k; }
6565      * static int fin(int i, int acc, int k) { return acc; }
6566      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6567      * // null initializer for counter, should initialize to 0
6568      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6569      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6570      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6571      * assertEquals(120, loop.invoke(5));
6572      * }</pre></blockquote>
6573      * The same example, dropping arguments and using combinators:
6574      * <blockquote><pre>{@code
6575      * // simplified implementation of the factorial function as a loop handle
6576      * static int inc(int i) { return i + 1; } // drop acc, k
6577      * static int mult(int i, int acc) { return i * acc; } //drop k
6578      * static boolean cmp(int i, int k) { return i < k; }
6579      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6580      * // null initializer for counter, should initialize to 0
6581      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6582      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6583      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6584      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6585      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6586      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6587      * assertEquals(720, loop.invoke(6));
6588      * }</pre></blockquote>
6589      * A similar example, using a helper object to hold a loop parameter:
6590      * <blockquote><pre>{@code
6591      * // instance-based implementation of the factorial function as a loop handle
6592      * static class FacLoop {
6593      *   final int k;
6594      *   FacLoop(int k) { this.k = k; }
6595      *   int inc(int i) { return i + 1; }
6596      *   int mult(int i, int acc) { return i * acc; }
6597      *   boolean pred(int i) { return i < k; }
6598      *   int fin(int i, int acc) { return acc; }
6599      * }
6600      * // assume MH_FacLoop is a handle to the constructor
6601      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6602      * // null initializer for counter, should initialize to 0
6603      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6604      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6605      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6606      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6607      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6608      * assertEquals(5040, loop.invoke(7));
6609      * }</pre></blockquote>
6610      *
6611      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6612      *
6613      * @return a method handle embodying the looping behavior as defined by the arguments.
6614      *
6615      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6616      *
6617      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6618      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6619      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6620      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6621      * @since 9
6622      */
6623     public static MethodHandle loop(MethodHandle[]... clauses) {
6624         // Step 0: determine clause structure.
6625         loopChecks0(clauses);
6626 
6627         List<MethodHandle> init = new ArrayList<>();
6628         List<MethodHandle> step = new ArrayList<>();
6629         List<MethodHandle> pred = new ArrayList<>();
6630         List<MethodHandle> fini = new ArrayList<>();
6631 
6632         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6633             init.add(clause[0]); // all clauses have at least length 1
6634             step.add(clause.length <= 1 ? null : clause[1]);
6635             pred.add(clause.length <= 2 ? null : clause[2]);
6636             fini.add(clause.length <= 3 ? null : clause[3]);
6637         });
6638 
6639         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6640         final int nclauses = init.size();
6641 
6642         // Step 1A: determine iteration variables (V...).
6643         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6644         for (int i = 0; i < nclauses; ++i) {
6645             MethodHandle in = init.get(i);
6646             MethodHandle st = step.get(i);
6647             if (in == null && st == null) {
6648                 iterationVariableTypes.add(void.class);
6649             } else if (in != null && st != null) {
6650                 loopChecks1a(i, in, st);
6651                 iterationVariableTypes.add(in.type().returnType());
6652             } else {
6653                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6654             }
6655         }
6656         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6657 
6658         // Step 1B: determine loop parameters (A...).
6659         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6660         loopChecks1b(init, commonSuffix);
6661 
6662         // Step 1C: determine loop return type.
6663         // Step 1D: check other types.
6664         // local variable required here; see JDK-8223553
6665         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6666                 .map(MethodType::returnType);
6667         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6668         loopChecks1cd(pred, fini, loopReturnType);
6669 
6670         // Step 2: determine parameter lists.
6671         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6672         commonParameterSequence.addAll(commonSuffix);
6673         loopChecks2(step, pred, fini, commonParameterSequence);
6674 
6675         // Step 3: fill in omitted functions.
6676         for (int i = 0; i < nclauses; ++i) {
6677             Class<?> t = iterationVariableTypes.get(i);
6678             if (init.get(i) == null) {
6679                 init.set(i, empty(methodType(t, commonSuffix)));
6680             }
6681             if (step.get(i) == null) {
6682                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6683             }
6684             if (pred.get(i) == null) {
6685                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6686             }
6687             if (fini.get(i) == null) {
6688                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6689             }
6690         }
6691 
6692         // Step 4: fill in missing parameter types.
6693         // Also convert all handles to fixed-arity handles.
6694         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6695         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6696         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6697         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6698 
6699         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6700                 allMatch(pl -> pl.equals(commonSuffix));
6701         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6702                 allMatch(pl -> pl.equals(commonParameterSequence));
6703 
6704         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6705     }
6706 
6707     private static void loopChecks0(MethodHandle[][] clauses) {
6708         if (clauses == null || clauses.length == 0) {
6709             throw newIllegalArgumentException("null or no clauses passed");
6710         }
6711         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6712             throw newIllegalArgumentException("null clauses are not allowed");
6713         }
6714         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6715             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6716         }
6717     }
6718 
6719     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6720         if (in.type().returnType() != st.type().returnType()) {
6721             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6722                     st.type().returnType());
6723         }
6724     }
6725 
6726     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6727         final List<Class<?>> empty = List.of();
6728         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6729                 // take only those that can contribute to a common suffix because they are longer than the prefix
6730                         map(MethodHandle::type).
6731                         filter(t -> t.parameterCount() > skipSize).
6732                         map(MethodType::parameterList).
6733                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6734         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6735     }
6736 
6737     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6738         final List<Class<?>> empty = List.of();
6739         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6740     }
6741 
6742     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6743         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6744         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6745         return longestParameterList(Arrays.asList(longest1, longest2));
6746     }
6747 
6748     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6749         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6750                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6751             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6752                     " (common suffix: " + commonSuffix + ")");
6753         }
6754     }
6755 
6756     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6757         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6758                 anyMatch(t -> t != loopReturnType)) {
6759             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6760                     loopReturnType + ")");
6761         }
6762 
6763         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6764             throw newIllegalArgumentException("no predicate found", pred);
6765         }
6766         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6767                 anyMatch(t -> t != boolean.class)) {
6768             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6769         }
6770     }
6771 
6772     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6773         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6774                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6775             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6776                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6777         }
6778     }
6779 
6780     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6781         return hs.stream().map(h -> {
6782             int pc = h.type().parameterCount();
6783             int tpsize = targetParams.size();
6784             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6785         }).toList();
6786     }
6787 
6788     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6789         return hs.stream().map(MethodHandle::asFixedArity).toList();
6790     }
6791 
6792     /**
6793      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6794      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6795      * <p>
6796      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6797      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6798      * evaluates to {@code true}).
6799      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6800      * <p>
6801      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6802      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6803      * and updated with the value returned from its invocation. The result of loop execution will be
6804      * the final value of the additional loop-local variable (if present).
6805      * <p>
6806      * The following rules hold for these argument handles:<ul>
6807      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6808      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6809      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6810      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6811      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6812      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6813      * It will constrain the parameter lists of the other loop parts.
6814      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6815      * list {@code (A...)} is called the <em>external parameter list</em>.
6816      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6817      * additional state variable of the loop.
6818      * The body must both accept and return a value of this type {@code V}.
6819      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6820      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6821      * <a href="MethodHandles.html#effid">effectively identical</a>
6822      * to the external parameter list {@code (A...)}.
6823      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6824      * {@linkplain #empty default value}.
6825      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6826      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6827      * effectively identical to the internal parameter list.
6828      * </ul>
6829      * <p>
6830      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6831      * <li>The loop handle's result type is the result type {@code V} of the body.
6832      * <li>The loop handle's parameter types are the types {@code (A...)},
6833      * from the external parameter list.
6834      * </ul>
6835      * <p>
6836      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6837      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6838      * passed to the loop.
6839      * <blockquote><pre>{@code
6840      * V init(A...);
6841      * boolean pred(V, A...);
6842      * V body(V, A...);
6843      * V whileLoop(A... a...) {
6844      *   V v = init(a...);
6845      *   while (pred(v, a...)) {
6846      *     v = body(v, a...);
6847      *   }
6848      *   return v;
6849      * }
6850      * }</pre></blockquote>
6851      *
6852      * @apiNote Example:
6853      * <blockquote><pre>{@code
6854      * // implement the zip function for lists as a loop handle
6855      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6856      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6857      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6858      *   zip.add(a.next());
6859      *   zip.add(b.next());
6860      *   return zip;
6861      * }
6862      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6863      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6864      * List<String> a = Arrays.asList("a", "b", "c", "d");
6865      * List<String> b = Arrays.asList("e", "f", "g", "h");
6866      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6867      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6868      * }</pre></blockquote>
6869      *
6870      *
6871      * @apiNote The implementation of this method can be expressed as follows:
6872      * <blockquote><pre>{@code
6873      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6874      *     MethodHandle fini = (body.type().returnType() == void.class
6875      *                         ? null : identity(body.type().returnType()));
6876      *     MethodHandle[]
6877      *         checkExit = { null, null, pred, fini },
6878      *         varBody   = { init, body };
6879      *     return loop(checkExit, varBody);
6880      * }
6881      * }</pre></blockquote>
6882      *
6883      * @param init optional initializer, providing the initial value of the loop variable.
6884      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6885      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6886      *             above for other constraints.
6887      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6888      *             See above for other constraints.
6889      *
6890      * @return a method handle implementing the {@code while} loop as described by the arguments.
6891      * @throws IllegalArgumentException if the rules for the arguments are violated.
6892      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6893      *
6894      * @see #loop(MethodHandle[][])
6895      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6896      * @since 9
6897      */
6898     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6899         whileLoopChecks(init, pred, body);
6900         MethodHandle fini = identityOrVoid(body.type().returnType());
6901         MethodHandle[] checkExit = { null, null, pred, fini };
6902         MethodHandle[] varBody = { init, body };
6903         return loop(checkExit, varBody);
6904     }
6905 
6906     /**
6907      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6908      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6909      * <p>
6910      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6911      * method will, in each iteration, first execute its body and then evaluate the predicate.
6912      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6913      * <p>
6914      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6915      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6916      * and updated with the value returned from its invocation. The result of loop execution will be
6917      * the final value of the additional loop-local variable (if present).
6918      * <p>
6919      * The following rules hold for these argument handles:<ul>
6920      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6921      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6922      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6923      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6924      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6925      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6926      * It will constrain the parameter lists of the other loop parts.
6927      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6928      * list {@code (A...)} is called the <em>external parameter list</em>.
6929      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6930      * additional state variable of the loop.
6931      * The body must both accept and return a value of this type {@code V}.
6932      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6933      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6934      * <a href="MethodHandles.html#effid">effectively identical</a>
6935      * to the external parameter list {@code (A...)}.
6936      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6937      * {@linkplain #empty default value}.
6938      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6939      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6940      * effectively identical to the internal parameter list.
6941      * </ul>
6942      * <p>
6943      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6944      * <li>The loop handle's result type is the result type {@code V} of the body.
6945      * <li>The loop handle's parameter types are the types {@code (A...)},
6946      * from the external parameter list.
6947      * </ul>
6948      * <p>
6949      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6950      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6951      * passed to the loop.
6952      * <blockquote><pre>{@code
6953      * V init(A...);
6954      * boolean pred(V, A...);
6955      * V body(V, A...);
6956      * V doWhileLoop(A... a...) {
6957      *   V v = init(a...);
6958      *   do {
6959      *     v = body(v, a...);
6960      *   } while (pred(v, a...));
6961      *   return v;
6962      * }
6963      * }</pre></blockquote>
6964      *
6965      * @apiNote Example:
6966      * <blockquote><pre>{@code
6967      * // int i = 0; while (i < limit) { ++i; } return i; => limit
6968      * static int zero(int limit) { return 0; }
6969      * static int step(int i, int limit) { return i + 1; }
6970      * static boolean pred(int i, int limit) { return i < limit; }
6971      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6972      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6973      * assertEquals(23, loop.invoke(23));
6974      * }</pre></blockquote>
6975      *
6976      *
6977      * @apiNote The implementation of this method can be expressed as follows:
6978      * <blockquote><pre>{@code
6979      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6980      *     MethodHandle fini = (body.type().returnType() == void.class
6981      *                         ? null : identity(body.type().returnType()));
6982      *     MethodHandle[] clause = { init, body, pred, fini };
6983      *     return loop(clause);
6984      * }
6985      * }</pre></blockquote>
6986      *
6987      * @param init optional initializer, providing the initial value of the loop variable.
6988      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6989      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6990      *             See above for other constraints.
6991      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6992      *             above for other constraints.
6993      *
6994      * @return a method handle implementing the {@code while} loop as described by the arguments.
6995      * @throws IllegalArgumentException if the rules for the arguments are violated.
6996      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6997      *
6998      * @see #loop(MethodHandle[][])
6999      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7000      * @since 9
7001      */
7002     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7003         whileLoopChecks(init, pred, body);
7004         MethodHandle fini = identityOrVoid(body.type().returnType());
7005         MethodHandle[] clause = {init, body, pred, fini };
7006         return loop(clause);
7007     }
7008 
7009     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7010         Objects.requireNonNull(pred);
7011         Objects.requireNonNull(body);
7012         MethodType bodyType = body.type();
7013         Class<?> returnType = bodyType.returnType();
7014         List<Class<?>> innerList = bodyType.parameterList();
7015         List<Class<?>> outerList = innerList;
7016         if (returnType == void.class) {
7017             // OK
7018         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7019             // leading V argument missing => error
7020             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7021             throw misMatchedTypes("body function", bodyType, expected);
7022         } else {
7023             outerList = innerList.subList(1, innerList.size());
7024         }
7025         MethodType predType = pred.type();
7026         if (predType.returnType() != boolean.class ||
7027                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7028             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7029         }
7030         if (init != null) {
7031             MethodType initType = init.type();
7032             if (initType.returnType() != returnType ||
7033                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7034                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7035             }
7036         }
7037     }
7038 
7039     /**
7040      * Constructs a loop that runs a given number of iterations.
7041      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7042      * <p>
7043      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7044      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7045      * It will be initialized to 0 and incremented by 1 in each iteration.
7046      * <p>
7047      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7048      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7049      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7050      * <p>
7051      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7052      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7053      * iteration variable.
7054      * The result of the loop handle execution will be the final {@code V} value of that variable
7055      * (or {@code void} if there is no {@code V} variable).
7056      * <p>
7057      * The following rules hold for the argument handles:<ul>
7058      * <li>The {@code iterations} handle must not be {@code null}, and must return
7059      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7060      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7061      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7062      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7063      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7064      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7065      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7066      * of types called the <em>internal parameter list</em>.
7067      * It will constrain the parameter lists of the other loop parts.
7068      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7069      * with no additional {@code A} types, then the internal parameter list is extended by
7070      * the argument types {@code A...} of the {@code iterations} handle.
7071      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7072      * list {@code (A...)} is called the <em>external parameter list</em>.
7073      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7074      * additional state variable of the loop.
7075      * The body must both accept a leading parameter and return a value of this type {@code V}.
7076      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7077      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7078      * <a href="MethodHandles.html#effid">effectively identical</a>
7079      * to the external parameter list {@code (A...)}.
7080      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7081      * {@linkplain #empty default value}.
7082      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7083      * effectively identical to the external parameter list {@code (A...)}.
7084      * </ul>
7085      * <p>
7086      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7087      * <li>The loop handle's result type is the result type {@code V} of the body.
7088      * <li>The loop handle's parameter types are the types {@code (A...)},
7089      * from the external parameter list.
7090      * </ul>
7091      * <p>
7092      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7093      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7094      * arguments passed to the loop.
7095      * <blockquote><pre>{@code
7096      * int iterations(A...);
7097      * V init(A...);
7098      * V body(V, int, A...);
7099      * V countedLoop(A... a...) {
7100      *   int end = iterations(a...);
7101      *   V v = init(a...);
7102      *   for (int i = 0; i < end; ++i) {
7103      *     v = body(v, i, a...);
7104      *   }
7105      *   return v;
7106      * }
7107      * }</pre></blockquote>
7108      *
7109      * @apiNote Example with a fully conformant body method:
7110      * <blockquote><pre>{@code
7111      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7112      * // => a variation on a well known theme
7113      * static String step(String v, int counter, String init) { return "na " + v; }
7114      * // assume MH_step is a handle to the method above
7115      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7116      * MethodHandle start = MethodHandles.identity(String.class);
7117      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7118      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7119      * }</pre></blockquote>
7120      *
7121      * @apiNote Example with the simplest possible body method type,
7122      * and passing the number of iterations to the loop invocation:
7123      * <blockquote><pre>{@code
7124      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7125      * // => a variation on a well known theme
7126      * static String step(String v, int counter ) { return "na " + v; }
7127      * // assume MH_step is a handle to the method above
7128      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7129      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7130      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7131      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7132      * }</pre></blockquote>
7133      *
7134      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7135      * as loop parameters:
7136      * <blockquote><pre>{@code
7137      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7138      * // => a variation on a well known theme
7139      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7140      * // assume MH_step is a handle to the method above
7141      * MethodHandle count = MethodHandles.identity(int.class);
7142      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7143      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7144      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7145      * }</pre></blockquote>
7146      *
7147      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7148      * to enforce a loop type:
7149      * <blockquote><pre>{@code
7150      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7151      * // => a variation on a well known theme
7152      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7153      * // assume MH_step is a handle to the method above
7154      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7155      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7156      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7157      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7158      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7159      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7160      * }</pre></blockquote>
7161      *
7162      * @apiNote The implementation of this method can be expressed as follows:
7163      * <blockquote><pre>{@code
7164      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7165      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7166      * }
7167      * }</pre></blockquote>
7168      *
7169      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7170      *                   result type must be {@code int}. See above for other constraints.
7171      * @param init optional initializer, providing the initial value of the loop variable.
7172      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7173      * @param body body of the loop, which may not be {@code null}.
7174      *             It controls the loop parameters and result type in the standard case (see above for details).
7175      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7176      *             and may accept any number of additional types.
7177      *             See above for other constraints.
7178      *
7179      * @return a method handle representing the loop.
7180      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7181      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7182      *
7183      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7184      * @since 9
7185      */
7186     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7187         return countedLoop(empty(iterations.type()), iterations, init, body);
7188     }
7189 
7190     /**
7191      * Constructs a loop that counts over a range of numbers.
7192      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7193      * <p>
7194      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7195      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7196      * values of the loop counter.
7197      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7198      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7199      * <p>
7200      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7201      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7202      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7203      * <p>
7204      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7205      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7206      * iteration variable.
7207      * The result of the loop handle execution will be the final {@code V} value of that variable
7208      * (or {@code void} if there is no {@code V} variable).
7209      * <p>
7210      * The following rules hold for the argument handles:<ul>
7211      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7212      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7213      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7214      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7215      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7216      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7217      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7218      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7219      * of types called the <em>internal parameter list</em>.
7220      * It will constrain the parameter lists of the other loop parts.
7221      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7222      * with no additional {@code A} types, then the internal parameter list is extended by
7223      * the argument types {@code A...} of the {@code end} handle.
7224      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7225      * list {@code (A...)} is called the <em>external parameter list</em>.
7226      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7227      * additional state variable of the loop.
7228      * The body must both accept a leading parameter and return a value of this type {@code V}.
7229      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7230      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7231      * <a href="MethodHandles.html#effid">effectively identical</a>
7232      * to the external parameter list {@code (A...)}.
7233      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7234      * {@linkplain #empty default value}.
7235      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7236      * effectively identical to the external parameter list {@code (A...)}.
7237      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7238      * to the external parameter list.
7239      * </ul>
7240      * <p>
7241      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7242      * <li>The loop handle's result type is the result type {@code V} of the body.
7243      * <li>The loop handle's parameter types are the types {@code (A...)},
7244      * from the external parameter list.
7245      * </ul>
7246      * <p>
7247      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7248      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7249      * arguments passed to the loop.
7250      * <blockquote><pre>{@code
7251      * int start(A...);
7252      * int end(A...);
7253      * V init(A...);
7254      * V body(V, int, A...);
7255      * V countedLoop(A... a...) {
7256      *   int e = end(a...);
7257      *   int s = start(a...);
7258      *   V v = init(a...);
7259      *   for (int i = s; i < e; ++i) {
7260      *     v = body(v, i, a...);
7261      *   }
7262      *   return v;
7263      * }
7264      * }</pre></blockquote>
7265      *
7266      * @apiNote The implementation of this method can be expressed as follows:
7267      * <blockquote><pre>{@code
7268      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7269      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7270      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7271      *     // the following semantics:
7272      *     // MH_increment: (int limit, int counter) -> counter + 1
7273      *     // MH_predicate: (int limit, int counter) -> counter < limit
7274      *     Class<?> counterType = start.type().returnType();  // int
7275      *     Class<?> returnType = body.type().returnType();
7276      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7277      *     if (returnType != void.class) {  // ignore the V variable
7278      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7279      *         pred = dropArguments(pred, 1, returnType);  // ditto
7280      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7281      *     }
7282      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7283      *     MethodHandle[]
7284      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7285      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7286      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7287      *     return loop(loopLimit, bodyClause, indexVar);
7288      * }
7289      * }</pre></blockquote>
7290      *
7291      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7292      *              See above for other constraints.
7293      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7294      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7295      * @param init optional initializer, providing the initial value of the loop variable.
7296      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7297      * @param body body of the loop, which may not be {@code null}.
7298      *             It controls the loop parameters and result type in the standard case (see above for details).
7299      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7300      *             and may accept any number of additional types.
7301      *             See above for other constraints.
7302      *
7303      * @return a method handle representing the loop.
7304      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7305      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7306      *
7307      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7308      * @since 9
7309      */
7310     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7311         countedLoopChecks(start, end, init, body);
7312         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7313         Class<?> limitType   = end.type().returnType();    // yes, int again
7314         Class<?> returnType  = body.type().returnType();
7315         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7316         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7317         MethodHandle retv = null;
7318         if (returnType != void.class) {
7319             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7320             pred = dropArguments(pred, 1, returnType);  // ditto
7321             retv = dropArguments(identity(returnType), 0, counterType);
7322         }
7323         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7324         MethodHandle[]
7325             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7326             bodyClause = { init, body },            // v = init(); v = body(v, i)
7327             indexVar   = { start, incr };           // i = start(); i = i + 1
7328         return loop(loopLimit, bodyClause, indexVar);
7329     }
7330 
7331     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7332         Objects.requireNonNull(start);
7333         Objects.requireNonNull(end);
7334         Objects.requireNonNull(body);
7335         Class<?> counterType = start.type().returnType();
7336         if (counterType != int.class) {
7337             MethodType expected = start.type().changeReturnType(int.class);
7338             throw misMatchedTypes("start function", start.type(), expected);
7339         } else if (end.type().returnType() != counterType) {
7340             MethodType expected = end.type().changeReturnType(counterType);
7341             throw misMatchedTypes("end function", end.type(), expected);
7342         }
7343         MethodType bodyType = body.type();
7344         Class<?> returnType = bodyType.returnType();
7345         List<Class<?>> innerList = bodyType.parameterList();
7346         // strip leading V value if present
7347         int vsize = (returnType == void.class ? 0 : 1);
7348         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7349             // argument list has no "V" => error
7350             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7351             throw misMatchedTypes("body function", bodyType, expected);
7352         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7353             // missing I type => error
7354             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7355             throw misMatchedTypes("body function", bodyType, expected);
7356         }
7357         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7358         if (outerList.isEmpty()) {
7359             // special case; take lists from end handle
7360             outerList = end.type().parameterList();
7361             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7362         }
7363         MethodType expected = methodType(counterType, outerList);
7364         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7365             throw misMatchedTypes("start parameter types", start.type(), expected);
7366         }
7367         if (end.type() != start.type() &&
7368             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7369             throw misMatchedTypes("end parameter types", end.type(), expected);
7370         }
7371         if (init != null) {
7372             MethodType initType = init.type();
7373             if (initType.returnType() != returnType ||
7374                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7375                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7376             }
7377         }
7378     }
7379 
7380     /**
7381      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7382      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7383      * <p>
7384      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7385      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7386      * <p>
7387      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7388      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7389      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7390      * <p>
7391      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7392      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7393      * iteration variable.
7394      * The result of the loop handle execution will be the final {@code V} value of that variable
7395      * (or {@code void} if there is no {@code V} variable).
7396      * <p>
7397      * The following rules hold for the argument handles:<ul>
7398      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7399      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7400      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7401      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7402      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7403      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7404      * of types called the <em>internal parameter list</em>.
7405      * It will constrain the parameter lists of the other loop parts.
7406      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7407      * with no additional {@code A} types, then the internal parameter list is extended by
7408      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7409      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7410      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7411      * list {@code (A...)} is called the <em>external parameter list</em>.
7412      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7413      * additional state variable of the loop.
7414      * The body must both accept a leading parameter and return a value of this type {@code V}.
7415      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7416      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7417      * <a href="MethodHandles.html#effid">effectively identical</a>
7418      * to the external parameter list {@code (A...)}.
7419      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7420      * {@linkplain #empty default value}.
7421      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7422      * type {@code java.util.Iterator} or a subtype thereof.
7423      * The iterator it produces when the loop is executed will be assumed
7424      * to yield values which can be converted to type {@code T}.
7425      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7426      * effectively identical to the external parameter list {@code (A...)}.
7427      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7428      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7429      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7430      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7431      * the {@link MethodHandle#asType asType} conversion method.
7432      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7433      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7434      * </ul>
7435      * <p>
7436      * The type {@code T} may be either a primitive or reference.
7437      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7438      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7439      * as if by the {@link MethodHandle#asType asType} conversion method.
7440      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7441      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7442      * <p>
7443      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7444      * <li>The loop handle's result type is the result type {@code V} of the body.
7445      * <li>The loop handle's parameter types are the types {@code (A...)},
7446      * from the external parameter list.
7447      * </ul>
7448      * <p>
7449      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7450      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7451      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7452      * <blockquote><pre>{@code
7453      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7454      * V init(A...);
7455      * V body(V,T,A...);
7456      * V iteratedLoop(A... a...) {
7457      *   Iterator<T> it = iterator(a...);
7458      *   V v = init(a...);
7459      *   while (it.hasNext()) {
7460      *     T t = it.next();
7461      *     v = body(v, t, a...);
7462      *   }
7463      *   return v;
7464      * }
7465      * }</pre></blockquote>
7466      *
7467      * @apiNote Example:
7468      * <blockquote><pre>{@code
7469      * // get an iterator from a list
7470      * static List<String> reverseStep(List<String> r, String e) {
7471      *   r.add(0, e);
7472      *   return r;
7473      * }
7474      * static List<String> newArrayList() { return new ArrayList<>(); }
7475      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7476      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7477      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7478      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7479      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7480      * }</pre></blockquote>
7481      *
7482      * @apiNote The implementation of this method can be expressed approximately as follows:
7483      * <blockquote><pre>{@code
7484      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7485      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7486      *     Class<?> returnType = body.type().returnType();
7487      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7488      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7489      *     MethodHandle retv = null, step = body, startIter = iterator;
7490      *     if (returnType != void.class) {
7491      *         // the simple thing first:  in (I V A...), drop the I to get V
7492      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7493      *         // body type signature (V T A...), internal loop types (I V A...)
7494      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7495      *     }
7496      *     if (startIter == null)  startIter = MH_getIter;
7497      *     MethodHandle[]
7498      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7499      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7500      *     return loop(iterVar, bodyClause);
7501      * }
7502      * }</pre></blockquote>
7503      *
7504      * @param iterator an optional handle to return the iterator to start the loop.
7505      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7506      *                 See above for other constraints.
7507      * @param init optional initializer, providing the initial value of the loop variable.
7508      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7509      * @param body body of the loop, which may not be {@code null}.
7510      *             It controls the loop parameters and result type in the standard case (see above for details).
7511      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7512      *             and may accept any number of additional types.
7513      *             See above for other constraints.
7514      *
7515      * @return a method handle embodying the iteration loop functionality.
7516      * @throws NullPointerException if the {@code body} handle is {@code null}.
7517      * @throws IllegalArgumentException if any argument violates the above requirements.
7518      *
7519      * @since 9
7520      */
7521     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7522         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7523         Class<?> returnType = body.type().returnType();
7524         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7525         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7526         MethodHandle startIter;
7527         MethodHandle nextVal;
7528         {
7529             MethodType iteratorType;
7530             if (iterator == null) {
7531                 // derive argument type from body, if available, else use Iterable
7532                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7533                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7534             } else {
7535                 // force return type to the internal iterator class
7536                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7537                 startIter = iterator;
7538             }
7539             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7540             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7541 
7542             // perform the asType transforms under an exception transformer, as per spec.:
7543             try {
7544                 startIter = startIter.asType(iteratorType);
7545                 nextVal = nextRaw.asType(nextValType);
7546             } catch (WrongMethodTypeException ex) {
7547                 throw new IllegalArgumentException(ex);
7548             }
7549         }
7550 
7551         MethodHandle retv = null, step = body;
7552         if (returnType != void.class) {
7553             // the simple thing first:  in (I V A...), drop the I to get V
7554             retv = dropArguments(identity(returnType), 0, Iterator.class);
7555             // body type signature (V T A...), internal loop types (I V A...)
7556             step = swapArguments(body, 0, 1);  // swap V <-> T
7557         }
7558 
7559         MethodHandle[]
7560             iterVar    = { startIter, null, hasNext, retv },
7561             bodyClause = { init, filterArgument(step, 0, nextVal) };
7562         return loop(iterVar, bodyClause);
7563     }
7564 
7565     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7566         Objects.requireNonNull(body);
7567         MethodType bodyType = body.type();
7568         Class<?> returnType = bodyType.returnType();
7569         List<Class<?>> internalParamList = bodyType.parameterList();
7570         // strip leading V value if present
7571         int vsize = (returnType == void.class ? 0 : 1);
7572         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7573             // argument list has no "V" => error
7574             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7575             throw misMatchedTypes("body function", bodyType, expected);
7576         } else if (internalParamList.size() <= vsize) {
7577             // missing T type => error
7578             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7579             throw misMatchedTypes("body function", bodyType, expected);
7580         }
7581         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7582         Class<?> iterableType = null;
7583         if (iterator != null) {
7584             // special case; if the body handle only declares V and T then
7585             // the external parameter list is obtained from iterator handle
7586             if (externalParamList.isEmpty()) {
7587                 externalParamList = iterator.type().parameterList();
7588             }
7589             MethodType itype = iterator.type();
7590             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7591                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7592             }
7593             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7594                 MethodType expected = methodType(itype.returnType(), externalParamList);
7595                 throw misMatchedTypes("iterator parameters", itype, expected);
7596             }
7597         } else {
7598             if (externalParamList.isEmpty()) {
7599                 // special case; if the iterator handle is null and the body handle
7600                 // only declares V and T then the external parameter list consists
7601                 // of Iterable
7602                 externalParamList = Arrays.asList(Iterable.class);
7603                 iterableType = Iterable.class;
7604             } else {
7605                 // special case; if the iterator handle is null and the external
7606                 // parameter list is not empty then the first parameter must be
7607                 // assignable to Iterable
7608                 iterableType = externalParamList.get(0);
7609                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7610                     throw newIllegalArgumentException(
7611                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7612                 }
7613             }
7614         }
7615         if (init != null) {
7616             MethodType initType = init.type();
7617             if (initType.returnType() != returnType ||
7618                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7619                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7620             }
7621         }
7622         return iterableType;  // help the caller a bit
7623     }
7624 
7625     /*non-public*/
7626     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7627         // there should be a better way to uncross my wires
7628         int arity = mh.type().parameterCount();
7629         int[] order = new int[arity];
7630         for (int k = 0; k < arity; k++)  order[k] = k;
7631         order[i] = j; order[j] = i;
7632         Class<?>[] types = mh.type().parameterArray();
7633         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7634         MethodType swapType = methodType(mh.type().returnType(), types);
7635         return permuteArguments(mh, swapType, order);
7636     }
7637 
7638     /**
7639      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7640      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7641      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7642      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7643      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7644      * {@code try-finally} handle.
7645      * <p>
7646      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7647      * The first is the exception thrown during the
7648      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7649      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7650      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7651      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7652      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7653      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7654      * <p>
7655      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7656      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7657      * two extra leading parameters:<ul>
7658      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7659      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7660      * the result from the execution of the {@code target} handle.
7661      * This parameter is not present if the {@code target} returns {@code void}.
7662      * </ul>
7663      * <p>
7664      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7665      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7666      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7667      * the cleanup.
7668      * <blockquote><pre>{@code
7669      * V target(A..., B...);
7670      * V cleanup(Throwable, V, A...);
7671      * V adapter(A... a, B... b) {
7672      *   V result = (zero value for V);
7673      *   Throwable throwable = null;
7674      *   try {
7675      *     result = target(a..., b...);
7676      *   } catch (Throwable t) {
7677      *     throwable = t;
7678      *     throw t;
7679      *   } finally {
7680      *     result = cleanup(throwable, result, a...);
7681      *   }
7682      *   return result;
7683      * }
7684      * }</pre></blockquote>
7685      * <p>
7686      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7687      * be modified by execution of the target, and so are passed unchanged
7688      * from the caller to the cleanup, if it is invoked.
7689      * <p>
7690      * The target and cleanup must return the same type, even if the cleanup
7691      * always throws.
7692      * To create such a throwing cleanup, compose the cleanup logic
7693      * with {@link #throwException throwException},
7694      * in order to create a method handle of the correct return type.
7695      * <p>
7696      * Note that {@code tryFinally} never converts exceptions into normal returns.
7697      * In rare cases where exceptions must be converted in that way, first wrap
7698      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7699      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7700      * <p>
7701      * It is recommended that the first parameter type of {@code cleanup} be
7702      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7703      * {@code cleanup} will always be invoked with whatever exception that
7704      * {@code target} throws.  Declaring a narrower type may result in a
7705      * {@code ClassCastException} being thrown by the {@code try-finally}
7706      * handle if the type of the exception thrown by {@code target} is not
7707      * assignable to the first parameter type of {@code cleanup}.  Note that
7708      * various exception types of {@code VirtualMachineError},
7709      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7710      * thrown by almost any kind of Java code, and a finally clause that
7711      * catches (say) only {@code IOException} would mask any of the others
7712      * behind a {@code ClassCastException}.
7713      *
7714      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7715      * @param cleanup the handle that is invoked in the finally block.
7716      *
7717      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7718      * @throws NullPointerException if any argument is null
7719      * @throws IllegalArgumentException if {@code cleanup} does not accept
7720      *          the required leading arguments, or if the method handle types do
7721      *          not match in their return types and their
7722      *          corresponding trailing parameters
7723      *
7724      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7725      * @since 9
7726      */
7727     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7728         List<Class<?>> targetParamTypes = target.type().parameterList();
7729         Class<?> rtype = target.type().returnType();
7730 
7731         tryFinallyChecks(target, cleanup);
7732 
7733         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7734         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7735         // target parameter list.
7736         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7737 
7738         // Ensure that the intrinsic type checks the instance thrown by the
7739         // target against the first parameter of cleanup
7740         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7741 
7742         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7743         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7744     }
7745 
7746     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7747         Class<?> rtype = target.type().returnType();
7748         if (rtype != cleanup.type().returnType()) {
7749             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7750         }
7751         MethodType cleanupType = cleanup.type();
7752         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7753             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7754         }
7755         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7756             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7757         }
7758         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7759         // target parameter list.
7760         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7761         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7762             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7763                     cleanup.type(), target.type());
7764         }
7765     }
7766 
7767     /**
7768      * Creates a table switch method handle, which can be used to switch over a set of target
7769      * method handles, based on a given target index, called selector.
7770      * <p>
7771      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7772      * and where {@code N} is the number of target method handles, the table switch method
7773      * handle will invoke the n-th target method handle from the list of target method handles.
7774      * <p>
7775      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7776      * method handle will invoke the given fallback method handle.
7777      * <p>
7778      * All method handles passed to this method must have the same type, with the additional
7779      * requirement that the leading parameter be of type {@code int}. The leading parameter
7780      * represents the selector.
7781      * <p>
7782      * Any trailing parameters present in the type will appear on the returned table switch
7783      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7784      * together with the selector value, to the selected method handle when invoking it.
7785      *
7786      * @apiNote Example:
7787      * The cases each drop the {@code selector} value they are given, and take an additional
7788      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7789      * to a specific constant label string for each case:
7790      * <blockquote><pre>{@code
7791      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7792      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7793      *         MethodType.methodType(String.class, String.class));
7794      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7795      *
7796      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7797      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7798      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7799      *
7800      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7801      *     caseDefault,
7802      *     case0,
7803      *     case1
7804      * );
7805      *
7806      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7807      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7808      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7809      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7810      * }</pre></blockquote>
7811      *
7812      * @param fallback the fallback method handle that is called when the selector is not
7813      *                 within the range {@code [0, N)}.
7814      * @param targets array of target method handles.
7815      * @return the table switch method handle.
7816      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7817      *                              any of the elements of the {@code targets} array are
7818      *                              {@code null}.
7819      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7820      *                                  parameter of the fallback handle or any of the target
7821      *                                  handles is not {@code int}, or if the types of
7822      *                                  the fallback handle and all of target handles are
7823      *                                  not the same.
7824      */
7825     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7826         Objects.requireNonNull(fallback);
7827         Objects.requireNonNull(targets);
7828         targets = targets.clone();
7829         MethodType type = tableSwitchChecks(fallback, targets);
7830         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7831     }
7832 
7833     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7834         if (caseActions.length == 0)
7835             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7836 
7837         MethodType expectedType = defaultCase.type();
7838 
7839         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7840             throw new IllegalArgumentException(
7841                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7842 
7843         for (MethodHandle mh : caseActions) {
7844             Objects.requireNonNull(mh);
7845             if (mh.type() != expectedType)
7846                 throw new IllegalArgumentException(
7847                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7848         }
7849 
7850         return expectedType;
7851     }
7852 
7853 }