1 /*
   2  * Copyright (c) 2008, 2022, 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.value.PrimitiveClass;
  30 import jdk.internal.foreign.Utils;
  31 import jdk.internal.javac.PreviewFeature;
  32 import jdk.internal.misc.Unsafe;
  33 import jdk.internal.misc.VM;
  34 import jdk.internal.org.objectweb.asm.ClassReader;
  35 import jdk.internal.org.objectweb.asm.Opcodes;
  36 import jdk.internal.org.objectweb.asm.Type;
  37 import jdk.internal.reflect.CallerSensitive;
  38 import jdk.internal.reflect.CallerSensitiveAdapter;
  39 import jdk.internal.reflect.Reflection;
  40 import jdk.internal.vm.annotation.ForceInline;
  41 import sun.invoke.util.ValueConversions;
  42 import sun.invoke.util.VerifyAccess;
  43 import sun.invoke.util.Wrapper;
  44 import sun.reflect.misc.ReflectUtil;
  45 import sun.security.util.SecurityConstants;
  46 
  47 import java.lang.constant.ConstantDescs;
  48 import java.lang.foreign.GroupLayout;
  49 import java.lang.foreign.MemoryLayout;
  50 import java.lang.foreign.MemorySegment;
  51 import java.lang.foreign.ValueLayout;
  52 import java.lang.invoke.LambdaForm.BasicType;
  53 import java.lang.reflect.Constructor;
  54 import java.lang.reflect.Field;
  55 import java.lang.reflect.Member;
  56 import java.lang.reflect.Method;
  57 import java.lang.reflect.Modifier;
  58 import java.nio.ByteOrder;
  59 import java.security.ProtectionDomain;
  60 import java.util.ArrayList;
  61 import java.util.Arrays;
  62 import java.util.BitSet;
  63 import java.util.Iterator;
  64 import java.util.List;
  65 import java.util.Objects;
  66 import java.util.Set;
  67 import java.util.concurrent.ConcurrentHashMap;
  68 import java.util.stream.Stream;
  69 
  70 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  71 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  72 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  73 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  74 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  75 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  76 import static java.lang.invoke.MethodType.methodType;
  77 
  78 /**
  79  * This class consists exclusively of static methods that operate on or return
  80  * method handles. They fall into several categories:
  81  * <ul>
  82  * <li>Lookup methods which help create method handles for methods and fields.
  83  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  84  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  85  * </ul>
  86  * A lookup, combinator, or factory method will fail and throw an
  87  * {@code IllegalArgumentException} if the created method handle's type
  88  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  89  *
  90  * @author John Rose, JSR 292 EG
  91  * @since 1.7
  92  */
  93 public class MethodHandles {
  94 
  95     private MethodHandles() { }  // do not instantiate
  96 
  97     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  98 
  99     // See IMPL_LOOKUP below.
 100 
 101     //// Method handle creation from ordinary methods.
 102 
 103     /**
 104      * Returns a {@link Lookup lookup object} with
 105      * full capabilities to emulate all supported bytecode behaviors of the caller.
 106      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 107      * Factory methods on the lookup object can create
 108      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 109      * for any member that the caller has access to via bytecodes,
 110      * including protected and private fields and methods.
 111      * This lookup object is created by the original lookup class
 112      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 113      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 114      * Do not store it in place where untrusted code can access it.
 115      * <p>
 116      * This method is caller sensitive, which means that it may return different
 117      * values to different callers.
 118      * In cases where {@code MethodHandles.lookup} is called from a context where
 119      * there is no caller frame on the stack (e.g. when called directly
 120      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 121      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 122      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 123      * to obtain a low-privileged lookup instead.
 124      * @return a lookup object for the caller of this method, with
 125      * {@linkplain Lookup#ORIGINAL original} and
 126      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 127      * @throws IllegalCallerException if there is no caller frame on the stack.
 128      */
 129     @CallerSensitive
 130     @ForceInline // to ensure Reflection.getCallerClass optimization
 131     public static Lookup lookup() {
 132         final Class<?> c = Reflection.getCallerClass();
 133         if (c == null) {
 134             throw new IllegalCallerException("no caller frame");
 135         }
 136         return new Lookup(c);
 137     }
 138 
 139     /**
 140      * This lookup method is the alternate implementation of
 141      * the lookup method with a leading caller class argument which is
 142      * non-caller-sensitive.  This method is only invoked by reflection
 143      * and method handle.
 144      */
 145     @CallerSensitiveAdapter
 146     private static Lookup lookup(Class<?> caller) {
 147         if (caller.getClassLoader() == null) {
 148             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 149         }
 150         return new Lookup(caller);
 151     }
 152 
 153     /**
 154      * Returns a {@link Lookup lookup object} which is trusted minimally.
 155      * The lookup has the {@code UNCONDITIONAL} mode.
 156      * It can only be used to create method handles to public members of
 157      * public classes in packages that are exported unconditionally.
 158      * <p>
 159      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 160      * of this lookup object will be {@link java.lang.Object}.
 161      *
 162      * @apiNote The use of Object is conventional, and because the lookup modes are
 163      * limited, there is no special access provided to the internals of Object, its package
 164      * or its module.  This public lookup object or other lookup object with
 165      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 166      * is not used to determine the lookup context.
 167      *
 168      * <p style="font-size:smaller;">
 169      * <em>Discussion:</em>
 170      * The lookup class can be changed to any other class {@code C} using an expression of the form
 171      * {@link Lookup#in publicLookup().in(C.class)}.
 172      * A public lookup object is always subject to
 173      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 174      * Also, it cannot access
 175      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 176      * @return a lookup object which is trusted minimally
 177      *
 178      * @revised 9
 179      */
 180     public static Lookup publicLookup() {
 181         return Lookup.PUBLIC_LOOKUP;
 182     }
 183 
 184     /**
 185      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 186      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 187      * The returned lookup object can provide access to classes in modules and packages,
 188      * and members of those classes, outside the normal rules of Java access control,
 189      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 190      * <p>
 191      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 192      * allowed to do deep reflection on module {@code M2} and package of the target class
 193      * if and only if all of the following conditions are {@code true}:
 194      * <ul>
 195      * <li>If there is a security manager, its {@code checkPermission} method is
 196      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 197      * that must return normally.
 198      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 199      * full privilege access}.  Specifically:
 200      *   <ul>
 201      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 202      *         (This is because otherwise there would be no way to ensure the original lookup
 203      *         creator was a member of any particular module, and so any subsequent checks
 204      *         for readability and qualified exports would become ineffective.)
 205      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 206      *         (This is because an application intending to share intra-module access
 207      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 208      *         deep reflection to its own module.)
 209      *   </ul>
 210      * <li>The target class must be a proper class, not a primitive or array class.
 211      * (Thus, {@code M2} is well-defined.)
 212      * <li>If the caller module {@code M1} differs from
 213      * the target module {@code M2} then both of the following must be true:
 214      *   <ul>
 215      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 216      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 217      *         containing the target class to at least {@code M1}.</li>
 218      *   </ul>
 219      * </ul>
 220      * <p>
 221      * If any of the above checks is violated, this method fails with an
 222      * exception.
 223      * <p>
 224      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 225      * returns a {@code Lookup} on {@code targetClass} with
 226      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 227      * with {@code null} previous lookup class.
 228      * <p>
 229      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 230      * returns a {@code Lookup} on {@code targetClass} that records
 231      * the lookup class of the caller as the new previous lookup class with
 232      * {@code PRIVATE} access but no {@code MODULE} access.
 233      * <p>
 234      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 235      *
 236      * @param targetClass the target class
 237      * @param caller the caller lookup object
 238      * @return a lookup object for the target class, with private access
 239      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 240      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 241      * @throws SecurityException if denied by the security manager
 242      * @throws IllegalAccessException if any of the other access checks specified above fails
 243      * @since 9
 244      * @see Lookup#dropLookupMode
 245      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 246      */
 247     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 248         if (caller.allowedModes == Lookup.TRUSTED) {
 249             return new Lookup(targetClass);
 250         }
 251 
 252         @SuppressWarnings("removal")
 253         SecurityManager sm = System.getSecurityManager();
 254         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 255         if (targetClass.isPrimitive())
 256             throw new IllegalArgumentException(targetClass + " is a primitive class");
 257         if (targetClass.isArray())
 258             throw new IllegalArgumentException(targetClass + " is an array class");
 259         // Ensure that we can reason accurately about private and module access.
 260         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 261         if ((caller.lookupModes() & requireAccess) != requireAccess)
 262             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 263 
 264         // previous lookup class is never set if it has MODULE access
 265         assert caller.previousLookupClass() == null;
 266 
 267         Class<?> callerClass = caller.lookupClass();
 268         Module callerModule = callerClass.getModule();  // M1
 269         Module targetModule = targetClass.getModule();  // M2
 270         Class<?> newPreviousClass = null;
 271         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 272 
 273         if (targetModule != callerModule) {
 274             if (!callerModule.canRead(targetModule))
 275                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 276             if (targetModule.isNamed()) {
 277                 String pn = targetClass.getPackageName();
 278                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 279                 if (!targetModule.isOpen(pn, callerModule))
 280                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 281             }
 282 
 283             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 284             newPreviousClass = callerClass;
 285             newModes &= ~Lookup.MODULE;
 286         }
 287         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 288     }
 289 
 290     /**
 291      * Returns the <em>class data</em> associated with the lookup class
 292      * of the given {@code caller} lookup object, or {@code null}.
 293      *
 294      * <p> A hidden class with class data can be created by calling
 295      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 296      * Lookup::defineHiddenClassWithClassData}.
 297      * This method will cause the static class initializer of the lookup
 298      * class of the given {@code caller} lookup object be executed if
 299      * it has not been initialized.
 300      *
 301      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 302      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 303      * {@code null} is returned if this method is called on the lookup object
 304      * on these classes.
 305      *
 306      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 307      * must have {@linkplain Lookup#ORIGINAL original access}
 308      * in order to retrieve the class data.
 309      *
 310      * @apiNote
 311      * This method can be called as a bootstrap method for a dynamically computed
 312      * constant.  A framework can create a hidden class with class data, for
 313      * example that can be {@code Class} or {@code MethodHandle} object.
 314      * The class data is accessible only to the lookup object
 315      * created by the original caller but inaccessible to other members
 316      * in the same nest.  If a framework passes security sensitive objects
 317      * to a hidden class via class data, it is recommended to load the value
 318      * of class data as a dynamically computed constant instead of storing
 319      * the class data in private static field(s) which are accessible to
 320      * other nestmates.
 321      *
 322      * @param <T> the type to cast the class data object to
 323      * @param caller the lookup context describing the class performing the
 324      * operation (normally stacked by the JVM)
 325      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 326      *             ({@code "_"})
 327      * @param type the type of the class data
 328      * @return the value of the class data if present in the lookup class;
 329      * otherwise {@code null}
 330      * @throws IllegalArgumentException if name is not {@code "_"}
 331      * @throws IllegalAccessException if the lookup context does not have
 332      * {@linkplain Lookup#ORIGINAL original} access
 333      * @throws ClassCastException if the class data cannot be converted to
 334      * the given {@code type}
 335      * @throws NullPointerException if {@code caller} or {@code type} argument
 336      * is {@code null}
 337      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 338      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 339      * @since 16
 340      * @jvms 5.5 Initialization
 341      */
 342      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 343          Objects.requireNonNull(caller);
 344          Objects.requireNonNull(type);
 345          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 346              throw new IllegalArgumentException("name must be \"_\": " + name);
 347          }
 348 
 349          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 350              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 351          }
 352 
 353          Object classdata = classData(caller.lookupClass());
 354          if (classdata == null) return null;
 355 
 356          try {
 357              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 358          } catch (RuntimeException|Error e) {
 359              throw e; // let CCE and other runtime exceptions through
 360          } catch (Throwable e) {
 361              throw new InternalError(e);
 362          }
 363     }
 364 
 365     /*
 366      * Returns the class data set by the VM in the Class::classData field.
 367      *
 368      * This is also invoked by LambdaForms as it cannot use condy via
 369      * MethodHandles::classData due to bootstrapping issue.
 370      */
 371     static Object classData(Class<?> c) {
 372         UNSAFE.ensureClassInitialized(c);
 373         return SharedSecrets.getJavaLangAccess().classData(c);
 374     }
 375 
 376     /**
 377      * Returns the element at the specified index in the
 378      * {@linkplain #classData(Lookup, String, Class) class data},
 379      * if the class data associated with the lookup class
 380      * of the given {@code caller} lookup object is a {@code List}.
 381      * If the class data is not present in this lookup class, this method
 382      * returns {@code null}.
 383      *
 384      * <p> A hidden class with class data can be created by calling
 385      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 386      * Lookup::defineHiddenClassWithClassData}.
 387      * This method will cause the static class initializer of the lookup
 388      * class of the given {@code caller} lookup object be executed if
 389      * it has not been initialized.
 390      *
 391      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 392      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 393      * {@code null} is returned if this method is called on the lookup object
 394      * on these classes.
 395      *
 396      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 397      * must have {@linkplain Lookup#ORIGINAL original access}
 398      * in order to retrieve the class data.
 399      *
 400      * @apiNote
 401      * This method can be called as a bootstrap method for a dynamically computed
 402      * constant.  A framework can create a hidden class with class data, for
 403      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 404      * one object and use this method to load one element at a specific index.
 405      * The class data is accessible only to the lookup object
 406      * created by the original caller but inaccessible to other members
 407      * in the same nest.  If a framework passes security sensitive objects
 408      * to a hidden class via class data, it is recommended to load the value
 409      * of class data as a dynamically computed constant instead of storing
 410      * the class data in private static field(s) which are accessible to other
 411      * nestmates.
 412      *
 413      * @param <T> the type to cast the result object to
 414      * @param caller the lookup context describing the class performing the
 415      * operation (normally stacked by the JVM)
 416      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 417      *             ({@code "_"})
 418      * @param type the type of the element at the given index in the class data
 419      * @param index index of the element in the class data
 420      * @return the element at the given index in the class data
 421      * if the class data is present; otherwise {@code null}
 422      * @throws IllegalArgumentException if name is not {@code "_"}
 423      * @throws IllegalAccessException if the lookup context does not have
 424      * {@linkplain Lookup#ORIGINAL original} access
 425      * @throws ClassCastException if the class data cannot be converted to {@code List}
 426      * or the element at the specified index cannot be converted to the given type
 427      * @throws IndexOutOfBoundsException if the index is out of range
 428      * @throws NullPointerException if {@code caller} or {@code type} argument is
 429      * {@code null}; or if unboxing operation fails because
 430      * the element at the given index is {@code null}
 431      *
 432      * @since 16
 433      * @see #classData(Lookup, String, Class)
 434      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 435      */
 436     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 437             throws IllegalAccessException
 438     {
 439         @SuppressWarnings("unchecked")
 440         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 441         if (classdata == null) return null;
 442 
 443         try {
 444             Object element = classdata.get(index);
 445             return BootstrapMethodInvoker.widenAndCast(element, type);
 446         } catch (RuntimeException|Error e) {
 447             throw e; // let specified exceptions and other runtime exceptions/errors through
 448         } catch (Throwable e) {
 449             throw new InternalError(e);
 450         }
 451     }
 452 
 453     /**
 454      * Performs an unchecked "crack" of a
 455      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 456      * The result is as if the user had obtained a lookup object capable enough
 457      * to crack the target method handle, called
 458      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 459      * on the target to obtain its symbolic reference, and then called
 460      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 461      * to resolve the symbolic reference to a member.
 462      * <p>
 463      * If there is a security manager, its {@code checkPermission} method
 464      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 465      * @param <T> the desired type of the result, either {@link Member} or a subtype
 466      * @param target a direct method handle to crack into symbolic reference components
 467      * @param expected a class object representing the desired result type {@code T}
 468      * @return a reference to the method, constructor, or field object
 469      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 470      * @throws    NullPointerException if either argument is {@code null}
 471      * @throws    IllegalArgumentException if the target is not a direct method handle
 472      * @throws    ClassCastException if the member is not of the expected type
 473      * @since 1.8
 474      */
 475     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 476         @SuppressWarnings("removal")
 477         SecurityManager smgr = System.getSecurityManager();
 478         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 479         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 480         return lookup.revealDirect(target).reflectAs(expected, lookup);
 481     }
 482 
 483     /**
 484      * A <em>lookup object</em> is a factory for creating method handles,
 485      * when the creation requires access checking.
 486      * Method handles do not perform
 487      * access checks when they are called, but rather when they are created.
 488      * Therefore, method handle access
 489      * restrictions must be enforced when a method handle is created.
 490      * The caller class against which those restrictions are enforced
 491      * is known as the {@linkplain #lookupClass() lookup class}.
 492      * <p>
 493      * A lookup class which needs to create method handles will call
 494      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 495      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 496      * determined, and securely stored in the {@code Lookup} object.
 497      * The lookup class (or its delegates) may then use factory methods
 498      * on the {@code Lookup} object to create method handles for access-checked members.
 499      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 500      * even private ones.
 501      *
 502      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 503      * The factory methods on a {@code Lookup} object correspond to all major
 504      * use cases for methods, constructors, and fields.
 505      * Each method handle created by a factory method is the functional
 506      * equivalent of a particular <em>bytecode behavior</em>.
 507      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 508      * the Java Virtual Machine Specification.)
 509      * Here is a summary of the correspondence between these factory methods and
 510      * the behavior of the resulting method handles:
 511      * <table class="striped">
 512      * <caption style="display:none">lookup method behaviors</caption>
 513      * <thead>
 514      * <tr>
 515      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 516      *     <th scope="col">member</th>
 517      *     <th scope="col">bytecode behavior</th>
 518      * </tr>
 519      * </thead>
 520      * <tbody>
 521      * <tr>
 522      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 523      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 524      * </tr>
 525      * <tr>
 526      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 527      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 528      * </tr>
 529      * <tr>
 530      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 531      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 532      * </tr>
 533      * <tr>
 534      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 535      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 536      * </tr>
 537      * <tr>
 538      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 539      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 540      * </tr>
 541      * <tr>
 542      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 543      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 544      * </tr>
 545      * <tr>
 546      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 547      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 548      * </tr>
 549      * <tr>
 550      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 551      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 552      * </tr>
 553      * <tr>
 554      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 555      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 556      * </tr>
 557      * <tr>
 558      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 559      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 560      * </tr>
 561      * <tr>
 562      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 563      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 564      * </tr>
 565      * <tr>
 566      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 567      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 568      * </tr>
 569      * <tr>
 570      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 571      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 572      * </tr>
 573      * <tr>
 574      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 575      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 576      * </tr>
 577      * </tbody>
 578      * </table>
 579      *
 580      * Here, the type {@code C} is the class or interface being searched for a member,
 581      * documented as a parameter named {@code refc} in the lookup methods.
 582      * The method type {@code MT} is composed from the return type {@code T}
 583      * and the sequence of argument types {@code A*}.
 584      * The constructor also has a sequence of argument types {@code A*} and
 585      * is deemed to return the newly-created object of type {@code C}.
 586      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 587      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 588      * if it is present, it is always the leading argument to the method handle invocation.
 589      * (In the case of some {@code protected} members, {@code this} may be
 590      * restricted in type to the lookup class; see below.)
 591      * The name {@code arg} stands for all the other method handle arguments.
 592      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 593      * stands for a null reference if the accessed method or field is static,
 594      * and {@code this} otherwise.
 595      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 596      * for reflective objects corresponding to the given members declared in type {@code C}.
 597      * <p>
 598      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 599      * as if by {@code ldc CONSTANT_Class}.
 600      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 601      * <p>
 602      * In cases where the given member is of variable arity (i.e., a method or constructor)
 603      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 604      * In all other cases, the returned method handle will be of fixed arity.
 605      * <p style="font-size:smaller;">
 606      * <em>Discussion:</em>
 607      * The equivalence between looked-up method handles and underlying
 608      * class members and bytecode behaviors
 609      * can break down in a few ways:
 610      * <ul style="font-size:smaller;">
 611      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 612      * the lookup can still succeed, even when there is no equivalent
 613      * Java expression or bytecoded constant.
 614      * <li>Likewise, if {@code T} or {@code MT}
 615      * is not symbolically accessible from the lookup class's loader,
 616      * the lookup can still succeed.
 617      * For example, lookups for {@code MethodHandle.invokeExact} and
 618      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 619      * <li>If there is a security manager installed, it can forbid the lookup
 620      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 621      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 622      * constant is not subject to security manager checks.
 623      * <li>If the looked-up method has a
 624      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 625      * the method handle creation may fail with an
 626      * {@code IllegalArgumentException}, due to the method handle type having
 627      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 628      * </ul>
 629      *
 630      * <h2><a id="access"></a>Access checking</h2>
 631      * Access checks are applied in the factory methods of {@code Lookup},
 632      * when a method handle is created.
 633      * This is a key difference from the Core Reflection API, since
 634      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 635      * performs access checking against every caller, on every call.
 636      * <p>
 637      * All access checks start from a {@code Lookup} object, which
 638      * compares its recorded lookup class against all requests to
 639      * create method handles.
 640      * A single {@code Lookup} object can be used to create any number
 641      * of access-checked method handles, all checked against a single
 642      * lookup class.
 643      * <p>
 644      * A {@code Lookup} object can be shared with other trusted code,
 645      * such as a metaobject protocol.
 646      * A shared {@code Lookup} object delegates the capability
 647      * to create method handles on private members of the lookup class.
 648      * Even if privileged code uses the {@code Lookup} object,
 649      * the access checking is confined to the privileges of the
 650      * original lookup class.
 651      * <p>
 652      * A lookup can fail, because
 653      * the containing class is not accessible to the lookup class, or
 654      * because the desired class member is missing, or because the
 655      * desired class member is not accessible to the lookup class, or
 656      * because the lookup object is not trusted enough to access the member.
 657      * In the case of a field setter function on a {@code final} field,
 658      * finality enforcement is treated as a kind of access control,
 659      * and the lookup will fail, except in special cases of
 660      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 661      * In any of these cases, a {@code ReflectiveOperationException} will be
 662      * thrown from the attempted lookup.  The exact class will be one of
 663      * the following:
 664      * <ul>
 665      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 666      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 667      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 668      * </ul>
 669      * <p>
 670      * In general, the conditions under which a method handle may be
 671      * looked up for a method {@code M} are no more restrictive than the conditions
 672      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 673      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 674      * a method handle lookup will generally raise a corresponding
 675      * checked exception, such as {@code NoSuchMethodException}.
 676      * And the effect of invoking the method handle resulting from the lookup
 677      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 678      * to executing the compiled, verified, and resolved call to {@code M}.
 679      * The same point is true of fields and constructors.
 680      * <p style="font-size:smaller;">
 681      * <em>Discussion:</em>
 682      * Access checks only apply to named and reflected methods,
 683      * constructors, and fields.
 684      * Other method handle creation methods, such as
 685      * {@link MethodHandle#asType MethodHandle.asType},
 686      * do not require any access checks, and are used
 687      * independently of any {@code Lookup} object.
 688      * <p>
 689      * If the desired member is {@code protected}, the usual JVM rules apply,
 690      * including the requirement that the lookup class must either be in the
 691      * same package as the desired member, or must inherit that member.
 692      * (See the Java Virtual Machine Specification, sections {@jvms
 693      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 694      * In addition, if the desired member is a non-static field or method
 695      * in a different package, the resulting method handle may only be applied
 696      * to objects of the lookup class or one of its subclasses.
 697      * This requirement is enforced by narrowing the type of the leading
 698      * {@code this} parameter from {@code C}
 699      * (which will necessarily be a superclass of the lookup class)
 700      * to the lookup class itself.
 701      * <p>
 702      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 703      * that the receiver argument must match both the resolved method <em>and</em>
 704      * the current class.  Again, this requirement is enforced by narrowing the
 705      * type of the leading parameter to the resulting method handle.
 706      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 707      * <p>
 708      * The JVM represents constructors and static initializer blocks as internal methods
 709      * with special names ({@code "<init>"}, {@code "<vnew>"} and {@code "<clinit>"}).
 710      * The internal syntax of invocation instructions allows them to refer to such internal
 711      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 712      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 713      * <p>
 714      * If the relationship between nested types is expressed directly through the
 715      * {@code NestHost} and {@code NestMembers} attributes
 716      * (see the Java Virtual Machine Specification, sections {@jvms
 717      * 4.7.28} and {@jvms 4.7.29}),
 718      * then the associated {@code Lookup} object provides direct access to
 719      * the lookup class and all of its nestmates
 720      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 721      * Otherwise, access between nested classes is obtained by the Java compiler creating
 722      * a wrapper method to access a private method of another class in the same nest.
 723      * For example, a nested class {@code C.D}
 724      * can access private members within other related classes such as
 725      * {@code C}, {@code C.D.E}, or {@code C.B},
 726      * but the Java compiler may need to generate wrapper methods in
 727      * those related classes.  In such cases, a {@code Lookup} object on
 728      * {@code C.E} would be unable to access those private members.
 729      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 730      * which can transform a lookup on {@code C.E} into one on any of those other
 731      * classes, without special elevation of privilege.
 732      * <p>
 733      * The accesses permitted to a given lookup object may be limited,
 734      * according to its set of {@link #lookupModes lookupModes},
 735      * to a subset of members normally accessible to the lookup class.
 736      * For example, the {@link MethodHandles#publicLookup publicLookup}
 737      * method produces a lookup object which is only allowed to access
 738      * public members in public classes of exported packages.
 739      * The caller sensitive method {@link MethodHandles#lookup lookup}
 740      * produces a lookup object with full capabilities relative to
 741      * its caller class, to emulate all supported bytecode behaviors.
 742      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 743      * with fewer access modes than the original lookup object.
 744      *
 745      * <p style="font-size:smaller;">
 746      * <a id="privacc"></a>
 747      * <em>Discussion of private and module access:</em>
 748      * We say that a lookup has <em>private access</em>
 749      * if its {@linkplain #lookupModes lookup modes}
 750      * include the possibility of accessing {@code private} members
 751      * (which includes the private members of nestmates).
 752      * As documented in the relevant methods elsewhere,
 753      * only lookups with private access possess the following capabilities:
 754      * <ul style="font-size:smaller;">
 755      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 756      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 757      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 758      *     for classes accessible to the lookup class
 759      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 760      *     within the same package member
 761      * </ul>
 762      * <p style="font-size:smaller;">
 763      * Similarly, a lookup with module access ensures that the original lookup creator was
 764      * a member in the same module as the lookup class.
 765      * <p style="font-size:smaller;">
 766      * Private and module access are independently determined modes; a lookup may have
 767      * either or both or neither.  A lookup which possesses both access modes is said to
 768      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 769      * <p style="font-size:smaller;">
 770      * A lookup with <em>original access</em> ensures that this lookup is created by
 771      * the original lookup class and the bootstrap method invoked by the VM.
 772      * Such a lookup with original access also has private and module access
 773      * which has the following additional capability:
 774      * <ul style="font-size:smaller;">
 775      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 776      *     such as {@code Class.forName}
 777      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 778      * class data} associated with the lookup class</li>
 779      * </ul>
 780      * <p style="font-size:smaller;">
 781      * Each of these permissions is a consequence of the fact that a lookup object
 782      * with private access can be securely traced back to an originating class,
 783      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 784      * can be reliably determined and emulated by method handles.
 785      *
 786      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 787      * When a lookup class in one module {@code M1} accesses a class in another module
 788      * {@code M2}, extra access checking is performed beyond the access mode bits.
 789      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 790      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 791      * and when the type is in a package of {@code M2} that is exported to
 792      * at least {@code M1}.
 793      * <p>
 794      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 795      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 796      * MethodHandles.privateLookupIn} methods.
 797      * Teleporting across modules will always record the original lookup class as
 798      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 799      * and drops {@link Lookup#MODULE MODULE} access.
 800      * If the target class is in the same module as the lookup class {@code C},
 801      * then the target class becomes the new lookup class
 802      * and there is no change to the previous lookup class.
 803      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 804      * {@code C} becomes the new previous lookup class
 805      * and the target class becomes the new lookup class.
 806      * In that case, if there was already a previous lookup class in {@code M0},
 807      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 808      * drops all privileges.
 809      * For example,
 810      * {@snippet lang="java" :
 811      * Lookup lookup = MethodHandles.lookup();   // in class C
 812      * Lookup lookup2 = lookup.in(D.class);
 813      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 814      * }
 815      * <p>
 816      * The {@link #lookup()} factory method produces a {@code Lookup} object
 817      * with {@code null} previous lookup class.
 818      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 819      * to class {@code D} without elevation of privileges.
 820      * If {@code C} and {@code D} are in the same module,
 821      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 822      * same previous lookup class as the original {@code lookup}, or
 823      * {@code null} if not present.
 824      * <p>
 825      * When a {@code Lookup} teleports from a class
 826      * in one nest to another nest, {@code PRIVATE} access is dropped.
 827      * When a {@code Lookup} teleports from a class in one package to
 828      * another package, {@code PACKAGE} access is dropped.
 829      * When a {@code Lookup} teleports from a class in one module to another module,
 830      * {@code MODULE} access is dropped.
 831      * Teleporting across modules drops the ability to access non-exported classes
 832      * in both the module of the new lookup class and the module of the old lookup class
 833      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 834      * A {@code Lookup} can teleport back and forth to a class in the module of
 835      * the lookup class and the module of the previous class lookup.
 836      * Teleporting across modules can only decrease access but cannot increase it.
 837      * Teleporting to some third module drops all accesses.
 838      * <p>
 839      * In the above example, if {@code C} and {@code D} are in different modules,
 840      * {@code lookup2} records {@code D} as its lookup class and
 841      * {@code C} as its previous lookup class and {@code lookup2} has only
 842      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 843      * {@code C}'s module and {@code D}'s module.
 844      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 845      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 846      * class {@code D} is recorded as its previous lookup class.
 847      * <p>
 848      * Teleporting across modules restricts access to the public types that
 849      * both the lookup class and the previous lookup class can equally access
 850      * (see below).
 851      * <p>
 852      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 853      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 854      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 855      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 856      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 857      * to call {@code privateLookupIn}.
 858      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 859      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 860      * produces a new {@code Lookup} on {@code T} with full capabilities.
 861      * A {@code lookup} on {@code C} is also allowed
 862      * to do deep reflection on {@code T} in another module {@code M2} if
 863      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 864      * the package containing {@code T} to at least {@code M1}.
 865      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 866      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 867      * The resulting {@code Lookup} can be used to do member lookup or teleport
 868      * to another lookup class by calling {@link #in Lookup::in}.  But
 869      * it cannot be used to obtain another private {@code Lookup} by calling
 870      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 871      * because it has no {@code MODULE} access.
 872      *
 873      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 874      *
 875      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 876      * allows cross-module access. The access checking is performed with respect
 877      * to both the lookup class and the previous lookup class if present.
 878      * <p>
 879      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 880      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 881      * exported unconditionally}.
 882      * <p>
 883      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 884      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 885      * that are readable to {@code M1} and the type is in a package that is exported
 886      * at least to {@code M1}.
 887      * <p>
 888      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 889      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 890      * the intersection of all public types that are accessible to {@code M1}
 891      * with all public types that are accessible to {@code M0}. {@code M0}
 892      * reads {@code M1} and hence the set of accessible types includes:
 893      *
 894      * <ul>
 895      * <li>unconditional-exported packages from {@code M1}</li>
 896      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 897      * <li>
 898      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 899      *     and {@code M1} read {@code M2}
 900      * </li>
 901      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 902      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 903      * <li>
 904      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 905      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 906      * </li>
 907      * </ul>
 908      *
 909      * <h2><a id="access-modes"></a>Access modes</h2>
 910      *
 911      * The table below shows the access modes of a {@code Lookup} produced by
 912      * any of the following factory or transformation methods:
 913      * <ul>
 914      * <li>{@link #lookup() MethodHandles::lookup}</li>
 915      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 916      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 917      * <li>{@link Lookup#in Lookup::in}</li>
 918      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 919      * </ul>
 920      *
 921      * <table class="striped">
 922      * <caption style="display:none">
 923      * Access mode summary
 924      * </caption>
 925      * <thead>
 926      * <tr>
 927      * <th scope="col">Lookup object</th>
 928      * <th style="text-align:center">original</th>
 929      * <th style="text-align:center">protected</th>
 930      * <th style="text-align:center">private</th>
 931      * <th style="text-align:center">package</th>
 932      * <th style="text-align:center">module</th>
 933      * <th style="text-align:center">public</th>
 934      * </tr>
 935      * </thead>
 936      * <tbody>
 937      * <tr>
 938      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 939      * <td style="text-align:center">ORI</td>
 940      * <td style="text-align:center">PRO</td>
 941      * <td style="text-align:center">PRI</td>
 942      * <td style="text-align:center">PAC</td>
 943      * <td style="text-align:center">MOD</td>
 944      * <td style="text-align:center">1R</td>
 945      * </tr>
 946      * <tr>
 947      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 948      * <td></td>
 949      * <td></td>
 950      * <td></td>
 951      * <td style="text-align:center">PAC</td>
 952      * <td style="text-align:center">MOD</td>
 953      * <td style="text-align:center">1R</td>
 954      * </tr>
 955      * <tr>
 956      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 957      * <td></td>
 958      * <td></td>
 959      * <td></td>
 960      * <td></td>
 961      * <td style="text-align:center">MOD</td>
 962      * <td style="text-align:center">1R</td>
 963      * </tr>
 964      * <tr>
 965      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 966      * <td></td>
 967      * <td></td>
 968      * <td></td>
 969      * <td></td>
 970      * <td></td>
 971      * <td style="text-align:center">2R</td>
 972      * </tr>
 973      * <tr>
 974      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 975      * <td></td>
 976      * <td></td>
 977      * <td></td>
 978      * <td></td>
 979      * <td></td>
 980      * <td style="text-align:center">2R</td>
 981      * </tr>
 982      * <tr>
 983      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 984      * <td></td>
 985      * <td style="text-align:center">PRO</td>
 986      * <td style="text-align:center">PRI</td>
 987      * <td style="text-align:center">PAC</td>
 988      * <td style="text-align:center">MOD</td>
 989      * <td style="text-align:center">1R</td>
 990      * </tr>
 991      * <tr>
 992      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 993      * <td></td>
 994      * <td style="text-align:center">PRO</td>
 995      * <td style="text-align:center">PRI</td>
 996      * <td style="text-align:center">PAC</td>
 997      * <td style="text-align:center">MOD</td>
 998      * <td style="text-align:center">1R</td>
 999      * </tr>
1000      * <tr>
1001      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
1002      * <td></td>
1003      * <td></td>
1004      * <td></td>
1005      * <td style="text-align:center">PAC</td>
1006      * <td style="text-align:center">MOD</td>
1007      * <td style="text-align:center">1R</td>
1008      * </tr>
1009      * <tr>
1010      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1011      * <td></td>
1012      * <td></td>
1013      * <td></td>
1014      * <td></td>
1015      * <td style="text-align:center">MOD</td>
1016      * <td style="text-align:center">1R</td>
1017      * </tr>
1018      * <tr>
1019      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1020      * <td></td>
1021      * <td></td>
1022      * <td></td>
1023      * <td></td>
1024      * <td></td>
1025      * <td style="text-align:center">2R</td>
1026      * </tr>
1027      * <tr>
1028      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1029      * <td></td>
1030      * <td></td>
1031      * <td style="text-align:center">PRI</td>
1032      * <td style="text-align:center">PAC</td>
1033      * <td style="text-align:center">MOD</td>
1034      * <td style="text-align:center">1R</td>
1035      * </tr>
1036      * <tr>
1037      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1038      * <td></td>
1039      * <td></td>
1040      * <td></td>
1041      * <td style="text-align:center">PAC</td>
1042      * <td style="text-align:center">MOD</td>
1043      * <td style="text-align:center">1R</td>
1044      * </tr>
1045      * <tr>
1046      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1047      * <td></td>
1048      * <td></td>
1049      * <td></td>
1050      * <td></td>
1051      * <td style="text-align:center">MOD</td>
1052      * <td style="text-align:center">1R</td>
1053      * </tr>
1054      * <tr>
1055      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1056      * <td></td>
1057      * <td></td>
1058      * <td></td>
1059      * <td></td>
1060      * <td></td>
1061      * <td style="text-align:center">1R</td>
1062      * </tr>
1063      * <tr>
1064      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1065      * <td></td>
1066      * <td></td>
1067      * <td></td>
1068      * <td></td>
1069      * <td></td>
1070      * <td style="text-align:center">none</td>
1071      * <tr>
1072      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1073      * <td></td>
1074      * <td style="text-align:center">PRO</td>
1075      * <td style="text-align:center">PRI</td>
1076      * <td style="text-align:center">PAC</td>
1077      * <td></td>
1078      * <td style="text-align:center">2R</td>
1079      * </tr>
1080      * <tr>
1081      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1082      * <td></td>
1083      * <td style="text-align:center">PRO</td>
1084      * <td style="text-align:center">PRI</td>
1085      * <td style="text-align:center">PAC</td>
1086      * <td></td>
1087      * <td style="text-align:center">2R</td>
1088      * </tr>
1089      * <tr>
1090      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1091      * <td></td>
1092      * <td></td>
1093      * <td></td>
1094      * <td></td>
1095      * <td></td>
1096      * <td style="text-align:center">IAE</td>
1097      * </tr>
1098      * <tr>
1099      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1100      * <td></td>
1101      * <td></td>
1102      * <td></td>
1103      * <td style="text-align:center">PAC</td>
1104      * <td></td>
1105      * <td style="text-align:center">2R</td>
1106      * </tr>
1107      * <tr>
1108      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1109      * <td></td>
1110      * <td></td>
1111      * <td></td>
1112      * <td></td>
1113      * <td></td>
1114      * <td style="text-align:center">2R</td>
1115      * </tr>
1116      * <tr>
1117      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1118      * <td></td>
1119      * <td></td>
1120      * <td></td>
1121      * <td></td>
1122      * <td></td>
1123      * <td style="text-align:center">2R</td>
1124      * </tr>
1125      * <tr>
1126      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1127      * <td></td>
1128      * <td></td>
1129      * <td></td>
1130      * <td></td>
1131      * <td></td>
1132      * <td style="text-align:center">none</td>
1133      * </tr>
1134      * <tr>
1135      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1136      * <td></td>
1137      * <td></td>
1138      * <td style="text-align:center">PRI</td>
1139      * <td style="text-align:center">PAC</td>
1140      * <td></td>
1141      * <td style="text-align:center">2R</td>
1142      * </tr>
1143      * <tr>
1144      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1145      * <td></td>
1146      * <td></td>
1147      * <td></td>
1148      * <td style="text-align:center">PAC</td>
1149      * <td></td>
1150      * <td style="text-align:center">2R</td>
1151      * </tr>
1152      * <tr>
1153      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1154      * <td></td>
1155      * <td></td>
1156      * <td></td>
1157      * <td></td>
1158      * <td></td>
1159      * <td style="text-align:center">2R</td>
1160      * </tr>
1161      * <tr>
1162      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1163      * <td></td>
1164      * <td></td>
1165      * <td></td>
1166      * <td></td>
1167      * <td></td>
1168      * <td style="text-align:center">2R</td>
1169      * </tr>
1170      * <tr>
1171      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1172      * <td></td>
1173      * <td></td>
1174      * <td></td>
1175      * <td></td>
1176      * <td></td>
1177      * <td style="text-align:center">none</td>
1178      * </tr>
1179      * <tr>
1180      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1181      * <td></td>
1182      * <td></td>
1183      * <td style="text-align:center">PRI</td>
1184      * <td style="text-align:center">PAC</td>
1185      * <td style="text-align:center">MOD</td>
1186      * <td style="text-align:center">1R</td>
1187      * </tr>
1188      * <tr>
1189      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1190      * <td></td>
1191      * <td></td>
1192      * <td></td>
1193      * <td style="text-align:center">PAC</td>
1194      * <td style="text-align:center">MOD</td>
1195      * <td style="text-align:center">1R</td>
1196      * </tr>
1197      * <tr>
1198      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1199      * <td></td>
1200      * <td></td>
1201      * <td></td>
1202      * <td></td>
1203      * <td style="text-align:center">MOD</td>
1204      * <td style="text-align:center">1R</td>
1205      * </tr>
1206      * <tr>
1207      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1208      * <td></td>
1209      * <td></td>
1210      * <td></td>
1211      * <td></td>
1212      * <td></td>
1213      * <td style="text-align:center">1R</td>
1214      * </tr>
1215      * <tr>
1216      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1217      * <td></td>
1218      * <td></td>
1219      * <td></td>
1220      * <td></td>
1221      * <td></td>
1222      * <td style="text-align:center">none</td>
1223      * </tr>
1224      * <tr>
1225      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1226      * <td></td>
1227      * <td></td>
1228      * <td></td>
1229      * <td></td>
1230      * <td></td>
1231      * <td style="text-align:center">U</td>
1232      * </tr>
1233      * <tr>
1234      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1235      * <td></td>
1236      * <td></td>
1237      * <td></td>
1238      * <td></td>
1239      * <td></td>
1240      * <td style="text-align:center">U</td>
1241      * </tr>
1242      * <tr>
1243      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1244      * <td></td>
1245      * <td></td>
1246      * <td></td>
1247      * <td></td>
1248      * <td></td>
1249      * <td style="text-align:center">U</td>
1250      * </tr>
1251      * <tr>
1252      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1253      * <td></td>
1254      * <td></td>
1255      * <td></td>
1256      * <td></td>
1257      * <td></td>
1258      * <td style="text-align:center">none</td>
1259      * </tr>
1260      * <tr>
1261      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1262      * <td></td>
1263      * <td></td>
1264      * <td></td>
1265      * <td></td>
1266      * <td></td>
1267      * <td style="text-align:center">IAE</td>
1268      * </tr>
1269      * <tr>
1270      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1271      * <td></td>
1272      * <td></td>
1273      * <td></td>
1274      * <td></td>
1275      * <td></td>
1276      * <td style="text-align:center">none</td>
1277      * </tr>
1278      * </tbody>
1279      * </table>
1280      *
1281      * <p>
1282      * Notes:
1283      * <ul>
1284      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1285      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1286      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1287      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1288      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1289      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1290      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1291      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1292      *     {@code MOD} indicates {@link #MODULE} bit set,
1293      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1294      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1295      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1296      * <li>Public access comes in three kinds:
1297      * <ul>
1298      * <li>unconditional ({@code U}): the lookup assumes readability.
1299      *     The lookup has {@code null} previous lookup class.
1300      * <li>one-module-reads ({@code 1R}): the module access checking is
1301      *     performed with respect to the lookup class.  The lookup has {@code null}
1302      *     previous lookup class.
1303      * <li>two-module-reads ({@code 2R}): the module access checking is
1304      *     performed with respect to the lookup class and the previous lookup class.
1305      *     The lookup has a non-null previous lookup class which is in a
1306      *     different module from the current lookup class.
1307      * </ul>
1308      * <li>Any attempt to reach a third module loses all access.</li>
1309      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1310      * all access modes are dropped.</li>
1311      * </ul>
1312      *
1313      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1314      * Although bytecode instructions can only refer to classes in
1315      * a related class loader, this API can search for methods in any
1316      * class, as long as a reference to its {@code Class} object is
1317      * available.  Such cross-loader references are also possible with the
1318      * Core Reflection API, and are impossible to bytecode instructions
1319      * such as {@code invokestatic} or {@code getfield}.
1320      * There is a {@linkplain java.lang.SecurityManager security manager API}
1321      * to allow applications to check such cross-loader references.
1322      * These checks apply to both the {@code MethodHandles.Lookup} API
1323      * and the Core Reflection API
1324      * (as found on {@link java.lang.Class Class}).
1325      * <p>
1326      * If a security manager is present, member and class lookups are subject to
1327      * additional checks.
1328      * From one to three calls are made to the security manager.
1329      * Any of these calls can refuse access by throwing a
1330      * {@link java.lang.SecurityException SecurityException}.
1331      * Define {@code smgr} as the security manager,
1332      * {@code lookc} as the lookup class of the current lookup object,
1333      * {@code refc} as the containing class in which the member
1334      * is being sought, and {@code defc} as the class in which the
1335      * member is actually defined.
1336      * (If a class or other type is being accessed,
1337      * the {@code refc} and {@code defc} values are the class itself.)
1338      * The value {@code lookc} is defined as <em>not present</em>
1339      * if the current lookup object does not have
1340      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1341      * The calls are made according to the following rules:
1342      * <ul>
1343      * <li><b>Step 1:</b>
1344      *     If {@code lookc} is not present, or if its class loader is not
1345      *     the same as or an ancestor of the class loader of {@code refc},
1346      *     then {@link SecurityManager#checkPackageAccess
1347      *     smgr.checkPackageAccess(refcPkg)} is called,
1348      *     where {@code refcPkg} is the package of {@code refc}.
1349      * <li><b>Step 2a:</b>
1350      *     If the retrieved member is not public and
1351      *     {@code lookc} is not present, then
1352      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1353      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1354      * <li><b>Step 2b:</b>
1355      *     If the retrieved class has a {@code null} class loader,
1356      *     and {@code lookc} is not present, then
1357      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1358      *     with {@code RuntimePermission("getClassLoader")} is called.
1359      * <li><b>Step 3:</b>
1360      *     If the retrieved member is not public,
1361      *     and if {@code lookc} is not present,
1362      *     and if {@code defc} and {@code refc} are different,
1363      *     then {@link SecurityManager#checkPackageAccess
1364      *     smgr.checkPackageAccess(defcPkg)} is called,
1365      *     where {@code defcPkg} is the package of {@code defc}.
1366      * </ul>
1367      * Security checks are performed after other access checks have passed.
1368      * Therefore, the above rules presuppose a member or class that is public,
1369      * or else that is being accessed from a lookup class that has
1370      * rights to access the member or class.
1371      * <p>
1372      * If a security manager is present and the current lookup object does not have
1373      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1374      * {@link #defineClass(byte[]) defineClass},
1375      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1376      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1377      * defineHiddenClassWithClassData}
1378      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1379      * with {@code RuntimePermission("defineClass")}.
1380      *
1381      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1382      * A small number of Java methods have a special property called caller sensitivity.
1383      * A <em>caller-sensitive</em> method can behave differently depending on the
1384      * identity of its immediate caller.
1385      * <p>
1386      * If a method handle for a caller-sensitive method is requested,
1387      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1388      * but they take account of the lookup class in a special way.
1389      * The resulting method handle behaves as if it were called
1390      * from an instruction contained in the lookup class,
1391      * so that the caller-sensitive method detects the lookup class.
1392      * (By contrast, the invoker of the method handle is disregarded.)
1393      * Thus, in the case of caller-sensitive methods,
1394      * different lookup classes may give rise to
1395      * differently behaving method handles.
1396      * <p>
1397      * In cases where the lookup object is
1398      * {@link MethodHandles#publicLookup() publicLookup()},
1399      * or some other lookup object without the
1400      * {@linkplain #ORIGINAL original access},
1401      * the lookup class is disregarded.
1402      * In such cases, no caller-sensitive method handle can be created,
1403      * access is forbidden, and the lookup fails with an
1404      * {@code IllegalAccessException}.
1405      * <p style="font-size:smaller;">
1406      * <em>Discussion:</em>
1407      * For example, the caller-sensitive method
1408      * {@link java.lang.Class#forName(String) Class.forName(x)}
1409      * can return varying classes or throw varying exceptions,
1410      * depending on the class loader of the class that calls it.
1411      * A public lookup of {@code Class.forName} will fail, because
1412      * there is no reasonable way to determine its bytecode behavior.
1413      * <p style="font-size:smaller;">
1414      * If an application caches method handles for broad sharing,
1415      * it should use {@code publicLookup()} to create them.
1416      * If there is a lookup of {@code Class.forName}, it will fail,
1417      * and the application must take appropriate action in that case.
1418      * It may be that a later lookup, perhaps during the invocation of a
1419      * bootstrap method, can incorporate the specific identity
1420      * of the caller, making the method accessible.
1421      * <p style="font-size:smaller;">
1422      * The function {@code MethodHandles.lookup} is caller sensitive
1423      * so that there can be a secure foundation for lookups.
1424      * Nearly all other methods in the JSR 292 API rely on lookup
1425      * objects to check access requests.
1426      *
1427      * @revised 9
1428      */
1429     public static final
1430     class Lookup {
1431         /** The class on behalf of whom the lookup is being performed. */
1432         private final Class<?> lookupClass;
1433 
1434         /** previous lookup class */
1435         private final Class<?> prevLookupClass;
1436 
1437         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1438         private final int allowedModes;
1439 
1440         static {
1441             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1442         }
1443 
1444         /** A single-bit mask representing {@code public} access,
1445          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1446          *  The value, {@code 0x01}, happens to be the same as the value of the
1447          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1448          *  <p>
1449          *  A {@code Lookup} with this lookup mode performs cross-module access check
1450          *  with respect to the {@linkplain #lookupClass() lookup class} and
1451          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1452          */
1453         public static final int PUBLIC = Modifier.PUBLIC;
1454 
1455         /** A single-bit mask representing {@code private} access,
1456          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1457          *  The value, {@code 0x02}, happens to be the same as the value of the
1458          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1459          */
1460         public static final int PRIVATE = Modifier.PRIVATE;
1461 
1462         /** A single-bit mask representing {@code protected} access,
1463          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1464          *  The value, {@code 0x04}, happens to be the same as the value of the
1465          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1466          */
1467         public static final int PROTECTED = Modifier.PROTECTED;
1468 
1469         /** A single-bit mask representing {@code package} access (default access),
1470          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1471          *  The value is {@code 0x08}, which does not correspond meaningfully to
1472          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1473          */
1474         public static final int PACKAGE = Modifier.STATIC;
1475 
1476         /** A single-bit mask representing {@code module} access,
1477          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1478          *  The value is {@code 0x10}, which does not correspond meaningfully to
1479          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1480          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1481          *  with this lookup mode can access all public types in the module of the
1482          *  lookup class and public types in packages exported by other modules
1483          *  to the module of the lookup class.
1484          *  <p>
1485          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1486          *  previous lookup class} is always {@code null}.
1487          *
1488          *  @since 9
1489          */
1490         public static final int MODULE = PACKAGE << 1;
1491 
1492         /** A single-bit mask representing {@code unconditional} access
1493          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1494          *  The value is {@code 0x20}, which does not correspond meaningfully to
1495          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1496          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1497          *  java.lang.Module#canRead(java.lang.Module) readability}.
1498          *  This lookup mode can access all public members of public types
1499          *  of all modules when the type is in a package that is {@link
1500          *  java.lang.Module#isExported(String) exported unconditionally}.
1501          *
1502          *  <p>
1503          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1504          *  previous lookup class} is always {@code null}.
1505          *
1506          *  @since 9
1507          *  @see #publicLookup()
1508          */
1509         public static final int UNCONDITIONAL = PACKAGE << 2;
1510 
1511         /** A single-bit mask representing {@code original} access
1512          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1513          *  The value is {@code 0x40}, which does not correspond meaningfully to
1514          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1515          *
1516          *  <p>
1517          *  If this lookup mode is set, the {@code Lookup} object must be
1518          *  created by the original lookup class by calling
1519          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1520          *  invoked by the VM.  The {@code Lookup} object with this lookup
1521          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1522          *
1523          *  @since 16
1524          */
1525         public static final int ORIGINAL = PACKAGE << 3;
1526 
1527         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1528         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1529         private static final int TRUSTED   = -1;
1530 
1531         /*
1532          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1533          * Adjust 0 => PACKAGE
1534          */
1535         private static int fixmods(int mods) {
1536             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1537             if (Modifier.isPublic(mods))
1538                 mods |= UNCONDITIONAL;
1539             return (mods != 0) ? mods : PACKAGE;
1540         }
1541 
1542         /** Tells which class is performing the lookup.  It is this class against
1543          *  which checks are performed for visibility and access permissions.
1544          *  <p>
1545          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1546          *  access checks are performed against both the lookup class and the previous lookup class.
1547          *  <p>
1548          *  The class implies a maximum level of access permission,
1549          *  but the permissions may be additionally limited by the bitmask
1550          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1551          *  can be accessed.
1552          *  @return the lookup class, on behalf of which this lookup object finds members
1553          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1554          */
1555         public Class<?> lookupClass() {
1556             return lookupClass;
1557         }
1558 
1559         /** Reports a lookup class in another module that this lookup object
1560          * was previously teleported from, or {@code null}.
1561          * <p>
1562          * A {@code Lookup} object produced by the factory methods, such as the
1563          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1564          * has {@code null} previous lookup class.
1565          * A {@code Lookup} object has a non-null previous lookup class
1566          * when this lookup was teleported from an old lookup class
1567          * in one module to a new lookup class in another module.
1568          *
1569          * @return the lookup class in another module that this lookup object was
1570          *         previously teleported from, or {@code null}
1571          * @since 14
1572          * @see #in(Class)
1573          * @see MethodHandles#privateLookupIn(Class, Lookup)
1574          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1575          */
1576         public Class<?> previousLookupClass() {
1577             return prevLookupClass;
1578         }
1579 
1580         // This is just for calling out to MethodHandleImpl.
1581         private Class<?> lookupClassOrNull() {
1582             return (allowedModes == TRUSTED) ? null : lookupClass;
1583         }
1584 
1585         /** Tells which access-protection classes of members this lookup object can produce.
1586          *  The result is a bit-mask of the bits
1587          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1588          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1589          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1590          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1591          *  {@linkplain #MODULE MODULE (0x10)},
1592          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1593          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1594          *  <p>
1595          *  A freshly-created lookup object
1596          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1597          *  all possible bits set, except {@code UNCONDITIONAL}.
1598          *  A lookup object on a new lookup class
1599          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1600          *  may have some mode bits set to zero.
1601          *  Mode bits can also be
1602          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1603          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1604          *  The purpose of this is to restrict access via the new lookup object,
1605          *  so that it can access only names which can be reached by the original
1606          *  lookup object, and also by the new lookup class.
1607          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1608          *  @see #in
1609          *  @see #dropLookupMode
1610          *
1611          *  @revised 9
1612          */
1613         public int lookupModes() {
1614             return allowedModes & ALL_MODES;
1615         }
1616 
1617         /** Embody the current class (the lookupClass) as a lookup class
1618          * for method handle creation.
1619          * Must be called by from a method in this package,
1620          * which in turn is called by a method not in this package.
1621          */
1622         Lookup(Class<?> lookupClass) {
1623             this(lookupClass, null, FULL_POWER_MODES);
1624         }
1625 
1626         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1627             assert PrimitiveClass.isPrimaryType(lookupClass);
1628             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1629                     && prevLookupClass.getModule() != lookupClass.getModule());
1630             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1631             this.lookupClass = lookupClass;
1632             this.prevLookupClass = prevLookupClass;
1633             this.allowedModes = allowedModes;
1634         }
1635 
1636         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1637             // make sure we haven't accidentally picked up a privileged class:
1638             checkUnprivilegedlookupClass(lookupClass);
1639             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1640         }
1641 
1642         /**
1643          * Creates a lookup on the specified new lookup class.
1644          * The resulting object will report the specified
1645          * class as its own {@link #lookupClass() lookupClass}.
1646          *
1647          * <p>
1648          * However, the resulting {@code Lookup} object is guaranteed
1649          * to have no more access capabilities than the original.
1650          * In particular, access capabilities can be lost as follows:<ul>
1651          * <li>If the new lookup class is different from the old lookup class,
1652          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1653          * <li>If the new lookup class is in a different module from the old one,
1654          * i.e. {@link #MODULE MODULE} access is lost.
1655          * <li>If the new lookup class is in a different package
1656          * than the old one, protected and default (package) members will not be accessible,
1657          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1658          * <li>If the new lookup class is not within the same package member
1659          * as the old one, private members will not be accessible, and protected members
1660          * will not be accessible by virtue of inheritance,
1661          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1662          * (Protected members may continue to be accessible because of package sharing.)
1663          * <li>If the new lookup class is not
1664          * {@linkplain #accessClass(Class) accessible} to this lookup,
1665          * then no members, not even public members, will be accessible
1666          * i.e. all access modes are lost.
1667          * <li>If the new lookup class, the old lookup class and the previous lookup class
1668          * are all in different modules i.e. teleporting to a third module,
1669          * all access modes are lost.
1670          * </ul>
1671          * <p>
1672          * The new previous lookup class is chosen as follows:
1673          * <ul>
1674          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1675          * the new previous lookup class is {@code null}.
1676          * <li>If the new lookup class is in the same module as the old lookup class,
1677          * the new previous lookup class is the old previous lookup class.
1678          * <li>If the new lookup class is in a different module from the old lookup class,
1679          * the new previous lookup class is the old lookup class.
1680          *</ul>
1681          * <p>
1682          * The resulting lookup's capabilities for loading classes
1683          * (used during {@link #findClass} invocations)
1684          * are determined by the lookup class' loader,
1685          * which may change due to this operation.
1686          *
1687          * @param requestedLookupClass the desired lookup class for the new lookup object
1688          * @return a lookup object which reports the desired lookup class, or the same object
1689          * if there is no change
1690          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1691          * @throws NullPointerException if the argument is null
1692          *
1693          * @revised 9
1694          * @see #accessClass(Class)
1695          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1696          */
1697         public Lookup in(Class<?> requestedLookupClass) {
1698             Objects.requireNonNull(requestedLookupClass);
1699             if (requestedLookupClass.isPrimitive())
1700                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1701             if (requestedLookupClass.isArray())
1702                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1703 
1704             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1705                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1706             if (requestedLookupClass == this.lookupClass)
1707                 return this;  // keep same capabilities
1708             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1709             Module fromModule = this.lookupClass.getModule();
1710             Module targetModule = requestedLookupClass.getModule();
1711             Class<?> plc = this.previousLookupClass();
1712             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1713                 assert plc == null;
1714                 newModes = UNCONDITIONAL;
1715             } else if (fromModule != targetModule) {
1716                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1717                     // allow hopping back and forth between fromModule and plc's module
1718                     // but not the third module
1719                     newModes = 0;
1720                 }
1721                 // drop MODULE access
1722                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1723                 // teleport from this lookup class
1724                 plc = this.lookupClass;
1725             }
1726             if ((newModes & PACKAGE) != 0
1727                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1728                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1729             }
1730             // Allow nestmate lookups to be created without special privilege:
1731             if ((newModes & PRIVATE) != 0
1732                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1733                 newModes &= ~(PRIVATE|PROTECTED);
1734             }
1735             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1736                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1737                 // The requested class it not accessible from the lookup class.
1738                 // No permissions.
1739                 newModes = 0;
1740             }
1741             return newLookup(requestedLookupClass, plc, newModes);
1742         }
1743 
1744         /**
1745          * Creates a lookup on the same lookup class which this lookup object
1746          * finds members, but with a lookup mode that has lost the given lookup mode.
1747          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1748          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1749          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1750          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1751          *
1752          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1753          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1754          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1755          * lookup has no access.
1756          *
1757          * <p> If this lookup is not a public lookup, then the following applies
1758          * regardless of its {@linkplain #lookupModes() lookup modes}.
1759          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1760          * dropped and so the resulting lookup mode will never have these access
1761          * capabilities. When dropping {@code PACKAGE}
1762          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1763          * access. When dropping {@code MODULE} then the resulting lookup will not
1764          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1765          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1766          *
1767          * @apiNote
1768          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1769          * delegate non-public access within the package of the lookup class without
1770          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1771          * A lookup with {@code MODULE} but not
1772          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1773          * the module of the lookup class without conferring package access.
1774          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1775          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1776          * to public classes accessible to both the module of the lookup class
1777          * and the module of the previous lookup class.
1778          *
1779          * @param modeToDrop the lookup mode to drop
1780          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1781          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1782          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1783          * or {@code UNCONDITIONAL}
1784          * @see MethodHandles#privateLookupIn
1785          * @since 9
1786          */
1787         public Lookup dropLookupMode(int modeToDrop) {
1788             int oldModes = lookupModes();
1789             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1790             switch (modeToDrop) {
1791                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1792                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1793                 case PACKAGE: newModes &= ~(PRIVATE); break;
1794                 case PROTECTED:
1795                 case PRIVATE:
1796                 case ORIGINAL:
1797                 case UNCONDITIONAL: break;
1798                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1799             }
1800             if (newModes == oldModes) return this;  // return self if no change
1801             return newLookup(lookupClass(), previousLookupClass(), newModes);
1802         }
1803 
1804         /**
1805          * Creates and links a class or interface from {@code bytes}
1806          * with the same class loader and in the same runtime package and
1807          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1808          * {@linkplain #lookupClass() lookup class} as if calling
1809          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1810          * ClassLoader::defineClass}.
1811          *
1812          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1813          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1814          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1815          * that the lookup object was created by a caller in the runtime package (or derived
1816          * from a lookup originally created by suitably privileged code to a target class in
1817          * the runtime package). </p>
1818          *
1819          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1820          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1821          * same package as the lookup class. </p>
1822          *
1823          * <p> This method does not run the class initializer. The class initializer may
1824          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1825          * Specification</em>. </p>
1826          *
1827          * <p> If there is a security manager and this lookup does not have {@linkplain
1828          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1829          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1830          *
1831          * @param bytes the class bytes
1832          * @return the {@code Class} object for the class
1833          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1834          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1835          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1836          * than the lookup class or {@code bytes} is not a class or interface
1837          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1838          * @throws VerifyError if the newly created class cannot be verified
1839          * @throws LinkageError if the newly created class cannot be linked for any other reason
1840          * @throws SecurityException if a security manager is present and it
1841          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1842          * @throws NullPointerException if {@code bytes} is {@code null}
1843          * @since 9
1844          * @see Lookup#privateLookupIn
1845          * @see Lookup#dropLookupMode
1846          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1847          */
1848         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1849             ensureDefineClassPermission();
1850             if ((lookupModes() & PACKAGE) == 0)
1851                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1852             return makeClassDefiner(bytes.clone()).defineClass(false);
1853         }
1854 
1855         private void ensureDefineClassPermission() {
1856             if (allowedModes == TRUSTED)  return;
1857 
1858             if (!hasFullPrivilegeAccess()) {
1859                 @SuppressWarnings("removal")
1860                 SecurityManager sm = System.getSecurityManager();
1861                 if (sm != null)
1862                     sm.checkPermission(new RuntimePermission("defineClass"));
1863             }
1864         }
1865 
1866         /**
1867          * The set of class options that specify whether a hidden class created by
1868          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1869          * Lookup::defineHiddenClass} method is dynamically added as a new member
1870          * to the nest of a lookup class and/or whether a hidden class has
1871          * a strong relationship with the class loader marked as its defining loader.
1872          *
1873          * @since 15
1874          */
1875         public enum ClassOption {
1876             /**
1877              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1878              * of a lookup class as a nestmate.
1879              *
1880              * <p> A hidden nestmate class has access to the private members of all
1881              * classes and interfaces in the same nest.
1882              *
1883              * @see Class#getNestHost()
1884              */
1885             NESTMATE(NESTMATE_CLASS),
1886 
1887             /**
1888              * Specifies that a hidden class has a <em>strong</em>
1889              * relationship with the class loader marked as its defining loader,
1890              * as a normal class or interface has with its own defining loader.
1891              * This means that the hidden class may be unloaded if and only if
1892              * its defining loader is not reachable and thus may be reclaimed
1893              * by a garbage collector (JLS {@jls 12.7}).
1894              *
1895              * <p> By default, a hidden class or interface may be unloaded
1896              * even if the class loader that is marked as its defining loader is
1897              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1898 
1899              *
1900              * @jls 12.7 Unloading of Classes and Interfaces
1901              */
1902             STRONG(STRONG_LOADER_LINK);
1903 
1904             /* the flag value is used by VM at define class time */
1905             private final int flag;
1906             ClassOption(int flag) {
1907                 this.flag = flag;
1908             }
1909 
1910             static int optionsToFlag(Set<ClassOption> options) {
1911                 int flags = 0;
1912                 for (ClassOption cp : options) {
1913                     flags |= cp.flag;
1914                 }
1915                 return flags;
1916             }
1917         }
1918 
1919         /**
1920          * Creates a <em>hidden</em> class or interface from {@code bytes},
1921          * returning a {@code Lookup} on the newly created class or interface.
1922          *
1923          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1924          * which either defines {@code C} directly or delegates to another class loader.
1925          * A class loader defines {@code C} directly by invoking
1926          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1927          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1928          * to derive {@code C} from a purported representation in {@code class} file format.
1929          * In situations where use of a class loader is undesirable, a class or interface
1930          * {@code C} can be created by this method instead. This method is capable of
1931          * defining {@code C}, and thereby creating it, without invoking
1932          * {@code ClassLoader::defineClass}.
1933          * Instead, this method defines {@code C} as if by arranging for
1934          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1935          * from a purported representation in {@code class} file format
1936          * using the following rules:
1937          *
1938          * <ol>
1939          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1940          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1941          * This level of access is needed to create {@code C} in the module
1942          * of the lookup class of this {@code Lookup}.</li>
1943          *
1944          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1945          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1946          * The major and minor version may differ from the {@code class} file version
1947          * of the lookup class of this {@code Lookup}.</li>
1948          *
1949          * <li> The value of {@code this_class} must be a valid index in the
1950          * {@code constant_pool} table, and the entry at that index must be a valid
1951          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1952          * encoded in internal form that is specified by this structure. {@code N} must
1953          * denote a class or interface in the same package as the lookup class.</li>
1954          *
1955          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1956          * where {@code <suffix>} is an unqualified name.
1957          *
1958          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1959          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1960          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1961          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1962          * refers to the new {@code CONSTANT_Utf8_info} structure.
1963          *
1964          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1965          *
1966          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1967          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1968          * with the following adjustments:
1969          * <ul>
1970          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1971          * that includes a single {@code "."} character, even though this is not a valid
1972          * binary class or interface name in internal form.</li>
1973          *
1974          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1975          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1976          *
1977          * <li> {@code C} is considered to have the same runtime
1978          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1979          * and {@linkplain java.security.ProtectionDomain protection domain}
1980          * as the lookup class of this {@code Lookup}.
1981          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1982          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1983          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1984          * <ul>
1985          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1986          *      even though this is not a valid binary class or interface name.</li>
1987          * <li> {@link Class#descriptorString()} returns the string
1988          *      {@code "L" + N + "." + <suffix> + ";"},
1989          *      even though this is not a valid type descriptor name.</li>
1990          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1991          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1992          * </ul>
1993          * </ul>
1994          * </li>
1995          * </ol>
1996          *
1997          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1998          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1999          * <ul>
2000          * <li> During verification, whenever it is necessary to load the class named
2001          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
2002          * made of any class loader.</li>
2003          *
2004          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
2005          * by {@code this_class}, the symbolic reference is considered to be resolved to
2006          * {@code C} and resolution always succeeds immediately.</li>
2007          * </ul>
2008          *
2009          * <p> If the {@code initialize} parameter is {@code true},
2010          * then {@code C} is initialized by the Java Virtual Machine.
2011          *
2012          * <p> The newly created class or interface {@code C} serves as the
2013          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2014          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2015          * no other class or interface can refer to {@code C} via a constant pool entry.
2016          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2017          * a method parameter type, or a method return type by any other class.
2018          * This is because a hidden class or interface does not have a binary name, so
2019          * there is no internal form available to record in any class's constant pool.
2020          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2021          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2022          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2023          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2024          * JVM Tool Interface</a>.
2025          *
2026          * <p> A class or interface created by
2027          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2028          * a class loader} has a strong relationship with that class loader.
2029          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2030          * that {@linkplain Class#getClassLoader() defined it}.
2031          * This means that a class created by a class loader may be unloaded if and
2032          * only if its defining loader is not reachable and thus may be reclaimed
2033          * by a garbage collector (JLS {@jls 12.7}).
2034          *
2035          * By default, however, a hidden class or interface may be unloaded even if
2036          * the class loader that is marked as its defining loader is
2037          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2038          * This behavior is useful when a hidden class or interface serves multiple
2039          * classes defined by arbitrary class loaders.  In other cases, a hidden
2040          * class or interface may be linked to a single class (or a small number of classes)
2041          * with the same defining loader as the hidden class or interface.
2042          * In such cases, where the hidden class or interface must be coterminous
2043          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2044          * option may be passed in {@code options}.
2045          * This arranges for a hidden class to have the same strong relationship
2046          * with the class loader marked as its defining loader,
2047          * as a normal class or interface has with its own defining loader.
2048          *
2049          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2050          * may still prevent a hidden class or interface from being
2051          * unloaded by ensuring that the {@code Class} object is reachable.
2052          *
2053          * <p> The unloading characteristics are set for each hidden class when it is
2054          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2055          * to be unloaded independently of the class loader marked as their defining loader
2056          * is that a very large number of hidden classes may be created by an application.
2057          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2058          * just as if normal classes were created by class loaders.
2059          *
2060          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2061          * their private members.  The nest relationship is determined by
2062          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2063          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2064          * By default, a hidden class belongs to a nest consisting only of itself
2065          * because a hidden class has no binary name.
2066          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2067          * to create a hidden class or interface {@code C} as a member of a nest.
2068          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2069          * in the {@code ClassFile} structure from which {@code C} was derived.
2070          * Instead, the following rules determine the nest host of {@code C}:
2071          * <ul>
2072          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2073          *     been determined, then let {@code H} be the nest host of the lookup class.
2074          *     Otherwise, the nest host of the lookup class is determined using the
2075          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2076          * <li>The nest host of {@code C} is determined to be {@code H},
2077          *     the nest host of the lookup class.</li>
2078          * </ul>
2079          *
2080          * <p> A hidden class or interface may be serializable, but this requires a custom
2081          * serialization mechanism in order to ensure that instances are properly serialized
2082          * and deserialized. The default serialization mechanism supports only classes and
2083          * interfaces that are discoverable by their class name.
2084          *
2085          * @param bytes the bytes that make up the class data,
2086          * in the format of a valid {@code class} file as defined by
2087          * <cite>The Java Virtual Machine Specification</cite>.
2088          * @param initialize if {@code true} the class will be initialized.
2089          * @param options {@linkplain ClassOption class options}
2090          * @return the {@code Lookup} object on the hidden class,
2091          * with {@linkplain #ORIGINAL original} and
2092          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2093          *
2094          * @throws IllegalAccessException if this {@code Lookup} does not have
2095          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2096          * @throws SecurityException if a security manager is present and it
2097          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2098          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2099          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2100          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2101          * than the lookup class or {@code bytes} is not a class or interface
2102          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2103          * @throws IncompatibleClassChangeError if the class or interface named as
2104          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2105          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2106          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2107          * {@code C} is {@code C} itself
2108          * @throws VerifyError if the newly created class cannot be verified
2109          * @throws LinkageError if the newly created class cannot be linked for any other reason
2110          * @throws NullPointerException if any parameter is {@code null}
2111          *
2112          * @since 15
2113          * @see Class#isHidden()
2114          * @jvms 4.2.1 Binary Class and Interface Names
2115          * @jvms 4.2.2 Unqualified Names
2116          * @jvms 4.7.28 The {@code NestHost} Attribute
2117          * @jvms 4.7.29 The {@code NestMembers} Attribute
2118          * @jvms 5.4.3.1 Class and Interface Resolution
2119          * @jvms 5.4.4 Access Control
2120          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2121          * @jvms 5.4 Linking
2122          * @jvms 5.5 Initialization
2123          * @jls 12.7 Unloading of Classes and Interfaces
2124          */
2125         @SuppressWarnings("doclint:reference") // cross-module links
2126         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2127                 throws IllegalAccessException
2128         {
2129             Objects.requireNonNull(bytes);
2130             Objects.requireNonNull(options);
2131 
2132             ensureDefineClassPermission();
2133             if (!hasFullPrivilegeAccess()) {
2134                 throw new IllegalAccessException(this + " does not have full privilege access");
2135             }
2136 
2137             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2138         }
2139 
2140         /**
2141          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2142          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2143          * returning a {@code Lookup} on the newly created class or interface.
2144          *
2145          * <p> This method is equivalent to calling
2146          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2147          * as if the hidden class is injected with a private static final <i>unnamed</i>
2148          * field which is initialized with the given {@code classData} at
2149          * the first instruction of the class initializer.
2150          * The newly created class is linked by the Java Virtual Machine.
2151          *
2152          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2153          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2154          * methods can be used to retrieve the {@code classData}.
2155          *
2156          * @apiNote
2157          * A framework can create a hidden class with class data with one or more
2158          * objects and load the class data as dynamically-computed constant(s)
2159          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2160          * Class data} is accessible only to the lookup object created by the newly
2161          * defined hidden class but inaccessible to other members in the same nest
2162          * (unlike private static fields that are accessible to nestmates).
2163          * Care should be taken w.r.t. mutability for example when passing
2164          * an array or other mutable structure through the class data.
2165          * Changing any value stored in the class data at runtime may lead to
2166          * unpredictable behavior.
2167          * If the class data is a {@code List}, it is good practice to make it
2168          * unmodifiable for example via {@link List#of List::of}.
2169          *
2170          * @param bytes     the class bytes
2171          * @param classData pre-initialized class data
2172          * @param initialize if {@code true} the class will be initialized.
2173          * @param options   {@linkplain ClassOption class options}
2174          * @return the {@code Lookup} object on the hidden class,
2175          * with {@linkplain #ORIGINAL original} and
2176          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2177          *
2178          * @throws IllegalAccessException if this {@code Lookup} does not have
2179          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2180          * @throws SecurityException if a security manager is present and it
2181          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2182          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2183          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2184          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2185          * than the lookup class or {@code bytes} is not a class or interface
2186          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2187          * @throws IncompatibleClassChangeError if the class or interface named as
2188          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2189          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2190          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2191          * {@code C} is {@code C} itself
2192          * @throws VerifyError if the newly created class cannot be verified
2193          * @throws LinkageError if the newly created class cannot be linked for any other reason
2194          * @throws NullPointerException if any parameter is {@code null}
2195          *
2196          * @since 16
2197          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2198          * @see Class#isHidden()
2199          * @see MethodHandles#classData(Lookup, String, Class)
2200          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2201          * @jvms 4.2.1 Binary Class and Interface Names
2202          * @jvms 4.2.2 Unqualified Names
2203          * @jvms 4.7.28 The {@code NestHost} Attribute
2204          * @jvms 4.7.29 The {@code NestMembers} Attribute
2205          * @jvms 5.4.3.1 Class and Interface Resolution
2206          * @jvms 5.4.4 Access Control
2207          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2208          * @jvms 5.4 Linking
2209          * @jvms 5.5 Initialization
2210          * @jls 12.7 Unloading of Classes and Interface
2211          */
2212         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2213                 throws IllegalAccessException
2214         {
2215             Objects.requireNonNull(bytes);
2216             Objects.requireNonNull(classData);
2217             Objects.requireNonNull(options);
2218 
2219             ensureDefineClassPermission();
2220             if (!hasFullPrivilegeAccess()) {
2221                 throw new IllegalAccessException(this + " does not have full privilege access");
2222             }
2223 
2224             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2225                        .defineClassAsLookup(initialize, classData);
2226         }
2227 
2228         static class ClassFile {
2229             final String name;
2230             final int accessFlags;
2231             final byte[] bytes;
2232             ClassFile(String name, int accessFlags, byte[] bytes) {
2233                 this.name = name;
2234                 this.accessFlags = accessFlags;
2235                 this.bytes = bytes;
2236             }
2237 
2238             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2239                 return new ClassFile(name, 0, bytes);
2240             }
2241 
2242             /**
2243              * This method checks the class file version and the structure of `this_class`.
2244              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2245              * that is in the named package.
2246              *
2247              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2248              * or the class is not in the given package name.
2249              */
2250             static ClassFile newInstance(byte[] bytes, String pkgName) {
2251                 int magic = readInt(bytes, 0);
2252                 if (magic != 0xCAFEBABE) {
2253                     throw new ClassFormatError("Incompatible magic value: " + magic);
2254                 }
2255                 int minor = readUnsignedShort(bytes, 4);
2256                 int major = readUnsignedShort(bytes, 6);
2257                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2258                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2259                 }
2260 
2261                 String name;
2262                 int accessFlags;
2263                 try {
2264                     ClassReader reader = new ClassReader(bytes);
2265                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2266                     // workaround to read `this_class` using readConst and validate the value
2267                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2268                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2269                     if (!(constant instanceof Type type)) {
2270                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2271                     }
2272                     if (!type.getDescriptor().startsWith("L")) {
2273                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2274                     }
2275                     name = type.getClassName();
2276                     accessFlags = reader.readUnsignedShort(reader.header);
2277                 } catch (RuntimeException e) {
2278                     // ASM exceptions are poorly specified
2279                     ClassFormatError cfe = new ClassFormatError();
2280                     cfe.initCause(e);
2281                     throw cfe;
2282                 }
2283 
2284                 // must be a class or interface
2285                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2286                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2287                 }
2288 
2289                 // check if it's in the named package
2290                 int index = name.lastIndexOf('.');
2291                 String pn = (index == -1) ? "" : name.substring(0, index);
2292                 if (!pn.equals(pkgName)) {
2293                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2294                 }
2295 
2296                 return new ClassFile(name, accessFlags, bytes);
2297             }
2298 
2299             private static int readInt(byte[] bytes, int offset) {
2300                 if ((offset+4) > bytes.length) {
2301                     throw new ClassFormatError("Invalid ClassFile structure");
2302                 }
2303                 return ((bytes[offset] & 0xFF) << 24)
2304                         | ((bytes[offset + 1] & 0xFF) << 16)
2305                         | ((bytes[offset + 2] & 0xFF) << 8)
2306                         | (bytes[offset + 3] & 0xFF);
2307             }
2308 
2309             private static int readUnsignedShort(byte[] bytes, int offset) {
2310                 if ((offset+2) > bytes.length) {
2311                     throw new ClassFormatError("Invalid ClassFile structure");
2312                 }
2313                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2314             }
2315         }
2316 
2317         /*
2318          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2319          * from the given bytes.
2320          *
2321          * Caller should make a defensive copy of the arguments if needed
2322          * before calling this factory method.
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         private ClassDefiner makeClassDefiner(byte[] bytes) {
2328             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2329             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2330         }
2331 
2332         /**
2333          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2334          * from the given bytes.  The name must be in the same package as the lookup class.
2335          *
2336          * Caller should make a defensive copy of the arguments if needed
2337          * before calling this factory method.
2338          *
2339          * @param bytes   class bytes
2340          * @return ClassDefiner that defines a hidden class of the given bytes.
2341          *
2342          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2343          * {@bytes} denotes a class in a different package than the lookup class
2344          */
2345         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2346             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2347             return makeHiddenClassDefiner(cf, Set.of(), false);
2348         }
2349 
2350         /**
2351          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2352          * from the given bytes and options.
2353          * The name must be in the same package as the lookup class.
2354          *
2355          * Caller should make a defensive copy of the arguments if needed
2356          * before calling this factory method.
2357          *
2358          * @param bytes   class bytes
2359          * @param options class options
2360          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2361          * @return ClassDefiner that defines a hidden class of the given bytes and options
2362          *
2363          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2364          * {@bytes} denotes a class in a different package than the lookup class
2365          */
2366         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2367                                             Set<ClassOption> options,
2368                                             boolean accessVmAnnotations) {
2369             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2370             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2371         }
2372 
2373         /**
2374          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2375          * from the given bytes and the given options.  No package name check on the given name.
2376          *
2377          * @param name    fully-qualified name that specifies the prefix of the hidden class
2378          * @param bytes   class bytes
2379          * @param options class options
2380          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2381          */
2382         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) {
2383             // skip name and access flags validation
2384             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false);
2385         }
2386 
2387         /**
2388          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2389          * from the given class file and options.
2390          *
2391          * @param cf ClassFile
2392          * @param options class options
2393          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2394          */
2395         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2396                                                     Set<ClassOption> options,
2397                                                     boolean accessVmAnnotations) {
2398             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2399             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2400                 // jdk.internal.vm.annotations are permitted for classes
2401                 // defined to boot loader and platform loader
2402                 flags |= ACCESS_VM_ANNOTATIONS;
2403             }
2404 
2405             return new ClassDefiner(this, cf, flags);
2406         }
2407 
2408         static class ClassDefiner {
2409             private final Lookup lookup;
2410             private final String name;
2411             private final byte[] bytes;
2412             private final int classFlags;
2413 
2414             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2415                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2416                 this.lookup = lookup;
2417                 this.bytes = cf.bytes;
2418                 this.name = cf.name;
2419                 this.classFlags = flags;
2420             }
2421 
2422             String className() {
2423                 return name;
2424             }
2425 
2426             Class<?> defineClass(boolean initialize) {
2427                 return defineClass(initialize, null);
2428             }
2429 
2430             Lookup defineClassAsLookup(boolean initialize) {
2431                 Class<?> c = defineClass(initialize, null);
2432                 return new Lookup(c, null, FULL_POWER_MODES);
2433             }
2434 
2435             /**
2436              * Defines the class of the given bytes and the given classData.
2437              * If {@code initialize} parameter is true, then the class will be initialized.
2438              *
2439              * @param initialize true if the class to be initialized
2440              * @param classData classData or null
2441              * @return the class
2442              *
2443              * @throws LinkageError linkage error
2444              */
2445             Class<?> defineClass(boolean initialize, Object classData) {
2446                 Class<?> lookupClass = lookup.lookupClass();
2447                 ClassLoader loader = lookupClass.getClassLoader();
2448                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2449                 Class<?> c = SharedSecrets.getJavaLangAccess()
2450                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2451                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2452                 return c;
2453             }
2454 
2455             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2456                 Class<?> c = defineClass(initialize, classData);
2457                 return new Lookup(c, null, FULL_POWER_MODES);
2458             }
2459 
2460             private boolean isNestmate() {
2461                 return (classFlags & NESTMATE_CLASS) != 0;
2462             }
2463         }
2464 
2465         private ProtectionDomain lookupClassProtectionDomain() {
2466             ProtectionDomain pd = cachedProtectionDomain;
2467             if (pd == null) {
2468                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2469             }
2470             return pd;
2471         }
2472 
2473         // cached protection domain
2474         private volatile ProtectionDomain cachedProtectionDomain;
2475 
2476         // Make sure outer class is initialized first.
2477         static { IMPL_NAMES.getClass(); }
2478 
2479         /** Package-private version of lookup which is trusted. */
2480         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2481 
2482         /** Version of lookup which is trusted minimally.
2483          *  It can only be used to create method handles to publicly accessible
2484          *  members in packages that are exported unconditionally.
2485          */
2486         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2487 
2488         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2489             String name = lookupClass.getName();
2490             if (name.startsWith("java.lang.invoke."))
2491                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2492         }
2493 
2494         /**
2495          * Displays the name of the class from which lookups are to be made,
2496          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2497          * previous lookup class} if present.
2498          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2499          * If there are restrictions on the access permitted to this lookup,
2500          * this is indicated by adding a suffix to the class name, consisting
2501          * of a slash and a keyword.  The keyword represents the strongest
2502          * allowed access, and is chosen as follows:
2503          * <ul>
2504          * <li>If no access is allowed, the suffix is "/noaccess".
2505          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2506          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2507          * <li>If only public and module access are allowed, the suffix is "/module".
2508          * <li>If public and package access are allowed, the suffix is "/package".
2509          * <li>If public, package, and private access are allowed, the suffix is "/private".
2510          * </ul>
2511          * If none of the above cases apply, it is the case that
2512          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2513          * (public, module, package, private, and protected) is allowed.
2514          * In this case, no suffix is added.
2515          * This is true only of an object obtained originally from
2516          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2517          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2518          * always have restricted access, and will display a suffix.
2519          * <p>
2520          * (It may seem strange that protected access should be
2521          * stronger than private access.  Viewed independently from
2522          * package access, protected access is the first to be lost,
2523          * because it requires a direct subclass relationship between
2524          * caller and callee.)
2525          * @see #in
2526          *
2527          * @revised 9
2528          */
2529         @Override
2530         public String toString() {
2531             String cname = lookupClass.getName();
2532             if (prevLookupClass != null)
2533                 cname += "/" + prevLookupClass.getName();
2534             switch (allowedModes) {
2535             case 0:  // no privileges
2536                 return cname + "/noaccess";
2537             case UNCONDITIONAL:
2538                 return cname + "/publicLookup";
2539             case PUBLIC:
2540                 return cname + "/public";
2541             case PUBLIC|MODULE:
2542                 return cname + "/module";
2543             case PUBLIC|PACKAGE:
2544             case PUBLIC|MODULE|PACKAGE:
2545                 return cname + "/package";
2546             case PUBLIC|PACKAGE|PRIVATE:
2547             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2548                     return cname + "/private";
2549             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2550             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2551             case FULL_POWER_MODES:
2552                     return cname;
2553             case TRUSTED:
2554                 return "/trusted";  // internal only; not exported
2555             default:  // Should not happen, but it's a bitfield...
2556                 cname = cname + "/" + Integer.toHexString(allowedModes);
2557                 assert(false) : cname;
2558                 return cname;
2559             }
2560         }
2561 
2562         /**
2563          * Produces a method handle for a static method.
2564          * The type of the method handle will be that of the method.
2565          * (Since static methods do not take receivers, there is no
2566          * additional receiver argument inserted into the method handle type,
2567          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2568          * The method and all its argument types must be accessible to the lookup object.
2569          * <p>
2570          * The returned method handle will have
2571          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2572          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2573          * <p>
2574          * If the returned method handle is invoked, the method's class will
2575          * be initialized, if it has not already been initialized.
2576          * <p><b>Example:</b>
2577          * {@snippet lang="java" :
2578 import static java.lang.invoke.MethodHandles.*;
2579 import static java.lang.invoke.MethodType.*;
2580 ...
2581 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2582   "asList", methodType(List.class, Object[].class));
2583 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2584          * }
2585          * @param refc the class from which the method is accessed
2586          * @param name the name of the method
2587          * @param type the type of the method
2588          * @return the desired method handle
2589          * @throws NoSuchMethodException if the method does not exist
2590          * @throws IllegalAccessException if access checking fails,
2591          *                                or if the method is not {@code static},
2592          *                                or if the method's variable arity modifier bit
2593          *                                is set and {@code asVarargsCollector} fails
2594          * @throws    SecurityException if a security manager is present and it
2595          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2596          * @throws NullPointerException if any argument is null
2597          */
2598         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2599             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2600             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2601         }
2602 
2603         /**
2604          * Produces a method handle for a virtual method.
2605          * The type of the method handle will be that of the method,
2606          * with the receiver type (usually {@code refc}) prepended.
2607          * The method and all its argument types must be accessible to the lookup object.
2608          * <p>
2609          * When called, the handle will treat the first argument as a receiver
2610          * and, for non-private methods, dispatch on the receiver's type to determine which method
2611          * implementation to enter.
2612          * For private methods the named method in {@code refc} will be invoked on the receiver.
2613          * (The dispatching action is identical with that performed by an
2614          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2615          * <p>
2616          * The first argument will be of type {@code refc} if the lookup
2617          * class has full privileges to access the member.  Otherwise
2618          * the member must be {@code protected} and the first argument
2619          * will be restricted in type to the lookup class.
2620          * <p>
2621          * The returned method handle will have
2622          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2623          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2624          * <p>
2625          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2626          * instructions and method handles produced by {@code findVirtual},
2627          * if the class is {@code MethodHandle} and the name string is
2628          * {@code invokeExact} or {@code invoke}, the resulting
2629          * method handle is equivalent to one produced by
2630          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2631          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2632          * with the same {@code type} argument.
2633          * <p>
2634          * If the class is {@code VarHandle} and the name string corresponds to
2635          * the name of a signature-polymorphic access mode method, the resulting
2636          * method handle is equivalent to one produced by
2637          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2638          * the access mode corresponding to the name string and with the same
2639          * {@code type} arguments.
2640          * <p>
2641          * <b>Example:</b>
2642          * {@snippet lang="java" :
2643 import static java.lang.invoke.MethodHandles.*;
2644 import static java.lang.invoke.MethodType.*;
2645 ...
2646 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2647   "concat", methodType(String.class, String.class));
2648 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2649   "hashCode", methodType(int.class));
2650 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2651   "hashCode", methodType(int.class));
2652 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2653 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2654 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2655 // interface method:
2656 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2657   "subSequence", methodType(CharSequence.class, int.class, int.class));
2658 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2659 // constructor "internal method" must be accessed differently:
2660 MethodType MT_newString = methodType(void.class); //()V for new String()
2661 try { assertEquals("impossible", lookup()
2662         .findVirtual(String.class, "<init>", MT_newString));
2663  } catch (NoSuchMethodException ex) { } // OK
2664 MethodHandle MH_newString = publicLookup()
2665   .findConstructor(String.class, MT_newString);
2666 assertEquals("", (String) MH_newString.invokeExact());
2667          * }
2668          *
2669          * @param refc the class or interface from which the method is accessed
2670          * @param name the name of the method
2671          * @param type the type of the method, with the receiver argument omitted
2672          * @return the desired method handle
2673          * @throws NoSuchMethodException if the method does not exist
2674          * @throws IllegalAccessException if access checking fails,
2675          *                                or if the method is {@code static},
2676          *                                or if the method's variable arity modifier bit
2677          *                                is set and {@code asVarargsCollector} fails
2678          * @throws    SecurityException if a security manager is present and it
2679          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2680          * @throws NullPointerException if any argument is null
2681          */
2682         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2683             if (refc == MethodHandle.class) {
2684                 MethodHandle mh = findVirtualForMH(name, type);
2685                 if (mh != null)  return mh;
2686             } else if (refc == VarHandle.class) {
2687                 MethodHandle mh = findVirtualForVH(name, type);
2688                 if (mh != null)  return mh;
2689             }
2690             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2691             MemberName method = resolveOrFail(refKind, refc, name, type);
2692             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2693         }
2694         private MethodHandle findVirtualForMH(String name, MethodType type) {
2695             // these names require special lookups because of the implicit MethodType argument
2696             if ("invoke".equals(name))
2697                 return invoker(type);
2698             if ("invokeExact".equals(name))
2699                 return exactInvoker(type);
2700             assert(!MemberName.isMethodHandleInvokeName(name));
2701             return null;
2702         }
2703         private MethodHandle findVirtualForVH(String name, MethodType type) {
2704             try {
2705                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2706             } catch (IllegalArgumentException e) {
2707                 return null;
2708             }
2709         }
2710 
2711         /**
2712          * Produces a method handle which creates an object and initializes it, using
2713          * the constructor of the specified type.
2714          * The parameter types of the method handle will be those of the constructor,
2715          * while the return type will be a reference to the constructor's class.
2716          * The constructor and all its argument types must be accessible to the lookup object.
2717          * <p>
2718          * The requested type must have a return type of {@code void}.
2719          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2720          * <p>
2721          * The returned method handle will have
2722          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2723          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2724          * <p>
2725          * If the returned method handle is invoked, the constructor's class will
2726          * be initialized, if it has not already been initialized.
2727          * <p><b>Example:</b>
2728          * {@snippet lang="java" :
2729 import static java.lang.invoke.MethodHandles.*;
2730 import static java.lang.invoke.MethodType.*;
2731 ...
2732 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2733   ArrayList.class, methodType(void.class, Collection.class));
2734 Collection orig = Arrays.asList("x", "y");
2735 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2736 assert(orig != copy);
2737 assertEquals(orig, copy);
2738 // a variable-arity constructor:
2739 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2740   ProcessBuilder.class, methodType(void.class, String[].class));
2741 ProcessBuilder pb = (ProcessBuilder)
2742   MH_newProcessBuilder.invoke("x", "y", "z");
2743 assertEquals("[x, y, z]", pb.command().toString());
2744          * }
2745          *
2746          *
2747          * @param refc the class or interface from which the method is accessed
2748          * @param type the type of the method, with the receiver argument omitted, and a void return type
2749          * @return the desired method handle
2750          * @throws NoSuchMethodException if the constructor does not exist
2751          * @throws IllegalAccessException if access checking fails
2752          *                                or if the method's variable arity modifier bit
2753          *                                is set and {@code asVarargsCollector} fails
2754          * @throws    SecurityException if a security manager is present and it
2755          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2756          * @throws NullPointerException if any argument is null
2757          */
2758         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2759             if (refc.isArray()) {
2760                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2761             }
2762             if (type.returnType() != void.class) {
2763                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2764             }
2765             String name = "<init>";
2766             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2767             return getDirectConstructor(refc, ctor);
2768         }
2769 
2770         /**
2771          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2772          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2773          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2774          * and then determines whether the class is accessible to this lookup object.
2775          * <p>
2776          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2777          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2778          *
2779          * @param targetName the fully qualified name of the class to be looked up.
2780          * @return the requested class.
2781          * @throws SecurityException if a security manager is present and it
2782          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2783          * @throws LinkageError if the linkage fails
2784          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2785          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2786          * modes.
2787          * @throws NullPointerException if {@code targetName} is null
2788          * @since 9
2789          * @jvms 5.4.3.1 Class and Interface Resolution
2790          */
2791         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2792             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2793             return accessClass(targetClass);
2794         }
2795 
2796         /**
2797          * Ensures that {@code targetClass} has been initialized. The class
2798          * to be initialized must be {@linkplain #accessClass accessible}
2799          * to this {@code Lookup} object.  This method causes {@code targetClass}
2800          * to be initialized if it has not been already initialized,
2801          * as specified in JVMS {@jvms 5.5}.
2802          *
2803          * <p>
2804          * This method returns when {@code targetClass} is fully initialized, or
2805          * when {@code targetClass} is being initialized by the current thread.
2806          *
2807          * @param targetClass the class to be initialized
2808          * @return {@code targetClass} that has been initialized, or that is being
2809          *         initialized by the current thread.
2810          *
2811          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2812          *          or array class
2813          * @throws  IllegalAccessException if {@code targetClass} is not
2814          *          {@linkplain #accessClass accessible} to this lookup
2815          * @throws  ExceptionInInitializerError if the class initialization provoked
2816          *          by this method fails
2817          * @throws  SecurityException if a security manager is present and it
2818          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2819          * @since 15
2820          * @jvms 5.5 Initialization
2821          */
2822         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2823             if (targetClass.isPrimitive())
2824                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2825             if (targetClass.isArray())
2826                 throw new IllegalArgumentException(targetClass + " is an array class");
2827 
2828             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2829                 throw makeAccessException(targetClass);
2830             }
2831             checkSecurityManager(targetClass);
2832 
2833             // ensure class initialization
2834             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2835             return targetClass;
2836         }
2837 
2838         /*
2839          * Returns IllegalAccessException due to access violation to the given targetClass.
2840          *
2841          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2842          * which verifies access to a class rather a member.
2843          */
2844         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2845             String message = "access violation: "+ targetClass;
2846             if (this == MethodHandles.publicLookup()) {
2847                 message += ", from public Lookup";
2848             } else {
2849                 Module m = lookupClass().getModule();
2850                 message += ", from " + lookupClass() + " (" + m + ")";
2851                 if (prevLookupClass != null) {
2852                     message += ", previous lookup " +
2853                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2854                 }
2855             }
2856             return new IllegalAccessException(message);
2857         }
2858 
2859         /**
2860          * Determines if a class can be accessed from the lookup context defined by
2861          * this {@code Lookup} object. The static initializer of the class is not run.
2862          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2863          * if the element type of the array class is accessible.  Otherwise,
2864          * {@code targetClass} is determined as accessible as follows.
2865          *
2866          * <p>
2867          * If {@code targetClass} is in the same module as the lookup class,
2868          * the lookup class is {@code LC} in module {@code M1} and
2869          * the previous lookup class is in module {@code M0} or
2870          * {@code null} if not present,
2871          * {@code targetClass} is accessible if and only if one of the following is true:
2872          * <ul>
2873          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2874          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2875          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2876          *     in the same runtime package of {@code LC}.</li>
2877          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2878          *     a public type in {@code M1}.</li>
2879          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2880          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2881          *     if the previous lookup class is present; otherwise, {@code targetClass}
2882          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2883          * </ul>
2884          *
2885          * <p>
2886          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2887          * can access public types in all modules when the type is in a package
2888          * that is exported unconditionally.
2889          * <p>
2890          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2891          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2892          * is inaccessible.
2893          * <p>
2894          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2895          * {@code M1} is the module containing {@code lookupClass} and
2896          * {@code M2} is the module containing {@code targetClass},
2897          * then {@code targetClass} is accessible if and only if
2898          * <ul>
2899          * <li>{@code M1} reads {@code M2}, and
2900          * <li>{@code targetClass} is public and in a package exported by
2901          *     {@code M2} at least to {@code M1}.
2902          * </ul>
2903          * <p>
2904          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2905          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2906          * containing the previous lookup class, then {@code targetClass} is accessible
2907          * if and only if one of the following is true:
2908          * <ul>
2909          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2910          *     {@linkplain Module#reads reads} {@code M0} and the type is
2911          *     in a package that is exported to at least {@code M1}.
2912          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2913          *     {@linkplain Module#reads reads} {@code M1} and the type is
2914          *     in a package that is exported to at least {@code M0}.
2915          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2916          *     and {@code M1} reads {@code M2} and the type is in a package
2917          *     that is exported to at least both {@code M0} and {@code M2}.
2918          * </ul>
2919          * <p>
2920          * Otherwise, {@code targetClass} is not accessible.
2921          *
2922          * @param targetClass the class to be access-checked
2923          * @return the class that has been access-checked
2924          * @throws IllegalAccessException if the class is not accessible from the lookup class
2925          * and previous lookup class, if present, using the allowed access modes.
2926          * @throws SecurityException if a security manager is present and it
2927          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2928          * @throws NullPointerException if {@code targetClass} is {@code null}
2929          * @since 9
2930          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2931          */
2932         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2933             if (!isClassAccessible(targetClass)) {
2934                 throw makeAccessException(targetClass);
2935             }
2936             checkSecurityManager(targetClass);
2937             return targetClass;
2938         }
2939 
2940         /**
2941          * Produces an early-bound method handle for a virtual method.
2942          * It will bypass checks for overriding methods on the receiver,
2943          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2944          * instruction from within the explicitly specified {@code specialCaller}.
2945          * The type of the method handle will be that of the method,
2946          * with a suitably restricted receiver type prepended.
2947          * (The receiver type will be {@code specialCaller} or a subtype.)
2948          * The method and all its argument types must be accessible
2949          * to the lookup object.
2950          * <p>
2951          * Before method resolution,
2952          * if the explicitly specified caller class is not identical with the
2953          * lookup class, or if this lookup object does not have
2954          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2955          * privileges, the access fails.
2956          * <p>
2957          * The returned method handle will have
2958          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2959          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2960          * <p style="font-size:smaller;">
2961          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2962          * even though the {@code invokespecial} instruction can refer to them
2963          * in special circumstances.  Use {@link #findConstructor findConstructor}
2964          * to access instance initialization methods in a safe manner.)</em>
2965          * <p><b>Example:</b>
2966          * {@snippet lang="java" :
2967 import static java.lang.invoke.MethodHandles.*;
2968 import static java.lang.invoke.MethodType.*;
2969 ...
2970 static class Listie extends ArrayList {
2971   public String toString() { return "[wee Listie]"; }
2972   static Lookup lookup() { return MethodHandles.lookup(); }
2973 }
2974 ...
2975 // no access to constructor via invokeSpecial:
2976 MethodHandle MH_newListie = Listie.lookup()
2977   .findConstructor(Listie.class, methodType(void.class));
2978 Listie l = (Listie) MH_newListie.invokeExact();
2979 try { assertEquals("impossible", Listie.lookup().findSpecial(
2980         Listie.class, "<init>", methodType(void.class), Listie.class));
2981  } catch (NoSuchMethodException ex) { } // OK
2982 // access to super and self methods via invokeSpecial:
2983 MethodHandle MH_super = Listie.lookup().findSpecial(
2984   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2985 MethodHandle MH_this = Listie.lookup().findSpecial(
2986   Listie.class, "toString" , methodType(String.class), Listie.class);
2987 MethodHandle MH_duper = Listie.lookup().findSpecial(
2988   Object.class, "toString" , methodType(String.class), Listie.class);
2989 assertEquals("[]", (String) MH_super.invokeExact(l));
2990 assertEquals(""+l, (String) MH_this.invokeExact(l));
2991 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2992 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2993         String.class, "toString", methodType(String.class), Listie.class));
2994  } catch (IllegalAccessException ex) { } // OK
2995 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2996 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2997          * }
2998          *
2999          * @param refc the class or interface from which the method is accessed
3000          * @param name the name of the method (which must not be "&lt;init&gt;")
3001          * @param type the type of the method, with the receiver argument omitted
3002          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3003          * @return the desired method handle
3004          * @throws NoSuchMethodException if the method does not exist
3005          * @throws IllegalAccessException if access checking fails,
3006          *                                or if the method is {@code static},
3007          *                                or if the method's variable arity modifier bit
3008          *                                is set and {@code asVarargsCollector} fails
3009          * @throws    SecurityException if a security manager is present and it
3010          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3011          * @throws NullPointerException if any argument is null
3012          */
3013         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3014                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3015             checkSpecialCaller(specialCaller, refc);
3016             Lookup specialLookup = this.in(specialCaller);
3017             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3018             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3019         }
3020 
3021         /**
3022          * Produces a method handle giving read access to a non-static field.
3023          * The type of the method handle will have a return type of the field's
3024          * value type.
3025          * The method handle's single argument will be the instance containing
3026          * the field.
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 load values from 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          * @throws    SecurityException if a security manager is present and it
3035          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3036          * @throws NullPointerException if any argument is null
3037          * @see #findVarHandle(Class, String, Class)
3038          */
3039         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3040             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3041             return getDirectField(REF_getField, refc, field);
3042         }
3043 
3044         /**
3045          * Produces a method handle giving write access to a non-static field.
3046          * The type of the method handle will have a void return type.
3047          * The method handle will take two arguments, the instance containing
3048          * the field, and the value to be stored.
3049          * The second argument will be of the field's value type.
3050          * Access checking is performed immediately on behalf of the lookup class.
3051          * @param refc the class or interface from which the method is accessed
3052          * @param name the field's name
3053          * @param type the field's type
3054          * @return a method handle which can store values into the field
3055          * @throws NoSuchFieldException if the field does not exist
3056          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3057          *                                or {@code final}
3058          * @throws    SecurityException if a security manager is present and it
3059          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3060          * @throws NullPointerException if any argument is null
3061          * @see #findVarHandle(Class, String, Class)
3062          */
3063         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3064             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3065             return getDirectField(REF_putField, refc, field);
3066         }
3067 
3068         /**
3069          * Produces a VarHandle giving access to a non-static field {@code name}
3070          * of type {@code type} declared in a class of type {@code recv}.
3071          * The VarHandle's variable type is {@code type} and it has one
3072          * coordinate type, {@code recv}.
3073          * <p>
3074          * Access checking is performed immediately on behalf of the lookup
3075          * class.
3076          * <p>
3077          * Certain access modes of the returned VarHandle are unsupported under
3078          * the following conditions:
3079          * <ul>
3080          * <li>if the field is declared {@code final}, then the write, atomic
3081          *     update, numeric atomic update, and bitwise atomic update access
3082          *     modes are unsupported.
3083          * <li>if the field type is anything other than {@code byte},
3084          *     {@code short}, {@code char}, {@code int}, {@code long},
3085          *     {@code float}, or {@code double} then numeric atomic update
3086          *     access modes are unsupported.
3087          * <li>if the field type is anything other than {@code boolean},
3088          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3089          *     {@code long} then bitwise atomic update access modes are
3090          *     unsupported.
3091          * </ul>
3092          * <p>
3093          * If the field is declared {@code volatile} then the returned VarHandle
3094          * will override access to the field (effectively ignore the
3095          * {@code volatile} declaration) in accordance to its specified
3096          * access modes.
3097          * <p>
3098          * If the field type is {@code float} or {@code double} then numeric
3099          * and atomic update access modes compare values using their bitwise
3100          * representation (see {@link Float#floatToRawIntBits} and
3101          * {@link Double#doubleToRawLongBits}, respectively).
3102          * @apiNote
3103          * Bitwise comparison of {@code float} values or {@code double} values,
3104          * as performed by the numeric and atomic update access modes, differ
3105          * from the primitive {@code ==} operator and the {@link Float#equals}
3106          * and {@link Double#equals} methods, specifically with respect to
3107          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3108          * Care should be taken when performing a compare and set or a compare
3109          * and exchange operation with such values since the operation may
3110          * unexpectedly fail.
3111          * There are many possible NaN values that are considered to be
3112          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3113          * provided by Java can distinguish between them.  Operation failure can
3114          * occur if the expected or witness value is a NaN value and it is
3115          * transformed (perhaps in a platform specific manner) into another NaN
3116          * value, and thus has a different bitwise representation (see
3117          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3118          * details).
3119          * The values {@code -0.0} and {@code +0.0} have different bitwise
3120          * representations but are considered equal when using the primitive
3121          * {@code ==} operator.  Operation failure can occur if, for example, a
3122          * numeric algorithm computes an expected value to be say {@code -0.0}
3123          * and previously computed the witness value to be say {@code +0.0}.
3124          * @param recv the receiver class, of type {@code R}, that declares the
3125          * non-static field
3126          * @param name the field's name
3127          * @param type the field's type, of type {@code T}
3128          * @return a VarHandle giving access to non-static fields.
3129          * @throws NoSuchFieldException if the field does not exist
3130          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3131          * @throws    SecurityException if a security manager is present and it
3132          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3133          * @throws NullPointerException if any argument is null
3134          * @since 9
3135          */
3136         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3137             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3138             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3139             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3140         }
3141 
3142         /**
3143          * Produces a method handle giving read access to a static field.
3144          * The type of the method handle will have a return type of the field's
3145          * value type.
3146          * The method handle will take no arguments.
3147          * Access checking is performed immediately on behalf of the lookup class.
3148          * <p>
3149          * If the returned method handle is invoked, the field's class will
3150          * be initialized, if it has not already been initialized.
3151          * @param refc the class or interface from which the method is accessed
3152          * @param name the field's name
3153          * @param type the field's type
3154          * @return a method handle which can load values from the field
3155          * @throws NoSuchFieldException if the field does not exist
3156          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3157          * @throws    SecurityException if a security manager is present and it
3158          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3159          * @throws NullPointerException if any argument is null
3160          */
3161         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3162             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3163             return getDirectField(REF_getStatic, refc, field);
3164         }
3165 
3166         /**
3167          * Produces a method handle giving write access to a static field.
3168          * The type of the method handle will have a void return type.
3169          * The method handle will take a single
3170          * argument, of the field's value type, the value to be stored.
3171          * Access checking is performed immediately on behalf of the lookup class.
3172          * <p>
3173          * If the returned method handle is invoked, the field's class will
3174          * be initialized, if it has not already been initialized.
3175          * @param refc the class or interface from which the method is accessed
3176          * @param name the field's name
3177          * @param type the field's type
3178          * @return a method handle which can store values into the field
3179          * @throws NoSuchFieldException if the field does not exist
3180          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3181          *                                or is {@code final}
3182          * @throws    SecurityException if a security manager is present and it
3183          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3184          * @throws NullPointerException if any argument is null
3185          */
3186         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3187             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3188             return getDirectField(REF_putStatic, refc, field);
3189         }
3190 
3191         /**
3192          * Produces a VarHandle giving access to a static field {@code name} of
3193          * type {@code type} declared in a class of type {@code decl}.
3194          * The VarHandle's variable type is {@code type} and it has no
3195          * coordinate types.
3196          * <p>
3197          * Access checking is performed immediately on behalf of the lookup
3198          * class.
3199          * <p>
3200          * If the returned VarHandle is operated on, the declaring class will be
3201          * initialized, if it has not already been initialized.
3202          * <p>
3203          * Certain access modes of the returned VarHandle are unsupported under
3204          * the following conditions:
3205          * <ul>
3206          * <li>if the field is declared {@code final}, then the write, atomic
3207          *     update, numeric atomic update, and bitwise atomic update access
3208          *     modes are unsupported.
3209          * <li>if the field type is anything other than {@code byte},
3210          *     {@code short}, {@code char}, {@code int}, {@code long},
3211          *     {@code float}, or {@code double}, then numeric atomic update
3212          *     access modes are unsupported.
3213          * <li>if the field type is anything other than {@code boolean},
3214          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3215          *     {@code long} then bitwise atomic update access modes are
3216          *     unsupported.
3217          * </ul>
3218          * <p>
3219          * If the field is declared {@code volatile} then the returned VarHandle
3220          * will override access to the field (effectively ignore the
3221          * {@code volatile} declaration) in accordance to its specified
3222          * access modes.
3223          * <p>
3224          * If the field type is {@code float} or {@code double} then numeric
3225          * and atomic update access modes compare values using their bitwise
3226          * representation (see {@link Float#floatToRawIntBits} and
3227          * {@link Double#doubleToRawLongBits}, respectively).
3228          * @apiNote
3229          * Bitwise comparison of {@code float} values or {@code double} values,
3230          * as performed by the numeric and atomic update access modes, differ
3231          * from the primitive {@code ==} operator and the {@link Float#equals}
3232          * and {@link Double#equals} methods, specifically with respect to
3233          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3234          * Care should be taken when performing a compare and set or a compare
3235          * and exchange operation with such values since the operation may
3236          * unexpectedly fail.
3237          * There are many possible NaN values that are considered to be
3238          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3239          * provided by Java can distinguish between them.  Operation failure can
3240          * occur if the expected or witness value is a NaN value and it is
3241          * transformed (perhaps in a platform specific manner) into another NaN
3242          * value, and thus has a different bitwise representation (see
3243          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3244          * details).
3245          * The values {@code -0.0} and {@code +0.0} have different bitwise
3246          * representations but are considered equal when using the primitive
3247          * {@code ==} operator.  Operation failure can occur if, for example, a
3248          * numeric algorithm computes an expected value to be say {@code -0.0}
3249          * and previously computed the witness value to be say {@code +0.0}.
3250          * @param decl the class that declares the static field
3251          * @param name the field's name
3252          * @param type the field's type, of type {@code T}
3253          * @return a VarHandle giving access to a static field
3254          * @throws NoSuchFieldException if the field does not exist
3255          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3256          * @throws    SecurityException if a security manager is present and it
3257          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3258          * @throws NullPointerException if any argument is null
3259          * @since 9
3260          */
3261         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3262             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3263             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3264             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3265         }
3266 
3267         /**
3268          * Produces an early-bound method handle for a non-static method.
3269          * The receiver must have a supertype {@code defc} in which a method
3270          * of the given name and type is accessible to the lookup class.
3271          * The method and all its argument types must be accessible to the lookup object.
3272          * The type of the method handle will be that of the method,
3273          * without any insertion of an additional receiver parameter.
3274          * The given receiver will be bound into the method handle,
3275          * so that every call to the method handle will invoke the
3276          * requested method on the given receiver.
3277          * <p>
3278          * The returned method handle will have
3279          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3280          * the method's variable arity modifier bit ({@code 0x0080}) is set
3281          * <em>and</em> the trailing array argument is not the only argument.
3282          * (If the trailing array argument is the only argument,
3283          * the given receiver value will be bound to it.)
3284          * <p>
3285          * This is almost equivalent to the following code, with some differences noted below:
3286          * {@snippet lang="java" :
3287 import static java.lang.invoke.MethodHandles.*;
3288 import static java.lang.invoke.MethodType.*;
3289 ...
3290 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3291 MethodHandle mh1 = mh0.bindTo(receiver);
3292 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3293 return mh1;
3294          * }
3295          * where {@code defc} is either {@code receiver.getClass()} or a super
3296          * type of that class, in which the requested method is accessible
3297          * to the lookup class.
3298          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3299          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3300          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3301          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3302          * @param receiver the object from which the method is accessed
3303          * @param name the name of the method
3304          * @param type the type of the method, with the receiver argument omitted
3305          * @return the desired method handle
3306          * @throws NoSuchMethodException if the method does not exist
3307          * @throws IllegalAccessException if access checking fails
3308          *                                or if the method's variable arity modifier bit
3309          *                                is set and {@code asVarargsCollector} fails
3310          * @throws    SecurityException if a security manager is present and it
3311          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3312          * @throws NullPointerException if any argument is null
3313          * @see MethodHandle#bindTo
3314          * @see #findVirtual
3315          */
3316         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3317             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3318             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3319             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3320             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3321                 throw new IllegalAccessException("The restricted defining class " +
3322                                                  mh.type().leadingReferenceParameter().getName() +
3323                                                  " is not assignable from receiver class " +
3324                                                  receiver.getClass().getName());
3325             }
3326             return mh.bindArgumentL(0, receiver).setVarargs(method);
3327         }
3328 
3329         /**
3330          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3331          * to <i>m</i>, if the lookup class has permission.
3332          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3333          * If <i>m</i> is virtual, overriding is respected on every call.
3334          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3335          * The type of the method handle will be that of the method,
3336          * with the receiver type prepended (but only if it is non-static).
3337          * If the method's {@code accessible} flag is not set,
3338          * access checking is performed immediately on behalf of the lookup class.
3339          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3340          * <p>
3341          * The returned method handle will have
3342          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3343          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3344          * <p>
3345          * If <i>m</i> is static, and
3346          * if the returned method handle is invoked, the method's class will
3347          * be initialized, if it has not already been initialized.
3348          * @param m the reflected method
3349          * @return a method handle which can invoke the reflected method
3350          * @throws IllegalAccessException if access checking fails
3351          *                                or if the method's variable arity modifier bit
3352          *                                is set and {@code asVarargsCollector} fails
3353          * @throws NullPointerException if the argument is null
3354          */
3355         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3356             if (m.getDeclaringClass() == MethodHandle.class) {
3357                 MethodHandle mh = unreflectForMH(m);
3358                 if (mh != null)  return mh;
3359             }
3360             if (m.getDeclaringClass() == VarHandle.class) {
3361                 MethodHandle mh = unreflectForVH(m);
3362                 if (mh != null)  return mh;
3363             }
3364             MemberName method = new MemberName(m);
3365             byte refKind = method.getReferenceKind();
3366             if (refKind == REF_invokeSpecial)
3367                 refKind = REF_invokeVirtual;
3368             assert(method.isMethod());
3369             @SuppressWarnings("deprecation")
3370             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3371             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3372         }
3373         private MethodHandle unreflectForMH(Method m) {
3374             // these names require special lookups because they throw UnsupportedOperationException
3375             if (MemberName.isMethodHandleInvokeName(m.getName()))
3376                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3377             return null;
3378         }
3379         private MethodHandle unreflectForVH(Method m) {
3380             // these names require special lookups because they throw UnsupportedOperationException
3381             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3382                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3383             return null;
3384         }
3385 
3386         /**
3387          * Produces a method handle for a reflected method.
3388          * It will bypass checks for overriding methods on the receiver,
3389          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3390          * instruction from within the explicitly specified {@code specialCaller}.
3391          * The type of the method handle will be that of the method,
3392          * with a suitably restricted receiver type prepended.
3393          * (The receiver type will be {@code specialCaller} or a subtype.)
3394          * If the method's {@code accessible} flag is not set,
3395          * access checking is performed immediately on behalf of the lookup class,
3396          * as if {@code invokespecial} instruction were being linked.
3397          * <p>
3398          * Before method resolution,
3399          * if the explicitly specified caller class is not identical with the
3400          * lookup class, or if this lookup object does not have
3401          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3402          * privileges, the access fails.
3403          * <p>
3404          * The returned method handle will have
3405          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3406          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3407          * @param m the reflected method
3408          * @param specialCaller the class nominally calling the method
3409          * @return a method handle which can invoke the reflected method
3410          * @throws IllegalAccessException if access checking fails,
3411          *                                or if the method is {@code static},
3412          *                                or if the method's variable arity modifier bit
3413          *                                is set and {@code asVarargsCollector} fails
3414          * @throws NullPointerException if any argument is null
3415          */
3416         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3417             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3418             Lookup specialLookup = this.in(specialCaller);
3419             MemberName method = new MemberName(m, true);
3420             assert(method.isMethod());
3421             // ignore m.isAccessible:  this is a new kind of access
3422             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3423         }
3424 
3425         /**
3426          * Produces a method handle for a reflected constructor.
3427          * The type of the method handle will be that of the constructor,
3428          * with the return type changed to the declaring class.
3429          * The method handle will perform a {@code newInstance} operation,
3430          * creating a new instance of the constructor's class on the
3431          * arguments passed to the method handle.
3432          * <p>
3433          * If the constructor's {@code accessible} flag is not set,
3434          * access checking is performed immediately on behalf of the lookup class.
3435          * <p>
3436          * The returned method handle will have
3437          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3438          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3439          * <p>
3440          * If the returned method handle is invoked, the constructor's class will
3441          * be initialized, if it has not already been initialized.
3442          * @param c the reflected constructor
3443          * @return a method handle which can invoke the reflected constructor
3444          * @throws IllegalAccessException if access checking fails
3445          *                                or if the method's variable arity modifier bit
3446          *                                is set and {@code asVarargsCollector} fails
3447          * @throws NullPointerException if the argument is null
3448          */
3449         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3450             MemberName ctor = new MemberName(c);
3451             assert(ctor.isObjectConstructor() || ctor.isStaticValueFactoryMethod());
3452             @SuppressWarnings("deprecation")
3453             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3454             Class<?> defc = c.getDeclaringClass();
3455             if (ctor.isObjectConstructor()) {
3456                 assert(ctor.getMethodType().returnType() == void.class);
3457                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3458             } else {
3459                 // static init factory is a static method
3460                 assert(ctor.isMethod() && ctor.getMethodType().returnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3461                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3462                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3463             }
3464         }
3465 
3466         /**
3467          * Produces a method handle giving read access to a reflected field.
3468          * The type of the method handle will have a return type of the field's
3469          * value type.
3470          * If the field is {@code static}, the method handle will take no arguments.
3471          * Otherwise, its single argument will be the instance containing
3472          * the field.
3473          * If the {@code Field} object's {@code accessible} flag is not set,
3474          * access checking is performed immediately on behalf of the lookup class.
3475          * <p>
3476          * If the field is static, and
3477          * if the returned method handle is invoked, the field's class will
3478          * be initialized, if it has not already been initialized.
3479          * @param f the reflected field
3480          * @return a method handle which can load values from the reflected field
3481          * @throws IllegalAccessException if access checking fails
3482          * @throws NullPointerException if the argument is null
3483          */
3484         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3485             return unreflectField(f, false);
3486         }
3487 
3488         /**
3489          * Produces a method handle giving write access to a reflected field.
3490          * The type of the method handle will have a void return type.
3491          * If the field is {@code static}, the method handle will take a single
3492          * argument, of the field's value type, the value to be stored.
3493          * Otherwise, the two arguments will be the instance containing
3494          * the field, and the value to be stored.
3495          * If the {@code Field} object's {@code accessible} flag is not set,
3496          * access checking is performed immediately on behalf of the lookup class.
3497          * <p>
3498          * If the field is {@code final}, write access will not be
3499          * allowed and access checking will fail, except under certain
3500          * narrow circumstances documented for {@link Field#set Field.set}.
3501          * A method handle is returned only if a corresponding call to
3502          * the {@code Field} object's {@code set} method could return
3503          * normally.  In particular, fields which are both {@code static}
3504          * and {@code final} may never be set.
3505          * <p>
3506          * If the field is {@code static}, and
3507          * if the returned method handle is invoked, the field's class will
3508          * be initialized, if it has not already been initialized.
3509          * @param f the reflected field
3510          * @return a method handle which can store values into the reflected field
3511          * @throws IllegalAccessException if access checking fails,
3512          *         or if the field is {@code final} and write access
3513          *         is not enabled on the {@code Field} object
3514          * @throws NullPointerException if the argument is null
3515          */
3516         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3517             return unreflectField(f, true);
3518         }
3519 
3520         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3521             MemberName field = new MemberName(f, isSetter);
3522             if (isSetter && field.isFinal()) {
3523                 if (field.isTrustedFinalField()) {
3524                     String msg = field.isStatic() ? "static final field has no write access"
3525                                                   : "final field has no write access";
3526                     throw field.makeAccessException(msg, this);
3527                 }
3528             }
3529             assert(isSetter
3530                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3531                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3532             @SuppressWarnings("deprecation")
3533             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3534             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3535         }
3536 
3537         /**
3538          * Produces a VarHandle giving access to a reflected field {@code f}
3539          * of type {@code T} declared in a class of type {@code R}.
3540          * The VarHandle's variable type is {@code T}.
3541          * If the field is non-static the VarHandle has one coordinate type,
3542          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3543          * coordinate types.
3544          * <p>
3545          * Access checking is performed immediately on behalf of the lookup
3546          * class, regardless of the value of the field's {@code accessible}
3547          * flag.
3548          * <p>
3549          * If the field is static, and if the returned VarHandle is operated
3550          * on, the field's declaring class will be initialized, if it has not
3551          * already been initialized.
3552          * <p>
3553          * Certain access modes of the returned VarHandle are unsupported under
3554          * the following conditions:
3555          * <ul>
3556          * <li>if the field is declared {@code final}, then the write, atomic
3557          *     update, numeric atomic update, and bitwise atomic update access
3558          *     modes are unsupported.
3559          * <li>if the field type is anything other than {@code byte},
3560          *     {@code short}, {@code char}, {@code int}, {@code long},
3561          *     {@code float}, or {@code double} then numeric atomic update
3562          *     access modes are unsupported.
3563          * <li>if the field type is anything other than {@code boolean},
3564          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3565          *     {@code long} then bitwise atomic update access modes are
3566          *     unsupported.
3567          * </ul>
3568          * <p>
3569          * If the field is declared {@code volatile} then the returned VarHandle
3570          * will override access to the field (effectively ignore the
3571          * {@code volatile} declaration) in accordance to its specified
3572          * access modes.
3573          * <p>
3574          * If the field type is {@code float} or {@code double} then numeric
3575          * and atomic update access modes compare values using their bitwise
3576          * representation (see {@link Float#floatToRawIntBits} and
3577          * {@link Double#doubleToRawLongBits}, respectively).
3578          * @apiNote
3579          * Bitwise comparison of {@code float} values or {@code double} values,
3580          * as performed by the numeric and atomic update access modes, differ
3581          * from the primitive {@code ==} operator and the {@link Float#equals}
3582          * and {@link Double#equals} methods, specifically with respect to
3583          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3584          * Care should be taken when performing a compare and set or a compare
3585          * and exchange operation with such values since the operation may
3586          * unexpectedly fail.
3587          * There are many possible NaN values that are considered to be
3588          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3589          * provided by Java can distinguish between them.  Operation failure can
3590          * occur if the expected or witness value is a NaN value and it is
3591          * transformed (perhaps in a platform specific manner) into another NaN
3592          * value, and thus has a different bitwise representation (see
3593          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3594          * details).
3595          * The values {@code -0.0} and {@code +0.0} have different bitwise
3596          * representations but are considered equal when using the primitive
3597          * {@code ==} operator.  Operation failure can occur if, for example, a
3598          * numeric algorithm computes an expected value to be say {@code -0.0}
3599          * and previously computed the witness value to be say {@code +0.0}.
3600          * @param f the reflected field, with a field of type {@code T}, and
3601          * a declaring class of type {@code R}
3602          * @return a VarHandle giving access to non-static fields or a static
3603          * field
3604          * @throws IllegalAccessException if access checking fails
3605          * @throws NullPointerException if the argument is null
3606          * @since 9
3607          */
3608         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3609             MemberName getField = new MemberName(f, false);
3610             MemberName putField = new MemberName(f, true);
3611             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3612                                                       f.getDeclaringClass(), getField, putField);
3613         }
3614 
3615         /**
3616          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3617          * created by this lookup object or a similar one.
3618          * Security and access checks are performed to ensure that this lookup object
3619          * is capable of reproducing the target method handle.
3620          * This means that the cracking may fail if target is a direct method handle
3621          * but was created by an unrelated lookup object.
3622          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3623          * and was created by a lookup object for a different class.
3624          * @param target a direct method handle to crack into symbolic reference components
3625          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3626          * @throws    SecurityException if a security manager is present and it
3627          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3628          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3629          * @throws    NullPointerException if the target is {@code null}
3630          * @see MethodHandleInfo
3631          * @since 1.8
3632          */
3633         public MethodHandleInfo revealDirect(MethodHandle target) {
3634             if (!target.isCrackable()) {
3635                 throw newIllegalArgumentException("not a direct method handle");
3636             }
3637             MemberName member = target.internalMemberName();
3638             Class<?> defc = member.getDeclaringClass();
3639             byte refKind = member.getReferenceKind();
3640             assert(MethodHandleNatives.refKindIsValid(refKind));
3641             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3642                 // Devirtualized method invocation is usually formally virtual.
3643                 // To avoid creating extra MemberName objects for this common case,
3644                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3645                 refKind = REF_invokeVirtual;
3646             if (refKind == REF_invokeVirtual && defc.isInterface())
3647                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3648                 refKind = REF_invokeInterface;
3649             // Check SM permissions and member access before cracking.
3650             try {
3651                 checkAccess(refKind, defc, member);
3652                 checkSecurityManager(defc, member);
3653             } catch (IllegalAccessException ex) {
3654                 throw new IllegalArgumentException(ex);
3655             }
3656             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3657                 Class<?> callerClass = target.internalCallerClass();
3658                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3659                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3660             }
3661             // Produce the handle to the results.
3662             return new InfoFromMemberName(this, member, refKind);
3663         }
3664 
3665         /// Helper methods, all package-private.
3666 
3667         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3668             checkSymbolicClass(refc);  // do this before attempting to resolve
3669             Objects.requireNonNull(name);
3670             Objects.requireNonNull(type);
3671             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3672                                             NoSuchFieldException.class);
3673         }
3674 
3675         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3676             checkSymbolicClass(refc);  // do this before attempting to resolve
3677             Objects.requireNonNull(type);
3678             checkMethodName(refKind, name);  // implicit null-check of name
3679             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3680                                             NoSuchMethodException.class);
3681         }
3682 
3683         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3684             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3685             Objects.requireNonNull(member.getName());
3686             Objects.requireNonNull(member.getType());
3687             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3688                                             ReflectiveOperationException.class);
3689         }
3690 
3691         MemberName resolveOrNull(byte refKind, MemberName member) {
3692             // do this before attempting to resolve
3693             if (!isClassAccessible(member.getDeclaringClass())) {
3694                 return null;
3695             }
3696             Objects.requireNonNull(member.getName());
3697             Objects.requireNonNull(member.getType());
3698             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3699         }
3700 
3701         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3702             // do this before attempting to resolve
3703             if (!isClassAccessible(refc)) {
3704                 return null;
3705             }
3706             Objects.requireNonNull(type);
3707             // implicit null-check of name
3708             if (isIllegalMethodName(refKind, name)) {
3709                 return null;
3710             }
3711 
3712             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3713         }
3714 
3715         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3716             if (!isClassAccessible(refc)) {
3717                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3718             }
3719         }
3720 
3721         boolean isClassAccessible(Class<?> refc) {
3722             Objects.requireNonNull(refc);
3723             Class<?> caller = lookupClassOrNull();
3724             Class<?> type = refc;
3725             while (type.isArray()) {
3726                 type = type.getComponentType();
3727             }
3728             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3729         }
3730 
3731         /*
3732          * "<init>" can only be invoked via invokespecial
3733          * "<vnew>" factory can only invoked via invokestatic
3734          */
3735         boolean isIllegalMethodName(byte refKind, String name) {
3736             if (name.startsWith("<")) {
3737                 return MemberName.VALUE_FACTORY_NAME.equals(name) ? refKind != REF_invokeStatic
3738                                                                   : refKind != REF_newInvokeSpecial;
3739             }
3740             return false;
3741         }
3742 
3743         /** Check name for an illegal leading "&lt;" character. */
3744         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3745             if (isIllegalMethodName(refKind, name)) {
3746                 throw new NoSuchMethodException("illegal method name: " + name + " " + refKind);
3747             }
3748         }
3749 
3750         /**
3751          * Find my trustable caller class if m is a caller sensitive method.
3752          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3753          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3754          */
3755         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3756             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3757                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3758                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3759             }
3760             return this;
3761         }
3762 
3763         /**
3764          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3765          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3766          *
3767          * @deprecated This method was originally designed to test {@code PRIVATE} access
3768          * that implies full privilege access but {@code MODULE} access has since become
3769          * independent of {@code PRIVATE} access.  It is recommended to call
3770          * {@link #hasFullPrivilegeAccess()} instead.
3771          * @since 9
3772          */
3773         @Deprecated(since="14")
3774         public boolean hasPrivateAccess() {
3775             return hasFullPrivilegeAccess();
3776         }
3777 
3778         /**
3779          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3780          * i.e. {@code PRIVATE} and {@code MODULE} access.
3781          * A {@code Lookup} object must have full privilege access in order to
3782          * access all members that are allowed to the
3783          * {@linkplain #lookupClass() lookup class}.
3784          *
3785          * @return {@code true} if this lookup has full privilege access.
3786          * @since 14
3787          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3788          */
3789         public boolean hasFullPrivilegeAccess() {
3790             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3791         }
3792 
3793         /**
3794          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3795          * for ensureInitialzed, findClass or accessClass.
3796          */
3797         void checkSecurityManager(Class<?> refc) {
3798             if (allowedModes == TRUSTED)  return;
3799 
3800             @SuppressWarnings("removal")
3801             SecurityManager smgr = System.getSecurityManager();
3802             if (smgr == null)  return;
3803 
3804             // Step 1:
3805             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3806             if (!fullPrivilegeLookup ||
3807                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3808                 ReflectUtil.checkPackageAccess(refc);
3809             }
3810 
3811             // Step 2b:
3812             if (!fullPrivilegeLookup) {
3813                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3814             }
3815         }
3816 
3817         /**
3818          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3819          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3820          * If this lookup object has full privilege access except original access,
3821          * then the caller class is the lookupClass.
3822          *
3823          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3824          * from the same module skips the security permission check.
3825          */
3826         void checkSecurityManager(Class<?> refc, MemberName m) {
3827             Objects.requireNonNull(refc);
3828             Objects.requireNonNull(m);
3829 
3830             if (allowedModes == TRUSTED)  return;
3831 
3832             @SuppressWarnings("removal")
3833             SecurityManager smgr = System.getSecurityManager();
3834             if (smgr == null)  return;
3835 
3836             // Step 1:
3837             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3838             if (!fullPrivilegeLookup ||
3839                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3840                 ReflectUtil.checkPackageAccess(refc);
3841             }
3842 
3843             // Step 2a:
3844             if (m.isPublic()) return;
3845             if (!fullPrivilegeLookup) {
3846                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3847             }
3848 
3849             // Step 3:
3850             Class<?> defc = m.getDeclaringClass();
3851             if (!fullPrivilegeLookup && PrimitiveClass.asPrimaryType(defc) != PrimitiveClass.asPrimaryType(refc)) {
3852                 ReflectUtil.checkPackageAccess(defc);
3853             }
3854         }
3855 
3856         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3857             boolean wantStatic = (refKind == REF_invokeStatic);
3858             String message;
3859             if (m.isObjectConstructor())
3860                 message = "expected a method, not a constructor";
3861             else if (!m.isMethod())
3862                 message = "expected a method";
3863             else if (wantStatic != m.isStatic())
3864                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3865             else
3866                 { checkAccess(refKind, refc, m); return; }
3867             throw m.makeAccessException(message, this);
3868         }
3869 
3870         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3871             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3872             String message;
3873             if (wantStatic != m.isStatic())
3874                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3875             else
3876                 { checkAccess(refKind, refc, m); return; }
3877             throw m.makeAccessException(message, this);
3878         }
3879 
3880         /** Check public/protected/private bits on the symbolic reference class and its member. */
3881         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3882             assert(m.referenceKindIsConsistentWith(refKind) &&
3883                    MethodHandleNatives.refKindIsValid(refKind) &&
3884                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3885             int allowedModes = this.allowedModes;
3886             if (allowedModes == TRUSTED)  return;
3887             int mods = m.getModifiers();
3888             if (Modifier.isProtected(mods) &&
3889                     refKind == REF_invokeVirtual &&
3890                     m.getDeclaringClass() == Object.class &&
3891                     m.getName().equals("clone") &&
3892                     refc.isArray()) {
3893                 // The JVM does this hack also.
3894                 // (See ClassVerifier::verify_invoke_instructions
3895                 // and LinkResolver::check_method_accessability.)
3896                 // Because the JVM does not allow separate methods on array types,
3897                 // there is no separate method for int[].clone.
3898                 // All arrays simply inherit Object.clone.
3899                 // But for access checking logic, we make Object.clone
3900                 // (normally protected) appear to be public.
3901                 // Later on, when the DirectMethodHandle is created,
3902                 // its leading argument will be restricted to the
3903                 // requested array type.
3904                 // N.B. The return type is not adjusted, because
3905                 // that is *not* the bytecode behavior.
3906                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3907             }
3908             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3909                 // cannot "new" a protected ctor in a different package
3910                 mods ^= Modifier.PROTECTED;
3911             }
3912             if (Modifier.isFinal(mods) &&
3913                     MethodHandleNatives.refKindIsSetter(refKind))
3914                 throw m.makeAccessException("unexpected set of a final field", this);
3915             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3916             if ((requestedModes & allowedModes) != 0) {
3917                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3918                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3919                     return;
3920             } else {
3921                 // Protected members can also be checked as if they were package-private.
3922                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3923                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3924                     return;
3925             }
3926             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3927         }
3928 
3929         String accessFailedMessage(Class<?> refc, MemberName m) {
3930             Class<?> defc = m.getDeclaringClass();
3931             int mods = m.getModifiers();
3932             // check the class first:
3933             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3934                                (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
3935                                 Modifier.isPublic(refc.getModifiers())));
3936             if (!classOK && (allowedModes & PACKAGE) != 0) {
3937                 // ignore previous lookup class to check if default package access
3938                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3939                            (PrimitiveClass.asPrimaryType(defc) == PrimitiveClass.asPrimaryType(refc) ||
3940                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3941             }
3942             if (!classOK)
3943                 return "class is not public";
3944             if (Modifier.isPublic(mods))
3945                 return "access to public member failed";  // (how?, module not readable?)
3946             if (Modifier.isPrivate(mods))
3947                 return "member is private";
3948             if (Modifier.isProtected(mods))
3949                 return "member is protected";
3950             return "member is private to package";
3951         }
3952 
3953         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3954             int allowedModes = this.allowedModes;
3955             if (allowedModes == TRUSTED)  return;
3956             if ((lookupModes() & PRIVATE) == 0
3957                 || (specialCaller != lookupClass()
3958                        // ensure non-abstract methods in superinterfaces can be special-invoked
3959                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3960                 throw new MemberName(specialCaller).
3961                     makeAccessException("no private access for invokespecial", this);
3962         }
3963 
3964         private boolean restrictProtectedReceiver(MemberName method) {
3965             // The accessing class only has the right to use a protected member
3966             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3967             if (!method.isProtected() || method.isStatic()
3968                 || allowedModes == TRUSTED
3969                 || method.getDeclaringClass() == lookupClass()
3970                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3971                 return false;
3972             return true;
3973         }
3974         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3975             assert(!method.isStatic());
3976             // receiver type of mh is too wide; narrow to caller
3977             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3978                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3979             }
3980             MethodType rawType = mh.type();
3981             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3982             MethodType narrowType = rawType.changeParameterType(0, caller);
3983             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3984             assert(mh.viewAsTypeChecks(narrowType, true));
3985             return mh.copyWith(narrowType, mh.form);
3986         }
3987 
3988         /** Check access and get the requested method. */
3989         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3990             final boolean doRestrict    = true;
3991             final boolean checkSecurity = true;
3992             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3993         }
3994         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3995         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3996             final boolean doRestrict    = false;
3997             final boolean checkSecurity = true;
3998             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3999         }
4000         /** Check access and get the requested method, eliding security manager checks. */
4001         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
4002             final boolean doRestrict    = true;
4003             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4004             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
4005         }
4006         /** Common code for all methods; do not call directly except from immediately above. */
4007         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4008                                                    boolean checkSecurity,
4009                                                    boolean doRestrict,
4010                                                    Lookup boundCaller) throws IllegalAccessException {
4011             checkMethod(refKind, refc, method);
4012             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4013             if (checkSecurity)
4014                 checkSecurityManager(refc, method);
4015             assert(!method.isMethodHandleInvoke());
4016             if (refKind == REF_invokeSpecial &&
4017                 refc != lookupClass() &&
4018                 !refc.isInterface() &&
4019                 refc != lookupClass().getSuperclass() &&
4020                 refc.isAssignableFrom(lookupClass())) {
4021                 assert(!method.getName().equals("<init>"));  // not this code path
4022 
4023                 // Per JVMS 6.5, desc. of invokespecial instruction:
4024                 // If the method is in a superclass of the LC,
4025                 // and if our original search was above LC.super,
4026                 // repeat the search (symbolic lookup) from LC.super
4027                 // and continue with the direct superclass of that class,
4028                 // and so forth, until a match is found or no further superclasses exist.
4029                 // FIXME: MemberName.resolve should handle this instead.
4030                 Class<?> refcAsSuper = lookupClass();
4031                 MemberName m2;
4032                 do {
4033                     refcAsSuper = refcAsSuper.getSuperclass();
4034                     m2 = new MemberName(refcAsSuper,
4035                                         method.getName(),
4036                                         method.getMethodType(),
4037                                         REF_invokeSpecial);
4038                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4039                 } while (m2 == null &&         // no method is found yet
4040                          refc != refcAsSuper); // search up to refc
4041                 if (m2 == null)  throw new InternalError(method.toString());
4042                 method = m2;
4043                 refc = refcAsSuper;
4044                 // redo basic checks
4045                 checkMethod(refKind, refc, method);
4046             }
4047             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4048             MethodHandle mh = dmh;
4049             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4050             if ((doRestrict && refKind == REF_invokeSpecial) ||
4051                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4052                 mh = restrictReceiver(method, dmh, lookupClass());
4053             }
4054             mh = maybeBindCaller(method, mh, boundCaller);
4055             mh = mh.setVarargs(method);
4056             return mh;
4057         }
4058         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4059                                              throws IllegalAccessException {
4060             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4061                 return mh;
4062 
4063             // boundCaller must have full privilege access.
4064             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4065             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4066                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4067 
4068             assert boundCaller.hasFullPrivilegeAccess();
4069 
4070             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4071             // Note: caller will apply varargs after this step happens.
4072             return cbmh;
4073         }
4074 
4075         /** Check access and get the requested field. */
4076         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4077             final boolean checkSecurity = true;
4078             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4079         }
4080         /** Check access and get the requested field, eliding security manager checks. */
4081         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4082             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4083             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4084         }
4085         /** Common code for all fields; do not call directly except from immediately above. */
4086         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4087                                                   boolean checkSecurity) throws IllegalAccessException {
4088             checkField(refKind, refc, field);
4089             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4090             if (checkSecurity)
4091                 checkSecurityManager(refc, field);
4092             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4093             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4094                                     restrictProtectedReceiver(field));
4095             if (doRestrict)
4096                 return restrictReceiver(field, dmh, lookupClass());
4097             return dmh;
4098         }
4099         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4100                                             Class<?> refc, MemberName getField, MemberName putField)
4101                 throws IllegalAccessException {
4102             final boolean checkSecurity = true;
4103             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4104         }
4105         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4106                                                              Class<?> refc, MemberName getField, MemberName putField)
4107                 throws IllegalAccessException {
4108             final boolean checkSecurity = false;
4109             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4110         }
4111         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4112                                                   Class<?> refc, MemberName getField, MemberName putField,
4113                                                   boolean checkSecurity) throws IllegalAccessException {
4114             assert getField.isStatic() == putField.isStatic();
4115             assert getField.isGetter() && putField.isSetter();
4116             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4117             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4118 
4119             checkField(getRefKind, refc, getField);
4120             if (checkSecurity)
4121                 checkSecurityManager(refc, getField);
4122 
4123             if (!putField.isFinal()) {
4124                 // A VarHandle does not support updates to final fields, any
4125                 // such VarHandle to a final field will be read-only and
4126                 // therefore the following write-based accessibility checks are
4127                 // only required for non-final fields
4128                 checkField(putRefKind, refc, putField);
4129                 if (checkSecurity)
4130                     checkSecurityManager(refc, putField);
4131             }
4132 
4133             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4134                                   restrictProtectedReceiver(getField));
4135             if (doRestrict) {
4136                 assert !getField.isStatic();
4137                 // receiver type of VarHandle is too wide; narrow to caller
4138                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4139                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4140                 }
4141                 refc = lookupClass();
4142             }
4143             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4144                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4145         }
4146         /** Check access and get the requested constructor. */
4147         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4148             final boolean checkSecurity = true;
4149             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4150         }
4151         /** Check access and get the requested constructor, eliding security manager checks. */
4152         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4153             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4154             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4155         }
4156         /** Common code for all constructors; do not call directly except from immediately above. */
4157         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4158                                                   boolean checkSecurity) throws IllegalAccessException {
4159             assert(ctor.isObjectConstructor());
4160             checkAccess(REF_newInvokeSpecial, refc, ctor);
4161             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4162             if (checkSecurity)
4163                 checkSecurityManager(refc, ctor);
4164             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4165             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4166         }
4167 
4168         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4169          */
4170         /*non-public*/
4171         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4172                 throws ReflectiveOperationException {
4173             if (!(type instanceof Class || type instanceof MethodType))
4174                 throw new InternalError("unresolved MemberName");
4175             MemberName member = new MemberName(refKind, defc, name, type);
4176             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4177             if (mh != null) {
4178                 checkSymbolicClass(defc);
4179                 return mh;
4180             }
4181             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4182                 // Treat MethodHandle.invoke and invokeExact specially.
4183                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4184                 if (mh != null) {
4185                     return mh;
4186                 }
4187             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4188                 // Treat signature-polymorphic methods on VarHandle specially.
4189                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4190                 if (mh != null) {
4191                     return mh;
4192                 }
4193             }
4194             MemberName resolved = resolveOrFail(refKind, member);
4195             mh = getDirectMethodForConstant(refKind, defc, resolved);
4196             if (mh instanceof DirectMethodHandle
4197                     && canBeCached(refKind, defc, resolved)) {
4198                 MemberName key = mh.internalMemberName();
4199                 if (key != null) {
4200                     key = key.asNormalOriginal();
4201                 }
4202                 if (member.equals(key)) {  // better safe than sorry
4203                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4204                 }
4205             }
4206             return mh;
4207         }
4208         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4209             if (refKind == REF_invokeSpecial) {
4210                 return false;
4211             }
4212             if (!Modifier.isPublic(defc.getModifiers()) ||
4213                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4214                     !member.isPublic() ||
4215                     member.isCallerSensitive()) {
4216                 return false;
4217             }
4218             ClassLoader loader = defc.getClassLoader();
4219             if (loader != null) {
4220                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4221                 boolean found = false;
4222                 while (sysl != null) {
4223                     if (loader == sysl) { found = true; break; }
4224                     sysl = sysl.getParent();
4225                 }
4226                 if (!found) {
4227                     return false;
4228                 }
4229             }
4230             try {
4231                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4232                     new MemberName(refKind, defc, member.getName(), member.getType()));
4233                 if (resolved2 == null) {
4234                     return false;
4235                 }
4236                 checkSecurityManager(defc, resolved2);
4237             } catch (SecurityException ex) {
4238                 return false;
4239             }
4240             return true;
4241         }
4242         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4243                 throws ReflectiveOperationException {
4244             if (MethodHandleNatives.refKindIsField(refKind)) {
4245                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4246             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4247                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4248             } else if (refKind == REF_newInvokeSpecial) {
4249                 return getDirectConstructorNoSecurityManager(defc, member);
4250             }
4251             // oops
4252             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4253         }
4254 
4255         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4256     }
4257 
4258     /**
4259      * Produces a method handle constructing arrays of a desired type,
4260      * as if by the {@code anewarray} bytecode.
4261      * The return type of the method handle will be the array type.
4262      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4263      *
4264      * <p> If the returned method handle is invoked with a negative
4265      * array size, a {@code NegativeArraySizeException} will be thrown.
4266      *
4267      * @param arrayClass an array type
4268      * @return a method handle which can create arrays of the given type
4269      * @throws NullPointerException if the argument is {@code null}
4270      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4271      * @see java.lang.reflect.Array#newInstance(Class, int)
4272      * @jvms 6.5 {@code anewarray} Instruction
4273      * @since 9
4274      */
4275     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4276         if (!arrayClass.isArray()) {
4277             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4278         }
4279         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4280                 bindTo(arrayClass.getComponentType());
4281         return ani.asType(ani.type().changeReturnType(arrayClass));
4282     }
4283 
4284     /**
4285      * Produces a method handle returning the length of an array,
4286      * as if by the {@code arraylength} bytecode.
4287      * The type of the method handle will have {@code int} as return type,
4288      * and its sole argument will be the array type.
4289      *
4290      * <p> If the returned method handle is invoked with a {@code null}
4291      * array reference, a {@code NullPointerException} will be thrown.
4292      *
4293      * @param arrayClass an array type
4294      * @return a method handle which can retrieve the length of an array of the given array type
4295      * @throws NullPointerException if the argument is {@code null}
4296      * @throws IllegalArgumentException if arrayClass is not an array type
4297      * @jvms 6.5 {@code arraylength} Instruction
4298      * @since 9
4299      */
4300     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4301         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4302     }
4303 
4304     /**
4305      * Produces a method handle giving read access to elements of an array,
4306      * as if by the {@code aaload} bytecode.
4307      * The type of the method handle will have a return type of the array's
4308      * element type.  Its first argument will be the array type,
4309      * and the second will be {@code int}.
4310      *
4311      * <p> When the returned method handle is invoked,
4312      * the array reference and array index are checked.
4313      * A {@code NullPointerException} will be thrown if the array reference
4314      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4315      * thrown if the index is negative or if it is greater than or equal to
4316      * the length of the array.
4317      *
4318      * @param arrayClass an array type
4319      * @return a method handle which can load values from the given array type
4320      * @throws NullPointerException if the argument is null
4321      * @throws  IllegalArgumentException if arrayClass is not an array type
4322      * @jvms 6.5 {@code aaload} Instruction
4323      */
4324     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4325         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4326     }
4327 
4328     /**
4329      * Produces a method handle giving write access to elements of an array,
4330      * as if by the {@code astore} bytecode.
4331      * The type of the method handle will have a void return type.
4332      * Its last argument will be the array's element type.
4333      * The first and second arguments will be the array type and int.
4334      *
4335      * <p> When the returned method handle is invoked,
4336      * the array reference and array index are checked.
4337      * A {@code NullPointerException} will be thrown if the array reference
4338      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4339      * thrown if the index is negative or if it is greater than or equal to
4340      * the length of the array.
4341      *
4342      * @param arrayClass the class of an array
4343      * @return a method handle which can store values into the array type
4344      * @throws NullPointerException if the argument is null
4345      * @throws IllegalArgumentException if arrayClass is not an array type
4346      * @jvms 6.5 {@code aastore} Instruction
4347      */
4348     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4349         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4350     }
4351 
4352     /**
4353      * Produces a VarHandle giving access to elements of an array of type
4354      * {@code arrayClass}.  The VarHandle's variable type is the component type
4355      * of {@code arrayClass} and the list of coordinate types is
4356      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4357      * corresponds to an argument that is an index into an array.
4358      * <p>
4359      * Certain access modes of the returned VarHandle are unsupported under
4360      * the following conditions:
4361      * <ul>
4362      * <li>if the component type is anything other than {@code byte},
4363      *     {@code short}, {@code char}, {@code int}, {@code long},
4364      *     {@code float}, or {@code double} then numeric atomic update access
4365      *     modes are unsupported.
4366      * <li>if the component type is anything other than {@code boolean},
4367      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4368      *     {@code long} then bitwise atomic update access modes are
4369      *     unsupported.
4370      * </ul>
4371      * <p>
4372      * If the component type is {@code float} or {@code double} then numeric
4373      * and atomic update access modes compare values using their bitwise
4374      * representation (see {@link Float#floatToRawIntBits} and
4375      * {@link Double#doubleToRawLongBits}, respectively).
4376      *
4377      * <p> When the returned {@code VarHandle} is invoked,
4378      * the array reference and array index are checked.
4379      * A {@code NullPointerException} will be thrown if the array reference
4380      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4381      * thrown if the index is negative or if it is greater than or equal to
4382      * the length of the array.
4383      *
4384      * @apiNote
4385      * Bitwise comparison of {@code float} values or {@code double} values,
4386      * as performed by the numeric and atomic update access modes, differ
4387      * from the primitive {@code ==} operator and the {@link Float#equals}
4388      * and {@link Double#equals} methods, specifically with respect to
4389      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4390      * Care should be taken when performing a compare and set or a compare
4391      * and exchange operation with such values since the operation may
4392      * unexpectedly fail.
4393      * There are many possible NaN values that are considered to be
4394      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4395      * provided by Java can distinguish between them.  Operation failure can
4396      * occur if the expected or witness value is a NaN value and it is
4397      * transformed (perhaps in a platform specific manner) into another NaN
4398      * value, and thus has a different bitwise representation (see
4399      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4400      * details).
4401      * The values {@code -0.0} and {@code +0.0} have different bitwise
4402      * representations but are considered equal when using the primitive
4403      * {@code ==} operator.  Operation failure can occur if, for example, a
4404      * numeric algorithm computes an expected value to be say {@code -0.0}
4405      * and previously computed the witness value to be say {@code +0.0}.
4406      * @param arrayClass the class of an array, of type {@code T[]}
4407      * @return a VarHandle giving access to elements of an array
4408      * @throws NullPointerException if the arrayClass is null
4409      * @throws IllegalArgumentException if arrayClass is not an array type
4410      * @since 9
4411      */
4412     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4413         return VarHandles.makeArrayElementHandle(arrayClass);
4414     }
4415 
4416     /**
4417      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4418      * viewed as if it were a different primitive array type, such as
4419      * {@code int[]} or {@code long[]}.
4420      * The VarHandle's variable type is the component type of
4421      * {@code viewArrayClass} and the list of coordinate types is
4422      * {@code (byte[], int)}, where the {@code int} coordinate type
4423      * corresponds to an argument that is an index into a {@code byte[]} array.
4424      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4425      * array, composing bytes to or from a value of the component type of
4426      * {@code viewArrayClass} according to the given endianness.
4427      * <p>
4428      * The supported component types (variables types) are {@code short},
4429      * {@code char}, {@code int}, {@code long}, {@code float} and
4430      * {@code double}.
4431      * <p>
4432      * Access of bytes at a given index will result in an
4433      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4434      * or greater than the {@code byte[]} array length minus the size (in bytes)
4435      * of {@code T}.
4436      * <p>
4437      * Access of bytes at an index may be aligned or misaligned for {@code T},
4438      * with respect to the underlying memory address, {@code A} say, associated
4439      * with the array and index.
4440      * If access is misaligned then access for anything other than the
4441      * {@code get} and {@code set} access modes will result in an
4442      * {@code IllegalStateException}.  In such cases atomic access is only
4443      * guaranteed with respect to the largest power of two that divides the GCD
4444      * of {@code A} and the size (in bytes) of {@code T}.
4445      * If access is aligned then following access modes are supported and are
4446      * guaranteed to support atomic access:
4447      * <ul>
4448      * <li>read write access modes for all {@code T}, with the exception of
4449      *     access modes {@code get} and {@code set} for {@code long} and
4450      *     {@code double} on 32-bit platforms.
4451      * <li>atomic update access modes for {@code int}, {@code long},
4452      *     {@code float} or {@code double}.
4453      *     (Future major platform releases of the JDK may support additional
4454      *     types for certain currently unsupported access modes.)
4455      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4456      *     (Future major platform releases of the JDK may support additional
4457      *     numeric types for certain currently unsupported access modes.)
4458      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4459      *     (Future major platform releases of the JDK may support additional
4460      *     numeric types for certain currently unsupported access modes.)
4461      * </ul>
4462      * <p>
4463      * Misaligned access, and therefore atomicity guarantees, may be determined
4464      * for {@code byte[]} arrays without operating on a specific array.  Given
4465      * an {@code index}, {@code T} and its corresponding boxed type,
4466      * {@code T_BOX}, misalignment may be determined as follows:
4467      * <pre>{@code
4468      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4469      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4470      *     alignmentOffset(0, sizeOfT);
4471      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4472      * boolean isMisaligned = misalignedAtIndex != 0;
4473      * }</pre>
4474      * <p>
4475      * If the variable type is {@code float} or {@code double} then atomic
4476      * update access modes compare values using their bitwise representation
4477      * (see {@link Float#floatToRawIntBits} and
4478      * {@link Double#doubleToRawLongBits}, respectively).
4479      * @param viewArrayClass the view array class, with a component type of
4480      * type {@code T}
4481      * @param byteOrder the endianness of the view array elements, as
4482      * stored in the underlying {@code byte} array
4483      * @return a VarHandle giving access to elements of a {@code byte[]} array
4484      * viewed as if elements corresponding to the components type of the view
4485      * array class
4486      * @throws NullPointerException if viewArrayClass or byteOrder is null
4487      * @throws IllegalArgumentException if viewArrayClass is not an array type
4488      * @throws UnsupportedOperationException if the component type of
4489      * viewArrayClass is not supported as a variable type
4490      * @since 9
4491      */
4492     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4493                                      ByteOrder byteOrder) throws IllegalArgumentException {
4494         Objects.requireNonNull(byteOrder);
4495         return VarHandles.byteArrayViewHandle(viewArrayClass,
4496                                               byteOrder == ByteOrder.BIG_ENDIAN);
4497     }
4498 
4499     /**
4500      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4501      * viewed as if it were an array of elements of a different primitive
4502      * component type to that of {@code byte}, such as {@code int[]} or
4503      * {@code long[]}.
4504      * The VarHandle's variable type is the component type of
4505      * {@code viewArrayClass} and the list of coordinate types is
4506      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4507      * corresponds to an argument that is an index into a {@code byte[]} array.
4508      * The returned VarHandle accesses bytes at an index in a
4509      * {@code ByteBuffer}, composing bytes to or from a value of the component
4510      * type of {@code viewArrayClass} according to the given endianness.
4511      * <p>
4512      * The supported component types (variables types) are {@code short},
4513      * {@code char}, {@code int}, {@code long}, {@code float} and
4514      * {@code double}.
4515      * <p>
4516      * Access will result in a {@code ReadOnlyBufferException} for anything
4517      * other than the read access modes if the {@code ByteBuffer} is read-only.
4518      * <p>
4519      * Access of bytes at a given index will result in an
4520      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4521      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4522      * {@code T}.
4523      * <p>
4524      * Access of bytes at an index may be aligned or misaligned for {@code T},
4525      * with respect to the underlying memory address, {@code A} say, associated
4526      * with the {@code ByteBuffer} and index.
4527      * If access is misaligned then access for anything other than the
4528      * {@code get} and {@code set} access modes will result in an
4529      * {@code IllegalStateException}.  In such cases atomic access is only
4530      * guaranteed with respect to the largest power of two that divides the GCD
4531      * of {@code A} and the size (in bytes) of {@code T}.
4532      * If access is aligned then following access modes are supported and are
4533      * guaranteed to support atomic access:
4534      * <ul>
4535      * <li>read write access modes for all {@code T}, with the exception of
4536      *     access modes {@code get} and {@code set} for {@code long} and
4537      *     {@code double} on 32-bit platforms.
4538      * <li>atomic update access modes for {@code int}, {@code long},
4539      *     {@code float} or {@code double}.
4540      *     (Future major platform releases of the JDK may support additional
4541      *     types for certain currently unsupported access modes.)
4542      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4543      *     (Future major platform releases of the JDK may support additional
4544      *     numeric types for certain currently unsupported access modes.)
4545      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4546      *     (Future major platform releases of the JDK may support additional
4547      *     numeric types for certain currently unsupported access modes.)
4548      * </ul>
4549      * <p>
4550      * Misaligned access, and therefore atomicity guarantees, may be determined
4551      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4552      * {@code index}, {@code T} and its corresponding boxed type,
4553      * {@code T_BOX}, as follows:
4554      * <pre>{@code
4555      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4556      * ByteBuffer bb = ...
4557      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4558      * boolean isMisaligned = misalignedAtIndex != 0;
4559      * }</pre>
4560      * <p>
4561      * If the variable type is {@code float} or {@code double} then atomic
4562      * update access modes compare values using their bitwise representation
4563      * (see {@link Float#floatToRawIntBits} and
4564      * {@link Double#doubleToRawLongBits}, respectively).
4565      * @param viewArrayClass the view array class, with a component type of
4566      * type {@code T}
4567      * @param byteOrder the endianness of the view array elements, as
4568      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4569      * endianness of a {@code ByteBuffer})
4570      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4571      * viewed as if elements corresponding to the components type of the view
4572      * array class
4573      * @throws NullPointerException if viewArrayClass or byteOrder is null
4574      * @throws IllegalArgumentException if viewArrayClass is not an array type
4575      * @throws UnsupportedOperationException if the component type of
4576      * viewArrayClass is not supported as a variable type
4577      * @since 9
4578      */
4579     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4580                                       ByteOrder byteOrder) throws IllegalArgumentException {
4581         Objects.requireNonNull(byteOrder);
4582         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4583                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4584     }
4585 
4586 
4587     /// method handle invocation (reflective style)
4588 
4589     /**
4590      * Produces a method handle which will invoke any method handle of the
4591      * given {@code type}, with a given number of trailing arguments replaced by
4592      * a single trailing {@code Object[]} array.
4593      * The resulting invoker will be a method handle with the following
4594      * arguments:
4595      * <ul>
4596      * <li>a single {@code MethodHandle} target
4597      * <li>zero or more leading values (counted by {@code leadingArgCount})
4598      * <li>an {@code Object[]} array containing trailing arguments
4599      * </ul>
4600      * <p>
4601      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4602      * the indicated {@code type}.
4603      * That is, if the target is exactly of the given {@code type}, it will behave
4604      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4605      * is used to convert the target to the required {@code type}.
4606      * <p>
4607      * The type of the returned invoker will not be the given {@code type}, but rather
4608      * will have all parameters except the first {@code leadingArgCount}
4609      * replaced by a single array of type {@code Object[]}, which will be
4610      * the final parameter.
4611      * <p>
4612      * Before invoking its target, the invoker will spread the final array, apply
4613      * reference casts as necessary, and unbox and widen primitive arguments.
4614      * If, when the invoker is called, the supplied array argument does
4615      * not have the correct number of elements, the invoker will throw
4616      * an {@link IllegalArgumentException} instead of invoking the target.
4617      * <p>
4618      * This method is equivalent to the following code (though it may be more efficient):
4619      * {@snippet lang="java" :
4620 MethodHandle invoker = MethodHandles.invoker(type);
4621 int spreadArgCount = type.parameterCount() - leadingArgCount;
4622 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4623 return invoker;
4624      * }
4625      * This method throws no reflective or security exceptions.
4626      * @param type the desired target type
4627      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4628      * @return a method handle suitable for invoking any method handle of the given type
4629      * @throws NullPointerException if {@code type} is null
4630      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4631      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4632      *                  or if the resulting method handle's type would have
4633      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4634      */
4635     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4636         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4637             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4638         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4639         return type.invokers().spreadInvoker(leadingArgCount);
4640     }
4641 
4642     /**
4643      * Produces a special <em>invoker method handle</em> which can be used to
4644      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4645      * The resulting invoker will have a type which is
4646      * exactly equal to the desired type, except that it will accept
4647      * an additional leading argument of type {@code MethodHandle}.
4648      * <p>
4649      * This method is equivalent to the following code (though it may be more efficient):
4650      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4651      *
4652      * <p style="font-size:smaller;">
4653      * <em>Discussion:</em>
4654      * Invoker method handles can be useful when working with variable method handles
4655      * of unknown types.
4656      * For example, to emulate an {@code invokeExact} call to a variable method
4657      * handle {@code M}, extract its type {@code T},
4658      * look up the invoker method {@code X} for {@code T},
4659      * and call the invoker method, as {@code X.invoke(T, A...)}.
4660      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4661      * is unknown.)
4662      * If spreading, collecting, or other argument transformations are required,
4663      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4664      * method handle values, as long as they are compatible with the type of {@code X}.
4665      * <p style="font-size:smaller;">
4666      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4667      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4668      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4669      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4670      * <p>
4671      * This method throws no reflective or security exceptions.
4672      * @param type the desired target type
4673      * @return a method handle suitable for invoking any method handle of the given type
4674      * @throws IllegalArgumentException if the resulting method handle's type would have
4675      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4676      */
4677     public static MethodHandle exactInvoker(MethodType type) {
4678         return type.invokers().exactInvoker();
4679     }
4680 
4681     /**
4682      * Produces a special <em>invoker method handle</em> which can be used to
4683      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4684      * The resulting invoker will have a type which is
4685      * exactly equal to the desired type, except that it will accept
4686      * an additional leading argument of type {@code MethodHandle}.
4687      * <p>
4688      * Before invoking its target, if the target differs from the expected type,
4689      * the invoker will apply reference casts as
4690      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4691      * Similarly, the return value will be converted as necessary.
4692      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4693      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4694      * <p>
4695      * This method is equivalent to the following code (though it may be more efficient):
4696      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4697      * <p style="font-size:smaller;">
4698      * <em>Discussion:</em>
4699      * A {@linkplain MethodType#genericMethodType general method type} is one which
4700      * mentions only {@code Object} arguments and return values.
4701      * An invoker for such a type is capable of calling any method handle
4702      * of the same arity as the general type.
4703      * <p style="font-size:smaller;">
4704      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4705      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4706      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4707      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4708      * <p>
4709      * This method throws no reflective or security exceptions.
4710      * @param type the desired target type
4711      * @return a method handle suitable for invoking any method handle convertible to the given type
4712      * @throws IllegalArgumentException if the resulting method handle's type would have
4713      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4714      */
4715     public static MethodHandle invoker(MethodType type) {
4716         return type.invokers().genericInvoker();
4717     }
4718 
4719     /**
4720      * Produces a special <em>invoker method handle</em> which can be used to
4721      * invoke a signature-polymorphic access mode method on any VarHandle whose
4722      * associated access mode type is compatible with the given type.
4723      * The resulting invoker will have a type which is exactly equal to the
4724      * desired given type, except that it will accept an additional leading
4725      * argument of type {@code VarHandle}.
4726      *
4727      * @param accessMode the VarHandle access mode
4728      * @param type the desired target type
4729      * @return a method handle suitable for invoking an access mode method of
4730      *         any VarHandle whose access mode type is of the given type.
4731      * @since 9
4732      */
4733     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4734         return type.invokers().varHandleMethodExactInvoker(accessMode);
4735     }
4736 
4737     /**
4738      * Produces a special <em>invoker method handle</em> which can be used to
4739      * invoke a signature-polymorphic access mode method on any VarHandle whose
4740      * associated access mode type is compatible with the given type.
4741      * The resulting invoker will have a type which is exactly equal to the
4742      * desired given type, except that it will accept an additional leading
4743      * argument of type {@code VarHandle}.
4744      * <p>
4745      * Before invoking its target, if the access mode type differs from the
4746      * desired given type, the invoker will apply reference casts as necessary
4747      * and box, unbox, or widen primitive values, as if by
4748      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4749      * converted as necessary.
4750      * <p>
4751      * This method is equivalent to the following code (though it may be more
4752      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4753      *
4754      * @param accessMode the VarHandle access mode
4755      * @param type the desired target type
4756      * @return a method handle suitable for invoking an access mode method of
4757      *         any VarHandle whose access mode type is convertible to the given
4758      *         type.
4759      * @since 9
4760      */
4761     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4762         return type.invokers().varHandleMethodInvoker(accessMode);
4763     }
4764 
4765     /*non-public*/
4766     static MethodHandle basicInvoker(MethodType type) {
4767         return type.invokers().basicInvoker();
4768     }
4769 
4770      /// method handle modification (creation from other method handles)
4771 
4772     /**
4773      * Produces a method handle which adapts the type of the
4774      * given method handle to a new type by pairwise argument and return type conversion.
4775      * The original type and new type must have the same number of arguments.
4776      * The resulting method handle is guaranteed to report a type
4777      * which is equal to the desired new type.
4778      * <p>
4779      * If the original type and new type are equal, returns target.
4780      * <p>
4781      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4782      * and some additional conversions are also applied if those conversions fail.
4783      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4784      * if possible, before or instead of any conversions done by {@code asType}:
4785      * <ul>
4786      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4787      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4788      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4789      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4790      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4791      *     (This treatment follows the usage of the bytecode verifier.)
4792      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4793      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4794      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4795      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4796      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4797      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4798      *     widening and/or narrowing.)
4799      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4800      *     conversion will be applied at runtime, possibly followed
4801      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4802      *     possibly followed by a conversion from byte to boolean by testing
4803      *     the low-order bit.
4804      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4805      *     and if the reference is null at runtime, a zero value is introduced.
4806      * </ul>
4807      * @param target the method handle to invoke after arguments are retyped
4808      * @param newType the expected type of the new method handle
4809      * @return a method handle which delegates to the target after performing
4810      *           any necessary argument conversions, and arranges for any
4811      *           necessary return value conversions
4812      * @throws NullPointerException if either argument is null
4813      * @throws WrongMethodTypeException if the conversion cannot be made
4814      * @see MethodHandle#asType
4815      */
4816     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4817         explicitCastArgumentsChecks(target, newType);
4818         // use the asTypeCache when possible:
4819         MethodType oldType = target.type();
4820         if (oldType == newType)  return target;
4821         if (oldType.explicitCastEquivalentToAsType(newType)) {
4822             return target.asFixedArity().asType(newType);
4823         }
4824         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4825     }
4826 
4827     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4828         if (target.type().parameterCount() != newType.parameterCount()) {
4829             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4830         }
4831     }
4832 
4833     /**
4834      * Produces a method handle which adapts the calling sequence of the
4835      * given method handle to a new type, by reordering the arguments.
4836      * The resulting method handle is guaranteed to report a type
4837      * which is equal to the desired new type.
4838      * <p>
4839      * The given array controls the reordering.
4840      * Call {@code #I} the number of incoming parameters (the value
4841      * {@code newType.parameterCount()}, and call {@code #O} the number
4842      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4843      * Then the length of the reordering array must be {@code #O},
4844      * and each element must be a non-negative number less than {@code #I}.
4845      * For every {@code N} less than {@code #O}, the {@code N}-th
4846      * outgoing argument will be taken from the {@code I}-th incoming
4847      * argument, where {@code I} is {@code reorder[N]}.
4848      * <p>
4849      * No argument or return value conversions are applied.
4850      * The type of each incoming argument, as determined by {@code newType},
4851      * must be identical to the type of the corresponding outgoing parameter
4852      * or parameters in the target method handle.
4853      * The return type of {@code newType} must be identical to the return
4854      * type of the original target.
4855      * <p>
4856      * The reordering array need not specify an actual permutation.
4857      * An incoming argument will be duplicated if its index appears
4858      * more than once in the array, and an incoming argument will be dropped
4859      * if its index does not appear in the array.
4860      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4861      * incoming arguments which are not mentioned in the reordering array
4862      * may be of any type, as determined only by {@code newType}.
4863      * {@snippet lang="java" :
4864 import static java.lang.invoke.MethodHandles.*;
4865 import static java.lang.invoke.MethodType.*;
4866 ...
4867 MethodType intfn1 = methodType(int.class, int.class);
4868 MethodType intfn2 = methodType(int.class, int.class, int.class);
4869 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4870 assert(sub.type().equals(intfn2));
4871 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4872 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4873 assert((int)rsub.invokeExact(1, 100) == 99);
4874 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4875 assert(add.type().equals(intfn2));
4876 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4877 assert(twice.type().equals(intfn1));
4878 assert((int)twice.invokeExact(21) == 42);
4879      * }
4880      * <p>
4881      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4882      * variable-arity method handle}, even if the original target method handle was.
4883      * @param target the method handle to invoke after arguments are reordered
4884      * @param newType the expected type of the new method handle
4885      * @param reorder an index array which controls the reordering
4886      * @return a method handle which delegates to the target after it
4887      *           drops unused arguments and moves and/or duplicates the other arguments
4888      * @throws NullPointerException if any argument is null
4889      * @throws IllegalArgumentException if the index array length is not equal to
4890      *                  the arity of the target, or if any index array element
4891      *                  not a valid index for a parameter of {@code newType},
4892      *                  or if two corresponding parameter types in
4893      *                  {@code target.type()} and {@code newType} are not identical,
4894      */
4895     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4896         reorder = reorder.clone();  // get a private copy
4897         MethodType oldType = target.type();
4898         permuteArgumentChecks(reorder, newType, oldType);
4899         // first detect dropped arguments and handle them separately
4900         int[] originalReorder = reorder;
4901         BoundMethodHandle result = target.rebind();
4902         LambdaForm form = result.form;
4903         int newArity = newType.parameterCount();
4904         // Normalize the reordering into a real permutation,
4905         // by removing duplicates and adding dropped elements.
4906         // This somewhat improves lambda form caching, as well
4907         // as simplifying the transform by breaking it up into steps.
4908         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4909             if (ddIdx > 0) {
4910                 // We found a duplicated entry at reorder[ddIdx].
4911                 // Example:  (x,y,z)->asList(x,y,z)
4912                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4913                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4914                 // The starred element corresponds to the argument
4915                 // deleted by the dupArgumentForm transform.
4916                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4917                 boolean killFirst = false;
4918                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4919                     // Set killFirst if the dup is larger than an intervening position.
4920                     // This will remove at least one inversion from the permutation.
4921                     if (dupVal > val) killFirst = true;
4922                 }
4923                 if (!killFirst) {
4924                     srcPos = dstPos;
4925                     dstPos = ddIdx;
4926                 }
4927                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4928                 assert (reorder[srcPos] == reorder[dstPos]);
4929                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4930                 // contract the reordering by removing the element at dstPos
4931                 int tailPos = dstPos + 1;
4932                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4933                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4934             } else {
4935                 int dropVal = ~ddIdx, insPos = 0;
4936                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4937                     // Find first element of reorder larger than dropVal.
4938                     // This is where we will insert the dropVal.
4939                     insPos += 1;
4940                 }
4941                 Class<?> ptype = newType.parameterType(dropVal);
4942                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4943                 oldType = oldType.insertParameterTypes(insPos, ptype);
4944                 // expand the reordering by inserting an element at insPos
4945                 int tailPos = insPos + 1;
4946                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4947                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4948                 reorder[insPos] = dropVal;
4949             }
4950             assert (permuteArgumentChecks(reorder, newType, oldType));
4951         }
4952         assert (reorder.length == newArity);  // a perfect permutation
4953         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4954         form = form.editor().permuteArgumentsForm(1, reorder);
4955         if (newType == result.type() && form == result.internalForm())
4956             return result;
4957         return result.copyWith(newType, form);
4958     }
4959 
4960     /**
4961      * Return an indication of any duplicate or omission in reorder.
4962      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4963      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4964      * Otherwise, return zero.
4965      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4966      */
4967     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4968         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4969         if (newArity < BIT_LIMIT) {
4970             long mask = 0;
4971             for (int i = 0; i < reorder.length; i++) {
4972                 int arg = reorder[i];
4973                 if (arg >= newArity) {
4974                     return reorder.length;
4975                 }
4976                 long bit = 1L << arg;
4977                 if ((mask & bit) != 0) {
4978                     return i;  // >0 indicates a dup
4979                 }
4980                 mask |= bit;
4981             }
4982             if (mask == (1L << newArity) - 1) {
4983                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4984                 return 0;
4985             }
4986             // find first zero
4987             long zeroBit = Long.lowestOneBit(~mask);
4988             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4989             assert(zeroPos <= newArity);
4990             if (zeroPos == newArity) {
4991                 return 0;
4992             }
4993             return ~zeroPos;
4994         } else {
4995             // same algorithm, different bit set
4996             BitSet mask = new BitSet(newArity);
4997             for (int i = 0; i < reorder.length; i++) {
4998                 int arg = reorder[i];
4999                 if (arg >= newArity) {
5000                     return reorder.length;
5001                 }
5002                 if (mask.get(arg)) {
5003                     return i;  // >0 indicates a dup
5004                 }
5005                 mask.set(arg);
5006             }
5007             int zeroPos = mask.nextClearBit(0);
5008             assert(zeroPos <= newArity);
5009             if (zeroPos == newArity) {
5010                 return 0;
5011             }
5012             return ~zeroPos;
5013         }
5014     }
5015 
5016     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5017         if (newType.returnType() != oldType.returnType())
5018             throw newIllegalArgumentException("return types do not match",
5019                     oldType, newType);
5020         if (reorder.length != oldType.parameterCount())
5021             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5022                     oldType, Arrays.toString(reorder));
5023 
5024         int limit = newType.parameterCount();
5025         for (int j = 0; j < reorder.length; j++) {
5026             int i = reorder[j];
5027             if (i < 0 || i >= limit) {
5028                 throw newIllegalArgumentException("index is out of bounds for new type",
5029                         i, newType);
5030             }
5031             Class<?> src = newType.parameterType(i);
5032             Class<?> dst = oldType.parameterType(j);
5033             if (src != dst)
5034                 throw newIllegalArgumentException("parameter types do not match after reorder",
5035                         oldType, newType);
5036         }
5037         return true;
5038     }
5039 
5040     /**
5041      * Produces a method handle of the requested return type which returns the given
5042      * constant value every time it is invoked.
5043      * <p>
5044      * Before the method handle is returned, the passed-in value is converted to the requested type.
5045      * If the requested type is primitive, widening primitive conversions are attempted,
5046      * else reference conversions are attempted.
5047      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5048      * @param type the return type of the desired method handle
5049      * @param value the value to return
5050      * @return a method handle of the given return type and no arguments, which always returns the given value
5051      * @throws NullPointerException if the {@code type} argument is null
5052      * @throws ClassCastException if the value cannot be converted to the required return type
5053      * @throws IllegalArgumentException if the given type is {@code void.class}
5054      */
5055     public static MethodHandle constant(Class<?> type, Object value) {
5056         if (type.isPrimitive()) {
5057             if (type == void.class)
5058                 throw newIllegalArgumentException("void type");
5059             Wrapper w = Wrapper.forPrimitiveType(type);
5060             value = w.convert(value, type);
5061             if (w.zero().equals(value))
5062                 return zero(w, type);
5063             return insertArguments(identity(type), 0, value);
5064         } else {
5065             if (!PrimitiveClass.isPrimitiveValueType(type) && value == null)
5066                 return zero(Wrapper.OBJECT, type);
5067             return identity(type).bindTo(value);
5068         }
5069     }
5070 
5071     /**
5072      * Produces a method handle which returns its sole argument when invoked.
5073      * @param type the type of the sole parameter and return value of the desired method handle
5074      * @return a unary method handle which accepts and returns the given type
5075      * @throws NullPointerException if the argument is null
5076      * @throws IllegalArgumentException if the given type is {@code void.class}
5077      */
5078     public static MethodHandle identity(Class<?> type) {
5079         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5080         int pos = btw.ordinal();
5081         MethodHandle ident = IDENTITY_MHS[pos];
5082         if (ident == null) {
5083             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5084         }
5085         if (ident.type().returnType() == type)
5086             return ident;
5087         // something like identity(Foo.class); do not bother to intern these
5088         assert (btw == Wrapper.OBJECT);
5089         return makeIdentity(type);
5090     }
5091 
5092     /**
5093      * Produces a constant method handle of the requested return type which
5094      * returns the default value for that type every time it is invoked.
5095      * The resulting constant method handle will have no side effects.
5096      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5097      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5098      * since {@code explicitCastArguments} converts {@code null} to default values.
5099      * @param type the expected return type of the desired method handle
5100      * @return a constant method handle that takes no arguments
5101      *         and returns the default value of the given type (or void, if the type is void)
5102      * @throws NullPointerException if the argument is null
5103      * @see MethodHandles#constant
5104      * @see MethodHandles#empty
5105      * @see MethodHandles#explicitCastArguments
5106      * @since 9
5107      */
5108     public static MethodHandle zero(Class<?> type) {
5109         Objects.requireNonNull(type);
5110         if (type.isPrimitive()) {
5111             return zero(Wrapper.forPrimitiveType(type), type);
5112         } else if (PrimitiveClass.isPrimitiveValueType(type)) {
5113             // singleton default value
5114             Object value = UNSAFE.uninitializedDefaultValue(type);
5115             return identity(type).bindTo(value);
5116         } else {
5117             return zero(Wrapper.OBJECT, type);
5118         }
5119     }
5120 
5121     private static MethodHandle identityOrVoid(Class<?> type) {
5122         return type == void.class ? zero(type) : identity(type);
5123     }
5124 
5125     /**
5126      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5127      * and returns a suitable default depending on the return type.
5128      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5129      * <p>The returned method handle is equivalent to
5130      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5131      *
5132      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5133      * {@code guardWithTest(pred, target, empty(target.type())}.
5134      * @param type the type of the desired method handle
5135      * @return a constant method handle of the given type, which returns a default value of the given return type
5136      * @throws NullPointerException if the argument is null
5137      * @see MethodHandles#zero
5138      * @see MethodHandles#constant
5139      * @since 9
5140      */
5141     public static  MethodHandle empty(MethodType type) {
5142         Objects.requireNonNull(type);
5143         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
5144     }
5145 
5146     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5147     private static MethodHandle makeIdentity(Class<?> ptype) {
5148         MethodType mtype = MethodType.methodType(ptype, ptype);
5149         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5150         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5151     }
5152 
5153     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5154         int pos = btw.ordinal();
5155         MethodHandle zero = ZERO_MHS[pos];
5156         if (zero == null) {
5157             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5158         }
5159         if (zero.type().returnType() == rtype)
5160             return zero;
5161         assert(btw == Wrapper.OBJECT);
5162         return makeZero(rtype);
5163     }
5164     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5165     private static MethodHandle makeZero(Class<?> rtype) {
5166         MethodType mtype = methodType(rtype);
5167         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5168         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5169     }
5170 
5171     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5172         // Simulate a CAS, to avoid racy duplication of results.
5173         MethodHandle prev = cache[pos];
5174         if (prev != null) return prev;
5175         return cache[pos] = value;
5176     }
5177 
5178     /**
5179      * Provides a target method handle with one or more <em>bound arguments</em>
5180      * in advance of the method handle's invocation.
5181      * The formal parameters to the target corresponding to the bound
5182      * arguments are called <em>bound parameters</em>.
5183      * Returns a new method handle which saves away the bound arguments.
5184      * When it is invoked, it receives arguments for any non-bound parameters,
5185      * binds the saved arguments to their corresponding parameters,
5186      * and calls the original target.
5187      * <p>
5188      * The type of the new method handle will drop the types for the bound
5189      * parameters from the original target type, since the new method handle
5190      * will no longer require those arguments to be supplied by its callers.
5191      * <p>
5192      * Each given argument object must match the corresponding bound parameter type.
5193      * If a bound parameter type is a primitive, the argument object
5194      * must be a wrapper, and will be unboxed to produce the primitive value.
5195      * <p>
5196      * The {@code pos} argument selects which parameters are to be bound.
5197      * It may range between zero and <i>N-L</i> (inclusively),
5198      * where <i>N</i> is the arity of the target method handle
5199      * and <i>L</i> is the length of the values array.
5200      * <p>
5201      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5202      * variable-arity method handle}, even if the original target method handle was.
5203      * @param target the method handle to invoke after the argument is inserted
5204      * @param pos where to insert the argument (zero for the first)
5205      * @param values the series of arguments to insert
5206      * @return a method handle which inserts an additional argument,
5207      *         before calling the original method handle
5208      * @throws NullPointerException if the target or the {@code values} array is null
5209      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5210      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5211      *         is the length of the values array.
5212      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5213      *         type.
5214      * @see MethodHandle#bindTo
5215      */
5216     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5217         int insCount = values.length;
5218         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5219         if (insCount == 0)  return target;
5220         BoundMethodHandle result = target.rebind();
5221         for (int i = 0; i < insCount; i++) {
5222             Object value = values[i];
5223             Class<?> ptype = ptypes[pos+i];
5224             if (ptype.isPrimitive()) {
5225                 result = insertArgumentPrimitive(result, pos, ptype, value);
5226             } else {
5227                 value = ptype.cast(value);  // throw CCE if needed
5228                 result = result.bindArgumentL(pos, value);
5229             }
5230         }
5231         return result;
5232     }
5233 
5234     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5235                                                              Class<?> ptype, Object value) {
5236         Wrapper w = Wrapper.forPrimitiveType(ptype);
5237         // perform unboxing and/or primitive conversion
5238         value = w.convert(value, ptype);
5239         return switch (w) {
5240             case INT    -> result.bindArgumentI(pos, (int) value);
5241             case LONG   -> result.bindArgumentJ(pos, (long) value);
5242             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5243             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5244             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5245         };
5246     }
5247 
5248     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5249         MethodType oldType = target.type();
5250         int outargs = oldType.parameterCount();
5251         int inargs  = outargs - insCount;
5252         if (inargs < 0)
5253             throw newIllegalArgumentException("too many values to insert");
5254         if (pos < 0 || pos > inargs)
5255             throw newIllegalArgumentException("no argument type to append");
5256         return oldType.ptypes();
5257     }
5258 
5259     /**
5260      * Produces a method handle which will discard some dummy arguments
5261      * before calling some other specified <i>target</i> method handle.
5262      * The type of the new method handle will be the same as the target's type,
5263      * except it will also include the dummy argument types,
5264      * at some given position.
5265      * <p>
5266      * The {@code pos} argument may range between zero and <i>N</i>,
5267      * where <i>N</i> is the arity of the target.
5268      * If {@code pos} is zero, the dummy arguments will precede
5269      * the target's real arguments; if {@code pos} is <i>N</i>
5270      * they will come after.
5271      * <p>
5272      * <b>Example:</b>
5273      * {@snippet lang="java" :
5274 import static java.lang.invoke.MethodHandles.*;
5275 import static java.lang.invoke.MethodType.*;
5276 ...
5277 MethodHandle cat = lookup().findVirtual(String.class,
5278   "concat", methodType(String.class, String.class));
5279 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5280 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5281 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5282 assertEquals(bigType, d0.type());
5283 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5284      * }
5285      * <p>
5286      * This method is also equivalent to the following code:
5287      * <blockquote><pre>
5288      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5289      * </pre></blockquote>
5290      * @param target the method handle to invoke after the arguments are dropped
5291      * @param pos position of first argument to drop (zero for the leftmost)
5292      * @param valueTypes the type(s) of the argument(s) to drop
5293      * @return a method handle which drops arguments of the given types,
5294      *         before calling the original method handle
5295      * @throws NullPointerException if the target is null,
5296      *                              or if the {@code valueTypes} list or any of its elements is null
5297      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5298      *                  or if {@code pos} is negative or greater than the arity of the target,
5299      *                  or if the new method handle's type would have too many parameters
5300      */
5301     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5302         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5303     }
5304 
5305     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5306         MethodType oldType = target.type();  // get NPE
5307         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5308         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5309         if (dropped == 0)  return target;
5310         BoundMethodHandle result = target.rebind();
5311         LambdaForm lform = result.form;
5312         int insertFormArg = 1 + pos;
5313         for (Class<?> ptype : valueTypes) {
5314             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5315         }
5316         result = result.copyWith(newType, lform);
5317         return result;
5318     }
5319 
5320     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5321         int dropped = valueTypes.length;
5322         MethodType.checkSlotCount(dropped);
5323         int outargs = oldType.parameterCount();
5324         int inargs  = outargs + dropped;
5325         if (pos < 0 || pos > outargs)
5326             throw newIllegalArgumentException("no argument type to remove"
5327                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5328                     );
5329         return dropped;
5330     }
5331 
5332     /**
5333      * Produces a method handle which will discard some dummy arguments
5334      * before calling some other specified <i>target</i> method handle.
5335      * The type of the new method handle will be the same as the target's type,
5336      * except it will also include the dummy argument types,
5337      * at some given position.
5338      * <p>
5339      * The {@code pos} argument may range between zero and <i>N</i>,
5340      * where <i>N</i> is the arity of the target.
5341      * If {@code pos} is zero, the dummy arguments will precede
5342      * the target's real arguments; if {@code pos} is <i>N</i>
5343      * they will come after.
5344      * @apiNote
5345      * {@snippet lang="java" :
5346 import static java.lang.invoke.MethodHandles.*;
5347 import static java.lang.invoke.MethodType.*;
5348 ...
5349 MethodHandle cat = lookup().findVirtual(String.class,
5350   "concat", methodType(String.class, String.class));
5351 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5352 MethodHandle d0 = dropArguments(cat, 0, String.class);
5353 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5354 MethodHandle d1 = dropArguments(cat, 1, String.class);
5355 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5356 MethodHandle d2 = dropArguments(cat, 2, String.class);
5357 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5358 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5359 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5360      * }
5361      * <p>
5362      * This method is also equivalent to the following code:
5363      * <blockquote><pre>
5364      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5365      * </pre></blockquote>
5366      * @param target the method handle to invoke after the arguments are dropped
5367      * @param pos position of first argument to drop (zero for the leftmost)
5368      * @param valueTypes the type(s) of the argument(s) to drop
5369      * @return a method handle which drops arguments of the given types,
5370      *         before calling the original method handle
5371      * @throws NullPointerException if the target is null,
5372      *                              or if the {@code valueTypes} array or any of its elements is null
5373      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5374      *                  or if {@code pos} is negative or greater than the arity of the target,
5375      *                  or if the new method handle's type would have
5376      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5377      */
5378     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5379         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5380     }
5381 
5382     /* Convenience overloads for trusting internal low-arity call-sites */
5383     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5384         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5385     }
5386     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5387         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5388     }
5389 
5390     // private version which allows caller some freedom with error handling
5391     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5392                                       boolean nullOnFailure) {
5393         Class<?>[] oldTypes = target.type().ptypes();
5394         int match = oldTypes.length;
5395         if (skip != 0) {
5396             if (skip < 0 || skip > match) {
5397                 throw newIllegalArgumentException("illegal skip", skip, target);
5398             }
5399             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5400             match -= skip;
5401         }
5402         Class<?>[] addTypes = newTypes;
5403         int add = addTypes.length;
5404         if (pos != 0) {
5405             if (pos < 0 || pos > add) {
5406                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5407             }
5408             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5409             add -= pos;
5410             assert(addTypes.length == add);
5411         }
5412         // Do not add types which already match the existing arguments.
5413         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5414             if (nullOnFailure) {
5415                 return null;
5416             }
5417             throw newIllegalArgumentException("argument lists do not match",
5418                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5419         }
5420         addTypes = Arrays.copyOfRange(addTypes, match, add);
5421         add -= match;
5422         assert(addTypes.length == add);
5423         // newTypes:     (   P*[pos], M*[match], A*[add] )
5424         // target: ( S*[skip],        M*[match]  )
5425         MethodHandle adapter = target;
5426         if (add > 0) {
5427             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5428         }
5429         // adapter: (S*[skip],        M*[match], A*[add] )
5430         if (pos > 0) {
5431             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5432         }
5433         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5434         return adapter;
5435     }
5436 
5437     /**
5438      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5439      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5440      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5441      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5442      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5443      * {@link #dropArguments(MethodHandle, int, Class[])}.
5444      * <p>
5445      * The resulting handle will have the same return type as the target handle.
5446      * <p>
5447      * In more formal terms, assume these two type lists:<ul>
5448      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5449      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5450      * {@code newTypes}.
5451      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5452      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5453      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5454      * sub-list.
5455      * </ul>
5456      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5457      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5458      * {@link #dropArguments(MethodHandle, int, Class[])}.
5459      *
5460      * @apiNote
5461      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5462      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5463      * {@snippet lang="java" :
5464 import static java.lang.invoke.MethodHandles.*;
5465 import static java.lang.invoke.MethodType.*;
5466 ...
5467 ...
5468 MethodHandle h0 = constant(boolean.class, true);
5469 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5470 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5471 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5472 if (h1.type().parameterCount() < h2.type().parameterCount())
5473     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5474 else
5475     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5476 MethodHandle h3 = guardWithTest(h0, h1, h2);
5477 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5478      * }
5479      * @param target the method handle to adapt
5480      * @param skip number of targets parameters to disregard (they will be unchanged)
5481      * @param newTypes the list of types to match {@code target}'s parameter type list to
5482      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5483      * @return a possibly adapted method handle
5484      * @throws NullPointerException if either argument is null
5485      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5486      *         or if {@code skip} is negative or greater than the arity of the target,
5487      *         or if {@code pos} is negative or greater than the newTypes list size,
5488      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5489      *         {@code pos}.
5490      * @since 9
5491      */
5492     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5493         Objects.requireNonNull(target);
5494         Objects.requireNonNull(newTypes);
5495         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5496     }
5497 
5498     /**
5499      * Drop the return value of the target handle (if any).
5500      * The returned method handle will have a {@code void} return type.
5501      *
5502      * @param target the method handle to adapt
5503      * @return a possibly adapted method handle
5504      * @throws NullPointerException if {@code target} is null
5505      * @since 16
5506      */
5507     public static MethodHandle dropReturn(MethodHandle target) {
5508         Objects.requireNonNull(target);
5509         MethodType oldType = target.type();
5510         Class<?> oldReturnType = oldType.returnType();
5511         if (oldReturnType == void.class)
5512             return target;
5513         MethodType newType = oldType.changeReturnType(void.class);
5514         BoundMethodHandle result = target.rebind();
5515         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5516         result = result.copyWith(newType, lform);
5517         return result;
5518     }
5519 
5520     /**
5521      * Adapts a target method handle by pre-processing
5522      * one or more of its arguments, each with its own unary filter function,
5523      * and then calling the target with each pre-processed argument
5524      * replaced by the result of its corresponding filter function.
5525      * <p>
5526      * The pre-processing is performed by one or more method handles,
5527      * specified in the elements of the {@code filters} array.
5528      * The first element of the filter array corresponds to the {@code pos}
5529      * argument of the target, and so on in sequence.
5530      * The filter functions are invoked in left to right order.
5531      * <p>
5532      * Null arguments in the array are treated as identity functions,
5533      * and the corresponding arguments left unchanged.
5534      * (If there are no non-null elements in the array, the original target is returned.)
5535      * Each filter is applied to the corresponding argument of the adapter.
5536      * <p>
5537      * If a filter {@code F} applies to the {@code N}th argument of
5538      * the target, then {@code F} must be a method handle which
5539      * takes exactly one argument.  The type of {@code F}'s sole argument
5540      * replaces the corresponding argument type of the target
5541      * in the resulting adapted method handle.
5542      * The return type of {@code F} must be identical to the corresponding
5543      * parameter type of the target.
5544      * <p>
5545      * It is an error if there are elements of {@code filters}
5546      * (null or not)
5547      * which do not correspond to argument positions in the target.
5548      * <p><b>Example:</b>
5549      * {@snippet lang="java" :
5550 import static java.lang.invoke.MethodHandles.*;
5551 import static java.lang.invoke.MethodType.*;
5552 ...
5553 MethodHandle cat = lookup().findVirtual(String.class,
5554   "concat", methodType(String.class, String.class));
5555 MethodHandle upcase = lookup().findVirtual(String.class,
5556   "toUpperCase", methodType(String.class));
5557 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5558 MethodHandle f0 = filterArguments(cat, 0, upcase);
5559 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5560 MethodHandle f1 = filterArguments(cat, 1, upcase);
5561 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5562 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5563 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5564      * }
5565      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5566      * denotes the return type of both the {@code target} and resulting adapter.
5567      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5568      * of the parameters and arguments that precede and follow the filter position
5569      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5570      * values of the filtered parameters and arguments; they also represent the
5571      * return types of the {@code filter[i]} handles. The latter accept arguments
5572      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5573      * the resulting adapter.
5574      * {@snippet lang="java" :
5575      * T target(P... p, A[i]... a[i], B... b);
5576      * A[i] filter[i](V[i]);
5577      * T adapter(P... p, V[i]... v[i], B... b) {
5578      *   return target(p..., filter[i](v[i])..., b...);
5579      * }
5580      * }
5581      * <p>
5582      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5583      * variable-arity method handle}, even if the original target method handle was.
5584      *
5585      * @param target the method handle to invoke after arguments are filtered
5586      * @param pos the position of the first argument to filter
5587      * @param filters method handles to call initially on filtered arguments
5588      * @return method handle which incorporates the specified argument filtering logic
5589      * @throws NullPointerException if the target is null
5590      *                              or if the {@code filters} array is null
5591      * @throws IllegalArgumentException if a non-null element of {@code filters}
5592      *          does not match a corresponding argument type of target as described above,
5593      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5594      *          or if the resulting method handle's type would have
5595      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5596      */
5597     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5598         // In method types arguments start at index 0, while the LF
5599         // editor have the MH receiver at position 0 - adjust appropriately.
5600         final int MH_RECEIVER_OFFSET = 1;
5601         filterArgumentsCheckArity(target, pos, filters);
5602         MethodHandle adapter = target;
5603 
5604         // keep track of currently matched filters, as to optimize repeated filters
5605         int index = 0;
5606         int[] positions = new int[filters.length];
5607         MethodHandle filter = null;
5608 
5609         // process filters in reverse order so that the invocation of
5610         // the resulting adapter will invoke the filters in left-to-right order
5611         for (int i = filters.length - 1; i >= 0; --i) {
5612             MethodHandle newFilter = filters[i];
5613             if (newFilter == null) continue;  // ignore null elements of filters
5614 
5615             // flush changes on update
5616             if (filter != newFilter) {
5617                 if (filter != null) {
5618                     if (index > 1) {
5619                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5620                     } else {
5621                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5622                     }
5623                 }
5624                 filter = newFilter;
5625                 index = 0;
5626             }
5627 
5628             filterArgumentChecks(target, pos + i, newFilter);
5629             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5630         }
5631         if (index > 1) {
5632             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5633         } else if (index == 1) {
5634             adapter = filterArgument(adapter, positions[0] - 1, filter);
5635         }
5636         return adapter;
5637     }
5638 
5639     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5640         MethodType targetType = adapter.type();
5641         MethodType filterType = filter.type();
5642         BoundMethodHandle result = adapter.rebind();
5643         Class<?> newParamType = filterType.parameterType(0);
5644 
5645         Class<?>[] ptypes = targetType.ptypes().clone();
5646         for (int pos : positions) {
5647             ptypes[pos - 1] = newParamType;
5648         }
5649         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5650 
5651         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5652         return result.copyWithExtendL(newType, lform, filter);
5653     }
5654 
5655     /*non-public*/
5656     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5657         filterArgumentChecks(target, pos, filter);
5658         MethodType targetType = target.type();
5659         MethodType filterType = filter.type();
5660         BoundMethodHandle result = target.rebind();
5661         Class<?> newParamType = filterType.parameterType(0);
5662         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5663         MethodType newType = targetType.changeParameterType(pos, newParamType);
5664         result = result.copyWithExtendL(newType, lform, filter);
5665         return result;
5666     }
5667 
5668     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5669         MethodType targetType = target.type();
5670         int maxPos = targetType.parameterCount();
5671         if (pos + filters.length > maxPos)
5672             throw newIllegalArgumentException("too many filters");
5673     }
5674 
5675     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5676         MethodType targetType = target.type();
5677         MethodType filterType = filter.type();
5678         if (filterType.parameterCount() != 1
5679             || filterType.returnType() != targetType.parameterType(pos))
5680             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5681     }
5682 
5683     /**
5684      * Adapts a target method handle by pre-processing
5685      * a sub-sequence of its arguments with a filter (another method handle).
5686      * The pre-processed arguments are replaced by the result (if any) of the
5687      * filter function.
5688      * The target is then called on the modified (usually shortened) argument list.
5689      * <p>
5690      * If the filter returns a value, the target must accept that value as
5691      * its argument in position {@code pos}, preceded and/or followed by
5692      * any arguments not passed to the filter.
5693      * If the filter returns void, the target must accept all arguments
5694      * not passed to the filter.
5695      * No arguments are reordered, and a result returned from the filter
5696      * replaces (in order) the whole subsequence of arguments originally
5697      * passed to the adapter.
5698      * <p>
5699      * The argument types (if any) of the filter
5700      * replace zero or one argument types of the target, at position {@code pos},
5701      * in the resulting adapted method handle.
5702      * The return type of the filter (if any) must be identical to the
5703      * argument type of the target at position {@code pos}, and that target argument
5704      * is supplied by the return value of the filter.
5705      * <p>
5706      * In all cases, {@code pos} must be greater than or equal to zero, and
5707      * {@code pos} must also be less than or equal to the target's arity.
5708      * <p><b>Example:</b>
5709      * {@snippet lang="java" :
5710 import static java.lang.invoke.MethodHandles.*;
5711 import static java.lang.invoke.MethodType.*;
5712 ...
5713 MethodHandle deepToString = publicLookup()
5714   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5715 
5716 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5717 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5718 
5719 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5720 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5721 
5722 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5723 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5724 assertEquals("[top, [up, down], strange]",
5725              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5726 
5727 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5728 assertEquals("[top, [up, down], [strange]]",
5729              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5730 
5731 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5732 assertEquals("[top, [[up, down, strange], charm], bottom]",
5733              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5734      * }
5735      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5736      * represents the return type of the {@code target} and resulting adapter.
5737      * {@code V}/{@code v} stand for the return type and value of the
5738      * {@code filter}, which are also found in the signature and arguments of
5739      * the {@code target}, respectively, unless {@code V} is {@code void}.
5740      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5741      * and values preceding and following the collection position, {@code pos},
5742      * in the {@code target}'s signature. They also turn up in the resulting
5743      * adapter's signature and arguments, where they surround
5744      * {@code B}/{@code b}, which represent the parameter types and arguments
5745      * to the {@code filter} (if any).
5746      * {@snippet lang="java" :
5747      * T target(A...,V,C...);
5748      * V filter(B...);
5749      * T adapter(A... a,B... b,C... c) {
5750      *   V v = filter(b...);
5751      *   return target(a...,v,c...);
5752      * }
5753      * // and if the filter has no arguments:
5754      * T target2(A...,V,C...);
5755      * V filter2();
5756      * T adapter2(A... a,C... c) {
5757      *   V v = filter2();
5758      *   return target2(a...,v,c...);
5759      * }
5760      * // and if the filter has a void return:
5761      * T target3(A...,C...);
5762      * void filter3(B...);
5763      * T adapter3(A... a,B... b,C... c) {
5764      *   filter3(b...);
5765      *   return target3(a...,c...);
5766      * }
5767      * }
5768      * <p>
5769      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5770      * one which first "folds" the affected arguments, and then drops them, in separate
5771      * steps as follows:
5772      * {@snippet lang="java" :
5773      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5774      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5775      * }
5776      * If the target method handle consumes no arguments besides than the result
5777      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5778      * is equivalent to {@code filterReturnValue(coll, mh)}.
5779      * If the filter method handle {@code coll} consumes one argument and produces
5780      * a non-void result, then {@code collectArguments(mh, N, coll)}
5781      * is equivalent to {@code filterArguments(mh, N, coll)}.
5782      * Other equivalences are possible but would require argument permutation.
5783      * <p>
5784      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5785      * variable-arity method handle}, even if the original target method handle was.
5786      *
5787      * @param target the method handle to invoke after filtering the subsequence of arguments
5788      * @param pos the position of the first adapter argument to pass to the filter,
5789      *            and/or the target argument which receives the result of the filter
5790      * @param filter method handle to call on the subsequence of arguments
5791      * @return method handle which incorporates the specified argument subsequence filtering logic
5792      * @throws NullPointerException if either argument is null
5793      * @throws IllegalArgumentException if the return type of {@code filter}
5794      *          is non-void and is not the same as the {@code pos} argument of the target,
5795      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5796      *          or if the resulting method handle's type would have
5797      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5798      * @see MethodHandles#foldArguments
5799      * @see MethodHandles#filterArguments
5800      * @see MethodHandles#filterReturnValue
5801      */
5802     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5803         MethodType newType = collectArgumentsChecks(target, pos, filter);
5804         MethodType collectorType = filter.type();
5805         BoundMethodHandle result = target.rebind();
5806         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5807         return result.copyWithExtendL(newType, lform, filter);
5808     }
5809 
5810     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5811         MethodType targetType = target.type();
5812         MethodType filterType = filter.type();
5813         Class<?> rtype = filterType.returnType();
5814         Class<?>[] filterArgs = filterType.ptypes();
5815         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5816                        (rtype != void.class && pos >= targetType.parameterCount())) {
5817             throw newIllegalArgumentException("position is out of range for target", target, pos);
5818         }
5819         if (rtype == void.class) {
5820             return targetType.insertParameterTypes(pos, filterArgs);
5821         }
5822         if (rtype != targetType.parameterType(pos)) {
5823             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5824         }
5825         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5826     }
5827 
5828     /**
5829      * Adapts a target method handle by post-processing
5830      * its return value (if any) with a filter (another method handle).
5831      * The result of the filter is returned from the adapter.
5832      * <p>
5833      * If the target returns a value, the filter must accept that value as
5834      * its only argument.
5835      * If the target returns void, the filter must accept no arguments.
5836      * <p>
5837      * The return type of the filter
5838      * replaces the return type of the target
5839      * in the resulting adapted method handle.
5840      * The argument type of the filter (if any) must be identical to the
5841      * return type of the target.
5842      * <p><b>Example:</b>
5843      * {@snippet lang="java" :
5844 import static java.lang.invoke.MethodHandles.*;
5845 import static java.lang.invoke.MethodType.*;
5846 ...
5847 MethodHandle cat = lookup().findVirtual(String.class,
5848   "concat", methodType(String.class, String.class));
5849 MethodHandle length = lookup().findVirtual(String.class,
5850   "length", methodType(int.class));
5851 System.out.println((String) cat.invokeExact("x", "y")); // xy
5852 MethodHandle f0 = filterReturnValue(cat, length);
5853 System.out.println((int) f0.invokeExact("x", "y")); // 2
5854      * }
5855      * <p>Here is pseudocode for the resulting adapter. In the code,
5856      * {@code T}/{@code t} represent the result type and value of the
5857      * {@code target}; {@code V}, the result type of the {@code filter}; and
5858      * {@code A}/{@code a}, the types and values of the parameters and arguments
5859      * of the {@code target} as well as the resulting adapter.
5860      * {@snippet lang="java" :
5861      * T target(A...);
5862      * V filter(T);
5863      * V adapter(A... a) {
5864      *   T t = target(a...);
5865      *   return filter(t);
5866      * }
5867      * // and if the target has a void return:
5868      * void target2(A...);
5869      * V filter2();
5870      * V adapter2(A... a) {
5871      *   target2(a...);
5872      *   return filter2();
5873      * }
5874      * // and if the filter has a void return:
5875      * T target3(A...);
5876      * void filter3(V);
5877      * void adapter3(A... a) {
5878      *   T t = target3(a...);
5879      *   filter3(t);
5880      * }
5881      * }
5882      * <p>
5883      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5884      * variable-arity method handle}, even if the original target method handle was.
5885      * @param target the method handle to invoke before filtering the return value
5886      * @param filter method handle to call on the return value
5887      * @return method handle which incorporates the specified return value filtering logic
5888      * @throws NullPointerException if either argument is null
5889      * @throws IllegalArgumentException if the argument list of {@code filter}
5890      *          does not match the return type of target as described above
5891      */
5892     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5893         MethodType targetType = target.type();
5894         MethodType filterType = filter.type();
5895         filterReturnValueChecks(targetType, filterType);
5896         BoundMethodHandle result = target.rebind();
5897         BasicType rtype = BasicType.basicType(filterType.returnType());
5898         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5899         MethodType newType = targetType.changeReturnType(filterType.returnType());
5900         result = result.copyWithExtendL(newType, lform, filter);
5901         return result;
5902     }
5903 
5904     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5905         Class<?> rtype = targetType.returnType();
5906         int filterValues = filterType.parameterCount();
5907         if (filterValues == 0
5908                 ? (rtype != void.class)
5909                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5910             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5911     }
5912 
5913     /**
5914      * Filter the return value of a target method handle with a filter function. The filter function is
5915      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5916      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5917      * as follows:
5918      * {@snippet lang="java" :
5919      * T target(A...)
5920      * V filter(B... , T)
5921      * V adapter(A... a, B... b) {
5922      *     T t = target(a...);
5923      *     return filter(b..., t);
5924      * }
5925      * }
5926      * <p>
5927      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5928      *
5929      * @param target the target method handle
5930      * @param filter the filter method handle
5931      * @return the adapter method handle
5932      */
5933     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5934         MethodType targetType = target.type();
5935         MethodType filterType = filter.type();
5936         BoundMethodHandle result = target.rebind();
5937         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5938         MethodType newType = targetType.changeReturnType(filterType.returnType());
5939         if (filterType.parameterCount() > 1) {
5940             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5941                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5942             }
5943         }
5944         result = result.copyWithExtendL(newType, lform, filter);
5945         return result;
5946     }
5947 
5948     /**
5949      * Adapts a target method handle by pre-processing
5950      * some of its arguments, and then calling the target with
5951      * the result of the pre-processing, inserted into the original
5952      * sequence of arguments.
5953      * <p>
5954      * The pre-processing is performed by {@code combiner}, a second method handle.
5955      * Of the arguments passed to the adapter, the first {@code N} arguments
5956      * are copied to the combiner, which is then called.
5957      * (Here, {@code N} is defined as the parameter count of the combiner.)
5958      * After this, control passes to the target, with any result
5959      * from the combiner inserted before the original {@code N} incoming
5960      * arguments.
5961      * <p>
5962      * If the combiner returns a value, the first parameter type of the target
5963      * must be identical with the return type of the combiner, and the next
5964      * {@code N} parameter types of the target must exactly match the parameters
5965      * of the combiner.
5966      * <p>
5967      * If the combiner has a void return, no result will be inserted,
5968      * and the first {@code N} parameter types of the target
5969      * must exactly match the parameters of the combiner.
5970      * <p>
5971      * The resulting adapter is the same type as the target, except that the
5972      * first parameter type is dropped,
5973      * if it corresponds to the result of the combiner.
5974      * <p>
5975      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5976      * that either the combiner or the target does not wish to receive.
5977      * If some of the incoming arguments are destined only for the combiner,
5978      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5979      * arguments will not need to be live on the stack on entry to the
5980      * target.)
5981      * <p><b>Example:</b>
5982      * {@snippet lang="java" :
5983 import static java.lang.invoke.MethodHandles.*;
5984 import static java.lang.invoke.MethodType.*;
5985 ...
5986 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5987   "println", methodType(void.class, String.class))
5988     .bindTo(System.out);
5989 MethodHandle cat = lookup().findVirtual(String.class,
5990   "concat", methodType(String.class, String.class));
5991 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5992 MethodHandle catTrace = foldArguments(cat, trace);
5993 // also prints "boo":
5994 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5995      * }
5996      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5997      * represents the result type of the {@code target} and resulting adapter.
5998      * {@code V}/{@code v} represent the type and value of the parameter and argument
5999      * of {@code target} that precedes the folding position; {@code V} also is
6000      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6001      * types and values of the {@code N} parameters and arguments at the folding
6002      * position. {@code B}/{@code b} represent the types and values of the
6003      * {@code target} parameters and arguments that follow the folded parameters
6004      * and arguments.
6005      * {@snippet lang="java" :
6006      * // there are N arguments in A...
6007      * T target(V, A[N]..., B...);
6008      * V combiner(A...);
6009      * T adapter(A... a, B... b) {
6010      *   V v = combiner(a...);
6011      *   return target(v, a..., b...);
6012      * }
6013      * // and if the combiner has a void return:
6014      * T target2(A[N]..., B...);
6015      * void combiner2(A...);
6016      * T adapter2(A... a, B... b) {
6017      *   combiner2(a...);
6018      *   return target2(a..., b...);
6019      * }
6020      * }
6021      * <p>
6022      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6023      * variable-arity method handle}, even if the original target method handle was.
6024      * @param target the method handle to invoke after arguments are combined
6025      * @param combiner method handle to call initially on the incoming arguments
6026      * @return method handle which incorporates the specified argument folding logic
6027      * @throws NullPointerException if either argument is null
6028      * @throws IllegalArgumentException if {@code combiner}'s return type
6029      *          is non-void and not the same as the first argument type of
6030      *          the target, or if the initial {@code N} argument types
6031      *          of the target
6032      *          (skipping one matching the {@code combiner}'s return type)
6033      *          are not identical with the argument types of {@code combiner}
6034      */
6035     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6036         return foldArguments(target, 0, combiner);
6037     }
6038 
6039     /**
6040      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6041      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6042      * before the folded arguments.
6043      * <p>
6044      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6045      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6046      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6047      * 0.
6048      *
6049      * @apiNote Example:
6050      * {@snippet lang="java" :
6051     import static java.lang.invoke.MethodHandles.*;
6052     import static java.lang.invoke.MethodType.*;
6053     ...
6054     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6055     "println", methodType(void.class, String.class))
6056     .bindTo(System.out);
6057     MethodHandle cat = lookup().findVirtual(String.class,
6058     "concat", methodType(String.class, String.class));
6059     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6060     MethodHandle catTrace = foldArguments(cat, 1, trace);
6061     // also prints "jum":
6062     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6063      * }
6064      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6065      * represents the result type of the {@code target} and resulting adapter.
6066      * {@code V}/{@code v} represent the type and value of the parameter and argument
6067      * of {@code target} that precedes the folding position; {@code V} also is
6068      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6069      * types and values of the {@code N} parameters and arguments at the folding
6070      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6071      * and values of the {@code target} parameters and arguments that precede and
6072      * follow the folded parameters and arguments starting at {@code pos},
6073      * respectively.
6074      * {@snippet lang="java" :
6075      * // there are N arguments in A...
6076      * T target(Z..., V, A[N]..., B...);
6077      * V combiner(A...);
6078      * T adapter(Z... z, A... a, B... b) {
6079      *   V v = combiner(a...);
6080      *   return target(z..., v, a..., b...);
6081      * }
6082      * // and if the combiner has a void return:
6083      * T target2(Z..., A[N]..., B...);
6084      * void combiner2(A...);
6085      * T adapter2(Z... z, A... a, B... b) {
6086      *   combiner2(a...);
6087      *   return target2(z..., a..., b...);
6088      * }
6089      * }
6090      * <p>
6091      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6092      * variable-arity method handle}, even if the original target method handle was.
6093      *
6094      * @param target the method handle to invoke after arguments are combined
6095      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6096      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6097      * @param combiner method handle to call initially on the incoming arguments
6098      * @return method handle which incorporates the specified argument folding logic
6099      * @throws NullPointerException if either argument is null
6100      * @throws IllegalArgumentException if either of the following two conditions holds:
6101      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6102      *              {@code pos} of the target signature;
6103      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6104      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6105      *
6106      * @see #foldArguments(MethodHandle, MethodHandle)
6107      * @since 9
6108      */
6109     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6110         MethodType targetType = target.type();
6111         MethodType combinerType = combiner.type();
6112         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6113         BoundMethodHandle result = target.rebind();
6114         boolean dropResult = rtype == void.class;
6115         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6116         MethodType newType = targetType;
6117         if (!dropResult) {
6118             newType = newType.dropParameterTypes(pos, pos + 1);
6119         }
6120         result = result.copyWithExtendL(newType, lform, combiner);
6121         return result;
6122     }
6123 
6124     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6125         int foldArgs   = combinerType.parameterCount();
6126         Class<?> rtype = combinerType.returnType();
6127         int foldVals = rtype == void.class ? 0 : 1;
6128         int afterInsertPos = foldPos + foldVals;
6129         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6130         if (ok) {
6131             for (int i = 0; i < foldArgs; i++) {
6132                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6133                     ok = false;
6134                     break;
6135                 }
6136             }
6137         }
6138         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6139             ok = false;
6140         if (!ok)
6141             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6142         return rtype;
6143     }
6144 
6145     /**
6146      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6147      * of the pre-processing replacing the argument at the given position.
6148      *
6149      * @param target the method handle to invoke after arguments are combined
6150      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6151      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6152      * @param combiner method handle to call initially on the incoming arguments
6153      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6154      * @return method handle which incorporates the specified argument folding logic
6155      * @throws NullPointerException if either argument is null
6156      * @throws IllegalArgumentException if either of the following two conditions holds:
6157      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6158      *              {@code pos} of the target signature;
6159      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6160      *              not identical with the argument types of {@code combiner}.
6161      */
6162     /*non-public*/
6163     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6164         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6165     }
6166 
6167     /**
6168      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6169      * the pre-processing inserted into the original sequence of arguments at the given position.
6170      *
6171      * @param target the method handle to invoke after arguments are combined
6172      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6173      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6174      * @param combiner method handle to call initially on the incoming arguments
6175      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6176      * @return method handle which incorporates the specified argument folding logic
6177      * @throws NullPointerException if either argument is null
6178      * @throws IllegalArgumentException if either of the following two conditions holds:
6179      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6180      *              {@code pos} of the target signature;
6181      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6182      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6183      *              with the argument types of {@code combiner}.
6184      */
6185     /*non-public*/
6186     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6187         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6188     }
6189 
6190     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6191         MethodType targetType = target.type();
6192         MethodType combinerType = combiner.type();
6193         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6194         BoundMethodHandle result = target.rebind();
6195 
6196         MethodType newType = targetType;
6197         LambdaForm lform;
6198         if (filter) {
6199             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6200         } else {
6201             boolean dropResult = rtype == void.class;
6202             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6203             if (!dropResult) {
6204                 newType = newType.dropParameterTypes(position, position + 1);
6205             }
6206         }
6207         result = result.copyWithExtendL(newType, lform, combiner);
6208         return result;
6209     }
6210 
6211     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6212         int combinerArgs = combinerType.parameterCount();
6213         if (argPos.length != combinerArgs) {
6214             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6215         }
6216         Class<?> rtype = combinerType.returnType();
6217 
6218         for (int i = 0; i < combinerArgs; i++) {
6219             int arg = argPos[i];
6220             if (arg < 0 || arg > targetType.parameterCount()) {
6221                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6222             }
6223             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6224                 throw newIllegalArgumentException("target argument type at position " + arg
6225                         + " must match combiner argument type at index " + i + ": " + targetType
6226                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6227             }
6228         }
6229         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6230             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6231         }
6232         return rtype;
6233     }
6234 
6235     /**
6236      * Makes a method handle which adapts a target method handle,
6237      * by guarding it with a test, a boolean-valued method handle.
6238      * If the guard fails, a fallback handle is called instead.
6239      * All three method handles must have the same corresponding
6240      * argument and return types, except that the return type
6241      * of the test must be boolean, and the test is allowed
6242      * to have fewer arguments than the other two method handles.
6243      * <p>
6244      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6245      * represents the uniform result type of the three involved handles;
6246      * {@code A}/{@code a}, the types and values of the {@code target}
6247      * parameters and arguments that are consumed by the {@code test}; and
6248      * {@code B}/{@code b}, those types and values of the {@code target}
6249      * parameters and arguments that are not consumed by the {@code test}.
6250      * {@snippet lang="java" :
6251      * boolean test(A...);
6252      * T target(A...,B...);
6253      * T fallback(A...,B...);
6254      * T adapter(A... a,B... b) {
6255      *   if (test(a...))
6256      *     return target(a..., b...);
6257      *   else
6258      *     return fallback(a..., b...);
6259      * }
6260      * }
6261      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6262      * be modified by execution of the test, and so are passed unchanged
6263      * from the caller to the target or fallback as appropriate.
6264      * @param test method handle used for test, must return boolean
6265      * @param target method handle to call if test passes
6266      * @param fallback method handle to call if test fails
6267      * @return method handle which incorporates the specified if/then/else logic
6268      * @throws NullPointerException if any argument is null
6269      * @throws IllegalArgumentException if {@code test} does not return boolean,
6270      *          or if all three method types do not match (with the return
6271      *          type of {@code test} changed to match that of the target).
6272      */
6273     public static MethodHandle guardWithTest(MethodHandle test,
6274                                MethodHandle target,
6275                                MethodHandle fallback) {
6276         MethodType gtype = test.type();
6277         MethodType ttype = target.type();
6278         MethodType ftype = fallback.type();
6279         if (!ttype.equals(ftype))
6280             throw misMatchedTypes("target and fallback types", ttype, ftype);
6281         if (gtype.returnType() != boolean.class)
6282             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6283 
6284         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6285         if (test == null) {
6286             throw misMatchedTypes("target and test types", ttype, gtype);
6287         }
6288         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6289     }
6290 
6291     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6292         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6293     }
6294 
6295     /**
6296      * Makes a method handle which adapts a target method handle,
6297      * by running it inside an exception handler.
6298      * If the target returns normally, the adapter returns that value.
6299      * If an exception matching the specified type is thrown, the fallback
6300      * handle is called instead on the exception, plus the original arguments.
6301      * <p>
6302      * The target and handler must have the same corresponding
6303      * argument and return types, except that handler may omit trailing arguments
6304      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6305      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6306      * <p>
6307      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6308      * represents the return type of the {@code target} and {@code handler},
6309      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6310      * the types and values of arguments to the resulting handle consumed by
6311      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6312      * resulting handle discarded by {@code handler}.
6313      * {@snippet lang="java" :
6314      * T target(A..., B...);
6315      * T handler(ExType, A...);
6316      * T adapter(A... a, B... b) {
6317      *   try {
6318      *     return target(a..., b...);
6319      *   } catch (ExType ex) {
6320      *     return handler(ex, a...);
6321      *   }
6322      * }
6323      * }
6324      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6325      * be modified by execution of the target, and so are passed unchanged
6326      * from the caller to the handler, if the handler is invoked.
6327      * <p>
6328      * The target and handler must return the same type, even if the handler
6329      * always throws.  (This might happen, for instance, because the handler
6330      * is simulating a {@code finally} clause).
6331      * To create such a throwing handler, compose the handler creation logic
6332      * with {@link #throwException throwException},
6333      * in order to create a method handle of the correct return type.
6334      * @param target method handle to call
6335      * @param exType the type of exception which the handler will catch
6336      * @param handler method handle to call if a matching exception is thrown
6337      * @return method handle which incorporates the specified try/catch logic
6338      * @throws NullPointerException if any argument is null
6339      * @throws IllegalArgumentException if {@code handler} does not accept
6340      *          the given exception type, or if the method handle types do
6341      *          not match in their return types and their
6342      *          corresponding parameters
6343      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6344      */
6345     public static MethodHandle catchException(MethodHandle target,
6346                                 Class<? extends Throwable> exType,
6347                                 MethodHandle handler) {
6348         MethodType ttype = target.type();
6349         MethodType htype = handler.type();
6350         if (!Throwable.class.isAssignableFrom(exType))
6351             throw new ClassCastException(exType.getName());
6352         if (htype.parameterCount() < 1 ||
6353             !htype.parameterType(0).isAssignableFrom(exType))
6354             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6355         if (htype.returnType() != ttype.returnType())
6356             throw misMatchedTypes("target and handler return types", ttype, htype);
6357         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6358         if (handler == null) {
6359             throw misMatchedTypes("target and handler types", ttype, htype);
6360         }
6361         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6362     }
6363 
6364     /**
6365      * Produces a method handle which will throw exceptions of the given {@code exType}.
6366      * The method handle will accept a single argument of {@code exType},
6367      * and immediately throw it as an exception.
6368      * The method type will nominally specify a return of {@code returnType}.
6369      * The return type may be anything convenient:  It doesn't matter to the
6370      * method handle's behavior, since it will never return normally.
6371      * @param returnType the return type of the desired method handle
6372      * @param exType the parameter type of the desired method handle
6373      * @return method handle which can throw the given exceptions
6374      * @throws NullPointerException if either argument is null
6375      */
6376     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6377         if (!Throwable.class.isAssignableFrom(exType))
6378             throw new ClassCastException(exType.getName());
6379         return MethodHandleImpl.throwException(methodType(returnType, exType));
6380     }
6381 
6382     /**
6383      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6384      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6385      * delivers the loop's result, which is the return value of the resulting handle.
6386      * <p>
6387      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6388      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6389      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6390      * terms of method handles, each clause will specify up to four independent actions:<ul>
6391      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6392      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6393      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6394      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6395      * </ul>
6396      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6397      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6398      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6399      * <p>
6400      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6401      * this case. See below for a detailed description.
6402      * <p>
6403      * <em>Parameters optional everywhere:</em>
6404      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6405      * As an exception, the init functions cannot take any {@code v} parameters,
6406      * because those values are not yet computed when the init functions are executed.
6407      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6408      * In fact, any clause function may take no arguments at all.
6409      * <p>
6410      * <em>Loop parameters:</em>
6411      * A clause function may take all the iteration variable values it is entitled to, in which case
6412      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6413      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6414      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6415      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6416      * init function is automatically a loop parameter {@code a}.)
6417      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6418      * These loop parameters act as loop-invariant values visible across the whole loop.
6419      * <p>
6420      * <em>Parameters visible everywhere:</em>
6421      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6422      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6423      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6424      * Most clause functions will not need all of this information, but they will be formally connected to it
6425      * as if by {@link #dropArguments}.
6426      * <a id="astar"></a>
6427      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6428      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6429      * In that notation, the general form of an init function parameter list
6430      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6431      * <p>
6432      * <em>Checking clause structure:</em>
6433      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6434      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6435      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6436      * met by the inputs to the loop combinator.
6437      * <p>
6438      * <em>Effectively identical sequences:</em>
6439      * <a id="effid"></a>
6440      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6441      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6442      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6443      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6444      * that longest list.
6445      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6446      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6447      * <p>
6448      * <em>Step 0: Determine clause structure.</em><ol type="a">
6449      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6450      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6451      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6452      * four. Padding takes place by appending elements to the array.
6453      * <li>Clauses with all {@code null}s are disregarded.
6454      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6455      * </ol>
6456      * <p>
6457      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6458      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6459      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6460      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6461      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6462      * iteration variable type.
6463      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6464      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6465      * </ol>
6466      * <p>
6467      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6468      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6469      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6470      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6471      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6472      * (These types will be checked in step 2, along with all the clause function types.)
6473      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6474      * <li>All of the collected parameter lists must be effectively identical.
6475      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6476      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6477      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6478      * the "internal parameter list".
6479      * </ul>
6480      * <p>
6481      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6482      * <li>Examine fini function return types, disregarding omitted fini functions.
6483      * <li>If there are no fini functions, the loop return type is {@code void}.
6484      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6485      * type.
6486      * </ol>
6487      * <p>
6488      * <em>Step 1D: Check other types.</em><ol type="a">
6489      * <li>There must be at least one non-omitted pred function.
6490      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6491      * </ol>
6492      * <p>
6493      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6494      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6495      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6496      * (Note that their parameter lists are already effectively identical to this list.)
6497      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6498      * effectively identical to the internal parameter list {@code (V... A...)}.
6499      * </ol>
6500      * <p>
6501      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6502      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6503      * type.
6504      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6505      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6506      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6507      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6508      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6509      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6510      * loop return type.
6511      * </ol>
6512      * <p>
6513      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6514      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6515      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6516      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6517      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6518      * pad out the end of the list.
6519      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6520      * </ol>
6521      * <p>
6522      * <em>Final observations.</em><ol type="a">
6523      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6524      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6525      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6526      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6527      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6528      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6529      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6530      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6531      * </ol>
6532      * <p>
6533      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6534      * <ul>
6535      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6536      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6537      * (Only one {@code Pn} has to be non-{@code null}.)
6538      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6539      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6540      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6541      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6542      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6543      * the resulting loop handle's parameter types {@code (A...)}.
6544      * </ul>
6545      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6546      * which is natural if most of the loop computation happens in the steps.  For some loops,
6547      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6548      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6549      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6550      * where the init functions will need the extra parameters.  For such reasons, the rules for
6551      * determining these parameters are as symmetric as possible, across all clause parts.
6552      * In general, the loop parameters function as common invariant values across the whole
6553      * loop, while the iteration variables function as common variant values, or (if there is
6554      * no step function) as internal loop invariant temporaries.
6555      * <p>
6556      * <em>Loop execution.</em><ol type="a">
6557      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6558      * every clause function. These locals are loop invariant.
6559      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6560      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6561      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6562      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6563      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6564      * (in argument order).
6565      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6566      * returns {@code false}.
6567      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6568      * sequence {@code (v...)} of loop variables.
6569      * The updated value is immediately visible to all subsequent function calls.
6570      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6571      * (of type {@code R}) is returned from the loop as a whole.
6572      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6573      * except by throwing an exception.
6574      * </ol>
6575      * <p>
6576      * <em>Usage tips.</em>
6577      * <ul>
6578      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6579      * sometimes a step function only needs to observe the current value of its own variable.
6580      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6581      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6582      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6583      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6584      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6585      * <li>If some of the clause functions are virtual methods on an instance, the instance
6586      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6587      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6588      * will be the first iteration variable value, and it will be easy to use virtual
6589      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6590      * </ul>
6591      * <p>
6592      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6593      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6594      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6595      * {@snippet lang="java" :
6596      * V... init...(A...);
6597      * boolean pred...(V..., A...);
6598      * V... step...(V..., A...);
6599      * R fini...(V..., A...);
6600      * R loop(A... a) {
6601      *   V... v... = init...(a...);
6602      *   for (;;) {
6603      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6604      *       v = s(v..., a...);
6605      *       if (!p(v..., a...)) {
6606      *         return f(v..., a...);
6607      *       }
6608      *     }
6609      *   }
6610      * }
6611      * }
6612      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6613      * to their full length, even though individual clause functions may neglect to take them all.
6614      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6615      *
6616      * @apiNote Example:
6617      * {@snippet lang="java" :
6618      * // iterative implementation of the factorial function as a loop handle
6619      * static int one(int k) { return 1; }
6620      * static int inc(int i, int acc, int k) { return i + 1; }
6621      * static int mult(int i, int acc, int k) { return i * acc; }
6622      * static boolean pred(int i, int acc, int k) { return i < k; }
6623      * static int fin(int i, int acc, int k) { return acc; }
6624      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6625      * // null initializer for counter, should initialize to 0
6626      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6627      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6628      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6629      * assertEquals(120, loop.invoke(5));
6630      * }
6631      * The same example, dropping arguments and using combinators:
6632      * {@snippet lang="java" :
6633      * // simplified implementation of the factorial function as a loop handle
6634      * static int inc(int i) { return i + 1; } // drop acc, k
6635      * static int mult(int i, int acc) { return i * acc; } //drop k
6636      * static boolean cmp(int i, int k) { return i < k; }
6637      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6638      * // null initializer for counter, should initialize to 0
6639      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6640      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6641      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6642      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6643      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6644      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6645      * assertEquals(720, loop.invoke(6));
6646      * }
6647      * A similar example, using a helper object to hold a loop parameter:
6648      * {@snippet lang="java" :
6649      * // instance-based implementation of the factorial function as a loop handle
6650      * static class FacLoop {
6651      *   final int k;
6652      *   FacLoop(int k) { this.k = k; }
6653      *   int inc(int i) { return i + 1; }
6654      *   int mult(int i, int acc) { return i * acc; }
6655      *   boolean pred(int i) { return i < k; }
6656      *   int fin(int i, int acc) { return acc; }
6657      * }
6658      * // assume MH_FacLoop is a handle to the constructor
6659      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6660      * // null initializer for counter, should initialize to 0
6661      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6662      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6663      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6664      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6665      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6666      * assertEquals(5040, loop.invoke(7));
6667      * }
6668      *
6669      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6670      *
6671      * @return a method handle embodying the looping behavior as defined by the arguments.
6672      *
6673      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6674      *
6675      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6676      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6677      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6678      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6679      * @since 9
6680      */
6681     public static MethodHandle loop(MethodHandle[]... clauses) {
6682         // Step 0: determine clause structure.
6683         loopChecks0(clauses);
6684 
6685         List<MethodHandle> init = new ArrayList<>();
6686         List<MethodHandle> step = new ArrayList<>();
6687         List<MethodHandle> pred = new ArrayList<>();
6688         List<MethodHandle> fini = new ArrayList<>();
6689 
6690         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6691             init.add(clause[0]); // all clauses have at least length 1
6692             step.add(clause.length <= 1 ? null : clause[1]);
6693             pred.add(clause.length <= 2 ? null : clause[2]);
6694             fini.add(clause.length <= 3 ? null : clause[3]);
6695         });
6696 
6697         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6698         final int nclauses = init.size();
6699 
6700         // Step 1A: determine iteration variables (V...).
6701         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6702         for (int i = 0; i < nclauses; ++i) {
6703             MethodHandle in = init.get(i);
6704             MethodHandle st = step.get(i);
6705             if (in == null && st == null) {
6706                 iterationVariableTypes.add(void.class);
6707             } else if (in != null && st != null) {
6708                 loopChecks1a(i, in, st);
6709                 iterationVariableTypes.add(in.type().returnType());
6710             } else {
6711                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6712             }
6713         }
6714         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6715 
6716         // Step 1B: determine loop parameters (A...).
6717         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6718         loopChecks1b(init, commonSuffix);
6719 
6720         // Step 1C: determine loop return type.
6721         // Step 1D: check other types.
6722         // local variable required here; see JDK-8223553
6723         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6724                 .map(MethodType::returnType);
6725         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6726         loopChecks1cd(pred, fini, loopReturnType);
6727 
6728         // Step 2: determine parameter lists.
6729         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6730         commonParameterSequence.addAll(commonSuffix);
6731         loopChecks2(step, pred, fini, commonParameterSequence);
6732         // Step 3: fill in omitted functions.
6733         for (int i = 0; i < nclauses; ++i) {
6734             Class<?> t = iterationVariableTypes.get(i);
6735             if (init.get(i) == null) {
6736                 init.set(i, empty(methodType(t, commonSuffix)));
6737             }
6738             if (step.get(i) == null) {
6739                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6740             }
6741             if (pred.get(i) == null) {
6742                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6743             }
6744             if (fini.get(i) == null) {
6745                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6746             }
6747         }
6748 
6749         // Step 4: fill in missing parameter types.
6750         // Also convert all handles to fixed-arity handles.
6751         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6752         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6753         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6754         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6755 
6756         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6757                 allMatch(pl -> pl.equals(commonSuffix));
6758         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6759                 allMatch(pl -> pl.equals(commonParameterSequence));
6760 
6761         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6762     }
6763 
6764     private static void loopChecks0(MethodHandle[][] clauses) {
6765         if (clauses == null || clauses.length == 0) {
6766             throw newIllegalArgumentException("null or no clauses passed");
6767         }
6768         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6769             throw newIllegalArgumentException("null clauses are not allowed");
6770         }
6771         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6772             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6773         }
6774     }
6775 
6776     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6777         if (in.type().returnType() != st.type().returnType()) {
6778             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6779                     st.type().returnType());
6780         }
6781     }
6782 
6783     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6784         final List<Class<?>> empty = List.of();
6785         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6786                 // take only those that can contribute to a common suffix because they are longer than the prefix
6787                         map(MethodHandle::type).
6788                         filter(t -> t.parameterCount() > skipSize).
6789                         map(MethodType::parameterList).
6790                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6791         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6792     }
6793 
6794     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6795         final List<Class<?>> empty = List.of();
6796         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6797     }
6798 
6799     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6800         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6801         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6802         return longestParameterList(List.of(longest1, longest2));
6803     }
6804 
6805     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6806         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6807                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6808             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6809                     " (common suffix: " + commonSuffix + ")");
6810         }
6811     }
6812 
6813     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6814         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6815                 anyMatch(t -> t != loopReturnType)) {
6816             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6817                     loopReturnType + ")");
6818         }
6819 
6820         if (pred.stream().noneMatch(Objects::nonNull)) {
6821             throw newIllegalArgumentException("no predicate found", pred);
6822         }
6823         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6824                 anyMatch(t -> t != boolean.class)) {
6825             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6826         }
6827     }
6828 
6829     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6830         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6831                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6832             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6833                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6834         }
6835     }
6836 
6837     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6838         return hs.stream().map(h -> {
6839             int pc = h.type().parameterCount();
6840             int tpsize = targetParams.size();
6841             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6842         }).toList();
6843     }
6844 
6845     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6846         return hs.stream().map(MethodHandle::asFixedArity).toList();
6847     }
6848 
6849     /**
6850      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6851      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6852      * <p>
6853      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6854      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6855      * evaluates to {@code true}).
6856      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6857      * <p>
6858      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6859      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6860      * and updated with the value returned from its invocation. The result of loop execution will be
6861      * the final value of the additional loop-local variable (if present).
6862      * <p>
6863      * The following rules hold for these argument handles:<ul>
6864      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6865      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6866      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6867      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6868      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6869      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6870      * It will constrain the parameter lists of the other loop parts.
6871      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6872      * list {@code (A...)} is called the <em>external parameter list</em>.
6873      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6874      * additional state variable of the loop.
6875      * The body must both accept and return a value of this type {@code V}.
6876      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6877      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6878      * <a href="MethodHandles.html#effid">effectively identical</a>
6879      * to the external parameter list {@code (A...)}.
6880      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6881      * {@linkplain #empty default value}.
6882      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6883      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6884      * effectively identical to the internal parameter list.
6885      * </ul>
6886      * <p>
6887      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6888      * <li>The loop handle's result type is the result type {@code V} of the body.
6889      * <li>The loop handle's parameter types are the types {@code (A...)},
6890      * from the external parameter list.
6891      * </ul>
6892      * <p>
6893      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6894      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6895      * passed to the loop.
6896      * {@snippet lang="java" :
6897      * V init(A...);
6898      * boolean pred(V, A...);
6899      * V body(V, A...);
6900      * V whileLoop(A... a...) {
6901      *   V v = init(a...);
6902      *   while (pred(v, a...)) {
6903      *     v = body(v, a...);
6904      *   }
6905      *   return v;
6906      * }
6907      * }
6908      *
6909      * @apiNote Example:
6910      * {@snippet lang="java" :
6911      * // implement the zip function for lists as a loop handle
6912      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6913      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6914      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6915      *   zip.add(a.next());
6916      *   zip.add(b.next());
6917      *   return zip;
6918      * }
6919      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6920      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6921      * List<String> a = Arrays.asList("a", "b", "c", "d");
6922      * List<String> b = Arrays.asList("e", "f", "g", "h");
6923      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6924      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6925      * }
6926      *
6927      *
6928      * @apiNote The implementation of this method can be expressed as follows:
6929      * {@snippet lang="java" :
6930      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6931      *     MethodHandle fini = (body.type().returnType() == void.class
6932      *                         ? null : identity(body.type().returnType()));
6933      *     MethodHandle[]
6934      *         checkExit = { null, null, pred, fini },
6935      *         varBody   = { init, body };
6936      *     return loop(checkExit, varBody);
6937      * }
6938      * }
6939      *
6940      * @param init optional initializer, providing the initial value of the loop variable.
6941      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6942      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6943      *             above for other constraints.
6944      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6945      *             See above for other constraints.
6946      *
6947      * @return a method handle implementing the {@code while} loop as described by the arguments.
6948      * @throws IllegalArgumentException if the rules for the arguments are violated.
6949      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6950      *
6951      * @see #loop(MethodHandle[][])
6952      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6953      * @since 9
6954      */
6955     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6956         whileLoopChecks(init, pred, body);
6957         MethodHandle fini = identityOrVoid(body.type().returnType());
6958         MethodHandle[] checkExit = { null, null, pred, fini };
6959         MethodHandle[] varBody = { init, body };
6960         return loop(checkExit, varBody);
6961     }
6962 
6963     /**
6964      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6965      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6966      * <p>
6967      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6968      * method will, in each iteration, first execute its body and then evaluate the predicate.
6969      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6970      * <p>
6971      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6972      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6973      * and updated with the value returned from its invocation. The result of loop execution will be
6974      * the final value of the additional loop-local variable (if present).
6975      * <p>
6976      * The following rules hold for these argument handles:<ul>
6977      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6978      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6979      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6980      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6981      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6982      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6983      * It will constrain the parameter lists of the other loop parts.
6984      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6985      * list {@code (A...)} is called the <em>external parameter list</em>.
6986      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6987      * additional state variable of the loop.
6988      * The body must both accept and return a value of this type {@code V}.
6989      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6990      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6991      * <a href="MethodHandles.html#effid">effectively identical</a>
6992      * to the external parameter list {@code (A...)}.
6993      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6994      * {@linkplain #empty default value}.
6995      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6996      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6997      * effectively identical to the internal parameter list.
6998      * </ul>
6999      * <p>
7000      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7001      * <li>The loop handle's result type is the result type {@code V} of the body.
7002      * <li>The loop handle's parameter types are the types {@code (A...)},
7003      * from the external parameter list.
7004      * </ul>
7005      * <p>
7006      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7007      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7008      * passed to the loop.
7009      * {@snippet lang="java" :
7010      * V init(A...);
7011      * boolean pred(V, A...);
7012      * V body(V, A...);
7013      * V doWhileLoop(A... a...) {
7014      *   V v = init(a...);
7015      *   do {
7016      *     v = body(v, a...);
7017      *   } while (pred(v, a...));
7018      *   return v;
7019      * }
7020      * }
7021      *
7022      * @apiNote Example:
7023      * {@snippet lang="java" :
7024      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7025      * static int zero(int limit) { return 0; }
7026      * static int step(int i, int limit) { return i + 1; }
7027      * static boolean pred(int i, int limit) { return i < limit; }
7028      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7029      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7030      * assertEquals(23, loop.invoke(23));
7031      * }
7032      *
7033      *
7034      * @apiNote The implementation of this method can be expressed as follows:
7035      * {@snippet lang="java" :
7036      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7037      *     MethodHandle fini = (body.type().returnType() == void.class
7038      *                         ? null : identity(body.type().returnType()));
7039      *     MethodHandle[] clause = { init, body, pred, fini };
7040      *     return loop(clause);
7041      * }
7042      * }
7043      *
7044      * @param init optional initializer, providing the initial value of the loop variable.
7045      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7046      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7047      *             See above for other constraints.
7048      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7049      *             above for other constraints.
7050      *
7051      * @return a method handle implementing the {@code while} loop as described by the arguments.
7052      * @throws IllegalArgumentException if the rules for the arguments are violated.
7053      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7054      *
7055      * @see #loop(MethodHandle[][])
7056      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7057      * @since 9
7058      */
7059     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7060         whileLoopChecks(init, pred, body);
7061         MethodHandle fini = identityOrVoid(body.type().returnType());
7062         MethodHandle[] clause = {init, body, pred, fini };
7063         return loop(clause);
7064     }
7065 
7066     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7067         Objects.requireNonNull(pred);
7068         Objects.requireNonNull(body);
7069         MethodType bodyType = body.type();
7070         Class<?> returnType = bodyType.returnType();
7071         List<Class<?>> innerList = bodyType.parameterList();
7072         List<Class<?>> outerList = innerList;
7073         if (returnType == void.class) {
7074             // OK
7075         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7076             // leading V argument missing => error
7077             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7078             throw misMatchedTypes("body function", bodyType, expected);
7079         } else {
7080             outerList = innerList.subList(1, innerList.size());
7081         }
7082         MethodType predType = pred.type();
7083         if (predType.returnType() != boolean.class ||
7084                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7085             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7086         }
7087         if (init != null) {
7088             MethodType initType = init.type();
7089             if (initType.returnType() != returnType ||
7090                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7091                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7092             }
7093         }
7094     }
7095 
7096     /**
7097      * Constructs a loop that runs a given number of iterations.
7098      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7099      * <p>
7100      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7101      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7102      * It will be initialized to 0 and incremented by 1 in each iteration.
7103      * <p>
7104      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7105      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7106      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7107      * <p>
7108      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7109      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7110      * iteration variable.
7111      * The result of the loop handle execution will be the final {@code V} value of that variable
7112      * (or {@code void} if there is no {@code V} variable).
7113      * <p>
7114      * The following rules hold for the argument handles:<ul>
7115      * <li>The {@code iterations} handle must not be {@code null}, and must return
7116      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7117      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7118      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7119      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7120      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7121      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7122      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7123      * of types called the <em>internal parameter list</em>.
7124      * It will constrain the parameter lists of the other loop parts.
7125      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7126      * with no additional {@code A} types, then the internal parameter list is extended by
7127      * the argument types {@code A...} of the {@code iterations} handle.
7128      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7129      * list {@code (A...)} is called the <em>external parameter list</em>.
7130      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7131      * additional state variable of the loop.
7132      * The body must both accept a leading parameter and return a value of this type {@code V}.
7133      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7134      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7135      * <a href="MethodHandles.html#effid">effectively identical</a>
7136      * to the external parameter list {@code (A...)}.
7137      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7138      * {@linkplain #empty default value}.
7139      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7140      * effectively identical to the external parameter list {@code (A...)}.
7141      * </ul>
7142      * <p>
7143      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7144      * <li>The loop handle's result type is the result type {@code V} of the body.
7145      * <li>The loop handle's parameter types are the types {@code (A...)},
7146      * from the external parameter list.
7147      * </ul>
7148      * <p>
7149      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7150      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7151      * arguments passed to the loop.
7152      * {@snippet lang="java" :
7153      * int iterations(A...);
7154      * V init(A...);
7155      * V body(V, int, A...);
7156      * V countedLoop(A... a...) {
7157      *   int end = iterations(a...);
7158      *   V v = init(a...);
7159      *   for (int i = 0; i < end; ++i) {
7160      *     v = body(v, i, a...);
7161      *   }
7162      *   return v;
7163      * }
7164      * }
7165      *
7166      * @apiNote Example with a fully conformant body method:
7167      * {@snippet lang="java" :
7168      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7169      * // => a variation on a well known theme
7170      * static String step(String v, int counter, String init) { return "na " + v; }
7171      * // assume MH_step is a handle to the method above
7172      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7173      * MethodHandle start = MethodHandles.identity(String.class);
7174      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7175      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7176      * }
7177      *
7178      * @apiNote Example with the simplest possible body method type,
7179      * and passing the number of iterations to the loop invocation:
7180      * {@snippet lang="java" :
7181      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7182      * // => a variation on a well known theme
7183      * static String step(String v, int counter ) { return "na " + v; }
7184      * // assume MH_step is a handle to the method above
7185      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7186      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7187      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7188      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7189      * }
7190      *
7191      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7192      * as loop parameters:
7193      * {@snippet lang="java" :
7194      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7195      * // => a variation on a well known theme
7196      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7197      * // assume MH_step is a handle to the method above
7198      * MethodHandle count = MethodHandles.identity(int.class);
7199      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7200      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7201      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7202      * }
7203      *
7204      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7205      * to enforce a loop type:
7206      * {@snippet lang="java" :
7207      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7208      * // => a variation on a well known theme
7209      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7210      * // assume MH_step is a handle to the method above
7211      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7212      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7213      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7214      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7215      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7216      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7217      * }
7218      *
7219      * @apiNote The implementation of this method can be expressed as follows:
7220      * {@snippet lang="java" :
7221      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7222      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7223      * }
7224      * }
7225      *
7226      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7227      *                   result type must be {@code int}. See above for other constraints.
7228      * @param init optional initializer, providing the initial value of the loop variable.
7229      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7230      * @param body body of the loop, which may not be {@code null}.
7231      *             It controls the loop parameters and result type in the standard case (see above for details).
7232      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7233      *             and may accept any number of additional types.
7234      *             See above for other constraints.
7235      *
7236      * @return a method handle representing the loop.
7237      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7238      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7239      *
7240      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7241      * @since 9
7242      */
7243     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7244         return countedLoop(empty(iterations.type()), iterations, init, body);
7245     }
7246 
7247     /**
7248      * Constructs a loop that counts over a range of numbers.
7249      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7250      * <p>
7251      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7252      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7253      * values of the loop counter.
7254      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7255      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7256      * <p>
7257      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7258      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7259      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7260      * <p>
7261      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7262      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7263      * iteration variable.
7264      * The result of the loop handle execution will be the final {@code V} value of that variable
7265      * (or {@code void} if there is no {@code V} variable).
7266      * <p>
7267      * The following rules hold for the argument handles:<ul>
7268      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7269      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7270      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7271      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7272      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7273      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7274      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7275      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7276      * of types called the <em>internal parameter list</em>.
7277      * It will constrain the parameter lists of the other loop parts.
7278      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7279      * with no additional {@code A} types, then the internal parameter list is extended by
7280      * the argument types {@code A...} of the {@code end} handle.
7281      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7282      * list {@code (A...)} is called the <em>external parameter list</em>.
7283      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7284      * additional state variable of the loop.
7285      * The body must both accept a leading parameter and return a value of this type {@code V}.
7286      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7287      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7288      * <a href="MethodHandles.html#effid">effectively identical</a>
7289      * to the external parameter list {@code (A...)}.
7290      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7291      * {@linkplain #empty default value}.
7292      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7293      * effectively identical to the external parameter list {@code (A...)}.
7294      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7295      * to the external parameter list.
7296      * </ul>
7297      * <p>
7298      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7299      * <li>The loop handle's result type is the result type {@code V} of the body.
7300      * <li>The loop handle's parameter types are the types {@code (A...)},
7301      * from the external parameter list.
7302      * </ul>
7303      * <p>
7304      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7305      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7306      * arguments passed to the loop.
7307      * {@snippet lang="java" :
7308      * int start(A...);
7309      * int end(A...);
7310      * V init(A...);
7311      * V body(V, int, A...);
7312      * V countedLoop(A... a...) {
7313      *   int e = end(a...);
7314      *   int s = start(a...);
7315      *   V v = init(a...);
7316      *   for (int i = s; i < e; ++i) {
7317      *     v = body(v, i, a...);
7318      *   }
7319      *   return v;
7320      * }
7321      * }
7322      *
7323      * @apiNote The implementation of this method can be expressed as follows:
7324      * {@snippet lang="java" :
7325      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7326      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7327      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7328      *     // the following semantics:
7329      *     // MH_increment: (int limit, int counter) -> counter + 1
7330      *     // MH_predicate: (int limit, int counter) -> counter < limit
7331      *     Class<?> counterType = start.type().returnType();  // int
7332      *     Class<?> returnType = body.type().returnType();
7333      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7334      *     if (returnType != void.class) {  // ignore the V variable
7335      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7336      *         pred = dropArguments(pred, 1, returnType);  // ditto
7337      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7338      *     }
7339      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7340      *     MethodHandle[]
7341      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7342      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7343      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7344      *     return loop(loopLimit, bodyClause, indexVar);
7345      * }
7346      * }
7347      *
7348      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7349      *              See above for other constraints.
7350      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7351      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7352      * @param init optional initializer, providing the initial value of the loop variable.
7353      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7354      * @param body body of the loop, which may not be {@code null}.
7355      *             It controls the loop parameters and result type in the standard case (see above for details).
7356      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7357      *             and may accept any number of additional types.
7358      *             See above for other constraints.
7359      *
7360      * @return a method handle representing the loop.
7361      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7362      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7363      *
7364      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7365      * @since 9
7366      */
7367     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7368         countedLoopChecks(start, end, init, body);
7369         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7370         Class<?> limitType   = end.type().returnType();    // yes, int again
7371         Class<?> returnType  = body.type().returnType();
7372         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7373         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7374         MethodHandle retv = null;
7375         if (returnType != void.class) {
7376             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7377             pred = dropArguments(pred, 1, returnType);  // ditto
7378             retv = dropArguments(identity(returnType), 0, counterType);
7379         }
7380         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7381         MethodHandle[]
7382             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7383             bodyClause = { init, body },            // v = init(); v = body(v, i)
7384             indexVar   = { start, incr };           // i = start(); i = i + 1
7385         return loop(loopLimit, bodyClause, indexVar);
7386     }
7387 
7388     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7389         Objects.requireNonNull(start);
7390         Objects.requireNonNull(end);
7391         Objects.requireNonNull(body);
7392         Class<?> counterType = start.type().returnType();
7393         if (counterType != int.class) {
7394             MethodType expected = start.type().changeReturnType(int.class);
7395             throw misMatchedTypes("start function", start.type(), expected);
7396         } else if (end.type().returnType() != counterType) {
7397             MethodType expected = end.type().changeReturnType(counterType);
7398             throw misMatchedTypes("end function", end.type(), expected);
7399         }
7400         MethodType bodyType = body.type();
7401         Class<?> returnType = bodyType.returnType();
7402         List<Class<?>> innerList = bodyType.parameterList();
7403         // strip leading V value if present
7404         int vsize = (returnType == void.class ? 0 : 1);
7405         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7406             // argument list has no "V" => error
7407             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7408             throw misMatchedTypes("body function", bodyType, expected);
7409         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7410             // missing I type => error
7411             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7412             throw misMatchedTypes("body function", bodyType, expected);
7413         }
7414         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7415         if (outerList.isEmpty()) {
7416             // special case; take lists from end handle
7417             outerList = end.type().parameterList();
7418             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7419         }
7420         MethodType expected = methodType(counterType, outerList);
7421         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7422             throw misMatchedTypes("start parameter types", start.type(), expected);
7423         }
7424         if (end.type() != start.type() &&
7425             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7426             throw misMatchedTypes("end parameter types", end.type(), expected);
7427         }
7428         if (init != null) {
7429             MethodType initType = init.type();
7430             if (initType.returnType() != returnType ||
7431                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7432                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7433             }
7434         }
7435     }
7436 
7437     /**
7438      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7439      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7440      * <p>
7441      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7442      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7443      * <p>
7444      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7445      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7446      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7447      * <p>
7448      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7449      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7450      * iteration variable.
7451      * The result of the loop handle execution will be the final {@code V} value of that variable
7452      * (or {@code void} if there is no {@code V} variable).
7453      * <p>
7454      * The following rules hold for the argument handles:<ul>
7455      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7456      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7457      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7458      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7459      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7460      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7461      * of types called the <em>internal parameter list</em>.
7462      * It will constrain the parameter lists of the other loop parts.
7463      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7464      * with no additional {@code A} types, then the internal parameter list is extended by
7465      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7466      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7467      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7468      * list {@code (A...)} is called the <em>external parameter list</em>.
7469      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7470      * additional state variable of the loop.
7471      * The body must both accept a leading parameter and return a value of this type {@code V}.
7472      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7473      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7474      * <a href="MethodHandles.html#effid">effectively identical</a>
7475      * to the external parameter list {@code (A...)}.
7476      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7477      * {@linkplain #empty default value}.
7478      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7479      * type {@code java.util.Iterator} or a subtype thereof.
7480      * The iterator it produces when the loop is executed will be assumed
7481      * to yield values which can be converted to type {@code T}.
7482      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7483      * effectively identical to the external parameter list {@code (A...)}.
7484      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7485      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7486      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7487      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7488      * the {@link MethodHandle#asType asType} conversion method.
7489      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7490      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7491      * </ul>
7492      * <p>
7493      * The type {@code T} may be either a primitive or reference.
7494      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7495      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7496      * as if by the {@link MethodHandle#asType asType} conversion method.
7497      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7498      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7499      * <p>
7500      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7501      * <li>The loop handle's result type is the result type {@code V} of the body.
7502      * <li>The loop handle's parameter types are the types {@code (A...)},
7503      * from the external parameter list.
7504      * </ul>
7505      * <p>
7506      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7507      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7508      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7509      * {@snippet lang="java" :
7510      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7511      * V init(A...);
7512      * V body(V,T,A...);
7513      * V iteratedLoop(A... a...) {
7514      *   Iterator<T> it = iterator(a...);
7515      *   V v = init(a...);
7516      *   while (it.hasNext()) {
7517      *     T t = it.next();
7518      *     v = body(v, t, a...);
7519      *   }
7520      *   return v;
7521      * }
7522      * }
7523      *
7524      * @apiNote Example:
7525      * {@snippet lang="java" :
7526      * // get an iterator from a list
7527      * static List<String> reverseStep(List<String> r, String e) {
7528      *   r.add(0, e);
7529      *   return r;
7530      * }
7531      * static List<String> newArrayList() { return new ArrayList<>(); }
7532      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7533      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7534      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7535      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7536      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7537      * }
7538      *
7539      * @apiNote The implementation of this method can be expressed approximately as follows:
7540      * {@snippet lang="java" :
7541      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7542      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7543      *     Class<?> returnType = body.type().returnType();
7544      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7545      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7546      *     MethodHandle retv = null, step = body, startIter = iterator;
7547      *     if (returnType != void.class) {
7548      *         // the simple thing first:  in (I V A...), drop the I to get V
7549      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7550      *         // body type signature (V T A...), internal loop types (I V A...)
7551      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7552      *     }
7553      *     if (startIter == null)  startIter = MH_getIter;
7554      *     MethodHandle[]
7555      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7556      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7557      *     return loop(iterVar, bodyClause);
7558      * }
7559      * }
7560      *
7561      * @param iterator an optional handle to return the iterator to start the loop.
7562      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7563      *                 See above for other constraints.
7564      * @param init optional initializer, providing the initial value of the loop variable.
7565      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7566      * @param body body of the loop, which may not be {@code null}.
7567      *             It controls the loop parameters and result type in the standard case (see above for details).
7568      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7569      *             and may accept any number of additional types.
7570      *             See above for other constraints.
7571      *
7572      * @return a method handle embodying the iteration loop functionality.
7573      * @throws NullPointerException if the {@code body} handle is {@code null}.
7574      * @throws IllegalArgumentException if any argument violates the above requirements.
7575      *
7576      * @since 9
7577      */
7578     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7579         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7580         Class<?> returnType = body.type().returnType();
7581         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7582         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7583         MethodHandle startIter;
7584         MethodHandle nextVal;
7585         {
7586             MethodType iteratorType;
7587             if (iterator == null) {
7588                 // derive argument type from body, if available, else use Iterable
7589                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7590                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7591             } else {
7592                 // force return type to the internal iterator class
7593                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7594                 startIter = iterator;
7595             }
7596             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7597             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7598 
7599             // perform the asType transforms under an exception transformer, as per spec.:
7600             try {
7601                 startIter = startIter.asType(iteratorType);
7602                 nextVal = nextRaw.asType(nextValType);
7603             } catch (WrongMethodTypeException ex) {
7604                 throw new IllegalArgumentException(ex);
7605             }
7606         }
7607 
7608         MethodHandle retv = null, step = body;
7609         if (returnType != void.class) {
7610             // the simple thing first:  in (I V A...), drop the I to get V
7611             retv = dropArguments(identity(returnType), 0, Iterator.class);
7612             // body type signature (V T A...), internal loop types (I V A...)
7613             step = swapArguments(body, 0, 1);  // swap V <-> T
7614         }
7615 
7616         MethodHandle[]
7617             iterVar    = { startIter, null, hasNext, retv },
7618             bodyClause = { init, filterArgument(step, 0, nextVal) };
7619         return loop(iterVar, bodyClause);
7620     }
7621 
7622     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7623         Objects.requireNonNull(body);
7624         MethodType bodyType = body.type();
7625         Class<?> returnType = bodyType.returnType();
7626         List<Class<?>> internalParamList = bodyType.parameterList();
7627         // strip leading V value if present
7628         int vsize = (returnType == void.class ? 0 : 1);
7629         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7630             // argument list has no "V" => error
7631             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7632             throw misMatchedTypes("body function", bodyType, expected);
7633         } else if (internalParamList.size() <= vsize) {
7634             // missing T type => error
7635             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7636             throw misMatchedTypes("body function", bodyType, expected);
7637         }
7638         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7639         Class<?> iterableType = null;
7640         if (iterator != null) {
7641             // special case; if the body handle only declares V and T then
7642             // the external parameter list is obtained from iterator handle
7643             if (externalParamList.isEmpty()) {
7644                 externalParamList = iterator.type().parameterList();
7645             }
7646             MethodType itype = iterator.type();
7647             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7648                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7649             }
7650             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7651                 MethodType expected = methodType(itype.returnType(), externalParamList);
7652                 throw misMatchedTypes("iterator parameters", itype, expected);
7653             }
7654         } else {
7655             if (externalParamList.isEmpty()) {
7656                 // special case; if the iterator handle is null and the body handle
7657                 // only declares V and T then the external parameter list consists
7658                 // of Iterable
7659                 externalParamList = List.of(Iterable.class);
7660                 iterableType = Iterable.class;
7661             } else {
7662                 // special case; if the iterator handle is null and the external
7663                 // parameter list is not empty then the first parameter must be
7664                 // assignable to Iterable
7665                 iterableType = externalParamList.get(0);
7666                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7667                     throw newIllegalArgumentException(
7668                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7669                 }
7670             }
7671         }
7672         if (init != null) {
7673             MethodType initType = init.type();
7674             if (initType.returnType() != returnType ||
7675                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7676                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7677             }
7678         }
7679         return iterableType;  // help the caller a bit
7680     }
7681 
7682     /*non-public*/
7683     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7684         // there should be a better way to uncross my wires
7685         int arity = mh.type().parameterCount();
7686         int[] order = new int[arity];
7687         for (int k = 0; k < arity; k++)  order[k] = k;
7688         order[i] = j; order[j] = i;
7689         Class<?>[] types = mh.type().parameterArray();
7690         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7691         MethodType swapType = methodType(mh.type().returnType(), types);
7692         return permuteArguments(mh, swapType, order);
7693     }
7694 
7695     /**
7696      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7697      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7698      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7699      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7700      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7701      * {@code try-finally} handle.
7702      * <p>
7703      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7704      * The first is the exception thrown during the
7705      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7706      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7707      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7708      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7709      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7710      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7711      * <p>
7712      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7713      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7714      * two extra leading parameters:<ul>
7715      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7716      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7717      * the result from the execution of the {@code target} handle.
7718      * This parameter is not present if the {@code target} returns {@code void}.
7719      * </ul>
7720      * <p>
7721      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7722      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7723      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7724      * the cleanup.
7725      * {@snippet lang="java" :
7726      * V target(A..., B...);
7727      * V cleanup(Throwable, V, A...);
7728      * V adapter(A... a, B... b) {
7729      *   V result = (zero value for V);
7730      *   Throwable throwable = null;
7731      *   try {
7732      *     result = target(a..., b...);
7733      *   } catch (Throwable t) {
7734      *     throwable = t;
7735      *     throw t;
7736      *   } finally {
7737      *     result = cleanup(throwable, result, a...);
7738      *   }
7739      *   return result;
7740      * }
7741      * }
7742      * <p>
7743      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7744      * be modified by execution of the target, and so are passed unchanged
7745      * from the caller to the cleanup, if it is invoked.
7746      * <p>
7747      * The target and cleanup must return the same type, even if the cleanup
7748      * always throws.
7749      * To create such a throwing cleanup, compose the cleanup logic
7750      * with {@link #throwException throwException},
7751      * in order to create a method handle of the correct return type.
7752      * <p>
7753      * Note that {@code tryFinally} never converts exceptions into normal returns.
7754      * In rare cases where exceptions must be converted in that way, first wrap
7755      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7756      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7757      * <p>
7758      * It is recommended that the first parameter type of {@code cleanup} be
7759      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7760      * {@code cleanup} will always be invoked with whatever exception that
7761      * {@code target} throws.  Declaring a narrower type may result in a
7762      * {@code ClassCastException} being thrown by the {@code try-finally}
7763      * handle if the type of the exception thrown by {@code target} is not
7764      * assignable to the first parameter type of {@code cleanup}.  Note that
7765      * various exception types of {@code VirtualMachineError},
7766      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7767      * thrown by almost any kind of Java code, and a finally clause that
7768      * catches (say) only {@code IOException} would mask any of the others
7769      * behind a {@code ClassCastException}.
7770      *
7771      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7772      * @param cleanup the handle that is invoked in the finally block.
7773      *
7774      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7775      * @throws NullPointerException if any argument is null
7776      * @throws IllegalArgumentException if {@code cleanup} does not accept
7777      *          the required leading arguments, or if the method handle types do
7778      *          not match in their return types and their
7779      *          corresponding trailing parameters
7780      *
7781      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7782      * @since 9
7783      */
7784     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7785         Class<?>[] targetParamTypes = target.type().ptypes();
7786         Class<?> rtype = target.type().returnType();
7787 
7788         tryFinallyChecks(target, cleanup);
7789 
7790         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7791         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7792         // target parameter list.
7793         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7794 
7795         // Ensure that the intrinsic type checks the instance thrown by the
7796         // target against the first parameter of cleanup
7797         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7798 
7799         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7800         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7801     }
7802 
7803     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7804         Class<?> rtype = target.type().returnType();
7805         if (rtype != cleanup.type().returnType()) {
7806             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7807         }
7808         MethodType cleanupType = cleanup.type();
7809         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7810             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7811         }
7812         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7813             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7814         }
7815         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7816         // target parameter list.
7817         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7818         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7819             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7820                     cleanup.type(), target.type());
7821         }
7822     }
7823 
7824     /**
7825      * Creates a table switch method handle, which can be used to switch over a set of target
7826      * method handles, based on a given target index, called selector.
7827      * <p>
7828      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7829      * and where {@code N} is the number of target method handles, the table switch method
7830      * handle will invoke the n-th target method handle from the list of target method handles.
7831      * <p>
7832      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7833      * method handle will invoke the given fallback method handle.
7834      * <p>
7835      * All method handles passed to this method must have the same type, with the additional
7836      * requirement that the leading parameter be of type {@code int}. The leading parameter
7837      * represents the selector.
7838      * <p>
7839      * Any trailing parameters present in the type will appear on the returned table switch
7840      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7841      * together with the selector value, to the selected method handle when invoking it.
7842      *
7843      * @apiNote Example:
7844      * The cases each drop the {@code selector} value they are given, and take an additional
7845      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7846      * to a specific constant label string for each case:
7847      * {@snippet lang="java" :
7848      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7849      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7850      *         MethodType.methodType(String.class, String.class));
7851      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7852      *
7853      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7854      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7855      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7856      *
7857      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7858      *     caseDefault,
7859      *     case0,
7860      *     case1
7861      * );
7862      *
7863      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7864      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7865      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7866      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7867      * }
7868      *
7869      * @param fallback the fallback method handle that is called when the selector is not
7870      *                 within the range {@code [0, N)}.
7871      * @param targets array of target method handles.
7872      * @return the table switch method handle.
7873      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7874      *                              any of the elements of the {@code targets} array are
7875      *                              {@code null}.
7876      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7877      *                                  parameter of the fallback handle or any of the target
7878      *                                  handles is not {@code int}, or if the types of
7879      *                                  the fallback handle and all of target handles are
7880      *                                  not the same.
7881      */
7882     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7883         Objects.requireNonNull(fallback);
7884         Objects.requireNonNull(targets);
7885         targets = targets.clone();
7886         MethodType type = tableSwitchChecks(fallback, targets);
7887         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7888     }
7889 
7890     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7891         if (caseActions.length == 0)
7892             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7893 
7894         MethodType expectedType = defaultCase.type();
7895 
7896         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7897             throw new IllegalArgumentException(
7898                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7899 
7900         for (MethodHandle mh : caseActions) {
7901             Objects.requireNonNull(mh);
7902             if (mh.type() != expectedType)
7903                 throw new IllegalArgumentException(
7904                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7905         }
7906 
7907         return expectedType;
7908     }
7909 
7910     /**
7911      * Creates a var handle object, which can be used to dereference a {@linkplain java.lang.foreign.MemorySegment memory segment}
7912      * by viewing its contents as a sequence of the provided value layout.
7913      *
7914      * <p>The provided layout specifies the {@linkplain ValueLayout#carrier() carrier type},
7915      * the {@linkplain ValueLayout#byteSize() byte size},
7916      * the {@linkplain ValueLayout#byteAlignment() byte alignment} and the {@linkplain ValueLayout#order() byte order}
7917      * associated with the returned var handle.
7918      *
7919      * <p>The returned var handle's type is {@code carrier} and the list of coordinate types is
7920      * {@code (MemorySegment, long)}, where the {@code long} coordinate type corresponds to byte offset into
7921      * a given memory segment. The returned var handle accesses bytes at an offset in a given
7922      * memory segment, composing bytes to or from a value of the type {@code carrier} according to the given endianness;
7923      * the alignment constraint (in bytes) for the resulting var handle is given by {@code alignmentBytes}.
7924      *
7925      * <p>As an example, consider the memory layout expressed by a {@link GroupLayout} instance constructed as follows:
7926      * {@snippet lang="java" :
7927      *     GroupLayout seq = java.lang.foreign.MemoryLayout.structLayout(
7928      *             MemoryLayout.paddingLayout(32),
7929      *             ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN).withName("value")
7930      *     );
7931      * }
7932      * To access the member layout named {@code value}, we can construct a memory segment view var handle as follows:
7933      * {@snippet lang="java" :
7934      *     VarHandle handle = MethodHandles.memorySegmentViewVarHandle(ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN)); //(MemorySegment, long) -> int
7935      *     handle = MethodHandles.insertCoordinates(handle, 1, 4); //(MemorySegment) -> int
7936      * }
7937      *
7938      * @apiNote The resulting var handle features certain <i>access mode restrictions</i>,
7939      * which are common to all memory segment view var handles. A memory segment view var handle is associated
7940      * with an access size {@code S} and an alignment constraint {@code B}
7941      * (both expressed in bytes). We say that a memory access operation is <em>fully aligned</em> if it occurs
7942      * at a memory address {@code A} which is compatible with both alignment constraints {@code S} and {@code B}.
7943      * If access is fully aligned then following access modes are supported and are
7944      * guaranteed to support atomic access:
7945      * <ul>
7946      * <li>read write access modes for all {@code T}, with the exception of
7947      *     access modes {@code get} and {@code set} for {@code long} and
7948      *     {@code double} on 32-bit platforms.
7949      * <li>atomic update access modes for {@code int}, {@code long},
7950      *     {@code float}, {@code double} or {@link MemorySegment}.
7951      *     (Future major platform releases of the JDK may support additional
7952      *     types for certain currently unsupported access modes.)
7953      * <li>numeric atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
7954      *     (Future major platform releases of the JDK may support additional
7955      *     numeric types for certain currently unsupported access modes.)
7956      * <li>bitwise atomic update access modes for {@code int}, {@code long} and {@link MemorySegment}.
7957      *     (Future major platform releases of the JDK may support additional
7958      *     numeric types for certain currently unsupported access modes.)
7959      * </ul>
7960      *
7961      * If {@code T} is {@code float}, {@code double} or {@link MemorySegment} then atomic
7962      * update access modes compare values using their bitwise representation
7963      * (see {@link Float#floatToRawIntBits},
7964      * {@link Double#doubleToRawLongBits} and {@link MemorySegment#address()}, respectively).
7965      * <p>
7966      * Alternatively, a memory access operation is <em>partially aligned</em> if it occurs at a memory address {@code A}
7967      * which is only compatible with the alignment constraint {@code B}; in such cases, access for anything other than the
7968      * {@code get} and {@code set} access modes will result in an {@code IllegalStateException}. If access is partially aligned,
7969      * atomic access is only guaranteed with respect to the largest power of two that divides the GCD of {@code A} and {@code S}.
7970      * <p>
7971      * In all other cases, we say that a memory access operation is <em>misaligned</em>; in such cases an
7972      * {@code IllegalStateException} is thrown, irrespective of the access mode being used.
7973      * <p>
7974      * Finally, if {@code T} is {@code MemorySegment} all write access modes throw {@link IllegalArgumentException}
7975      * unless the value to be written is a {@linkplain MemorySegment#isNative() native} memory segment.
7976      *
7977      * @param layout the value layout for which a memory access handle is to be obtained.
7978      * @return the new memory segment view var handle.
7979      * @throws IllegalArgumentException if an illegal carrier type is used, or if {@code alignmentBytes} is not a power of two.
7980      * @throws NullPointerException if {@code layout} is {@code null}.
7981      * @see MemoryLayout#varHandle(MemoryLayout.PathElement...)
7982      * @since 19
7983      */
7984     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
7985     public static VarHandle memorySegmentViewVarHandle(ValueLayout layout) {
7986         Objects.requireNonNull(layout);
7987         return Utils.makeSegmentViewVarHandle(layout);
7988     }
7989 
7990     /**
7991      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7992      * <p>
7993      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7994      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7995      * to the target var handle.
7996      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7997      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7998      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7999      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
8000      * <p>
8001      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
8002      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
8003      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
8004      * will be appended to the coordinates of the target var handle).
8005      * <p>
8006      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
8007      * throw an {@link IllegalStateException}.
8008      * <p>
8009      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8010      * atomic access guarantees as those featured by the target var handle.
8011      *
8012      * @param target the target var handle
8013      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
8014      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
8015      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
8016      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
8017      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
8018      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
8019      * @throws NullPointerException if any of the arguments is {@code null}.
8020      * @since 19
8021      */
8022     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8023     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
8024         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
8025     }
8026 
8027     /**
8028      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
8029      * <p>
8030      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
8031      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
8032      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
8033      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
8034      * by the adaptation) to the target var handle.
8035      * <p>
8036      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
8037      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8038      * <p>
8039      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8040      * throw an {@link IllegalStateException}.
8041      * <p>
8042      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8043      * atomic access guarantees as those featured by the target var handle.
8044      *
8045      * @param target the target var handle
8046      * @param pos the position of the first coordinate to be transformed
8047      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
8048      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
8049      * to the new coordinate values.
8050      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
8051      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
8052      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8053      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
8054      * or if it's determined that any of the filters throws any checked exceptions.
8055      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
8056      * @since 19
8057      */
8058     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8059     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
8060         return VarHandles.filterCoordinates(target, pos, filters);
8061     }
8062 
8063     /**
8064      * Provides a target var handle with one or more <em>bound coordinates</em>
8065      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
8066      * coordinate types than the target var handle.
8067      * <p>
8068      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
8069      * are joined with bound coordinate values, and then passed to the target var handle.
8070      * <p>
8071      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
8072      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
8073      * <p>
8074      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8075      * atomic access guarantees as those featured by the target var handle.
8076      *
8077      * @param target the var handle to invoke after the bound coordinates are inserted
8078      * @param pos the position of the first coordinate to be inserted
8079      * @param values the series of bound coordinates to insert
8080      * @return an adapter var handle which inserts additional coordinates,
8081      *         before calling the target var handle
8082      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8083      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
8084      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
8085      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
8086      * of the target var handle.
8087      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
8088      * @since 19
8089      */
8090     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8091     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
8092         return VarHandles.insertCoordinates(target, pos, values);
8093     }
8094 
8095     /**
8096      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
8097      * so that the new coordinates match the provided ones.
8098      * <p>
8099      * The given array controls the reordering.
8100      * Call {@code #I} the number of incoming coordinates (the value
8101      * {@code newCoordinates.size()}), and call {@code #O} the number
8102      * of outgoing coordinates (the number of coordinates associated with the target var handle).
8103      * Then the length of the reordering array must be {@code #O},
8104      * and each element must be a non-negative number less than {@code #I}.
8105      * For every {@code N} less than {@code #O}, the {@code N}-th
8106      * outgoing coordinate will be taken from the {@code I}-th incoming
8107      * coordinate, where {@code I} is {@code reorder[N]}.
8108      * <p>
8109      * No coordinate value conversions are applied.
8110      * The type of each incoming coordinate, as determined by {@code newCoordinates},
8111      * must be identical to the type of the corresponding outgoing coordinate
8112      * in the target var handle.
8113      * <p>
8114      * The reordering array need not specify an actual permutation.
8115      * An incoming coordinate will be duplicated if its index appears
8116      * more than once in the array, and an incoming coordinate will be dropped
8117      * if its index does not appear in the array.
8118      * <p>
8119      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8120      * atomic access guarantees as those featured by the target var handle.
8121      * @param target the var handle to invoke after the coordinates have been reordered
8122      * @param newCoordinates the new coordinate types
8123      * @param reorder an index array which controls the reordering
8124      * @return an adapter var handle which re-arranges the incoming coordinate values,
8125      * before calling the target var handle
8126      * @throws IllegalArgumentException if the index array length is not equal to
8127      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
8128      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
8129      * the target var handle and in {@code newCoordinates} are not identical.
8130      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
8131      * @since 19
8132      */
8133     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8134     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
8135         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
8136     }
8137 
8138     /**
8139      * Adapts a target var handle by pre-processing
8140      * a sub-sequence of its coordinate values with a filter (a method handle).
8141      * The pre-processed coordinates are replaced by the result (if any) of the
8142      * filter function and the target var handle is then called on the modified (usually shortened)
8143      * coordinate list.
8144      * <p>
8145      * If {@code R} is the return type of the filter (which cannot be void), the target var handle must accept a value of
8146      * type {@code R} as its coordinate in position {@code pos}, preceded and/or followed by
8147      * any coordinate not passed to the filter.
8148      * No coordinates are reordered, and the result returned from the filter
8149      * replaces (in order) the whole subsequence of coordinates originally
8150      * passed to the adapter.
8151      * <p>
8152      * The argument types (if any) of the filter
8153      * replace zero or one coordinate types of the target var handle, at position {@code pos},
8154      * in the resulting adapted var handle.
8155      * The return type of the filter must be identical to the
8156      * coordinate type of the target var handle at position {@code pos}, and that target var handle
8157      * coordinate is supplied by the return value of the filter.
8158      * <p>
8159      * If any of the filters throws a checked exception when invoked, the resulting var handle will
8160      * throw an {@link IllegalStateException}.
8161      * <p>
8162      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8163      * atomic access guarantees as those featured by the target var handle.
8164      *
8165      * @param target the var handle to invoke after the coordinates have been filtered
8166      * @param pos the position of the coordinate to be filtered
8167      * @param filter the filter method handle
8168      * @return an adapter var handle which filters the incoming coordinate values,
8169      * before calling the target var handle
8170      * @throws IllegalArgumentException if the return type of {@code filter}
8171      * is void, or it is not the same as the {@code pos} coordinate of the target var handle,
8172      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
8173      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
8174      * or if it's determined that {@code filter} throws any checked exceptions.
8175      * @throws NullPointerException if any of the arguments is {@code null}.
8176      * @since 19
8177      */
8178     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8179     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
8180         return VarHandles.collectCoordinates(target, pos, filter);
8181     }
8182 
8183     /**
8184      * Returns a var handle which will discard some dummy coordinates before delegating to the
8185      * target var handle. As a consequence, the resulting var handle will feature more
8186      * coordinate types than the target var handle.
8187      * <p>
8188      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
8189      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
8190      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
8191      * <p>
8192      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
8193      * atomic access guarantees as those featured by the target var handle.
8194      *
8195      * @param target the var handle to invoke after the dummy coordinates are dropped
8196      * @param pos position of the first coordinate to drop (zero for the leftmost)
8197      * @param valueTypes the type(s) of the coordinate(s) to drop
8198      * @return an adapter var handle which drops some dummy coordinates,
8199      *         before calling the target var handle
8200      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
8201      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
8202      * @since 19
8203      */
8204     @PreviewFeature(feature=PreviewFeature.Feature.FOREIGN)
8205     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
8206         return VarHandles.dropCoordinates(target, pos, valueTypes);
8207     }
8208 }