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.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.vm.annotation.ForceInline;
  38 import sun.invoke.util.ValueConversions;
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.Wrapper;
  41 import sun.reflect.misc.ReflectUtil;
  42 import sun.security.util.SecurityConstants;
  43 
  44 import java.lang.constant.ConstantDescs;
  45 import java.lang.invoke.LambdaForm.BasicType;
  46 import java.lang.reflect.Constructor;
  47 import java.lang.reflect.Field;
  48 import java.lang.reflect.Member;
  49 import java.lang.reflect.Method;
  50 import java.lang.reflect.Modifier;
  51 import java.lang.reflect.ReflectPermission;
  52 import java.nio.ByteOrder;
  53 import java.security.ProtectionDomain;
  54 import java.util.ArrayList;
  55 import java.util.Arrays;
  56 import java.util.BitSet;
  57 import java.util.Iterator;
  58 import java.util.List;
  59 import java.util.Objects;
  60 import java.util.Set;
  61 import java.util.concurrent.ConcurrentHashMap;
  62 import java.util.stream.Stream;
  63 
  64 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  65 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  66 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  67 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  68 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  69 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  70 import static java.lang.invoke.MethodType.methodType;
  71 
  72 /**
  73  * This class consists exclusively of static methods that operate on or return
  74  * method handles. They fall into several categories:
  75  * <ul>
  76  * <li>Lookup methods which help create method handles for methods and fields.
  77  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  78  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  79  * </ul>
  80  * A lookup, combinator, or factory method will fail and throw an
  81  * {@code IllegalArgumentException} if the created method handle's type
  82  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  83  *
  84  * @author John Rose, JSR 292 EG
  85  * @since 1.7
  86  */
  87 public class MethodHandles {
  88 
  89     private MethodHandles() { }  // do not instantiate
  90 
  91     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  92 
  93     // See IMPL_LOOKUP below.
  94 
  95     //// Method handle creation from ordinary methods.
  96 
  97     /**
  98      * Returns a {@link Lookup lookup object} with
  99      * full capabilities to emulate all supported bytecode behaviors of the caller.
 100      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 101      * Factory methods on the lookup object can create
 102      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 103      * for any member that the caller has access to via bytecodes,
 104      * including protected and private fields and methods.
 105      * This lookup object is created by the original lookup class
 106      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 107      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 108      * Do not store it in place where untrusted code can access it.
 109      * <p>
 110      * This method is caller sensitive, which means that it may return different
 111      * values to different callers.
 112      * In cases where {@code MethodHandles.lookup} is called from a context where
 113      * there is no caller frame on the stack (e.g. when called directly
 114      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 115      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 116      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 117      * to obtain a low-privileged lookup instead.
 118      * @return a lookup object for the caller of this method, with
 119      * {@linkplain Lookup#ORIGINAL original} and
 120      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 121      * @throws IllegalCallerException if there is no caller frame on the stack.
 122      */
 123     @CallerSensitive
 124     @ForceInline // to ensure Reflection.getCallerClass optimization
 125     public static Lookup lookup() {
 126         final Class<?> c = Reflection.getCallerClass();
 127         if (c == null) {
 128             throw new IllegalCallerException("no caller frame");
 129         }
 130         return new Lookup(c);
 131     }
 132 
 133     /**
 134      * This lookup method is the alternate implementation of
 135      * the lookup method with a leading caller class argument which is
 136      * non-caller-sensitive.  This method is only invoked by reflection
 137      * and method handle.
 138      */
 139     @CallerSensitiveAdapter
 140     private static Lookup lookup(Class<?> caller) {
 141         if (caller.getClassLoader() == null) {
 142             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 143         }
 144         return new Lookup(caller);
 145     }
 146 
 147     /**
 148      * Returns a {@link Lookup lookup object} which is trusted minimally.
 149      * The lookup has the {@code UNCONDITIONAL} mode.
 150      * It can only be used to create method handles to public members of
 151      * public classes in packages that are exported unconditionally.
 152      * <p>
 153      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 154      * of this lookup object will be {@link java.lang.Object}.
 155      *
 156      * @apiNote The use of Object is conventional, and because the lookup modes are
 157      * limited, there is no special access provided to the internals of Object, its package
 158      * or its module.  This public lookup object or other lookup object with
 159      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 160      * is not used to determine the lookup context.
 161      *
 162      * <p style="font-size:smaller;">
 163      * <em>Discussion:</em>
 164      * The lookup class can be changed to any other class {@code C} using an expression of the form
 165      * {@link Lookup#in publicLookup().in(C.class)}.
 166      * A public lookup object is always subject to
 167      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 168      * Also, it cannot access
 169      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 170      * @return a lookup object which is trusted minimally
 171      *
 172      * @revised 9
 173      */
 174     public static Lookup publicLookup() {
 175         return Lookup.PUBLIC_LOOKUP;
 176     }
 177 
 178     /**
 179      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 180      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 181      * The returned lookup object can provide access to classes in modules and packages,
 182      * and members of those classes, outside the normal rules of Java access control,
 183      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 184      * <p>
 185      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 186      * allowed to do deep reflection on module {@code M2} and package of the target class
 187      * if and only if all of the following conditions are {@code true}:
 188      * <ul>
 189      * <li>If there is a security manager, its {@code checkPermission} method is
 190      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 191      * that must return normally.
 192      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 193      * full privilege access}.  Specifically:
 194      *   <ul>
 195      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 196      *         (This is because otherwise there would be no way to ensure the original lookup
 197      *         creator was a member of any particular module, and so any subsequent checks
 198      *         for readability and qualified exports would become ineffective.)
 199      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 200      *         (This is because an application intending to share intra-module access
 201      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 202      *         deep reflection to its own module.)
 203      *   </ul>
 204      * <li>The target class must be a proper class, not a primitive or array class.
 205      * (Thus, {@code M2} is well-defined.)
 206      * <li>If the caller module {@code M1} differs from
 207      * the target module {@code M2} then both of the following must be true:
 208      *   <ul>
 209      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 210      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 211      *         containing the target class to at least {@code M1}.</li>
 212      *   </ul>
 213      * </ul>
 214      * <p>
 215      * If any of the above checks is violated, this method fails with an
 216      * exception.
 217      * <p>
 218      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 219      * returns a {@code Lookup} on {@code targetClass} with
 220      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 221      * with {@code null} previous lookup class.
 222      * <p>
 223      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 224      * returns a {@code Lookup} on {@code targetClass} that records
 225      * the lookup class of the caller as the new previous lookup class with
 226      * {@code PRIVATE} access but no {@code MODULE} access.
 227      * <p>
 228      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 229      *
 230      * @param targetClass the target class
 231      * @param caller the caller lookup object
 232      * @return a lookup object for the target class, with private access
 233      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 234      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 235      * @throws SecurityException if denied by the security manager
 236      * @throws IllegalAccessException if any of the other access checks specified above fails
 237      * @since 9
 238      * @see Lookup#dropLookupMode
 239      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 240      */
 241     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 242         if (caller.allowedModes == Lookup.TRUSTED) {
 243             return new Lookup(targetClass);
 244         }
 245 
 246         @SuppressWarnings("removal")
 247         SecurityManager sm = System.getSecurityManager();
 248         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 249         if (targetClass.isPrimitive())
 250             throw new IllegalArgumentException(targetClass + " is a primitive class");
 251         if (targetClass.isArray())
 252             throw new IllegalArgumentException(targetClass + " is an array class");
 253         // Ensure that we can reason accurately about private and module access.
 254         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 255         if ((caller.lookupModes() & requireAccess) != requireAccess)
 256             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 257 
 258         // previous lookup class is never set if it has MODULE access
 259         assert caller.previousLookupClass() == null;
 260 
 261         Class<?> callerClass = caller.lookupClass();
 262         Module callerModule = callerClass.getModule();  // M1
 263         Module targetModule = targetClass.getModule();  // M2
 264         Class<?> newPreviousClass = null;
 265         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 266 
 267         if (targetModule != callerModule) {
 268             if (!callerModule.canRead(targetModule))
 269                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 270             if (targetModule.isNamed()) {
 271                 String pn = targetClass.getPackageName();
 272                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 273                 if (!targetModule.isOpen(pn, callerModule))
 274                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 275             }
 276 
 277             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 278             newPreviousClass = callerClass;
 279             newModes &= ~Lookup.MODULE;
 280         }
 281         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 282     }
 283 
 284     /**
 285      * Returns the <em>class data</em> associated with the lookup class
 286      * of the given {@code caller} lookup object, or {@code null}.
 287      *
 288      * <p> A hidden class with class data can be created by calling
 289      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 290      * Lookup::defineHiddenClassWithClassData}.
 291      * This method will cause the static class initializer of the lookup
 292      * class of the given {@code caller} lookup object be executed if
 293      * it has not been initialized.
 294      *
 295      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 296      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 297      * {@code null} is returned if this method is called on the lookup object
 298      * on these classes.
 299      *
 300      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 301      * must have {@linkplain Lookup#ORIGINAL original access}
 302      * in order to retrieve the class data.
 303      *
 304      * @apiNote
 305      * This method can be called as a bootstrap method for a dynamically computed
 306      * constant.  A framework can create a hidden class with class data, for
 307      * example that can be {@code Class} or {@code MethodHandle} object.
 308      * The class data is accessible only to the lookup object
 309      * created by the original caller but inaccessible to other members
 310      * in the same nest.  If a framework passes security sensitive objects
 311      * to a hidden class via class data, it is recommended to load the value
 312      * of class data as a dynamically computed constant instead of storing
 313      * the class data in private static field(s) which are accessible to
 314      * other nestmates.
 315      *
 316      * @param <T> the type to cast the class data object to
 317      * @param caller the lookup context describing the class performing the
 318      * operation (normally stacked by the JVM)
 319      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 320      *             ({@code "_"})
 321      * @param type the type of the class data
 322      * @return the value of the class data if present in the lookup class;
 323      * otherwise {@code null}
 324      * @throws IllegalArgumentException if name is not {@code "_"}
 325      * @throws IllegalAccessException if the lookup context does not have
 326      * {@linkplain Lookup#ORIGINAL original} access
 327      * @throws ClassCastException if the class data cannot be converted to
 328      * the given {@code type}
 329      * @throws NullPointerException if {@code caller} or {@code type} argument
 330      * is {@code null}
 331      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 332      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 333      * @since 16
 334      * @jvms 5.5 Initialization
 335      */
 336      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 337          Objects.requireNonNull(caller);
 338          Objects.requireNonNull(type);
 339          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 340              throw new IllegalArgumentException("name must be \"_\": " + name);
 341          }
 342 
 343          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 344              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 345          }
 346 
 347          Object classdata = classData(caller.lookupClass());
 348          if (classdata == null) return null;
 349 
 350          try {
 351              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 352          } catch (RuntimeException|Error e) {
 353              throw e; // let CCE and other runtime exceptions through
 354          } catch (Throwable e) {
 355              throw new InternalError(e);
 356          }
 357     }
 358 
 359     /*
 360      * Returns the class data set by the VM in the Class::classData field.
 361      *
 362      * This is also invoked by LambdaForms as it cannot use condy via
 363      * MethodHandles::classData due to bootstrapping issue.
 364      */
 365     static Object classData(Class<?> c) {
 366         UNSAFE.ensureClassInitialized(c);
 367         return SharedSecrets.getJavaLangAccess().classData(c);
 368     }
 369 
 370     /**
 371      * Returns the element at the specified index in the
 372      * {@linkplain #classData(Lookup, String, Class) class data},
 373      * if the class data associated with the lookup class
 374      * of the given {@code caller} lookup object is a {@code List}.
 375      * If the class data is not present in this lookup class, this method
 376      * returns {@code null}.
 377      *
 378      * <p> A hidden class with class data can be created by calling
 379      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 380      * Lookup::defineHiddenClassWithClassData}.
 381      * This method will cause the static class initializer of the lookup
 382      * class of the given {@code caller} lookup object be executed if
 383      * it has not been initialized.
 384      *
 385      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 386      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 387      * {@code null} is returned if this method is called on the lookup object
 388      * on these classes.
 389      *
 390      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 391      * must have {@linkplain Lookup#ORIGINAL original access}
 392      * in order to retrieve the class data.
 393      *
 394      * @apiNote
 395      * This method can be called as a bootstrap method for a dynamically computed
 396      * constant.  A framework can create a hidden class with class data, for
 397      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 398      * one object and use this method to load one element at a specific index.
 399      * The class data is accessible only to the lookup object
 400      * created by the original caller but inaccessible to other members
 401      * in the same nest.  If a framework passes security sensitive objects
 402      * to a hidden class via class data, it is recommended to load the value
 403      * of class data as a dynamically computed constant instead of storing
 404      * the class data in private static field(s) which are accessible to other
 405      * nestmates.
 406      *
 407      * @param <T> the type to cast the result object to
 408      * @param caller the lookup context describing the class performing the
 409      * operation (normally stacked by the JVM)
 410      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 411      *             ({@code "_"})
 412      * @param type the type of the element at the given index in the class data
 413      * @param index index of the element in the class data
 414      * @return the element at the given index in the class data
 415      * if the class data is present; otherwise {@code null}
 416      * @throws IllegalArgumentException if name is not {@code "_"}
 417      * @throws IllegalAccessException if the lookup context does not have
 418      * {@linkplain Lookup#ORIGINAL original} access
 419      * @throws ClassCastException if the class data cannot be converted to {@code List}
 420      * or the element at the specified index cannot be converted to the given type
 421      * @throws IndexOutOfBoundsException if the index is out of range
 422      * @throws NullPointerException if {@code caller} or {@code type} argument is
 423      * {@code null}; or if unboxing operation fails because
 424      * the element at the given index is {@code null}
 425      *
 426      * @since 16
 427      * @see #classData(Lookup, String, Class)
 428      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 429      */
 430     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 431             throws IllegalAccessException
 432     {
 433         @SuppressWarnings("unchecked")
 434         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 435         if (classdata == null) return null;
 436 
 437         try {
 438             Object element = classdata.get(index);
 439             return BootstrapMethodInvoker.widenAndCast(element, type);
 440         } catch (RuntimeException|Error e) {
 441             throw e; // let specified exceptions and other runtime exceptions/errors through
 442         } catch (Throwable e) {
 443             throw new InternalError(e);
 444         }
 445     }
 446 
 447     /**
 448      * Performs an unchecked "crack" of a
 449      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 450      * The result is as if the user had obtained a lookup object capable enough
 451      * to crack the target method handle, called
 452      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 453      * on the target to obtain its symbolic reference, and then called
 454      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 455      * to resolve the symbolic reference to a member.
 456      * <p>
 457      * If there is a security manager, its {@code checkPermission} method
 458      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 459      * @param <T> the desired type of the result, either {@link Member} or a subtype
 460      * @param target a direct method handle to crack into symbolic reference components
 461      * @param expected a class object representing the desired result type {@code T}
 462      * @return a reference to the method, constructor, or field object
 463      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 464      * @throws    NullPointerException if either argument is {@code null}
 465      * @throws    IllegalArgumentException if the target is not a direct method handle
 466      * @throws    ClassCastException if the member is not of the expected type
 467      * @since 1.8
 468      */
 469     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 470         @SuppressWarnings("removal")
 471         SecurityManager smgr = System.getSecurityManager();
 472         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 473         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 474         return lookup.revealDirect(target).reflectAs(expected, lookup);
 475     }
 476 
 477     /**
 478      * A <em>lookup object</em> is a factory for creating method handles,
 479      * when the creation requires access checking.
 480      * Method handles do not perform
 481      * access checks when they are called, but rather when they are created.
 482      * Therefore, method handle access
 483      * restrictions must be enforced when a method handle is created.
 484      * The caller class against which those restrictions are enforced
 485      * is known as the {@linkplain #lookupClass() lookup class}.
 486      * <p>
 487      * A lookup class which needs to create method handles will call
 488      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 489      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 490      * determined, and securely stored in the {@code Lookup} object.
 491      * The lookup class (or its delegates) may then use factory methods
 492      * on the {@code Lookup} object to create method handles for access-checked members.
 493      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 494      * even private ones.
 495      *
 496      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 497      * The factory methods on a {@code Lookup} object correspond to all major
 498      * use cases for methods, constructors, and fields.
 499      * Each method handle created by a factory method is the functional
 500      * equivalent of a particular <em>bytecode behavior</em>.
 501      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 502      * the Java Virtual Machine Specification.)
 503      * Here is a summary of the correspondence between these factory methods and
 504      * the behavior of the resulting method handles:
 505      * <table class="striped">
 506      * <caption style="display:none">lookup method behaviors</caption>
 507      * <thead>
 508      * <tr>
 509      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 510      *     <th scope="col">member</th>
 511      *     <th scope="col">bytecode behavior</th>
 512      * </tr>
 513      * </thead>
 514      * <tbody>
 515      * <tr>
 516      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 517      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 518      * </tr>
 519      * <tr>
 520      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 521      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 522      * </tr>
 523      * <tr>
 524      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 525      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 526      * </tr>
 527      * <tr>
 528      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 529      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 530      * </tr>
 531      * <tr>
 532      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 533      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 534      * </tr>
 535      * <tr>
 536      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 537      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 538      * </tr>
 539      * <tr>
 540      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 541      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 542      * </tr>
 543      * <tr>
 544      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 545      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 546      * </tr>
 547      * <tr>
 548      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 549      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 550      * </tr>
 551      * <tr>
 552      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 553      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 554      * </tr>
 555      * <tr>
 556      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 557      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 558      * </tr>
 559      * <tr>
 560      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 561      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 562      * </tr>
 563      * <tr>
 564      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 565      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 566      * </tr>
 567      * <tr>
 568      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 569      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 570      * </tr>
 571      * </tbody>
 572      * </table>
 573      *
 574      * Here, the type {@code C} is the class or interface being searched for a member,
 575      * documented as a parameter named {@code refc} in the lookup methods.
 576      * The method type {@code MT} is composed from the return type {@code T}
 577      * and the sequence of argument types {@code A*}.
 578      * The constructor also has a sequence of argument types {@code A*} and
 579      * is deemed to return the newly-created object of type {@code C}.
 580      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 581      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 582      * if it is present, it is always the leading argument to the method handle invocation.
 583      * (In the case of some {@code protected} members, {@code this} may be
 584      * restricted in type to the lookup class; see below.)
 585      * The name {@code arg} stands for all the other method handle arguments.
 586      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 587      * stands for a null reference if the accessed method or field is static,
 588      * and {@code this} otherwise.
 589      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 590      * for reflective objects corresponding to the given members declared in type {@code C}.
 591      * <p>
 592      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 593      * as if by {@code ldc CONSTANT_Class}.
 594      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 595      * <p>
 596      * In cases where the given member is of variable arity (i.e., a method or constructor)
 597      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 598      * In all other cases, the returned method handle will be of fixed arity.
 599      * <p style="font-size:smaller;">
 600      * <em>Discussion:</em>
 601      * The equivalence between looked-up method handles and underlying
 602      * class members and bytecode behaviors
 603      * can break down in a few ways:
 604      * <ul style="font-size:smaller;">
 605      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 606      * the lookup can still succeed, even when there is no equivalent
 607      * Java expression or bytecoded constant.
 608      * <li>Likewise, if {@code T} or {@code MT}
 609      * is not symbolically accessible from the lookup class's loader,
 610      * the lookup can still succeed.
 611      * For example, lookups for {@code MethodHandle.invokeExact} and
 612      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 613      * <li>If there is a security manager installed, it can forbid the lookup
 614      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 615      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 616      * constant is not subject to security manager checks.
 617      * <li>If the looked-up method has a
 618      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 619      * the method handle creation may fail with an
 620      * {@code IllegalArgumentException}, due to the method handle type having
 621      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 622      * </ul>
 623      *
 624      * <h2><a id="access"></a>Access checking</h2>
 625      * Access checks are applied in the factory methods of {@code Lookup},
 626      * when a method handle is created.
 627      * This is a key difference from the Core Reflection API, since
 628      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 629      * performs access checking against every caller, on every call.
 630      * <p>
 631      * All access checks start from a {@code Lookup} object, which
 632      * compares its recorded lookup class against all requests to
 633      * create method handles.
 634      * A single {@code Lookup} object can be used to create any number
 635      * of access-checked method handles, all checked against a single
 636      * lookup class.
 637      * <p>
 638      * A {@code Lookup} object can be shared with other trusted code,
 639      * such as a metaobject protocol.
 640      * A shared {@code Lookup} object delegates the capability
 641      * to create method handles on private members of the lookup class.
 642      * Even if privileged code uses the {@code Lookup} object,
 643      * the access checking is confined to the privileges of the
 644      * original lookup class.
 645      * <p>
 646      * A lookup can fail, because
 647      * the containing class is not accessible to the lookup class, or
 648      * because the desired class member is missing, or because the
 649      * desired class member is not accessible to the lookup class, or
 650      * because the lookup object is not trusted enough to access the member.
 651      * In the case of a field setter function on a {@code final} field,
 652      * finality enforcement is treated as a kind of access control,
 653      * and the lookup will fail, except in special cases of
 654      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 655      * In any of these cases, a {@code ReflectiveOperationException} will be
 656      * thrown from the attempted lookup.  The exact class will be one of
 657      * the following:
 658      * <ul>
 659      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 660      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 661      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 662      * </ul>
 663      * <p>
 664      * In general, the conditions under which a method handle may be
 665      * looked up for a method {@code M} are no more restrictive than the conditions
 666      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 667      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 668      * a method handle lookup will generally raise a corresponding
 669      * checked exception, such as {@code NoSuchMethodException}.
 670      * And the effect of invoking the method handle resulting from the lookup
 671      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 672      * to executing the compiled, verified, and resolved call to {@code M}.
 673      * The same point is true of fields and constructors.
 674      * <p style="font-size:smaller;">
 675      * <em>Discussion:</em>
 676      * Access checks only apply to named and reflected methods,
 677      * constructors, and fields.
 678      * Other method handle creation methods, such as
 679      * {@link MethodHandle#asType MethodHandle.asType},
 680      * do not require any access checks, and are used
 681      * independently of any {@code Lookup} object.
 682      * <p>
 683      * If the desired member is {@code protected}, the usual JVM rules apply,
 684      * including the requirement that the lookup class must either be in the
 685      * same package as the desired member, or must inherit that member.
 686      * (See the Java Virtual Machine Specification, sections {@jvms
 687      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 688      * In addition, if the desired member is a non-static field or method
 689      * in a different package, the resulting method handle may only be applied
 690      * to objects of the lookup class or one of its subclasses.
 691      * This requirement is enforced by narrowing the type of the leading
 692      * {@code this} parameter from {@code C}
 693      * (which will necessarily be a superclass of the lookup class)
 694      * to the lookup class itself.
 695      * <p>
 696      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 697      * that the receiver argument must match both the resolved method <em>and</em>
 698      * the current class.  Again, this requirement is enforced by narrowing the
 699      * type of the leading parameter to the resulting method handle.
 700      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 701      * <p>
 702      * The JVM represents constructors and static initializer blocks as internal methods
 703      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 704      * The internal syntax of invocation instructions allows them to refer to such internal
 705      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 706      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 707      * <p>
 708      * If the relationship between nested types is expressed directly through the
 709      * {@code NestHost} and {@code NestMembers} attributes
 710      * (see the Java Virtual Machine Specification, sections {@jvms
 711      * 4.7.28} and {@jvms 4.7.29}),
 712      * then the associated {@code Lookup} object provides direct access to
 713      * the lookup class and all of its nestmates
 714      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 715      * Otherwise, access between nested classes is obtained by the Java compiler creating
 716      * a wrapper method to access a private method of another class in the same nest.
 717      * For example, a nested class {@code C.D}
 718      * can access private members within other related classes such as
 719      * {@code C}, {@code C.D.E}, or {@code C.B},
 720      * but the Java compiler may need to generate wrapper methods in
 721      * those related classes.  In such cases, a {@code Lookup} object on
 722      * {@code C.E} would be unable to access those private members.
 723      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 724      * which can transform a lookup on {@code C.E} into one on any of those other
 725      * classes, without special elevation of privilege.
 726      * <p>
 727      * The accesses permitted to a given lookup object may be limited,
 728      * according to its set of {@link #lookupModes lookupModes},
 729      * to a subset of members normally accessible to the lookup class.
 730      * For example, the {@link MethodHandles#publicLookup publicLookup}
 731      * method produces a lookup object which is only allowed to access
 732      * public members in public classes of exported packages.
 733      * The caller sensitive method {@link MethodHandles#lookup lookup}
 734      * produces a lookup object with full capabilities relative to
 735      * its caller class, to emulate all supported bytecode behaviors.
 736      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 737      * with fewer access modes than the original lookup object.
 738      *
 739      * <p style="font-size:smaller;">
 740      * <a id="privacc"></a>
 741      * <em>Discussion of private and module access:</em>
 742      * We say that a lookup has <em>private access</em>
 743      * if its {@linkplain #lookupModes lookup modes}
 744      * include the possibility of accessing {@code private} members
 745      * (which includes the private members of nestmates).
 746      * As documented in the relevant methods elsewhere,
 747      * only lookups with private access possess the following capabilities:
 748      * <ul style="font-size:smaller;">
 749      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 750      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 751      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 752      *     for classes accessible to the lookup class
 753      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 754      *     within the same package member
 755      * </ul>
 756      * <p style="font-size:smaller;">
 757      * Similarly, a lookup with module access ensures that the original lookup creator was
 758      * a member in the same module as the lookup class.
 759      * <p style="font-size:smaller;">
 760      * Private and module access are independently determined modes; a lookup may have
 761      * either or both or neither.  A lookup which possesses both access modes is said to
 762      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 763      * <p style="font-size:smaller;">
 764      * A lookup with <em>original access</em> ensures that this lookup is created by
 765      * the original lookup class and the bootstrap method invoked by the VM.
 766      * Such a lookup with original access also has private and module access
 767      * which has the following additional capability:
 768      * <ul style="font-size:smaller;">
 769      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 770      *     such as {@code Class.forName}
 771      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 772      * class data} associated with the lookup class</li>
 773      * </ul>
 774      * <p style="font-size:smaller;">
 775      * Each of these permissions is a consequence of the fact that a lookup object
 776      * with private access can be securely traced back to an originating class,
 777      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 778      * can be reliably determined and emulated by method handles.
 779      *
 780      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 781      * When a lookup class in one module {@code M1} accesses a class in another module
 782      * {@code M2}, extra access checking is performed beyond the access mode bits.
 783      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 784      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 785      * and when the type is in a package of {@code M2} that is exported to
 786      * at least {@code M1}.
 787      * <p>
 788      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 789      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 790      * MethodHandles.privateLookupIn} methods.
 791      * Teleporting across modules will always record the original lookup class as
 792      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 793      * and drops {@link Lookup#MODULE MODULE} access.
 794      * If the target class is in the same module as the lookup class {@code C},
 795      * then the target class becomes the new lookup class
 796      * and there is no change to the previous lookup class.
 797      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 798      * {@code C} becomes the new previous lookup class
 799      * and the target class becomes the new lookup class.
 800      * In that case, if there was already a previous lookup class in {@code M0},
 801      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 802      * drops all privileges.
 803      * For example,
 804      * <blockquote><pre>
 805      * {@code
 806      * Lookup lookup = MethodHandles.lookup();   // in class C
 807      * Lookup lookup2 = lookup.in(D.class);
 808      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 809      * }</pre></blockquote>
 810      * <p>
 811      * The {@link #lookup()} factory method produces a {@code Lookup} object
 812      * with {@code null} previous lookup class.
 813      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 814      * to class {@code D} without elevation of privileges.
 815      * If {@code C} and {@code D} are in the same module,
 816      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 817      * same previous lookup class as the original {@code lookup}, or
 818      * {@code null} if not present.
 819      * <p>
 820      * When a {@code Lookup} teleports from a class
 821      * in one nest to another nest, {@code PRIVATE} access is dropped.
 822      * When a {@code Lookup} teleports from a class in one package to
 823      * another package, {@code PACKAGE} access is dropped.
 824      * When a {@code Lookup} teleports from a class in one module to another module,
 825      * {@code MODULE} access is dropped.
 826      * Teleporting across modules drops the ability to access non-exported classes
 827      * in both the module of the new lookup class and the module of the old lookup class
 828      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 829      * A {@code Lookup} can teleport back and forth to a class in the module of
 830      * the lookup class and the module of the previous class lookup.
 831      * Teleporting across modules can only decrease access but cannot increase it.
 832      * Teleporting to some third module drops all accesses.
 833      * <p>
 834      * In the above example, if {@code C} and {@code D} are in different modules,
 835      * {@code lookup2} records {@code D} as its lookup class and
 836      * {@code C} as its previous lookup class and {@code lookup2} has only
 837      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 838      * {@code C}'s module and {@code D}'s module.
 839      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 840      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 841      * class {@code D} is recorded as its previous lookup class.
 842      * <p>
 843      * Teleporting across modules restricts access to the public types that
 844      * both the lookup class and the previous lookup class can equally access
 845      * (see below).
 846      * <p>
 847      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 848      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 849      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 850      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 851      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 852      * to call {@code privateLookupIn}.
 853      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 854      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 855      * produces a new {@code Lookup} on {@code T} with full capabilities.
 856      * A {@code lookup} on {@code C} is also allowed
 857      * to do deep reflection on {@code T} in another module {@code M2} if
 858      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 859      * the package containing {@code T} to at least {@code M1}.
 860      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 861      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 862      * The resulting {@code Lookup} can be used to do member lookup or teleport
 863      * to another lookup class by calling {@link #in Lookup::in}.  But
 864      * it cannot be used to obtain another private {@code Lookup} by calling
 865      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 866      * because it has no {@code MODULE} access.
 867      *
 868      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 869      *
 870      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 871      * allows cross-module access. The access checking is performed with respect
 872      * to both the lookup class and the previous lookup class if present.
 873      * <p>
 874      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 875      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 876      * exported unconditionally}.
 877      * <p>
 878      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 879      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 880      * that are readable to {@code M1} and the type is in a package that is exported
 881      * at least to {@code M1}.
 882      * <p>
 883      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 884      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 885      * the intersection of all public types that are accessible to {@code M1}
 886      * with all public types that are accessible to {@code M0}. {@code M0}
 887      * reads {@code M1} and hence the set of accessible types includes:
 888      *
 889      * <ul>
 890      * <li>unconditional-exported packages from {@code M1}</li>
 891      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 892      * <li>
 893      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 894      *     and {@code M1} read {@code M2}
 895      * </li>
 896      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 897      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 898      * <li>
 899      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 900      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 901      * </li>
 902      * </ul>
 903      *
 904      * <h2><a id="access-modes"></a>Access modes</h2>
 905      *
 906      * The table below shows the access modes of a {@code Lookup} produced by
 907      * any of the following factory or transformation methods:
 908      * <ul>
 909      * <li>{@link #lookup() MethodHandles::lookup}</li>
 910      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 911      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 912      * <li>{@link Lookup#in Lookup::in}</li>
 913      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 914      * </ul>
 915      *
 916      * <table class="striped">
 917      * <caption style="display:none">
 918      * Access mode summary
 919      * </caption>
 920      * <thead>
 921      * <tr>
 922      * <th scope="col">Lookup object</th>
 923      * <th style="text-align:center">original</th>
 924      * <th style="text-align:center">protected</th>
 925      * <th style="text-align:center">private</th>
 926      * <th style="text-align:center">package</th>
 927      * <th style="text-align:center">module</th>
 928      * <th style="text-align:center">public</th>
 929      * </tr>
 930      * </thead>
 931      * <tbody>
 932      * <tr>
 933      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 934      * <td style="text-align:center">ORI</td>
 935      * <td style="text-align:center">PRO</td>
 936      * <td style="text-align:center">PRI</td>
 937      * <td style="text-align:center">PAC</td>
 938      * <td style="text-align:center">MOD</td>
 939      * <td style="text-align:center">1R</td>
 940      * </tr>
 941      * <tr>
 942      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 943      * <td></td>
 944      * <td></td>
 945      * <td></td>
 946      * <td style="text-align:center">PAC</td>
 947      * <td style="text-align:center">MOD</td>
 948      * <td style="text-align:center">1R</td>
 949      * </tr>
 950      * <tr>
 951      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 952      * <td></td>
 953      * <td></td>
 954      * <td></td>
 955      * <td></td>
 956      * <td style="text-align:center">MOD</td>
 957      * <td style="text-align:center">1R</td>
 958      * </tr>
 959      * <tr>
 960      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 961      * <td></td>
 962      * <td></td>
 963      * <td></td>
 964      * <td></td>
 965      * <td></td>
 966      * <td style="text-align:center">2R</td>
 967      * </tr>
 968      * <tr>
 969      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 970      * <td></td>
 971      * <td></td>
 972      * <td></td>
 973      * <td></td>
 974      * <td></td>
 975      * <td style="text-align:center">2R</td>
 976      * </tr>
 977      * <tr>
 978      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 979      * <td></td>
 980      * <td style="text-align:center">PRO</td>
 981      * <td style="text-align:center">PRI</td>
 982      * <td style="text-align:center">PAC</td>
 983      * <td style="text-align:center">MOD</td>
 984      * <td style="text-align:center">1R</td>
 985      * </tr>
 986      * <tr>
 987      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 988      * <td></td>
 989      * <td style="text-align:center">PRO</td>
 990      * <td style="text-align:center">PRI</td>
 991      * <td style="text-align:center">PAC</td>
 992      * <td style="text-align:center">MOD</td>
 993      * <td style="text-align:center">1R</td>
 994      * </tr>
 995      * <tr>
 996      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
 997      * <td></td>
 998      * <td></td>
 999      * <td></td>
1000      * <td style="text-align:center">PAC</td>
1001      * <td style="text-align:center">MOD</td>
1002      * <td style="text-align:center">1R</td>
1003      * </tr>
1004      * <tr>
1005      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1006      * <td></td>
1007      * <td></td>
1008      * <td></td>
1009      * <td></td>
1010      * <td style="text-align:center">MOD</td>
1011      * <td style="text-align:center">1R</td>
1012      * </tr>
1013      * <tr>
1014      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1015      * <td></td>
1016      * <td></td>
1017      * <td></td>
1018      * <td></td>
1019      * <td></td>
1020      * <td style="text-align:center">2R</td>
1021      * </tr>
1022      * <tr>
1023      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1024      * <td></td>
1025      * <td></td>
1026      * <td style="text-align:center">PRI</td>
1027      * <td style="text-align:center">PAC</td>
1028      * <td style="text-align:center">MOD</td>
1029      * <td style="text-align:center">1R</td>
1030      * </tr>
1031      * <tr>
1032      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1033      * <td></td>
1034      * <td></td>
1035      * <td></td>
1036      * <td style="text-align:center">PAC</td>
1037      * <td style="text-align:center">MOD</td>
1038      * <td style="text-align:center">1R</td>
1039      * </tr>
1040      * <tr>
1041      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1042      * <td></td>
1043      * <td></td>
1044      * <td></td>
1045      * <td></td>
1046      * <td style="text-align:center">MOD</td>
1047      * <td style="text-align:center">1R</td>
1048      * </tr>
1049      * <tr>
1050      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1051      * <td></td>
1052      * <td></td>
1053      * <td></td>
1054      * <td></td>
1055      * <td></td>
1056      * <td style="text-align:center">1R</td>
1057      * </tr>
1058      * <tr>
1059      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1060      * <td></td>
1061      * <td></td>
1062      * <td></td>
1063      * <td></td>
1064      * <td></td>
1065      * <td style="text-align:center">none</td>
1066      * <tr>
1067      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1068      * <td></td>
1069      * <td style="text-align:center">PRO</td>
1070      * <td style="text-align:center">PRI</td>
1071      * <td style="text-align:center">PAC</td>
1072      * <td></td>
1073      * <td style="text-align:center">2R</td>
1074      * </tr>
1075      * <tr>
1076      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1077      * <td></td>
1078      * <td style="text-align:center">PRO</td>
1079      * <td style="text-align:center">PRI</td>
1080      * <td style="text-align:center">PAC</td>
1081      * <td></td>
1082      * <td style="text-align:center">2R</td>
1083      * </tr>
1084      * <tr>
1085      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1086      * <td></td>
1087      * <td></td>
1088      * <td></td>
1089      * <td></td>
1090      * <td></td>
1091      * <td style="text-align:center">IAE</td>
1092      * </tr>
1093      * <tr>
1094      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1095      * <td></td>
1096      * <td></td>
1097      * <td></td>
1098      * <td style="text-align:center">PAC</td>
1099      * <td></td>
1100      * <td style="text-align:center">2R</td>
1101      * </tr>
1102      * <tr>
1103      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1104      * <td></td>
1105      * <td></td>
1106      * <td></td>
1107      * <td></td>
1108      * <td></td>
1109      * <td style="text-align:center">2R</td>
1110      * </tr>
1111      * <tr>
1112      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1113      * <td></td>
1114      * <td></td>
1115      * <td></td>
1116      * <td></td>
1117      * <td></td>
1118      * <td style="text-align:center">2R</td>
1119      * </tr>
1120      * <tr>
1121      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1122      * <td></td>
1123      * <td></td>
1124      * <td></td>
1125      * <td></td>
1126      * <td></td>
1127      * <td style="text-align:center">none</td>
1128      * </tr>
1129      * <tr>
1130      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1131      * <td></td>
1132      * <td></td>
1133      * <td style="text-align:center">PRI</td>
1134      * <td style="text-align:center">PAC</td>
1135      * <td></td>
1136      * <td style="text-align:center">2R</td>
1137      * </tr>
1138      * <tr>
1139      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1140      * <td></td>
1141      * <td></td>
1142      * <td></td>
1143      * <td style="text-align:center">PAC</td>
1144      * <td></td>
1145      * <td style="text-align:center">2R</td>
1146      * </tr>
1147      * <tr>
1148      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1149      * <td></td>
1150      * <td></td>
1151      * <td></td>
1152      * <td></td>
1153      * <td></td>
1154      * <td style="text-align:center">2R</td>
1155      * </tr>
1156      * <tr>
1157      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1158      * <td></td>
1159      * <td></td>
1160      * <td></td>
1161      * <td></td>
1162      * <td></td>
1163      * <td style="text-align:center">2R</td>
1164      * </tr>
1165      * <tr>
1166      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1167      * <td></td>
1168      * <td></td>
1169      * <td></td>
1170      * <td></td>
1171      * <td></td>
1172      * <td style="text-align:center">none</td>
1173      * </tr>
1174      * <tr>
1175      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1176      * <td></td>
1177      * <td></td>
1178      * <td style="text-align:center">PRI</td>
1179      * <td style="text-align:center">PAC</td>
1180      * <td style="text-align:center">MOD</td>
1181      * <td style="text-align:center">1R</td>
1182      * </tr>
1183      * <tr>
1184      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1185      * <td></td>
1186      * <td></td>
1187      * <td></td>
1188      * <td style="text-align:center">PAC</td>
1189      * <td style="text-align:center">MOD</td>
1190      * <td style="text-align:center">1R</td>
1191      * </tr>
1192      * <tr>
1193      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1194      * <td></td>
1195      * <td></td>
1196      * <td></td>
1197      * <td></td>
1198      * <td style="text-align:center">MOD</td>
1199      * <td style="text-align:center">1R</td>
1200      * </tr>
1201      * <tr>
1202      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1203      * <td></td>
1204      * <td></td>
1205      * <td></td>
1206      * <td></td>
1207      * <td></td>
1208      * <td style="text-align:center">1R</td>
1209      * </tr>
1210      * <tr>
1211      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1212      * <td></td>
1213      * <td></td>
1214      * <td></td>
1215      * <td></td>
1216      * <td></td>
1217      * <td style="text-align:center">none</td>
1218      * </tr>
1219      * <tr>
1220      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1221      * <td></td>
1222      * <td></td>
1223      * <td></td>
1224      * <td></td>
1225      * <td></td>
1226      * <td style="text-align:center">U</td>
1227      * </tr>
1228      * <tr>
1229      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1230      * <td></td>
1231      * <td></td>
1232      * <td></td>
1233      * <td></td>
1234      * <td></td>
1235      * <td style="text-align:center">U</td>
1236      * </tr>
1237      * <tr>
1238      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1239      * <td></td>
1240      * <td></td>
1241      * <td></td>
1242      * <td></td>
1243      * <td></td>
1244      * <td style="text-align:center">U</td>
1245      * </tr>
1246      * <tr>
1247      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1248      * <td></td>
1249      * <td></td>
1250      * <td></td>
1251      * <td></td>
1252      * <td></td>
1253      * <td style="text-align:center">none</td>
1254      * </tr>
1255      * <tr>
1256      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1257      * <td></td>
1258      * <td></td>
1259      * <td></td>
1260      * <td></td>
1261      * <td></td>
1262      * <td style="text-align:center">IAE</td>
1263      * </tr>
1264      * <tr>
1265      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1266      * <td></td>
1267      * <td></td>
1268      * <td></td>
1269      * <td></td>
1270      * <td></td>
1271      * <td style="text-align:center">none</td>
1272      * </tr>
1273      * </tbody>
1274      * </table>
1275      *
1276      * <p>
1277      * Notes:
1278      * <ul>
1279      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1280      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1281      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1282      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1283      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1284      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1285      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1286      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1287      *     {@code MOD} indicates {@link #MODULE} bit set,
1288      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1289      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1290      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1291      * <li>Public access comes in three kinds:
1292      * <ul>
1293      * <li>unconditional ({@code U}): the lookup assumes readability.
1294      *     The lookup has {@code null} previous lookup class.
1295      * <li>one-module-reads ({@code 1R}): the module access checking is
1296      *     performed with respect to the lookup class.  The lookup has {@code null}
1297      *     previous lookup class.
1298      * <li>two-module-reads ({@code 2R}): the module access checking is
1299      *     performed with respect to the lookup class and the previous lookup class.
1300      *     The lookup has a non-null previous lookup class which is in a
1301      *     different module from the current lookup class.
1302      * </ul>
1303      * <li>Any attempt to reach a third module loses all access.</li>
1304      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1305      * all access modes are dropped.</li>
1306      * </ul>
1307      *
1308      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1309      * Although bytecode instructions can only refer to classes in
1310      * a related class loader, this API can search for methods in any
1311      * class, as long as a reference to its {@code Class} object is
1312      * available.  Such cross-loader references are also possible with the
1313      * Core Reflection API, and are impossible to bytecode instructions
1314      * such as {@code invokestatic} or {@code getfield}.
1315      * There is a {@linkplain java.lang.SecurityManager security manager API}
1316      * to allow applications to check such cross-loader references.
1317      * These checks apply to both the {@code MethodHandles.Lookup} API
1318      * and the Core Reflection API
1319      * (as found on {@link java.lang.Class Class}).
1320      * <p>
1321      * If a security manager is present, member and class lookups are subject to
1322      * additional checks.
1323      * From one to three calls are made to the security manager.
1324      * Any of these calls can refuse access by throwing a
1325      * {@link java.lang.SecurityException SecurityException}.
1326      * Define {@code smgr} as the security manager,
1327      * {@code lookc} as the lookup class of the current lookup object,
1328      * {@code refc} as the containing class in which the member
1329      * is being sought, and {@code defc} as the class in which the
1330      * member is actually defined.
1331      * (If a class or other type is being accessed,
1332      * the {@code refc} and {@code defc} values are the class itself.)
1333      * The value {@code lookc} is defined as <em>not present</em>
1334      * if the current lookup object does not have
1335      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1336      * The calls are made according to the following rules:
1337      * <ul>
1338      * <li><b>Step 1:</b>
1339      *     If {@code lookc} is not present, or if its class loader is not
1340      *     the same as or an ancestor of the class loader of {@code refc},
1341      *     then {@link SecurityManager#checkPackageAccess
1342      *     smgr.checkPackageAccess(refcPkg)} is called,
1343      *     where {@code refcPkg} is the package of {@code refc}.
1344      * <li><b>Step 2a:</b>
1345      *     If the retrieved member is not public and
1346      *     {@code lookc} is not present, then
1347      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1348      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1349      * <li><b>Step 2b:</b>
1350      *     If the retrieved class has a {@code null} class loader,
1351      *     and {@code lookc} is not present, then
1352      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1353      *     with {@code RuntimePermission("getClassLoader")} is called.
1354      * <li><b>Step 3:</b>
1355      *     If the retrieved member is not public,
1356      *     and if {@code lookc} is not present,
1357      *     and if {@code defc} and {@code refc} are different,
1358      *     then {@link SecurityManager#checkPackageAccess
1359      *     smgr.checkPackageAccess(defcPkg)} is called,
1360      *     where {@code defcPkg} is the package of {@code defc}.
1361      * </ul>
1362      * Security checks are performed after other access checks have passed.
1363      * Therefore, the above rules presuppose a member or class that is public,
1364      * or else that is being accessed from a lookup class that has
1365      * rights to access the member or class.
1366      * <p>
1367      * If a security manager is present and the current lookup object does not have
1368      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1369      * {@link #defineClass(byte[]) defineClass},
1370      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1371      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1372      * defineHiddenClassWithClassData}
1373      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1374      * with {@code RuntimePermission("defineClass")}.
1375      *
1376      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1377      * A small number of Java methods have a special property called caller sensitivity.
1378      * A <em>caller-sensitive</em> method can behave differently depending on the
1379      * identity of its immediate caller.
1380      * <p>
1381      * If a method handle for a caller-sensitive method is requested,
1382      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1383      * but they take account of the lookup class in a special way.
1384      * The resulting method handle behaves as if it were called
1385      * from an instruction contained in the lookup class,
1386      * so that the caller-sensitive method detects the lookup class.
1387      * (By contrast, the invoker of the method handle is disregarded.)
1388      * Thus, in the case of caller-sensitive methods,
1389      * different lookup classes may give rise to
1390      * differently behaving method handles.
1391      * <p>
1392      * In cases where the lookup object is
1393      * {@link MethodHandles#publicLookup() publicLookup()},
1394      * or some other lookup object without the
1395      * {@linkplain #ORIGINAL original access},
1396      * the lookup class is disregarded.
1397      * In such cases, no caller-sensitive method handle can be created,
1398      * access is forbidden, and the lookup fails with an
1399      * {@code IllegalAccessException}.
1400      * <p style="font-size:smaller;">
1401      * <em>Discussion:</em>
1402      * For example, the caller-sensitive method
1403      * {@link java.lang.Class#forName(String) Class.forName(x)}
1404      * can return varying classes or throw varying exceptions,
1405      * depending on the class loader of the class that calls it.
1406      * A public lookup of {@code Class.forName} will fail, because
1407      * there is no reasonable way to determine its bytecode behavior.
1408      * <p style="font-size:smaller;">
1409      * If an application caches method handles for broad sharing,
1410      * it should use {@code publicLookup()} to create them.
1411      * If there is a lookup of {@code Class.forName}, it will fail,
1412      * and the application must take appropriate action in that case.
1413      * It may be that a later lookup, perhaps during the invocation of a
1414      * bootstrap method, can incorporate the specific identity
1415      * of the caller, making the method accessible.
1416      * <p style="font-size:smaller;">
1417      * The function {@code MethodHandles.lookup} is caller sensitive
1418      * so that there can be a secure foundation for lookups.
1419      * Nearly all other methods in the JSR 292 API rely on lookup
1420      * objects to check access requests.
1421      *
1422      * @revised 9
1423      */
1424     public static final
1425     class Lookup {
1426         /** The class on behalf of whom the lookup is being performed. */
1427         private final Class<?> lookupClass;
1428 
1429         /** previous lookup class */
1430         private final Class<?> prevLookupClass;
1431 
1432         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1433         private final int allowedModes;
1434 
1435         static {
1436             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1437         }
1438 
1439         /** A single-bit mask representing {@code public} access,
1440          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1441          *  The value, {@code 0x01}, happens to be the same as the value of the
1442          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1443          *  <p>
1444          *  A {@code Lookup} with this lookup mode performs cross-module access check
1445          *  with respect to the {@linkplain #lookupClass() lookup class} and
1446          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1447          */
1448         public static final int PUBLIC = Modifier.PUBLIC;
1449 
1450         /** A single-bit mask representing {@code private} access,
1451          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1452          *  The value, {@code 0x02}, happens to be the same as the value of the
1453          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1454          */
1455         public static final int PRIVATE = Modifier.PRIVATE;
1456 
1457         /** A single-bit mask representing {@code protected} access,
1458          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1459          *  The value, {@code 0x04}, happens to be the same as the value of the
1460          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1461          */
1462         public static final int PROTECTED = Modifier.PROTECTED;
1463 
1464         /** A single-bit mask representing {@code package} access (default access),
1465          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1466          *  The value is {@code 0x08}, which does not correspond meaningfully to
1467          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1468          */
1469         public static final int PACKAGE = Modifier.STATIC;
1470 
1471         /** A single-bit mask representing {@code module} access,
1472          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1473          *  The value is {@code 0x10}, which does not correspond meaningfully to
1474          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1475          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1476          *  with this lookup mode can access all public types in the module of the
1477          *  lookup class and public types in packages exported by other modules
1478          *  to the module of the lookup class.
1479          *  <p>
1480          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1481          *  previous lookup class} is always {@code null}.
1482          *
1483          *  @since 9
1484          */
1485         public static final int MODULE = PACKAGE << 1;
1486 
1487         /** A single-bit mask representing {@code unconditional} access
1488          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1489          *  The value is {@code 0x20}, which does not correspond meaningfully to
1490          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1491          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1492          *  java.lang.Module#canRead(java.lang.Module) readability}.
1493          *  This lookup mode can access all public members of public types
1494          *  of all modules when the type is in a package that is {@link
1495          *  java.lang.Module#isExported(String) exported unconditionally}.
1496          *
1497          *  <p>
1498          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1499          *  previous lookup class} is always {@code null}.
1500          *
1501          *  @since 9
1502          *  @see #publicLookup()
1503          */
1504         public static final int UNCONDITIONAL = PACKAGE << 2;
1505 
1506         /** A single-bit mask representing {@code original} access
1507          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1508          *  The value is {@code 0x40}, which does not correspond meaningfully to
1509          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1510          *
1511          *  <p>
1512          *  If this lookup mode is set, the {@code Lookup} object must be
1513          *  created by the original lookup class by calling
1514          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1515          *  invoked by the VM.  The {@code Lookup} object with this lookup
1516          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1517          *
1518          *  @since 16
1519          */
1520         public static final int ORIGINAL = PACKAGE << 3;
1521 
1522         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1523         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1524         private static final int TRUSTED   = -1;
1525 
1526         /*
1527          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1528          * Adjust 0 => PACKAGE
1529          */
1530         private static int fixmods(int mods) {
1531             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1532             if (Modifier.isPublic(mods))
1533                 mods |= UNCONDITIONAL;
1534             return (mods != 0) ? mods : PACKAGE;
1535         }
1536 
1537         /** Tells which class is performing the lookup.  It is this class against
1538          *  which checks are performed for visibility and access permissions.
1539          *  <p>
1540          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1541          *  access checks are performed against both the lookup class and the previous lookup class.
1542          *  <p>
1543          *  The class implies a maximum level of access permission,
1544          *  but the permissions may be additionally limited by the bitmask
1545          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1546          *  can be accessed.
1547          *  @return the lookup class, on behalf of which this lookup object finds members
1548          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1549          */
1550         public Class<?> lookupClass() {
1551             return lookupClass;
1552         }
1553 
1554         /** Reports a lookup class in another module that this lookup object
1555          * was previously teleported from, or {@code null}.
1556          * <p>
1557          * A {@code Lookup} object produced by the factory methods, such as the
1558          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1559          * has {@code null} previous lookup class.
1560          * A {@code Lookup} object has a non-null previous lookup class
1561          * when this lookup was teleported from an old lookup class
1562          * in one module to a new lookup class in another module.
1563          *
1564          * @return the lookup class in another module that this lookup object was
1565          *         previously teleported from, or {@code null}
1566          * @since 14
1567          * @see #in(Class)
1568          * @see MethodHandles#privateLookupIn(Class, Lookup)
1569          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1570          */
1571         public Class<?> previousLookupClass() {
1572             return prevLookupClass;
1573         }
1574 
1575         // This is just for calling out to MethodHandleImpl.
1576         private Class<?> lookupClassOrNull() {
1577             return (allowedModes == TRUSTED) ? null : lookupClass;
1578         }
1579 
1580         /** Tells which access-protection classes of members this lookup object can produce.
1581          *  The result is a bit-mask of the bits
1582          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1583          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1584          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1585          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1586          *  {@linkplain #MODULE MODULE (0x10)},
1587          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1588          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1589          *  <p>
1590          *  A freshly-created lookup object
1591          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1592          *  all possible bits set, except {@code UNCONDITIONAL}.
1593          *  A lookup object on a new lookup class
1594          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1595          *  may have some mode bits set to zero.
1596          *  Mode bits can also be
1597          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1598          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1599          *  The purpose of this is to restrict access via the new lookup object,
1600          *  so that it can access only names which can be reached by the original
1601          *  lookup object, and also by the new lookup class.
1602          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1603          *  @see #in
1604          *  @see #dropLookupMode
1605          *
1606          *  @revised 9
1607          */
1608         public int lookupModes() {
1609             return allowedModes & ALL_MODES;
1610         }
1611 
1612         /** Embody the current class (the lookupClass) as a lookup class
1613          * for method handle creation.
1614          * Must be called by from a method in this package,
1615          * which in turn is called by a method not in this package.
1616          */
1617         Lookup(Class<?> lookupClass) {
1618             this(lookupClass, null, FULL_POWER_MODES);
1619         }
1620 
1621         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1622             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1623                     && prevLookupClass.getModule() != lookupClass.getModule());
1624             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1625             this.lookupClass = lookupClass;
1626             this.prevLookupClass = prevLookupClass;
1627             this.allowedModes = allowedModes;
1628         }
1629 
1630         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1631             // make sure we haven't accidentally picked up a privileged class:
1632             checkUnprivilegedlookupClass(lookupClass);
1633             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1634         }
1635 
1636         /**
1637          * Creates a lookup on the specified new lookup class.
1638          * The resulting object will report the specified
1639          * class as its own {@link #lookupClass() lookupClass}.
1640          *
1641          * <p>
1642          * However, the resulting {@code Lookup} object is guaranteed
1643          * to have no more access capabilities than the original.
1644          * In particular, access capabilities can be lost as follows:<ul>
1645          * <li>If the new lookup class is different from the old lookup class,
1646          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1647          * <li>If the new lookup class is in a different module from the old one,
1648          * i.e. {@link #MODULE MODULE} access is lost.
1649          * <li>If the new lookup class is in a different package
1650          * than the old one, protected and default (package) members will not be accessible,
1651          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1652          * <li>If the new lookup class is not within the same package member
1653          * as the old one, private members will not be accessible, and protected members
1654          * will not be accessible by virtue of inheritance,
1655          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1656          * (Protected members may continue to be accessible because of package sharing.)
1657          * <li>If the new lookup class is not
1658          * {@linkplain #accessClass(Class) accessible} to this lookup,
1659          * then no members, not even public members, will be accessible
1660          * i.e. all access modes are lost.
1661          * <li>If the new lookup class, the old lookup class and the previous lookup class
1662          * are all in different modules i.e. teleporting to a third module,
1663          * all access modes are lost.
1664          * </ul>
1665          * <p>
1666          * The new previous lookup class is chosen as follows:
1667          * <ul>
1668          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1669          * the new previous lookup class is {@code null}.
1670          * <li>If the new lookup class is in the same module as the old lookup class,
1671          * the new previous lookup class is the old previous lookup class.
1672          * <li>If the new lookup class is in a different module from the old lookup class,
1673          * the new previous lookup class is the old lookup class.
1674          *</ul>
1675          * <p>
1676          * The resulting lookup's capabilities for loading classes
1677          * (used during {@link #findClass} invocations)
1678          * are determined by the lookup class' loader,
1679          * which may change due to this operation.
1680          *
1681          * @param requestedLookupClass the desired lookup class for the new lookup object
1682          * @return a lookup object which reports the desired lookup class, or the same object
1683          * if there is no change
1684          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1685          * @throws NullPointerException if the argument is null
1686          *
1687          * @revised 9
1688          * @see #accessClass(Class)
1689          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1690          */
1691         public Lookup in(Class<?> requestedLookupClass) {
1692             Objects.requireNonNull(requestedLookupClass);
1693             if (requestedLookupClass.isPrimitive())
1694                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1695             if (requestedLookupClass.isArray())
1696                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1697 
1698             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1699                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1700             if (requestedLookupClass == this.lookupClass)
1701                 return this;  // keep same capabilities
1702             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1703             Module fromModule = this.lookupClass.getModule();
1704             Module targetModule = requestedLookupClass.getModule();
1705             Class<?> plc = this.previousLookupClass();
1706             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1707                 assert plc == null;
1708                 newModes = UNCONDITIONAL;
1709             } else if (fromModule != targetModule) {
1710                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1711                     // allow hopping back and forth between fromModule and plc's module
1712                     // but not the third module
1713                     newModes = 0;
1714                 }
1715                 // drop MODULE access
1716                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1717                 // teleport from this lookup class
1718                 plc = this.lookupClass;
1719             }
1720             if ((newModes & PACKAGE) != 0
1721                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1722                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1723             }
1724             // Allow nestmate lookups to be created without special privilege:
1725             if ((newModes & PRIVATE) != 0
1726                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1727                 newModes &= ~(PRIVATE|PROTECTED);
1728             }
1729             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1730                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1731                 // The requested class it not accessible from the lookup class.
1732                 // No permissions.
1733                 newModes = 0;
1734             }
1735             return newLookup(requestedLookupClass, plc, newModes);
1736         }
1737 
1738         /**
1739          * Creates a lookup on the same lookup class which this lookup object
1740          * finds members, but with a lookup mode that has lost the given lookup mode.
1741          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1742          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1743          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1744          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1745          *
1746          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1747          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1748          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1749          * lookup has no access.
1750          *
1751          * <p> If this lookup is not a public lookup, then the following applies
1752          * regardless of its {@linkplain #lookupModes() lookup modes}.
1753          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1754          * dropped and so the resulting lookup mode will never have these access
1755          * capabilities. When dropping {@code PACKAGE}
1756          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1757          * access. When dropping {@code MODULE} then the resulting lookup will not
1758          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1759          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1760          *
1761          * @apiNote
1762          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1763          * delegate non-public access within the package of the lookup class without
1764          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1765          * A lookup with {@code MODULE} but not
1766          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1767          * the module of the lookup class without conferring package access.
1768          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1769          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1770          * to public classes accessible to both the module of the lookup class
1771          * and the module of the previous lookup class.
1772          *
1773          * @param modeToDrop the lookup mode to drop
1774          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1775          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1776          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1777          * or {@code UNCONDITIONAL}
1778          * @see MethodHandles#privateLookupIn
1779          * @since 9
1780          */
1781         public Lookup dropLookupMode(int modeToDrop) {
1782             int oldModes = lookupModes();
1783             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1784             switch (modeToDrop) {
1785                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1786                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1787                 case PACKAGE: newModes &= ~(PRIVATE); break;
1788                 case PROTECTED:
1789                 case PRIVATE:
1790                 case ORIGINAL:
1791                 case UNCONDITIONAL: break;
1792                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1793             }
1794             if (newModes == oldModes) return this;  // return self if no change
1795             return newLookup(lookupClass(), previousLookupClass(), newModes);
1796         }
1797 
1798         /**
1799          * Creates and links a class or interface from {@code bytes}
1800          * with the same class loader and in the same runtime package and
1801          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1802          * {@linkplain #lookupClass() lookup class} as if calling
1803          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1804          * ClassLoader::defineClass}.
1805          *
1806          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1807          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1808          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1809          * that the lookup object was created by a caller in the runtime package (or derived
1810          * from a lookup originally created by suitably privileged code to a target class in
1811          * the runtime package). </p>
1812          *
1813          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1814          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1815          * same package as the lookup class. </p>
1816          *
1817          * <p> This method does not run the class initializer. The class initializer may
1818          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1819          * Specification</em>. </p>
1820          *
1821          * <p> If there is a security manager and this lookup does not have {@linkplain
1822          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1823          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1824          *
1825          * @param bytes the class bytes
1826          * @return the {@code Class} object for the class
1827          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1828          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1829          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1830          * than the lookup class or {@code bytes} is not a class or interface
1831          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1832          * @throws VerifyError if the newly created class cannot be verified
1833          * @throws LinkageError if the newly created class cannot be linked for any other reason
1834          * @throws SecurityException if a security manager is present and it
1835          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1836          * @throws NullPointerException if {@code bytes} is {@code null}
1837          * @since 9
1838          * @see Lookup#privateLookupIn
1839          * @see Lookup#dropLookupMode
1840          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1841          */
1842         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1843             ensureDefineClassPermission();
1844             if ((lookupModes() & PACKAGE) == 0)
1845                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1846             return makeClassDefiner(bytes.clone()).defineClass(false);
1847         }
1848 
1849         private void ensureDefineClassPermission() {
1850             if (allowedModes == TRUSTED)  return;
1851 
1852             if (!hasFullPrivilegeAccess()) {
1853                 @SuppressWarnings("removal")
1854                 SecurityManager sm = System.getSecurityManager();
1855                 if (sm != null)
1856                     sm.checkPermission(new RuntimePermission("defineClass"));
1857             }
1858         }
1859 
1860         /**
1861          * The set of class options that specify whether a hidden class created by
1862          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1863          * Lookup::defineHiddenClass} method is dynamically added as a new member
1864          * to the nest of a lookup class and/or whether a hidden class has
1865          * a strong relationship with the class loader marked as its defining loader.
1866          *
1867          * @since 15
1868          */
1869         public enum ClassOption {
1870             /**
1871              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1872              * of a lookup class as a nestmate.
1873              *
1874              * <p> A hidden nestmate class has access to the private members of all
1875              * classes and interfaces in the same nest.
1876              *
1877              * @see Class#getNestHost()
1878              */
1879             NESTMATE(NESTMATE_CLASS),
1880 
1881             /**
1882              * Specifies that a hidden class has a <em>strong</em>
1883              * relationship with the class loader marked as its defining loader,
1884              * as a normal class or interface has with its own defining loader.
1885              * This means that the hidden class may be unloaded if and only if
1886              * its defining loader is not reachable and thus may be reclaimed
1887              * by a garbage collector (JLS {@jls 12.7}).
1888              *
1889              * <p> By default, a hidden class or interface may be unloaded
1890              * even if the class loader that is marked as its defining loader is
1891              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1892 
1893              *
1894              * @jls 12.7 Unloading of Classes and Interfaces
1895              */
1896             STRONG(STRONG_LOADER_LINK);
1897 
1898             /* the flag value is used by VM at define class time */
1899             private final int flag;
1900             ClassOption(int flag) {
1901                 this.flag = flag;
1902             }
1903 
1904             static int optionsToFlag(Set<ClassOption> options) {
1905                 int flags = 0;
1906                 for (ClassOption cp : options) {
1907                     flags |= cp.flag;
1908                 }
1909                 return flags;
1910             }
1911         }
1912 
1913         /**
1914          * Creates a <em>hidden</em> class or interface from {@code bytes},
1915          * returning a {@code Lookup} on the newly created class or interface.
1916          *
1917          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1918          * which either defines {@code C} directly or delegates to another class loader.
1919          * A class loader defines {@code C} directly by invoking
1920          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1921          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1922          * to derive {@code C} from a purported representation in {@code class} file format.
1923          * In situations where use of a class loader is undesirable, a class or interface
1924          * {@code C} can be created by this method instead. This method is capable of
1925          * defining {@code C}, and thereby creating it, without invoking
1926          * {@code ClassLoader::defineClass}.
1927          * Instead, this method defines {@code C} as if by arranging for
1928          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1929          * from a purported representation in {@code class} file format
1930          * using the following rules:
1931          *
1932          * <ol>
1933          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1934          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1935          * This level of access is needed to create {@code C} in the module
1936          * of the lookup class of this {@code Lookup}.</li>
1937          *
1938          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1939          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1940          * The major and minor version may differ from the {@code class} file version
1941          * of the lookup class of this {@code Lookup}.</li>
1942          *
1943          * <li> The value of {@code this_class} must be a valid index in the
1944          * {@code constant_pool} table, and the entry at that index must be a valid
1945          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1946          * encoded in internal form that is specified by this structure. {@code N} must
1947          * denote a class or interface in the same package as the lookup class.</li>
1948          *
1949          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1950          * where {@code <suffix>} is an unqualified name.
1951          *
1952          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1953          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1954          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1955          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1956          * refers to the new {@code CONSTANT_Utf8_info} structure.
1957          *
1958          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1959          *
1960          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1961          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1962          * with the following adjustments:
1963          * <ul>
1964          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1965          * that includes a single {@code "."} character, even though this is not a valid
1966          * binary class or interface name in internal form.</li>
1967          *
1968          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1969          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1970          *
1971          * <li> {@code C} is considered to have the same runtime
1972          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1973          * and {@linkplain java.security.ProtectionDomain protection domain}
1974          * as the lookup class of this {@code Lookup}.
1975          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1976          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1977          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1978          * <ul>
1979          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1980          *      even though this is not a valid binary class or interface name.</li>
1981          * <li> {@link Class#descriptorString()} returns the string
1982          *      {@code "L" + N + "." + <suffix> + ";"},
1983          *      even though this is not a valid type descriptor name.</li>
1984          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1985          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1986          * </ul>
1987          * </ul>
1988          * </li>
1989          * </ol>
1990          *
1991          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1992          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1993          * <ul>
1994          * <li> During verification, whenever it is necessary to load the class named
1995          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1996          * made of any class loader.</li>
1997          *
1998          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1999          * by {@code this_class}, the symbolic reference is considered to be resolved to
2000          * {@code C} and resolution always succeeds immediately.</li>
2001          * </ul>
2002          *
2003          * <p> If the {@code initialize} parameter is {@code true},
2004          * then {@code C} is initialized by the Java Virtual Machine.
2005          *
2006          * <p> The newly created class or interface {@code C} serves as the
2007          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2008          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2009          * no other class or interface can refer to {@code C} via a constant pool entry.
2010          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2011          * a method parameter type, or a method return type by any other class.
2012          * This is because a hidden class or interface does not have a binary name, so
2013          * there is no internal form available to record in any class's constant pool.
2014          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2015          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2016          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2017          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2018          * JVM Tool Interface</a>.
2019          *
2020          * <p> A class or interface created by
2021          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2022          * a class loader} has a strong relationship with that class loader.
2023          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2024          * that {@linkplain Class#getClassLoader() defined it}.
2025          * This means that a class created by a class loader may be unloaded if and
2026          * only if its defining loader is not reachable and thus may be reclaimed
2027          * by a garbage collector (JLS {@jls 12.7}).
2028          *
2029          * By default, however, a hidden class or interface may be unloaded even if
2030          * the class loader that is marked as its defining loader is
2031          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2032          * This behavior is useful when a hidden class or interface serves multiple
2033          * classes defined by arbitrary class loaders.  In other cases, a hidden
2034          * class or interface may be linked to a single class (or a small number of classes)
2035          * with the same defining loader as the hidden class or interface.
2036          * In such cases, where the hidden class or interface must be coterminous
2037          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2038          * option may be passed in {@code options}.
2039          * This arranges for a hidden class to have the same strong relationship
2040          * with the class loader marked as its defining loader,
2041          * as a normal class or interface has with its own defining loader.
2042          *
2043          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2044          * may still prevent a hidden class or interface from being
2045          * unloaded by ensuring that the {@code Class} object is reachable.
2046          *
2047          * <p> The unloading characteristics are set for each hidden class when it is
2048          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2049          * to be unloaded independently of the class loader marked as their defining loader
2050          * is that a very large number of hidden classes may be created by an application.
2051          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2052          * just as if normal classes were created by class loaders.
2053          *
2054          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2055          * their private members.  The nest relationship is determined by
2056          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2057          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2058          * By default, a hidden class belongs to a nest consisting only of itself
2059          * because a hidden class has no binary name.
2060          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2061          * to create a hidden class or interface {@code C} as a member of a nest.
2062          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2063          * in the {@code ClassFile} structure from which {@code C} was derived.
2064          * Instead, the following rules determine the nest host of {@code C}:
2065          * <ul>
2066          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2067          *     been determined, then let {@code H} be the nest host of the lookup class.
2068          *     Otherwise, the nest host of the lookup class is determined using the
2069          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2070          * <li>The nest host of {@code C} is determined to be {@code H},
2071          *     the nest host of the lookup class.</li>
2072          * </ul>
2073          *
2074          * <p> A hidden class or interface may be serializable, but this requires a custom
2075          * serialization mechanism in order to ensure that instances are properly serialized
2076          * and deserialized. The default serialization mechanism supports only classes and
2077          * interfaces that are discoverable by their class name.
2078          *
2079          * @param bytes the bytes that make up the class data,
2080          * in the format of a valid {@code class} file as defined by
2081          * <cite>The Java Virtual Machine Specification</cite>.
2082          * @param initialize if {@code true} the class will be initialized.
2083          * @param options {@linkplain ClassOption class options}
2084          * @return the {@code Lookup} object on the hidden class,
2085          * with {@linkplain #ORIGINAL original} and
2086          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2087          *
2088          * @throws IllegalAccessException if this {@code Lookup} does not have
2089          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2090          * @throws SecurityException if a security manager is present and it
2091          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2092          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2093          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2094          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2095          * than the lookup class or {@code bytes} is not a class or interface
2096          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2097          * @throws IncompatibleClassChangeError if the class or interface named as
2098          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2099          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2100          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2101          * {@code C} is {@code C} itself
2102          * @throws VerifyError if the newly created class cannot be verified
2103          * @throws LinkageError if the newly created class cannot be linked for any other reason
2104          * @throws NullPointerException if any parameter is {@code null}
2105          *
2106          * @since 15
2107          * @see Class#isHidden()
2108          * @jvms 4.2.1 Binary Class and Interface Names
2109          * @jvms 4.2.2 Unqualified Names
2110          * @jvms 4.7.28 The {@code NestHost} Attribute
2111          * @jvms 4.7.29 The {@code NestMembers} Attribute
2112          * @jvms 5.4.3.1 Class and Interface Resolution
2113          * @jvms 5.4.4 Access Control
2114          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2115          * @jvms 5.4 Linking
2116          * @jvms 5.5 Initialization
2117          * @jls 12.7 Unloading of Classes and Interfaces
2118          */
2119         @SuppressWarnings("doclint:reference") // cross-module links
2120         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2121                 throws IllegalAccessException
2122         {
2123             Objects.requireNonNull(bytes);
2124             Objects.requireNonNull(options);
2125 
2126             ensureDefineClassPermission();
2127             if (!hasFullPrivilegeAccess()) {
2128                 throw new IllegalAccessException(this + " does not have full privilege access");
2129             }
2130 
2131             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2132         }
2133 
2134         /**
2135          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2136          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2137          * returning a {@code Lookup} on the newly created class or interface.
2138          *
2139          * <p> This method is equivalent to calling
2140          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2141          * as if the hidden class is injected with a private static final <i>unnamed</i>
2142          * field which is initialized with the given {@code classData} at
2143          * the first instruction of the class initializer.
2144          * The newly created class is linked by the Java Virtual Machine.
2145          *
2146          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2147          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2148          * methods can be used to retrieve the {@code classData}.
2149          *
2150          * @apiNote
2151          * A framework can create a hidden class with class data with one or more
2152          * objects and load the class data as dynamically-computed constant(s)
2153          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2154          * Class data} is accessible only to the lookup object created by the newly
2155          * defined hidden class but inaccessible to other members in the same nest
2156          * (unlike private static fields that are accessible to nestmates).
2157          * Care should be taken w.r.t. mutability for example when passing
2158          * an array or other mutable structure through the class data.
2159          * Changing any value stored in the class data at runtime may lead to
2160          * unpredictable behavior.
2161          * If the class data is a {@code List}, it is good practice to make it
2162          * unmodifiable for example via {@link List#of List::of}.
2163          *
2164          * @param bytes     the class bytes
2165          * @param classData pre-initialized class data
2166          * @param initialize if {@code true} the class will be initialized.
2167          * @param options   {@linkplain ClassOption class options}
2168          * @return the {@code Lookup} object on the hidden class,
2169          * with {@linkplain #ORIGINAL original} and
2170          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2171          *
2172          * @throws IllegalAccessException if this {@code Lookup} does not have
2173          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2174          * @throws SecurityException if a security manager is present and it
2175          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2176          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2177          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2178          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2179          * than the lookup class or {@code bytes} is not a class or interface
2180          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2181          * @throws IncompatibleClassChangeError if the class or interface named as
2182          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2183          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2184          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2185          * {@code C} is {@code C} itself
2186          * @throws VerifyError if the newly created class cannot be verified
2187          * @throws LinkageError if the newly created class cannot be linked for any other reason
2188          * @throws NullPointerException if any parameter is {@code null}
2189          *
2190          * @since 16
2191          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2192          * @see Class#isHidden()
2193          * @see MethodHandles#classData(Lookup, String, Class)
2194          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2195          * @jvms 4.2.1 Binary Class and Interface Names
2196          * @jvms 4.2.2 Unqualified Names
2197          * @jvms 4.7.28 The {@code NestHost} Attribute
2198          * @jvms 4.7.29 The {@code NestMembers} Attribute
2199          * @jvms 5.4.3.1 Class and Interface Resolution
2200          * @jvms 5.4.4 Access Control
2201          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2202          * @jvms 5.4 Linking
2203          * @jvms 5.5 Initialization
2204          * @jls 12.7 Unloading of Classes and Interface
2205          */
2206         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2207                 throws IllegalAccessException
2208         {
2209             Objects.requireNonNull(bytes);
2210             Objects.requireNonNull(classData);
2211             Objects.requireNonNull(options);
2212 
2213             ensureDefineClassPermission();
2214             if (!hasFullPrivilegeAccess()) {
2215                 throw new IllegalAccessException(this + " does not have full privilege access");
2216             }
2217 
2218             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2219                        .defineClassAsLookup(initialize, classData);
2220         }
2221 
2222         static class ClassFile {
2223             final String name;
2224             final int accessFlags;
2225             final byte[] bytes;
2226             ClassFile(String name, int accessFlags, byte[] bytes) {
2227                 this.name = name;
2228                 this.accessFlags = accessFlags;
2229                 this.bytes = bytes;
2230             }
2231 
2232             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2233                 return new ClassFile(name, 0, bytes);
2234             }
2235 
2236             /**
2237              * This method checks the class file version and the structure of `this_class`.
2238              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2239              * that is in the named package.
2240              *
2241              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2242              * or the class is not in the given package name.
2243              */
2244             static ClassFile newInstance(byte[] bytes, String pkgName) {
2245                 int magic = readInt(bytes, 0);
2246                 if (magic != 0xCAFEBABE) {
2247                     throw new ClassFormatError("Incompatible magic value: " + magic);
2248                 }
2249                 int minor = readUnsignedShort(bytes, 4);
2250                 int major = readUnsignedShort(bytes, 6);
2251                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2252                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2253                 }
2254 
2255                 String name;
2256                 int accessFlags;
2257                 try {
2258                     ClassReader reader = new ClassReader(bytes);
2259                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2260                     // workaround to read `this_class` using readConst and validate the value
2261                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2262                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2263                     if (!(constant instanceof Type type)) {
2264                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2265                     }
2266                     if (!type.getDescriptor().startsWith("L")) {
2267                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2268                     }
2269                     name = type.getClassName();
2270                     accessFlags = reader.readUnsignedShort(reader.header);
2271                 } catch (RuntimeException e) {
2272                     // ASM exceptions are poorly specified
2273                     ClassFormatError cfe = new ClassFormatError();
2274                     cfe.initCause(e);
2275                     throw cfe;
2276                 }
2277 
2278                 // must be a class or interface
2279                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2280                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2281                 }
2282 
2283                 // check if it's in the named package
2284                 int index = name.lastIndexOf('.');
2285                 String pn = (index == -1) ? "" : name.substring(0, index);
2286                 if (!pn.equals(pkgName)) {
2287                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2288                 }
2289 
2290                 return new ClassFile(name, accessFlags, bytes);
2291             }
2292 
2293             private static int readInt(byte[] bytes, int offset) {
2294                 if ((offset+4) > bytes.length) {
2295                     throw new ClassFormatError("Invalid ClassFile structure");
2296                 }
2297                 return ((bytes[offset] & 0xFF) << 24)
2298                         | ((bytes[offset + 1] & 0xFF) << 16)
2299                         | ((bytes[offset + 2] & 0xFF) << 8)
2300                         | (bytes[offset + 3] & 0xFF);
2301             }
2302 
2303             private static int readUnsignedShort(byte[] bytes, int offset) {
2304                 if ((offset+2) > bytes.length) {
2305                     throw new ClassFormatError("Invalid ClassFile structure");
2306                 }
2307                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2308             }
2309         }
2310 
2311         /*
2312          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2313          * from the given bytes.
2314          *
2315          * Caller should make a defensive copy of the arguments if needed
2316          * before calling this factory method.
2317          *
2318          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2319          * {@bytes} denotes a class in a different package than the lookup class
2320          */
2321         private ClassDefiner makeClassDefiner(byte[] bytes) {
2322             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2323             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2324         }
2325 
2326         /**
2327          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2328          * from the given bytes.  The name must be in the same package as the lookup class.
2329          *
2330          * Caller should make a defensive copy of the arguments if needed
2331          * before calling this factory method.
2332          *
2333          * @param bytes   class bytes
2334          * @return ClassDefiner that defines a hidden class of the given bytes.
2335          *
2336          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2337          * {@bytes} denotes a class in a different package than the lookup class
2338          */
2339         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2340             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2341             return makeHiddenClassDefiner(cf, Set.of(), false);
2342         }
2343 
2344         /**
2345          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2346          * from the given bytes and options.
2347          * The name must be in the same package as the lookup class.
2348          *
2349          * Caller should make a defensive copy of the arguments if needed
2350          * before calling this factory method.
2351          *
2352          * @param bytes   class bytes
2353          * @param options class options
2354          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2355          * @return ClassDefiner that defines a hidden class of the given bytes and options
2356          *
2357          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2358          * {@bytes} denotes a class in a different package than the lookup class
2359          */
2360         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2361                                             Set<ClassOption> options,
2362                                             boolean accessVmAnnotations) {
2363             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2364             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2365         }
2366 
2367         /**
2368          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2369          * from the given bytes and the given options.  No package name check on the given name.
2370          *
2371          * @param name    fully-qualified name that specifies the prefix of the hidden class
2372          * @param bytes   class bytes
2373          * @param options class options
2374          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2375          */
2376         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) {
2377             // skip name and access flags validation
2378             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false);
2379         }
2380 
2381         /**
2382          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2383          * from the given class file and options.
2384          *
2385          * @param cf ClassFile
2386          * @param options class options
2387          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2388          */
2389         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2390                                                     Set<ClassOption> options,
2391                                                     boolean accessVmAnnotations) {
2392             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2393             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2394                 // jdk.internal.vm.annotations are permitted for classes
2395                 // defined to boot loader and platform loader
2396                 flags |= ACCESS_VM_ANNOTATIONS;
2397             }
2398 
2399             return new ClassDefiner(this, cf, flags);
2400         }
2401 
2402         static class ClassDefiner {
2403             private final Lookup lookup;
2404             private final String name;
2405             private final byte[] bytes;
2406             private final int classFlags;
2407 
2408             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2409                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2410                 this.lookup = lookup;
2411                 this.bytes = cf.bytes;
2412                 this.name = cf.name;
2413                 this.classFlags = flags;
2414             }
2415 
2416             String className() {
2417                 return name;
2418             }
2419 
2420             Class<?> defineClass(boolean initialize) {
2421                 return defineClass(initialize, null);
2422             }
2423 
2424             Lookup defineClassAsLookup(boolean initialize) {
2425                 Class<?> c = defineClass(initialize, null);
2426                 return new Lookup(c, null, FULL_POWER_MODES);
2427             }
2428 
2429             /**
2430              * Defines the class of the given bytes and the given classData.
2431              * If {@code initialize} parameter is true, then the class will be initialized.
2432              *
2433              * @param initialize true if the class to be initialized
2434              * @param classData classData or null
2435              * @return the class
2436              *
2437              * @throws LinkageError linkage error
2438              */
2439             Class<?> defineClass(boolean initialize, Object classData) {
2440                 Class<?> lookupClass = lookup.lookupClass();
2441                 ClassLoader loader = lookupClass.getClassLoader();
2442                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2443                 Class<?> c = SharedSecrets.getJavaLangAccess()
2444                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2445                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2446                 return c;
2447             }
2448 
2449             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2450                 Class<?> c = defineClass(initialize, classData);
2451                 return new Lookup(c, null, FULL_POWER_MODES);
2452             }
2453 
2454             private boolean isNestmate() {
2455                 return (classFlags & NESTMATE_CLASS) != 0;
2456             }
2457         }
2458 
2459         private ProtectionDomain lookupClassProtectionDomain() {
2460             ProtectionDomain pd = cachedProtectionDomain;
2461             if (pd == null) {
2462                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2463             }
2464             return pd;
2465         }
2466 
2467         // cached protection domain
2468         private volatile ProtectionDomain cachedProtectionDomain;
2469 
2470         // Make sure outer class is initialized first.
2471         static { IMPL_NAMES.getClass(); }
2472 
2473         /** Package-private version of lookup which is trusted. */
2474         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2475 
2476         /** Version of lookup which is trusted minimally.
2477          *  It can only be used to create method handles to publicly accessible
2478          *  members in packages that are exported unconditionally.
2479          */
2480         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2481 
2482         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2483             String name = lookupClass.getName();
2484             if (name.startsWith("java.lang.invoke."))
2485                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2486         }
2487 
2488         /**
2489          * Displays the name of the class from which lookups are to be made,
2490          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2491          * previous lookup class} if present.
2492          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2493          * If there are restrictions on the access permitted to this lookup,
2494          * this is indicated by adding a suffix to the class name, consisting
2495          * of a slash and a keyword.  The keyword represents the strongest
2496          * allowed access, and is chosen as follows:
2497          * <ul>
2498          * <li>If no access is allowed, the suffix is "/noaccess".
2499          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2500          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2501          * <li>If only public and module access are allowed, the suffix is "/module".
2502          * <li>If public and package access are allowed, the suffix is "/package".
2503          * <li>If public, package, and private access are allowed, the suffix is "/private".
2504          * </ul>
2505          * If none of the above cases apply, it is the case that
2506          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2507          * (public, module, package, private, and protected) is allowed.
2508          * In this case, no suffix is added.
2509          * This is true only of an object obtained originally from
2510          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2511          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2512          * always have restricted access, and will display a suffix.
2513          * <p>
2514          * (It may seem strange that protected access should be
2515          * stronger than private access.  Viewed independently from
2516          * package access, protected access is the first to be lost,
2517          * because it requires a direct subclass relationship between
2518          * caller and callee.)
2519          * @see #in
2520          *
2521          * @revised 9
2522          */
2523         @Override
2524         public String toString() {
2525             String cname = lookupClass.getName();
2526             if (prevLookupClass != null)
2527                 cname += "/" + prevLookupClass.getName();
2528             switch (allowedModes) {
2529             case 0:  // no privileges
2530                 return cname + "/noaccess";
2531             case UNCONDITIONAL:
2532                 return cname + "/publicLookup";
2533             case PUBLIC:
2534                 return cname + "/public";
2535             case PUBLIC|MODULE:
2536                 return cname + "/module";
2537             case PUBLIC|PACKAGE:
2538             case PUBLIC|MODULE|PACKAGE:
2539                 return cname + "/package";
2540             case PUBLIC|PACKAGE|PRIVATE:
2541             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2542                     return cname + "/private";
2543             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2544             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2545             case FULL_POWER_MODES:
2546                     return cname;
2547             case TRUSTED:
2548                 return "/trusted";  // internal only; not exported
2549             default:  // Should not happen, but it's a bitfield...
2550                 cname = cname + "/" + Integer.toHexString(allowedModes);
2551                 assert(false) : cname;
2552                 return cname;
2553             }
2554         }
2555 
2556         /**
2557          * Produces a method handle for a static method.
2558          * The type of the method handle will be that of the method.
2559          * (Since static methods do not take receivers, there is no
2560          * additional receiver argument inserted into the method handle type,
2561          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2562          * The method and all its argument types must be accessible to the lookup object.
2563          * <p>
2564          * The returned method handle will have
2565          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2566          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2567          * <p>
2568          * If the returned method handle is invoked, the method's class will
2569          * be initialized, if it has not already been initialized.
2570          * <p><b>Example:</b>
2571          * <blockquote><pre>{@code
2572 import static java.lang.invoke.MethodHandles.*;
2573 import static java.lang.invoke.MethodType.*;
2574 ...
2575 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2576   "asList", methodType(List.class, Object[].class));
2577 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2578          * }</pre></blockquote>
2579          * @param refc the class from which the method is accessed
2580          * @param name the name of the method
2581          * @param type the type of the method
2582          * @return the desired method handle
2583          * @throws NoSuchMethodException if the method does not exist
2584          * @throws IllegalAccessException if access checking fails,
2585          *                                or if the method is not {@code static},
2586          *                                or if the method's variable arity modifier bit
2587          *                                is set and {@code asVarargsCollector} fails
2588          * @throws    SecurityException if a security manager is present and it
2589          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2590          * @throws NullPointerException if any argument is null
2591          */
2592         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2593             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2594             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2595         }
2596 
2597         /**
2598          * Produces a method handle for a virtual method.
2599          * The type of the method handle will be that of the method,
2600          * with the receiver type (usually {@code refc}) prepended.
2601          * The method and all its argument types must be accessible to the lookup object.
2602          * <p>
2603          * When called, the handle will treat the first argument as a receiver
2604          * and, for non-private methods, dispatch on the receiver's type to determine which method
2605          * implementation to enter.
2606          * For private methods the named method in {@code refc} will be invoked on the receiver.
2607          * (The dispatching action is identical with that performed by an
2608          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2609          * <p>
2610          * The first argument will be of type {@code refc} if the lookup
2611          * class has full privileges to access the member.  Otherwise
2612          * the member must be {@code protected} and the first argument
2613          * will be restricted in type to the lookup class.
2614          * <p>
2615          * The returned method handle will have
2616          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2617          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2618          * <p>
2619          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2620          * instructions and method handles produced by {@code findVirtual},
2621          * if the class is {@code MethodHandle} and the name string is
2622          * {@code invokeExact} or {@code invoke}, the resulting
2623          * method handle is equivalent to one produced by
2624          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2625          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2626          * with the same {@code type} argument.
2627          * <p>
2628          * If the class is {@code VarHandle} and the name string corresponds to
2629          * the name of a signature-polymorphic access mode method, the resulting
2630          * method handle is equivalent to one produced by
2631          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2632          * the access mode corresponding to the name string and with the same
2633          * {@code type} arguments.
2634          * <p>
2635          * <b>Example:</b>
2636          * <blockquote><pre>{@code
2637 import static java.lang.invoke.MethodHandles.*;
2638 import static java.lang.invoke.MethodType.*;
2639 ...
2640 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2641   "concat", methodType(String.class, String.class));
2642 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2643   "hashCode", methodType(int.class));
2644 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2645   "hashCode", methodType(int.class));
2646 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2647 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2648 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2649 // interface method:
2650 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2651   "subSequence", methodType(CharSequence.class, int.class, int.class));
2652 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2653 // constructor "internal method" must be accessed differently:
2654 MethodType MT_newString = methodType(void.class); //()V for new String()
2655 try { assertEquals("impossible", lookup()
2656         .findVirtual(String.class, "<init>", MT_newString));
2657  } catch (NoSuchMethodException ex) { } // OK
2658 MethodHandle MH_newString = publicLookup()
2659   .findConstructor(String.class, MT_newString);
2660 assertEquals("", (String) MH_newString.invokeExact());
2661          * }</pre></blockquote>
2662          *
2663          * @param refc the class or interface from which the method is accessed
2664          * @param name the name of the method
2665          * @param type the type of the method, with the receiver argument omitted
2666          * @return the desired method handle
2667          * @throws NoSuchMethodException if the method does not exist
2668          * @throws IllegalAccessException if access checking fails,
2669          *                                or if the method is {@code static},
2670          *                                or if the method's variable arity modifier bit
2671          *                                is set and {@code asVarargsCollector} fails
2672          * @throws    SecurityException if a security manager is present and it
2673          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2674          * @throws NullPointerException if any argument is null
2675          */
2676         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2677             if (refc == MethodHandle.class) {
2678                 MethodHandle mh = findVirtualForMH(name, type);
2679                 if (mh != null)  return mh;
2680             } else if (refc == VarHandle.class) {
2681                 MethodHandle mh = findVirtualForVH(name, type);
2682                 if (mh != null)  return mh;
2683             }
2684             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2685             MemberName method = resolveOrFail(refKind, refc, name, type);
2686             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2687         }
2688         private MethodHandle findVirtualForMH(String name, MethodType type) {
2689             // these names require special lookups because of the implicit MethodType argument
2690             if ("invoke".equals(name))
2691                 return invoker(type);
2692             if ("invokeExact".equals(name))
2693                 return exactInvoker(type);
2694             assert(!MemberName.isMethodHandleInvokeName(name));
2695             return null;
2696         }
2697         private MethodHandle findVirtualForVH(String name, MethodType type) {
2698             try {
2699                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2700             } catch (IllegalArgumentException e) {
2701                 return null;
2702             }
2703         }
2704 
2705         /**
2706          * Produces a method handle which creates an object and initializes it, using
2707          * the constructor of the specified type.
2708          * The parameter types of the method handle will be those of the constructor,
2709          * while the return type will be a reference to the constructor's class.
2710          * The constructor and all its argument types must be accessible to the lookup object.
2711          * <p>
2712          * The requested type must have a return type of {@code void}.
2713          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2714          * <p>
2715          * The returned method handle will have
2716          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2717          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2718          * <p>
2719          * If the returned method handle is invoked, the constructor's class will
2720          * be initialized, if it has not already been initialized.
2721          * <p><b>Example:</b>
2722          * <blockquote><pre>{@code
2723 import static java.lang.invoke.MethodHandles.*;
2724 import static java.lang.invoke.MethodType.*;
2725 ...
2726 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2727   ArrayList.class, methodType(void.class, Collection.class));
2728 Collection orig = Arrays.asList("x", "y");
2729 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2730 assert(orig != copy);
2731 assertEquals(orig, copy);
2732 // a variable-arity constructor:
2733 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2734   ProcessBuilder.class, methodType(void.class, String[].class));
2735 ProcessBuilder pb = (ProcessBuilder)
2736   MH_newProcessBuilder.invoke("x", "y", "z");
2737 assertEquals("[x, y, z]", pb.command().toString());
2738          * }</pre></blockquote>
2739          * @param refc the class or interface from which the method is accessed
2740          * @param type the type of the method, with the receiver argument omitted, and a void return type
2741          * @return the desired method handle
2742          * @throws NoSuchMethodException if the constructor does not exist
2743          * @throws IllegalAccessException if access checking fails
2744          *                                or if the method's variable arity modifier bit
2745          *                                is set and {@code asVarargsCollector} fails
2746          * @throws    SecurityException if a security manager is present and it
2747          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2748          * @throws NullPointerException if any argument is null
2749          */
2750         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2751             if (refc.isArray()) {
2752                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2753             }
2754             String name = "<init>";
2755             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2756             return getDirectConstructor(refc, ctor);
2757         }
2758 
2759         /**
2760          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2761          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2762          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2763          * and then determines whether the class is accessible to this lookup object.
2764          * <p>
2765          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2766          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2767          *
2768          * @param targetName the fully qualified name of the class to be looked up.
2769          * @return the requested class.
2770          * @throws SecurityException if a security manager is present and it
2771          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2772          * @throws LinkageError if the linkage fails
2773          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2774          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2775          * modes.
2776          * @throws NullPointerException if {@code targetName} is null
2777          * @since 9
2778          * @jvms 5.4.3.1 Class and Interface Resolution
2779          */
2780         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2781             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2782             return accessClass(targetClass);
2783         }
2784 
2785         /**
2786          * Ensures that {@code targetClass} has been initialized. The class
2787          * to be initialized must be {@linkplain #accessClass accessible}
2788          * to this {@code Lookup} object.  This method causes {@code targetClass}
2789          * to be initialized if it has not been already initialized,
2790          * as specified in JVMS {@jvms 5.5}.
2791          *
2792          * <p>
2793          * This method returns when {@code targetClass} is fully initialized, or
2794          * when {@code targetClass} is being initialized by the current thread.
2795          *
2796          * @param targetClass the class to be initialized
2797          * @return {@code targetClass} that has been initialized, or that is being
2798          *         initialized by the current thread.
2799          *
2800          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2801          *          or array class
2802          * @throws  IllegalAccessException if {@code targetClass} is not
2803          *          {@linkplain #accessClass accessible} to this lookup
2804          * @throws  ExceptionInInitializerError if the class initialization provoked
2805          *          by this method fails
2806          * @throws  SecurityException if a security manager is present and it
2807          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2808          * @since 15
2809          * @jvms 5.5 Initialization
2810          */
2811         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2812             if (targetClass.isPrimitive())
2813                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2814             if (targetClass.isArray())
2815                 throw new IllegalArgumentException(targetClass + " is an array class");
2816 
2817             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2818                 throw makeAccessException(targetClass);
2819             }
2820             checkSecurityManager(targetClass);
2821 
2822             // ensure class initialization
2823             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2824             return targetClass;
2825         }
2826 
2827         /*
2828          * Returns IllegalAccessException due to access violation to the given targetClass.
2829          *
2830          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2831          * which verifies access to a class rather a member.
2832          */
2833         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2834             String message = "access violation: "+ targetClass;
2835             if (this == MethodHandles.publicLookup()) {
2836                 message += ", from public Lookup";
2837             } else {
2838                 Module m = lookupClass().getModule();
2839                 message += ", from " + lookupClass() + " (" + m + ")";
2840                 if (prevLookupClass != null) {
2841                     message += ", previous lookup " +
2842                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2843                 }
2844             }
2845             return new IllegalAccessException(message);
2846         }
2847 
2848         /**
2849          * Determines if a class can be accessed from the lookup context defined by
2850          * this {@code Lookup} object. The static initializer of the class is not run.
2851          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2852          * if the element type of the array class is accessible.  Otherwise,
2853          * {@code targetClass} is determined as accessible as follows.
2854          *
2855          * <p>
2856          * If {@code targetClass} is in the same module as the lookup class,
2857          * the lookup class is {@code LC} in module {@code M1} and
2858          * the previous lookup class is in module {@code M0} or
2859          * {@code null} if not present,
2860          * {@code targetClass} is accessible if and only if one of the following is true:
2861          * <ul>
2862          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2863          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2864          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2865          *     in the same runtime package of {@code LC}.</li>
2866          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2867          *     a public type in {@code M1}.</li>
2868          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2869          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2870          *     if the previous lookup class is present; otherwise, {@code targetClass}
2871          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2872          * </ul>
2873          *
2874          * <p>
2875          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2876          * can access public types in all modules when the type is in a package
2877          * that is exported unconditionally.
2878          * <p>
2879          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2880          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2881          * is inaccessible.
2882          * <p>
2883          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2884          * {@code M1} is the module containing {@code lookupClass} and
2885          * {@code M2} is the module containing {@code targetClass},
2886          * then {@code targetClass} is accessible if and only if
2887          * <ul>
2888          * <li>{@code M1} reads {@code M2}, and
2889          * <li>{@code targetClass} is public and in a package exported by
2890          *     {@code M2} at least to {@code M1}.
2891          * </ul>
2892          * <p>
2893          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2894          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2895          * containing the previous lookup class, then {@code targetClass} is accessible
2896          * if and only if one of the following is true:
2897          * <ul>
2898          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2899          *     {@linkplain Module#reads reads} {@code M0} and the type is
2900          *     in a package that is exported to at least {@code M1}.
2901          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2902          *     {@linkplain Module#reads reads} {@code M1} and the type is
2903          *     in a package that is exported to at least {@code M0}.
2904          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2905          *     and {@code M1} reads {@code M2} and the type is in a package
2906          *     that is exported to at least both {@code M0} and {@code M2}.
2907          * </ul>
2908          * <p>
2909          * Otherwise, {@code targetClass} is not accessible.
2910          *
2911          * @param targetClass the class to be access-checked
2912          * @return the class that has been access-checked
2913          * @throws IllegalAccessException if the class is not accessible from the lookup class
2914          * and previous lookup class, if present, using the allowed access modes.
2915          * @throws SecurityException if a security manager is present and it
2916          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2917          * @throws NullPointerException if {@code targetClass} is {@code null}
2918          * @since 9
2919          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2920          */
2921         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2922             if (!isClassAccessible(targetClass)) {
2923                 throw makeAccessException(targetClass);
2924             }
2925             checkSecurityManager(targetClass);
2926             return targetClass;
2927         }
2928 
2929         /**
2930          * Produces an early-bound method handle for a virtual method.
2931          * It will bypass checks for overriding methods on the receiver,
2932          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2933          * instruction from within the explicitly specified {@code specialCaller}.
2934          * The type of the method handle will be that of the method,
2935          * with a suitably restricted receiver type prepended.
2936          * (The receiver type will be {@code specialCaller} or a subtype.)
2937          * The method and all its argument types must be accessible
2938          * to the lookup object.
2939          * <p>
2940          * Before method resolution,
2941          * if the explicitly specified caller class is not identical with the
2942          * lookup class, or if this lookup object does not have
2943          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2944          * privileges, the access fails.
2945          * <p>
2946          * The returned method handle will have
2947          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2948          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2949          * <p style="font-size:smaller;">
2950          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2951          * even though the {@code invokespecial} instruction can refer to them
2952          * in special circumstances.  Use {@link #findConstructor findConstructor}
2953          * to access instance initialization methods in a safe manner.)</em>
2954          * <p><b>Example:</b>
2955          * <blockquote><pre>{@code
2956 import static java.lang.invoke.MethodHandles.*;
2957 import static java.lang.invoke.MethodType.*;
2958 ...
2959 static class Listie extends ArrayList {
2960   public String toString() { return "[wee Listie]"; }
2961   static Lookup lookup() { return MethodHandles.lookup(); }
2962 }
2963 ...
2964 // no access to constructor via invokeSpecial:
2965 MethodHandle MH_newListie = Listie.lookup()
2966   .findConstructor(Listie.class, methodType(void.class));
2967 Listie l = (Listie) MH_newListie.invokeExact();
2968 try { assertEquals("impossible", Listie.lookup().findSpecial(
2969         Listie.class, "<init>", methodType(void.class), Listie.class));
2970  } catch (NoSuchMethodException ex) { } // OK
2971 // access to super and self methods via invokeSpecial:
2972 MethodHandle MH_super = Listie.lookup().findSpecial(
2973   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2974 MethodHandle MH_this = Listie.lookup().findSpecial(
2975   Listie.class, "toString" , methodType(String.class), Listie.class);
2976 MethodHandle MH_duper = Listie.lookup().findSpecial(
2977   Object.class, "toString" , methodType(String.class), Listie.class);
2978 assertEquals("[]", (String) MH_super.invokeExact(l));
2979 assertEquals(""+l, (String) MH_this.invokeExact(l));
2980 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2981 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2982         String.class, "toString", methodType(String.class), Listie.class));
2983  } catch (IllegalAccessException ex) { } // OK
2984 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2985 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2986          * }</pre></blockquote>
2987          *
2988          * @param refc the class or interface from which the method is accessed
2989          * @param name the name of the method (which must not be "&lt;init&gt;")
2990          * @param type the type of the method, with the receiver argument omitted
2991          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2992          * @return the desired method handle
2993          * @throws NoSuchMethodException if the method does not exist
2994          * @throws IllegalAccessException if access checking fails,
2995          *                                or if the method is {@code static},
2996          *                                or if the method's variable arity modifier bit
2997          *                                is set and {@code asVarargsCollector} fails
2998          * @throws    SecurityException if a security manager is present and it
2999          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3000          * @throws NullPointerException if any argument is null
3001          */
3002         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3003                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3004             checkSpecialCaller(specialCaller, refc);
3005             Lookup specialLookup = this.in(specialCaller);
3006             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3007             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3008         }
3009 
3010         /**
3011          * Produces a method handle giving read access to a non-static field.
3012          * The type of the method handle will have a return type of the field's
3013          * value type.
3014          * The method handle's single argument will be the instance containing
3015          * the field.
3016          * Access checking is performed immediately on behalf of the lookup class.
3017          * @param refc the class or interface from which the method is accessed
3018          * @param name the field's name
3019          * @param type the field's type
3020          * @return a method handle which can load values from the field
3021          * @throws NoSuchFieldException if the field does not exist
3022          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3023          * @throws    SecurityException if a security manager is present and it
3024          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3025          * @throws NullPointerException if any argument is null
3026          * @see #findVarHandle(Class, String, Class)
3027          */
3028         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3029             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3030             return getDirectField(REF_getField, refc, field);
3031         }
3032 
3033         /**
3034          * Produces a method handle giving write access to a non-static field.
3035          * The type of the method handle will have a void return type.
3036          * The method handle will take two arguments, the instance containing
3037          * the field, and the value to be stored.
3038          * The second argument will be of the field's value type.
3039          * Access checking is performed immediately on behalf of the lookup class.
3040          * @param refc the class or interface from which the method is accessed
3041          * @param name the field's name
3042          * @param type the field's type
3043          * @return a method handle which can store values into the field
3044          * @throws NoSuchFieldException if the field does not exist
3045          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3046          *                                or {@code final}
3047          * @throws    SecurityException if a security manager is present and it
3048          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3049          * @throws NullPointerException if any argument is null
3050          * @see #findVarHandle(Class, String, Class)
3051          */
3052         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3053             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3054             return getDirectField(REF_putField, refc, field);
3055         }
3056 
3057         /**
3058          * Produces a VarHandle giving access to a non-static field {@code name}
3059          * of type {@code type} declared in a class of type {@code recv}.
3060          * The VarHandle's variable type is {@code type} and it has one
3061          * coordinate type, {@code recv}.
3062          * <p>
3063          * Access checking is performed immediately on behalf of the lookup
3064          * class.
3065          * <p>
3066          * Certain access modes of the returned VarHandle are unsupported under
3067          * the following conditions:
3068          * <ul>
3069          * <li>if the field is declared {@code final}, then the write, atomic
3070          *     update, numeric atomic update, and bitwise atomic update access
3071          *     modes are unsupported.
3072          * <li>if the field type is anything other than {@code byte},
3073          *     {@code short}, {@code char}, {@code int}, {@code long},
3074          *     {@code float}, or {@code double} then numeric atomic update
3075          *     access modes are unsupported.
3076          * <li>if the field type is anything other than {@code boolean},
3077          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3078          *     {@code long} then bitwise atomic update access modes are
3079          *     unsupported.
3080          * </ul>
3081          * <p>
3082          * If the field is declared {@code volatile} then the returned VarHandle
3083          * will override access to the field (effectively ignore the
3084          * {@code volatile} declaration) in accordance to its specified
3085          * access modes.
3086          * <p>
3087          * If the field type is {@code float} or {@code double} then numeric
3088          * and atomic update access modes compare values using their bitwise
3089          * representation (see {@link Float#floatToRawIntBits} and
3090          * {@link Double#doubleToRawLongBits}, respectively).
3091          * @apiNote
3092          * Bitwise comparison of {@code float} values or {@code double} values,
3093          * as performed by the numeric and atomic update access modes, differ
3094          * from the primitive {@code ==} operator and the {@link Float#equals}
3095          * and {@link Double#equals} methods, specifically with respect to
3096          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3097          * Care should be taken when performing a compare and set or a compare
3098          * and exchange operation with such values since the operation may
3099          * unexpectedly fail.
3100          * There are many possible NaN values that are considered to be
3101          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3102          * provided by Java can distinguish between them.  Operation failure can
3103          * occur if the expected or witness value is a NaN value and it is
3104          * transformed (perhaps in a platform specific manner) into another NaN
3105          * value, and thus has a different bitwise representation (see
3106          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3107          * details).
3108          * The values {@code -0.0} and {@code +0.0} have different bitwise
3109          * representations but are considered equal when using the primitive
3110          * {@code ==} operator.  Operation failure can occur if, for example, a
3111          * numeric algorithm computes an expected value to be say {@code -0.0}
3112          * and previously computed the witness value to be say {@code +0.0}.
3113          * @param recv the receiver class, of type {@code R}, that declares the
3114          * non-static field
3115          * @param name the field's name
3116          * @param type the field's type, of type {@code T}
3117          * @return a VarHandle giving access to non-static fields.
3118          * @throws NoSuchFieldException if the field does not exist
3119          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3120          * @throws    SecurityException if a security manager is present and it
3121          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3122          * @throws NullPointerException if any argument is null
3123          * @since 9
3124          */
3125         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3126             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3127             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3128             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3129         }
3130 
3131         /**
3132          * Produces a method handle giving read access to a static field.
3133          * The type of the method handle will have a return type of the field's
3134          * value type.
3135          * The method handle will take no arguments.
3136          * Access checking is performed immediately on behalf of the lookup class.
3137          * <p>
3138          * If the returned method handle is invoked, the field's class will
3139          * be initialized, if it has not already been initialized.
3140          * @param refc the class or interface from which the method is accessed
3141          * @param name the field's name
3142          * @param type the field's type
3143          * @return a method handle which can load values from the field
3144          * @throws NoSuchFieldException if the field does not exist
3145          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3146          * @throws    SecurityException if a security manager is present and it
3147          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3148          * @throws NullPointerException if any argument is null
3149          */
3150         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3151             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3152             return getDirectField(REF_getStatic, refc, field);
3153         }
3154 
3155         /**
3156          * Produces a method handle giving write access to a static field.
3157          * The type of the method handle will have a void return type.
3158          * The method handle will take a single
3159          * argument, of the field's value type, the value to be stored.
3160          * Access checking is performed immediately on behalf of the lookup class.
3161          * <p>
3162          * If the returned method handle is invoked, the field's class will
3163          * be initialized, if it has not already been initialized.
3164          * @param refc the class or interface from which the method is accessed
3165          * @param name the field's name
3166          * @param type the field's type
3167          * @return a method handle which can store values into the field
3168          * @throws NoSuchFieldException if the field does not exist
3169          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3170          *                                or is {@code final}
3171          * @throws    SecurityException if a security manager is present and it
3172          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3173          * @throws NullPointerException if any argument is null
3174          */
3175         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3176             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3177             return getDirectField(REF_putStatic, refc, field);
3178         }
3179 
3180         /**
3181          * Produces a VarHandle giving access to a static field {@code name} of
3182          * type {@code type} declared in a class of type {@code decl}.
3183          * The VarHandle's variable type is {@code type} and it has no
3184          * coordinate types.
3185          * <p>
3186          * Access checking is performed immediately on behalf of the lookup
3187          * class.
3188          * <p>
3189          * If the returned VarHandle is operated on, the declaring class will be
3190          * initialized, if it has not already been initialized.
3191          * <p>
3192          * Certain access modes of the returned VarHandle are unsupported under
3193          * the following conditions:
3194          * <ul>
3195          * <li>if the field is declared {@code final}, then the write, atomic
3196          *     update, numeric atomic update, and bitwise atomic update access
3197          *     modes are unsupported.
3198          * <li>if the field type is anything other than {@code byte},
3199          *     {@code short}, {@code char}, {@code int}, {@code long},
3200          *     {@code float}, or {@code double}, then numeric atomic update
3201          *     access modes are unsupported.
3202          * <li>if the field type is anything other than {@code boolean},
3203          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3204          *     {@code long} then bitwise atomic update access modes are
3205          *     unsupported.
3206          * </ul>
3207          * <p>
3208          * If the field is declared {@code volatile} then the returned VarHandle
3209          * will override access to the field (effectively ignore the
3210          * {@code volatile} declaration) in accordance to its specified
3211          * access modes.
3212          * <p>
3213          * If the field type is {@code float} or {@code double} then numeric
3214          * and atomic update access modes compare values using their bitwise
3215          * representation (see {@link Float#floatToRawIntBits} and
3216          * {@link Double#doubleToRawLongBits}, respectively).
3217          * @apiNote
3218          * Bitwise comparison of {@code float} values or {@code double} values,
3219          * as performed by the numeric and atomic update access modes, differ
3220          * from the primitive {@code ==} operator and the {@link Float#equals}
3221          * and {@link Double#equals} methods, specifically with respect to
3222          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3223          * Care should be taken when performing a compare and set or a compare
3224          * and exchange operation with such values since the operation may
3225          * unexpectedly fail.
3226          * There are many possible NaN values that are considered to be
3227          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3228          * provided by Java can distinguish between them.  Operation failure can
3229          * occur if the expected or witness value is a NaN value and it is
3230          * transformed (perhaps in a platform specific manner) into another NaN
3231          * value, and thus has a different bitwise representation (see
3232          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3233          * details).
3234          * The values {@code -0.0} and {@code +0.0} have different bitwise
3235          * representations but are considered equal when using the primitive
3236          * {@code ==} operator.  Operation failure can occur if, for example, a
3237          * numeric algorithm computes an expected value to be say {@code -0.0}
3238          * and previously computed the witness value to be say {@code +0.0}.
3239          * @param decl the class that declares the static field
3240          * @param name the field's name
3241          * @param type the field's type, of type {@code T}
3242          * @return a VarHandle giving access to a static field
3243          * @throws NoSuchFieldException if the field does not exist
3244          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3245          * @throws    SecurityException if a security manager is present and it
3246          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3247          * @throws NullPointerException if any argument is null
3248          * @since 9
3249          */
3250         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3251             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3252             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3253             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3254         }
3255 
3256         /**
3257          * Produces an early-bound method handle for a non-static method.
3258          * The receiver must have a supertype {@code defc} in which a method
3259          * of the given name and type is accessible to the lookup class.
3260          * The method and all its argument types must be accessible to the lookup object.
3261          * The type of the method handle will be that of the method,
3262          * without any insertion of an additional receiver parameter.
3263          * The given receiver will be bound into the method handle,
3264          * so that every call to the method handle will invoke the
3265          * requested method on the given receiver.
3266          * <p>
3267          * The returned method handle will have
3268          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3269          * the method's variable arity modifier bit ({@code 0x0080}) is set
3270          * <em>and</em> the trailing array argument is not the only argument.
3271          * (If the trailing array argument is the only argument,
3272          * the given receiver value will be bound to it.)
3273          * <p>
3274          * This is almost equivalent to the following code, with some differences noted below:
3275          * <blockquote><pre>{@code
3276 import static java.lang.invoke.MethodHandles.*;
3277 import static java.lang.invoke.MethodType.*;
3278 ...
3279 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3280 MethodHandle mh1 = mh0.bindTo(receiver);
3281 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3282 return mh1;
3283          * }</pre></blockquote>
3284          * where {@code defc} is either {@code receiver.getClass()} or a super
3285          * type of that class, in which the requested method is accessible
3286          * to the lookup class.
3287          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3288          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3289          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3290          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3291          * @param receiver the object from which the method is accessed
3292          * @param name the name of the method
3293          * @param type the type of the method, with the receiver argument omitted
3294          * @return the desired method handle
3295          * @throws NoSuchMethodException if the method does not exist
3296          * @throws IllegalAccessException if access checking fails
3297          *                                or if the method's variable arity modifier bit
3298          *                                is set and {@code asVarargsCollector} fails
3299          * @throws    SecurityException if a security manager is present and it
3300          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3301          * @throws NullPointerException if any argument is null
3302          * @see MethodHandle#bindTo
3303          * @see #findVirtual
3304          */
3305         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3306             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3307             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3308             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3309             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3310                 throw new IllegalAccessException("The restricted defining class " +
3311                                                  mh.type().leadingReferenceParameter().getName() +
3312                                                  " is not assignable from receiver class " +
3313                                                  receiver.getClass().getName());
3314             }
3315             return mh.bindArgumentL(0, receiver).setVarargs(method);
3316         }
3317 
3318         /**
3319          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3320          * to <i>m</i>, if the lookup class has permission.
3321          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3322          * If <i>m</i> is virtual, overriding is respected on every call.
3323          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3324          * The type of the method handle will be that of the method,
3325          * with the receiver type prepended (but only if it is non-static).
3326          * If the method's {@code accessible} flag is not set,
3327          * access checking is performed immediately on behalf of the lookup class.
3328          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3329          * <p>
3330          * The returned method handle will have
3331          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3332          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3333          * <p>
3334          * If <i>m</i> is static, and
3335          * if the returned method handle is invoked, the method's class will
3336          * be initialized, if it has not already been initialized.
3337          * @param m the reflected method
3338          * @return a method handle which can invoke the reflected method
3339          * @throws IllegalAccessException if access checking fails
3340          *                                or if the method's variable arity modifier bit
3341          *                                is set and {@code asVarargsCollector} fails
3342          * @throws NullPointerException if the argument is null
3343          */
3344         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3345             if (m.getDeclaringClass() == MethodHandle.class) {
3346                 MethodHandle mh = unreflectForMH(m);
3347                 if (mh != null)  return mh;
3348             }
3349             if (m.getDeclaringClass() == VarHandle.class) {
3350                 MethodHandle mh = unreflectForVH(m);
3351                 if (mh != null)  return mh;
3352             }
3353             MemberName method = new MemberName(m);
3354             byte refKind = method.getReferenceKind();
3355             if (refKind == REF_invokeSpecial)
3356                 refKind = REF_invokeVirtual;
3357             assert(method.isMethod());
3358             @SuppressWarnings("deprecation")
3359             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3360             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3361         }
3362         private MethodHandle unreflectForMH(Method m) {
3363             // these names require special lookups because they throw UnsupportedOperationException
3364             if (MemberName.isMethodHandleInvokeName(m.getName()))
3365                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3366             return null;
3367         }
3368         private MethodHandle unreflectForVH(Method m) {
3369             // these names require special lookups because they throw UnsupportedOperationException
3370             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3371                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3372             return null;
3373         }
3374 
3375         /**
3376          * Produces a method handle for a reflected method.
3377          * It will bypass checks for overriding methods on the receiver,
3378          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3379          * instruction from within the explicitly specified {@code specialCaller}.
3380          * The type of the method handle will be that of the method,
3381          * with a suitably restricted receiver type prepended.
3382          * (The receiver type will be {@code specialCaller} or a subtype.)
3383          * If the method's {@code accessible} flag is not set,
3384          * access checking is performed immediately on behalf of the lookup class,
3385          * as if {@code invokespecial} instruction were being linked.
3386          * <p>
3387          * Before method resolution,
3388          * if the explicitly specified caller class is not identical with the
3389          * lookup class, or if this lookup object does not have
3390          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3391          * privileges, the access fails.
3392          * <p>
3393          * The returned method handle will have
3394          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3395          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3396          * @param m the reflected method
3397          * @param specialCaller the class nominally calling the method
3398          * @return a method handle which can invoke the reflected method
3399          * @throws IllegalAccessException if access checking fails,
3400          *                                or if the method is {@code static},
3401          *                                or if the method's variable arity modifier bit
3402          *                                is set and {@code asVarargsCollector} fails
3403          * @throws NullPointerException if any argument is null
3404          */
3405         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3406             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3407             Lookup specialLookup = this.in(specialCaller);
3408             MemberName method = new MemberName(m, true);
3409             assert(method.isMethod());
3410             // ignore m.isAccessible:  this is a new kind of access
3411             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3412         }
3413 
3414         /**
3415          * Produces a method handle for a reflected constructor.
3416          * The type of the method handle will be that of the constructor,
3417          * with the return type changed to the declaring class.
3418          * The method handle will perform a {@code newInstance} operation,
3419          * creating a new instance of the constructor's class on the
3420          * arguments passed to the method handle.
3421          * <p>
3422          * If the constructor's {@code accessible} flag is not set,
3423          * access checking is performed immediately on behalf of the lookup class.
3424          * <p>
3425          * The returned method handle will have
3426          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3427          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3428          * <p>
3429          * If the returned method handle is invoked, the constructor's class will
3430          * be initialized, if it has not already been initialized.
3431          * @param c the reflected constructor
3432          * @return a method handle which can invoke the reflected constructor
3433          * @throws IllegalAccessException if access checking fails
3434          *                                or if the method's variable arity modifier bit
3435          *                                is set and {@code asVarargsCollector} fails
3436          * @throws NullPointerException if the argument is null
3437          */
3438         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3439             MemberName ctor = new MemberName(c);
3440             assert(ctor.isConstructor());
3441             @SuppressWarnings("deprecation")
3442             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3443             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
3444         }
3445 
3446         /**
3447          * Produces a method handle giving read access to a reflected field.
3448          * The type of the method handle will have a return type of the field's
3449          * value type.
3450          * If the field is {@code static}, the method handle will take no arguments.
3451          * Otherwise, its single argument will be the instance containing
3452          * the field.
3453          * If the {@code Field} object's {@code accessible} flag is not set,
3454          * access checking is performed immediately on behalf of the lookup class.
3455          * <p>
3456          * If the field is static, and
3457          * if the returned method handle is invoked, the field's class will
3458          * be initialized, if it has not already been initialized.
3459          * @param f the reflected field
3460          * @return a method handle which can load values from the reflected field
3461          * @throws IllegalAccessException if access checking fails
3462          * @throws NullPointerException if the argument is null
3463          */
3464         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3465             return unreflectField(f, false);
3466         }
3467 
3468         /**
3469          * Produces a method handle giving write access to a reflected field.
3470          * The type of the method handle will have a void return type.
3471          * If the field is {@code static}, the method handle will take a single
3472          * argument, of the field's value type, the value to be stored.
3473          * Otherwise, the two arguments will be the instance containing
3474          * the field, and the value to be stored.
3475          * If the {@code Field} object's {@code accessible} flag is not set,
3476          * access checking is performed immediately on behalf of the lookup class.
3477          * <p>
3478          * If the field is {@code final}, write access will not be
3479          * allowed and access checking will fail, except under certain
3480          * narrow circumstances documented for {@link Field#set Field.set}.
3481          * A method handle is returned only if a corresponding call to
3482          * the {@code Field} object's {@code set} method could return
3483          * normally.  In particular, fields which are both {@code static}
3484          * and {@code final} may never be set.
3485          * <p>
3486          * If the field is {@code static}, and
3487          * if the returned method handle is invoked, the field's class will
3488          * be initialized, if it has not already been initialized.
3489          * @param f the reflected field
3490          * @return a method handle which can store values into the reflected field
3491          * @throws IllegalAccessException if access checking fails,
3492          *         or if the field is {@code final} and write access
3493          *         is not enabled on the {@code Field} object
3494          * @throws NullPointerException if the argument is null
3495          */
3496         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3497             return unreflectField(f, true);
3498         }
3499 
3500         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3501             MemberName field = new MemberName(f, isSetter);
3502             if (isSetter && field.isFinal()) {
3503                 if (field.isTrustedFinalField()) {
3504                     String msg = field.isStatic() ? "static final field has no write access"
3505                                                   : "final field has no write access";
3506                     throw field.makeAccessException(msg, this);
3507                 }
3508             }
3509             assert(isSetter
3510                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3511                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3512             @SuppressWarnings("deprecation")
3513             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3514             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3515         }
3516 
3517         /**
3518          * Produces a VarHandle giving access to a reflected field {@code f}
3519          * of type {@code T} declared in a class of type {@code R}.
3520          * The VarHandle's variable type is {@code T}.
3521          * If the field is non-static the VarHandle has one coordinate type,
3522          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3523          * coordinate types.
3524          * <p>
3525          * Access checking is performed immediately on behalf of the lookup
3526          * class, regardless of the value of the field's {@code accessible}
3527          * flag.
3528          * <p>
3529          * If the field is static, and if the returned VarHandle is operated
3530          * on, the field's declaring class will be initialized, if it has not
3531          * already been initialized.
3532          * <p>
3533          * Certain access modes of the returned VarHandle are unsupported under
3534          * the following conditions:
3535          * <ul>
3536          * <li>if the field is declared {@code final}, then the write, atomic
3537          *     update, numeric atomic update, and bitwise atomic update access
3538          *     modes are unsupported.
3539          * <li>if the field type is anything other than {@code byte},
3540          *     {@code short}, {@code char}, {@code int}, {@code long},
3541          *     {@code float}, or {@code double} then numeric atomic update
3542          *     access modes are unsupported.
3543          * <li>if the field type is anything other than {@code boolean},
3544          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3545          *     {@code long} then bitwise atomic update access modes are
3546          *     unsupported.
3547          * </ul>
3548          * <p>
3549          * If the field is declared {@code volatile} then the returned VarHandle
3550          * will override access to the field (effectively ignore the
3551          * {@code volatile} declaration) in accordance to its specified
3552          * access modes.
3553          * <p>
3554          * If the field type is {@code float} or {@code double} then numeric
3555          * and atomic update access modes compare values using their bitwise
3556          * representation (see {@link Float#floatToRawIntBits} and
3557          * {@link Double#doubleToRawLongBits}, respectively).
3558          * @apiNote
3559          * Bitwise comparison of {@code float} values or {@code double} values,
3560          * as performed by the numeric and atomic update access modes, differ
3561          * from the primitive {@code ==} operator and the {@link Float#equals}
3562          * and {@link Double#equals} methods, specifically with respect to
3563          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3564          * Care should be taken when performing a compare and set or a compare
3565          * and exchange operation with such values since the operation may
3566          * unexpectedly fail.
3567          * There are many possible NaN values that are considered to be
3568          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3569          * provided by Java can distinguish between them.  Operation failure can
3570          * occur if the expected or witness value is a NaN value and it is
3571          * transformed (perhaps in a platform specific manner) into another NaN
3572          * value, and thus has a different bitwise representation (see
3573          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3574          * details).
3575          * The values {@code -0.0} and {@code +0.0} have different bitwise
3576          * representations but are considered equal when using the primitive
3577          * {@code ==} operator.  Operation failure can occur if, for example, a
3578          * numeric algorithm computes an expected value to be say {@code -0.0}
3579          * and previously computed the witness value to be say {@code +0.0}.
3580          * @param f the reflected field, with a field of type {@code T}, and
3581          * a declaring class of type {@code R}
3582          * @return a VarHandle giving access to non-static fields or a static
3583          * field
3584          * @throws IllegalAccessException if access checking fails
3585          * @throws NullPointerException if the argument is null
3586          * @since 9
3587          */
3588         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3589             MemberName getField = new MemberName(f, false);
3590             MemberName putField = new MemberName(f, true);
3591             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3592                                                       f.getDeclaringClass(), getField, putField);
3593         }
3594 
3595         /**
3596          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3597          * created by this lookup object or a similar one.
3598          * Security and access checks are performed to ensure that this lookup object
3599          * is capable of reproducing the target method handle.
3600          * This means that the cracking may fail if target is a direct method handle
3601          * but was created by an unrelated lookup object.
3602          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3603          * and was created by a lookup object for a different class.
3604          * @param target a direct method handle to crack into symbolic reference components
3605          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3606          * @throws    SecurityException if a security manager is present and it
3607          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3608          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3609          * @throws    NullPointerException if the target is {@code null}
3610          * @see MethodHandleInfo
3611          * @since 1.8
3612          */
3613         public MethodHandleInfo revealDirect(MethodHandle target) {
3614             if (!target.isCrackable()) {
3615                 throw newIllegalArgumentException("not a direct method handle");
3616             }
3617             MemberName member = target.internalMemberName();
3618             Class<?> defc = member.getDeclaringClass();
3619             byte refKind = member.getReferenceKind();
3620             assert(MethodHandleNatives.refKindIsValid(refKind));
3621             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3622                 // Devirtualized method invocation is usually formally virtual.
3623                 // To avoid creating extra MemberName objects for this common case,
3624                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3625                 refKind = REF_invokeVirtual;
3626             if (refKind == REF_invokeVirtual && defc.isInterface())
3627                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3628                 refKind = REF_invokeInterface;
3629             // Check SM permissions and member access before cracking.
3630             try {
3631                 checkAccess(refKind, defc, member);
3632                 checkSecurityManager(defc, member);
3633             } catch (IllegalAccessException ex) {
3634                 throw new IllegalArgumentException(ex);
3635             }
3636             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3637                 Class<?> callerClass = target.internalCallerClass();
3638                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3639                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3640             }
3641             // Produce the handle to the results.
3642             return new InfoFromMemberName(this, member, refKind);
3643         }
3644 
3645         /// Helper methods, all package-private.
3646 
3647         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3648             checkSymbolicClass(refc);  // do this before attempting to resolve
3649             Objects.requireNonNull(name);
3650             Objects.requireNonNull(type);
3651             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3652                                             NoSuchFieldException.class);
3653         }
3654 
3655         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3656             checkSymbolicClass(refc);  // do this before attempting to resolve
3657             Objects.requireNonNull(type);
3658             checkMethodName(refKind, name);  // implicit null-check of name
3659             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3660                                             NoSuchMethodException.class);
3661         }
3662 
3663         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3664             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3665             Objects.requireNonNull(member.getName());
3666             Objects.requireNonNull(member.getType());
3667             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3668                                             ReflectiveOperationException.class);
3669         }
3670 
3671         MemberName resolveOrNull(byte refKind, MemberName member) {
3672             // do this before attempting to resolve
3673             if (!isClassAccessible(member.getDeclaringClass())) {
3674                 return null;
3675             }
3676             Objects.requireNonNull(member.getName());
3677             Objects.requireNonNull(member.getType());
3678             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3679         }
3680 
3681         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3682             // do this before attempting to resolve
3683             if (!isClassAccessible(refc)) {
3684                 return null;
3685             }
3686             Objects.requireNonNull(type);
3687             // implicit null-check of name
3688             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3689                 return null;
3690             }
3691             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3692         }
3693 
3694         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3695             if (!isClassAccessible(refc)) {
3696                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3697             }
3698         }
3699 
3700         boolean isClassAccessible(Class<?> refc) {
3701             Objects.requireNonNull(refc);
3702             Class<?> caller = lookupClassOrNull();
3703             Class<?> type = refc;
3704             while (type.isArray()) {
3705                 type = type.getComponentType();
3706             }
3707             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3708         }
3709 
3710         /** Check name for an illegal leading "&lt;" character. */
3711         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3712             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3713                 throw new NoSuchMethodException("illegal method name: "+name);
3714         }
3715 
3716         /**
3717          * Find my trustable caller class if m is a caller sensitive method.
3718          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3719          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3720          */
3721         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3722             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3723                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3724                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3725             }
3726             return this;
3727         }
3728 
3729         /**
3730          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3731          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3732          *
3733          * @deprecated This method was originally designed to test {@code PRIVATE} access
3734          * that implies full privilege access but {@code MODULE} access has since become
3735          * independent of {@code PRIVATE} access.  It is recommended to call
3736          * {@link #hasFullPrivilegeAccess()} instead.
3737          * @since 9
3738          */
3739         @Deprecated(since="14")
3740         public boolean hasPrivateAccess() {
3741             return hasFullPrivilegeAccess();
3742         }
3743 
3744         /**
3745          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3746          * i.e. {@code PRIVATE} and {@code MODULE} access.
3747          * A {@code Lookup} object must have full privilege access in order to
3748          * access all members that are allowed to the
3749          * {@linkplain #lookupClass() lookup class}.
3750          *
3751          * @return {@code true} if this lookup has full privilege access.
3752          * @since 14
3753          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3754          */
3755         public boolean hasFullPrivilegeAccess() {
3756             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3757         }
3758 
3759         /**
3760          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3761          * for ensureInitialzed, findClass or accessClass.
3762          */
3763         void checkSecurityManager(Class<?> refc) {
3764             if (allowedModes == TRUSTED)  return;
3765 
3766             @SuppressWarnings("removal")
3767             SecurityManager smgr = System.getSecurityManager();
3768             if (smgr == null)  return;
3769 
3770             // Step 1:
3771             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3772             if (!fullPrivilegeLookup ||
3773                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3774                 ReflectUtil.checkPackageAccess(refc);
3775             }
3776 
3777             // Step 2b:
3778             if (!fullPrivilegeLookup) {
3779                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3780             }
3781         }
3782 
3783         /**
3784          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3785          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3786          * If this lookup object has full privilege access except original access,
3787          * then the caller class is the lookupClass.
3788          *
3789          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3790          * from the same module skips the security permission check.
3791          */
3792         void checkSecurityManager(Class<?> refc, MemberName m) {
3793             Objects.requireNonNull(refc);
3794             Objects.requireNonNull(m);
3795 
3796             if (allowedModes == TRUSTED)  return;
3797 
3798             @SuppressWarnings("removal")
3799             SecurityManager smgr = System.getSecurityManager();
3800             if (smgr == null)  return;
3801 
3802             // Step 1:
3803             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3804             if (!fullPrivilegeLookup ||
3805                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3806                 ReflectUtil.checkPackageAccess(refc);
3807             }
3808 
3809             // Step 2a:
3810             if (m.isPublic()) return;
3811             if (!fullPrivilegeLookup) {
3812                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3813             }
3814 
3815             // Step 3:
3816             Class<?> defc = m.getDeclaringClass();
3817             if (!fullPrivilegeLookup && defc != refc) {
3818                 ReflectUtil.checkPackageAccess(defc);
3819             }
3820         }
3821 
3822         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3823             boolean wantStatic = (refKind == REF_invokeStatic);
3824             String message;
3825             if (m.isConstructor())
3826                 message = "expected a method, not a constructor";
3827             else if (!m.isMethod())
3828                 message = "expected a method";
3829             else if (wantStatic != m.isStatic())
3830                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3831             else
3832                 { checkAccess(refKind, refc, m); return; }
3833             throw m.makeAccessException(message, this);
3834         }
3835 
3836         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3837             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3838             String message;
3839             if (wantStatic != m.isStatic())
3840                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3841             else
3842                 { checkAccess(refKind, refc, m); return; }
3843             throw m.makeAccessException(message, this);
3844         }
3845 
3846         /** Check public/protected/private bits on the symbolic reference class and its member. */
3847         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3848             assert(m.referenceKindIsConsistentWith(refKind) &&
3849                    MethodHandleNatives.refKindIsValid(refKind) &&
3850                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3851             int allowedModes = this.allowedModes;
3852             if (allowedModes == TRUSTED)  return;
3853             int mods = m.getModifiers();
3854             if (Modifier.isProtected(mods) &&
3855                     refKind == REF_invokeVirtual &&
3856                     m.getDeclaringClass() == Object.class &&
3857                     m.getName().equals("clone") &&
3858                     refc.isArray()) {
3859                 // The JVM does this hack also.
3860                 // (See ClassVerifier::verify_invoke_instructions
3861                 // and LinkResolver::check_method_accessability.)
3862                 // Because the JVM does not allow separate methods on array types,
3863                 // there is no separate method for int[].clone.
3864                 // All arrays simply inherit Object.clone.
3865                 // But for access checking logic, we make Object.clone
3866                 // (normally protected) appear to be public.
3867                 // Later on, when the DirectMethodHandle is created,
3868                 // its leading argument will be restricted to the
3869                 // requested array type.
3870                 // N.B. The return type is not adjusted, because
3871                 // that is *not* the bytecode behavior.
3872                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3873             }
3874             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3875                 // cannot "new" a protected ctor in a different package
3876                 mods ^= Modifier.PROTECTED;
3877             }
3878             if (Modifier.isFinal(mods) &&
3879                     MethodHandleNatives.refKindIsSetter(refKind))
3880                 throw m.makeAccessException("unexpected set of a final field", this);
3881             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3882             if ((requestedModes & allowedModes) != 0) {
3883                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3884                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3885                     return;
3886             } else {
3887                 // Protected members can also be checked as if they were package-private.
3888                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3889                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3890                     return;
3891             }
3892             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3893         }
3894 
3895         String accessFailedMessage(Class<?> refc, MemberName m) {
3896             Class<?> defc = m.getDeclaringClass();
3897             int mods = m.getModifiers();
3898             // check the class first:
3899             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3900                                (defc == refc ||
3901                                 Modifier.isPublic(refc.getModifiers())));
3902             if (!classOK && (allowedModes & PACKAGE) != 0) {
3903                 // ignore previous lookup class to check if default package access
3904                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3905                            (defc == refc ||
3906                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3907             }
3908             if (!classOK)
3909                 return "class is not public";
3910             if (Modifier.isPublic(mods))
3911                 return "access to public member failed";  // (how?, module not readable?)
3912             if (Modifier.isPrivate(mods))
3913                 return "member is private";
3914             if (Modifier.isProtected(mods))
3915                 return "member is protected";
3916             return "member is private to package";
3917         }
3918 
3919         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3920             int allowedModes = this.allowedModes;
3921             if (allowedModes == TRUSTED)  return;
3922             if ((lookupModes() & PRIVATE) == 0
3923                 || (specialCaller != lookupClass()
3924                        // ensure non-abstract methods in superinterfaces can be special-invoked
3925                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3926                 throw new MemberName(specialCaller).
3927                     makeAccessException("no private access for invokespecial", this);
3928         }
3929 
3930         private boolean restrictProtectedReceiver(MemberName method) {
3931             // The accessing class only has the right to use a protected member
3932             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3933             if (!method.isProtected() || method.isStatic()
3934                 || allowedModes == TRUSTED
3935                 || method.getDeclaringClass() == lookupClass()
3936                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3937                 return false;
3938             return true;
3939         }
3940         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3941             assert(!method.isStatic());
3942             // receiver type of mh is too wide; narrow to caller
3943             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3944                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3945             }
3946             MethodType rawType = mh.type();
3947             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3948             MethodType narrowType = rawType.changeParameterType(0, caller);
3949             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3950             assert(mh.viewAsTypeChecks(narrowType, true));
3951             return mh.copyWith(narrowType, mh.form);
3952         }
3953 
3954         /** Check access and get the requested method. */
3955         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3956             final boolean doRestrict    = true;
3957             final boolean checkSecurity = true;
3958             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3959         }
3960         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3961         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3962             final boolean doRestrict    = false;
3963             final boolean checkSecurity = true;
3964             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3965         }
3966         /** Check access and get the requested method, eliding security manager checks. */
3967         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3968             final boolean doRestrict    = true;
3969             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3970             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3971         }
3972         /** Common code for all methods; do not call directly except from immediately above. */
3973         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3974                                                    boolean checkSecurity,
3975                                                    boolean doRestrict,
3976                                                    Lookup boundCaller) throws IllegalAccessException {
3977             checkMethod(refKind, refc, method);
3978             // Optionally check with the security manager; this isn't needed for unreflect* calls.
3979             if (checkSecurity)
3980                 checkSecurityManager(refc, method);
3981             assert(!method.isMethodHandleInvoke());
3982 
3983             if (refKind == REF_invokeSpecial &&
3984                 refc != lookupClass() &&
3985                 !refc.isInterface() &&
3986                 refc != lookupClass().getSuperclass() &&
3987                 refc.isAssignableFrom(lookupClass())) {
3988                 assert(!method.getName().equals("<init>"));  // not this code path
3989 
3990                 // Per JVMS 6.5, desc. of invokespecial instruction:
3991                 // If the method is in a superclass of the LC,
3992                 // and if our original search was above LC.super,
3993                 // repeat the search (symbolic lookup) from LC.super
3994                 // and continue with the direct superclass of that class,
3995                 // and so forth, until a match is found or no further superclasses exist.
3996                 // FIXME: MemberName.resolve should handle this instead.
3997                 Class<?> refcAsSuper = lookupClass();
3998                 MemberName m2;
3999                 do {
4000                     refcAsSuper = refcAsSuper.getSuperclass();
4001                     m2 = new MemberName(refcAsSuper,
4002                                         method.getName(),
4003                                         method.getMethodType(),
4004                                         REF_invokeSpecial);
4005                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4006                 } while (m2 == null &&         // no method is found yet
4007                          refc != refcAsSuper); // search up to refc
4008                 if (m2 == null)  throw new InternalError(method.toString());
4009                 method = m2;
4010                 refc = refcAsSuper;
4011                 // redo basic checks
4012                 checkMethod(refKind, refc, method);
4013             }
4014             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4015             MethodHandle mh = dmh;
4016             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4017             if ((doRestrict && refKind == REF_invokeSpecial) ||
4018                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4019                 mh = restrictReceiver(method, dmh, lookupClass());
4020             }
4021             mh = maybeBindCaller(method, mh, boundCaller);
4022             mh = mh.setVarargs(method);
4023             return mh;
4024         }
4025         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4026                                              throws IllegalAccessException {
4027             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4028                 return mh;
4029 
4030             // boundCaller must have full privilege access.
4031             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4032             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4033                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4034 
4035             assert boundCaller.hasFullPrivilegeAccess();
4036 
4037             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4038             // Note: caller will apply varargs after this step happens.
4039             return cbmh;
4040         }
4041 
4042         /** Check access and get the requested field. */
4043         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4044             final boolean checkSecurity = true;
4045             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4046         }
4047         /** Check access and get the requested field, eliding security manager checks. */
4048         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4049             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4050             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4051         }
4052         /** Common code for all fields; do not call directly except from immediately above. */
4053         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4054                                                   boolean checkSecurity) throws IllegalAccessException {
4055             checkField(refKind, refc, field);
4056             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4057             if (checkSecurity)
4058                 checkSecurityManager(refc, field);
4059             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4060             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4061                                     restrictProtectedReceiver(field));
4062             if (doRestrict)
4063                 return restrictReceiver(field, dmh, lookupClass());
4064             return dmh;
4065         }
4066         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4067                                             Class<?> refc, MemberName getField, MemberName putField)
4068                 throws IllegalAccessException {
4069             final boolean checkSecurity = true;
4070             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4071         }
4072         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4073                                                              Class<?> refc, MemberName getField, MemberName putField)
4074                 throws IllegalAccessException {
4075             final boolean checkSecurity = false;
4076             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4077         }
4078         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4079                                                   Class<?> refc, MemberName getField, MemberName putField,
4080                                                   boolean checkSecurity) throws IllegalAccessException {
4081             assert getField.isStatic() == putField.isStatic();
4082             assert getField.isGetter() && putField.isSetter();
4083             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4084             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4085 
4086             checkField(getRefKind, refc, getField);
4087             if (checkSecurity)
4088                 checkSecurityManager(refc, getField);
4089 
4090             if (!putField.isFinal()) {
4091                 // A VarHandle does not support updates to final fields, any
4092                 // such VarHandle to a final field will be read-only and
4093                 // therefore the following write-based accessibility checks are
4094                 // only required for non-final fields
4095                 checkField(putRefKind, refc, putField);
4096                 if (checkSecurity)
4097                     checkSecurityManager(refc, putField);
4098             }
4099 
4100             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4101                                   restrictProtectedReceiver(getField));
4102             if (doRestrict) {
4103                 assert !getField.isStatic();
4104                 // receiver type of VarHandle is too wide; narrow to caller
4105                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4106                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4107                 }
4108                 refc = lookupClass();
4109             }
4110             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4111                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4112         }
4113         /** Check access and get the requested constructor. */
4114         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4115             final boolean checkSecurity = true;
4116             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4117         }
4118         /** Check access and get the requested constructor, eliding security manager checks. */
4119         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4120             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4121             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4122         }
4123         /** Common code for all constructors; do not call directly except from immediately above. */
4124         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4125                                                   boolean checkSecurity) throws IllegalAccessException {
4126             assert(ctor.isConstructor());
4127             checkAccess(REF_newInvokeSpecial, refc, ctor);
4128             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4129             if (checkSecurity)
4130                 checkSecurityManager(refc, ctor);
4131             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4132             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4133         }
4134 
4135         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4136          */
4137         /*non-public*/
4138         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4139                 throws ReflectiveOperationException {
4140             if (!(type instanceof Class || type instanceof MethodType))
4141                 throw new InternalError("unresolved MemberName");
4142             MemberName member = new MemberName(refKind, defc, name, type);
4143             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4144             if (mh != null) {
4145                 checkSymbolicClass(defc);
4146                 return mh;
4147             }
4148             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4149                 // Treat MethodHandle.invoke and invokeExact specially.
4150                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4151                 if (mh != null) {
4152                     return mh;
4153                 }
4154             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4155                 // Treat signature-polymorphic methods on VarHandle specially.
4156                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4157                 if (mh != null) {
4158                     return mh;
4159                 }
4160             }
4161             MemberName resolved = resolveOrFail(refKind, member);
4162             mh = getDirectMethodForConstant(refKind, defc, resolved);
4163             if (mh instanceof DirectMethodHandle
4164                     && canBeCached(refKind, defc, resolved)) {
4165                 MemberName key = mh.internalMemberName();
4166                 if (key != null) {
4167                     key = key.asNormalOriginal();
4168                 }
4169                 if (member.equals(key)) {  // better safe than sorry
4170                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4171                 }
4172             }
4173             return mh;
4174         }
4175         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4176             if (refKind == REF_invokeSpecial) {
4177                 return false;
4178             }
4179             if (!Modifier.isPublic(defc.getModifiers()) ||
4180                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4181                     !member.isPublic() ||
4182                     member.isCallerSensitive()) {
4183                 return false;
4184             }
4185             ClassLoader loader = defc.getClassLoader();
4186             if (loader != null) {
4187                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4188                 boolean found = false;
4189                 while (sysl != null) {
4190                     if (loader == sysl) { found = true; break; }
4191                     sysl = sysl.getParent();
4192                 }
4193                 if (!found) {
4194                     return false;
4195                 }
4196             }
4197             try {
4198                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4199                     new MemberName(refKind, defc, member.getName(), member.getType()));
4200                 if (resolved2 == null) {
4201                     return false;
4202                 }
4203                 checkSecurityManager(defc, resolved2);
4204             } catch (SecurityException ex) {
4205                 return false;
4206             }
4207             return true;
4208         }
4209         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4210                 throws ReflectiveOperationException {
4211             if (MethodHandleNatives.refKindIsField(refKind)) {
4212                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4213             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4214                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4215             } else if (refKind == REF_newInvokeSpecial) {
4216                 return getDirectConstructorNoSecurityManager(defc, member);
4217             }
4218             // oops
4219             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4220         }
4221 
4222         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4223     }
4224 
4225     /**
4226      * Produces a method handle constructing arrays of a desired type,
4227      * as if by the {@code anewarray} bytecode.
4228      * The return type of the method handle will be the array type.
4229      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4230      *
4231      * <p> If the returned method handle is invoked with a negative
4232      * array size, a {@code NegativeArraySizeException} will be thrown.
4233      *
4234      * @param arrayClass an array type
4235      * @return a method handle which can create arrays of the given type
4236      * @throws NullPointerException if the argument is {@code null}
4237      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4238      * @see java.lang.reflect.Array#newInstance(Class, int)
4239      * @jvms 6.5 {@code anewarray} Instruction
4240      * @since 9
4241      */
4242     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4243         if (!arrayClass.isArray()) {
4244             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4245         }
4246         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4247                 bindTo(arrayClass.getComponentType());
4248         return ani.asType(ani.type().changeReturnType(arrayClass));
4249     }
4250 
4251     /**
4252      * Produces a method handle returning the length of an array,
4253      * as if by the {@code arraylength} bytecode.
4254      * The type of the method handle will have {@code int} as return type,
4255      * and its sole argument will be the array type.
4256      *
4257      * <p> If the returned method handle is invoked with a {@code null}
4258      * array reference, a {@code NullPointerException} will be thrown.
4259      *
4260      * @param arrayClass an array type
4261      * @return a method handle which can retrieve the length of an array of the given array type
4262      * @throws NullPointerException if the argument is {@code null}
4263      * @throws IllegalArgumentException if arrayClass is not an array type
4264      * @jvms 6.5 {@code arraylength} Instruction
4265      * @since 9
4266      */
4267     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4268         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4269     }
4270 
4271     /**
4272      * Produces a method handle giving read access to elements of an array,
4273      * as if by the {@code aaload} bytecode.
4274      * The type of the method handle will have a return type of the array's
4275      * element type.  Its first argument will be the array type,
4276      * and the second will be {@code int}.
4277      *
4278      * <p> When the returned method handle is invoked,
4279      * the array reference and array index are checked.
4280      * A {@code NullPointerException} will be thrown if the array reference
4281      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4282      * thrown if the index is negative or if it is greater than or equal to
4283      * the length of the array.
4284      *
4285      * @param arrayClass an array type
4286      * @return a method handle which can load values from the given array type
4287      * @throws NullPointerException if the argument is null
4288      * @throws  IllegalArgumentException if arrayClass is not an array type
4289      * @jvms 6.5 {@code aaload} Instruction
4290      */
4291     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4292         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4293     }
4294 
4295     /**
4296      * Produces a method handle giving write access to elements of an array,
4297      * as if by the {@code astore} bytecode.
4298      * The type of the method handle will have a void return type.
4299      * Its last argument will be the array's element type.
4300      * The first and second arguments will be the array type and int.
4301      *
4302      * <p> When the returned method handle is invoked,
4303      * the array reference and array index are checked.
4304      * A {@code NullPointerException} will be thrown if the array reference
4305      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4306      * thrown if the index is negative or if it is greater than or equal to
4307      * the length of the array.
4308      *
4309      * @param arrayClass the class of an array
4310      * @return a method handle which can store values into the array type
4311      * @throws NullPointerException if the argument is null
4312      * @throws IllegalArgumentException if arrayClass is not an array type
4313      * @jvms 6.5 {@code aastore} Instruction
4314      */
4315     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4316         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4317     }
4318 
4319     /**
4320      * Produces a VarHandle giving access to elements of an array of type
4321      * {@code arrayClass}.  The VarHandle's variable type is the component type
4322      * of {@code arrayClass} and the list of coordinate types is
4323      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4324      * corresponds to an argument that is an index into an array.
4325      * <p>
4326      * Certain access modes of the returned VarHandle are unsupported under
4327      * the following conditions:
4328      * <ul>
4329      * <li>if the component type is anything other than {@code byte},
4330      *     {@code short}, {@code char}, {@code int}, {@code long},
4331      *     {@code float}, or {@code double} then numeric atomic update access
4332      *     modes are unsupported.
4333      * <li>if the component type is anything other than {@code boolean},
4334      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4335      *     {@code long} then bitwise atomic update access modes are
4336      *     unsupported.
4337      * </ul>
4338      * <p>
4339      * If the component type is {@code float} or {@code double} then numeric
4340      * and atomic update access modes compare values using their bitwise
4341      * representation (see {@link Float#floatToRawIntBits} and
4342      * {@link Double#doubleToRawLongBits}, respectively).
4343      *
4344      * <p> When the returned {@code VarHandle} is invoked,
4345      * the array reference and array index are checked.
4346      * A {@code NullPointerException} will be thrown if the array reference
4347      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4348      * thrown if the index is negative or if it is greater than or equal to
4349      * the length of the array.
4350      *
4351      * @apiNote
4352      * Bitwise comparison of {@code float} values or {@code double} values,
4353      * as performed by the numeric and atomic update access modes, differ
4354      * from the primitive {@code ==} operator and the {@link Float#equals}
4355      * and {@link Double#equals} methods, specifically with respect to
4356      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4357      * Care should be taken when performing a compare and set or a compare
4358      * and exchange operation with such values since the operation may
4359      * unexpectedly fail.
4360      * There are many possible NaN values that are considered to be
4361      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4362      * provided by Java can distinguish between them.  Operation failure can
4363      * occur if the expected or witness value is a NaN value and it is
4364      * transformed (perhaps in a platform specific manner) into another NaN
4365      * value, and thus has a different bitwise representation (see
4366      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4367      * details).
4368      * The values {@code -0.0} and {@code +0.0} have different bitwise
4369      * representations but are considered equal when using the primitive
4370      * {@code ==} operator.  Operation failure can occur if, for example, a
4371      * numeric algorithm computes an expected value to be say {@code -0.0}
4372      * and previously computed the witness value to be say {@code +0.0}.
4373      * @param arrayClass the class of an array, of type {@code T[]}
4374      * @return a VarHandle giving access to elements of an array
4375      * @throws NullPointerException if the arrayClass is null
4376      * @throws IllegalArgumentException if arrayClass is not an array type
4377      * @since 9
4378      */
4379     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4380         return VarHandles.makeArrayElementHandle(arrayClass);
4381     }
4382 
4383     /**
4384      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4385      * viewed as if it were a different primitive array type, such as
4386      * {@code int[]} or {@code long[]}.
4387      * The VarHandle's variable type is the component type of
4388      * {@code viewArrayClass} and the list of coordinate types is
4389      * {@code (byte[], int)}, where the {@code int} coordinate type
4390      * corresponds to an argument that is an index into a {@code byte[]} array.
4391      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4392      * array, composing bytes to or from a value of the component type of
4393      * {@code viewArrayClass} according to the given endianness.
4394      * <p>
4395      * The supported component types (variables types) are {@code short},
4396      * {@code char}, {@code int}, {@code long}, {@code float} and
4397      * {@code double}.
4398      * <p>
4399      * Access of bytes at a given index will result in an
4400      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4401      * or greater than the {@code byte[]} array length minus the size (in bytes)
4402      * of {@code T}.
4403      * <p>
4404      * Access of bytes at an index may be aligned or misaligned for {@code T},
4405      * with respect to the underlying memory address, {@code A} say, associated
4406      * with the array and index.
4407      * If access is misaligned then access for anything other than the
4408      * {@code get} and {@code set} access modes will result in an
4409      * {@code IllegalStateException}.  In such cases atomic access is only
4410      * guaranteed with respect to the largest power of two that divides the GCD
4411      * of {@code A} and the size (in bytes) of {@code T}.
4412      * If access is aligned then following access modes are supported and are
4413      * guaranteed to support atomic access:
4414      * <ul>
4415      * <li>read write access modes for all {@code T}, with the exception of
4416      *     access modes {@code get} and {@code set} for {@code long} and
4417      *     {@code double} on 32-bit platforms.
4418      * <li>atomic update access modes for {@code int}, {@code long},
4419      *     {@code float} or {@code double}.
4420      *     (Future major platform releases of the JDK may support additional
4421      *     types for certain currently unsupported access modes.)
4422      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4423      *     (Future major platform releases of the JDK may support additional
4424      *     numeric types for certain currently unsupported access modes.)
4425      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4426      *     (Future major platform releases of the JDK may support additional
4427      *     numeric types for certain currently unsupported access modes.)
4428      * </ul>
4429      * <p>
4430      * Misaligned access, and therefore atomicity guarantees, may be determined
4431      * for {@code byte[]} arrays without operating on a specific array.  Given
4432      * an {@code index}, {@code T} and its corresponding boxed type,
4433      * {@code T_BOX}, misalignment may be determined as follows:
4434      * <pre>{@code
4435      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4436      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4437      *     alignmentOffset(0, sizeOfT);
4438      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4439      * boolean isMisaligned = misalignedAtIndex != 0;
4440      * }</pre>
4441      * <p>
4442      * If the variable type is {@code float} or {@code double} then atomic
4443      * update access modes compare values using their bitwise representation
4444      * (see {@link Float#floatToRawIntBits} and
4445      * {@link Double#doubleToRawLongBits}, respectively).
4446      * @param viewArrayClass the view array class, with a component type of
4447      * type {@code T}
4448      * @param byteOrder the endianness of the view array elements, as
4449      * stored in the underlying {@code byte} array
4450      * @return a VarHandle giving access to elements of a {@code byte[]} array
4451      * viewed as if elements corresponding to the components type of the view
4452      * array class
4453      * @throws NullPointerException if viewArrayClass or byteOrder is null
4454      * @throws IllegalArgumentException if viewArrayClass is not an array type
4455      * @throws UnsupportedOperationException if the component type of
4456      * viewArrayClass is not supported as a variable type
4457      * @since 9
4458      */
4459     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4460                                      ByteOrder byteOrder) throws IllegalArgumentException {
4461         Objects.requireNonNull(byteOrder);
4462         return VarHandles.byteArrayViewHandle(viewArrayClass,
4463                                               byteOrder == ByteOrder.BIG_ENDIAN);
4464     }
4465 
4466     /**
4467      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4468      * viewed as if it were an array of elements of a different primitive
4469      * component type to that of {@code byte}, such as {@code int[]} or
4470      * {@code long[]}.
4471      * The VarHandle's variable type is the component type of
4472      * {@code viewArrayClass} and the list of coordinate types is
4473      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4474      * corresponds to an argument that is an index into a {@code byte[]} array.
4475      * The returned VarHandle accesses bytes at an index in a
4476      * {@code ByteBuffer}, composing bytes to or from a value of the component
4477      * type of {@code viewArrayClass} according to the given endianness.
4478      * <p>
4479      * The supported component types (variables types) are {@code short},
4480      * {@code char}, {@code int}, {@code long}, {@code float} and
4481      * {@code double}.
4482      * <p>
4483      * Access will result in a {@code ReadOnlyBufferException} for anything
4484      * other than the read access modes if the {@code ByteBuffer} is read-only.
4485      * <p>
4486      * Access of bytes at a given index will result in an
4487      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4488      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4489      * {@code T}.
4490      * <p>
4491      * Access of bytes at an index may be aligned or misaligned for {@code T},
4492      * with respect to the underlying memory address, {@code A} say, associated
4493      * with the {@code ByteBuffer} and index.
4494      * If access is misaligned then access for anything other than the
4495      * {@code get} and {@code set} access modes will result in an
4496      * {@code IllegalStateException}.  In such cases atomic access is only
4497      * guaranteed with respect to the largest power of two that divides the GCD
4498      * of {@code A} and the size (in bytes) of {@code T}.
4499      * If access is aligned then following access modes are supported and are
4500      * guaranteed to support atomic access:
4501      * <ul>
4502      * <li>read write access modes for all {@code T}, with the exception of
4503      *     access modes {@code get} and {@code set} for {@code long} and
4504      *     {@code double} on 32-bit platforms.
4505      * <li>atomic update access modes for {@code int}, {@code long},
4506      *     {@code float} or {@code double}.
4507      *     (Future major platform releases of the JDK may support additional
4508      *     types for certain currently unsupported access modes.)
4509      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4510      *     (Future major platform releases of the JDK may support additional
4511      *     numeric types for certain currently unsupported access modes.)
4512      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4513      *     (Future major platform releases of the JDK may support additional
4514      *     numeric types for certain currently unsupported access modes.)
4515      * </ul>
4516      * <p>
4517      * Misaligned access, and therefore atomicity guarantees, may be determined
4518      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4519      * {@code index}, {@code T} and its corresponding boxed type,
4520      * {@code T_BOX}, as follows:
4521      * <pre>{@code
4522      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4523      * ByteBuffer bb = ...
4524      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4525      * boolean isMisaligned = misalignedAtIndex != 0;
4526      * }</pre>
4527      * <p>
4528      * If the variable type is {@code float} or {@code double} then atomic
4529      * update access modes compare values using their bitwise representation
4530      * (see {@link Float#floatToRawIntBits} and
4531      * {@link Double#doubleToRawLongBits}, respectively).
4532      * @param viewArrayClass the view array class, with a component type of
4533      * type {@code T}
4534      * @param byteOrder the endianness of the view array elements, as
4535      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4536      * endianness of a {@code ByteBuffer})
4537      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4538      * viewed as if elements corresponding to the components type of the view
4539      * array class
4540      * @throws NullPointerException if viewArrayClass or byteOrder is null
4541      * @throws IllegalArgumentException if viewArrayClass is not an array type
4542      * @throws UnsupportedOperationException if the component type of
4543      * viewArrayClass is not supported as a variable type
4544      * @since 9
4545      */
4546     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4547                                       ByteOrder byteOrder) throws IllegalArgumentException {
4548         Objects.requireNonNull(byteOrder);
4549         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4550                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4551     }
4552 
4553 
4554     /// method handle invocation (reflective style)
4555 
4556     /**
4557      * Produces a method handle which will invoke any method handle of the
4558      * given {@code type}, with a given number of trailing arguments replaced by
4559      * a single trailing {@code Object[]} array.
4560      * The resulting invoker will be a method handle with the following
4561      * arguments:
4562      * <ul>
4563      * <li>a single {@code MethodHandle} target
4564      * <li>zero or more leading values (counted by {@code leadingArgCount})
4565      * <li>an {@code Object[]} array containing trailing arguments
4566      * </ul>
4567      * <p>
4568      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4569      * the indicated {@code type}.
4570      * That is, if the target is exactly of the given {@code type}, it will behave
4571      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4572      * is used to convert the target to the required {@code type}.
4573      * <p>
4574      * The type of the returned invoker will not be the given {@code type}, but rather
4575      * will have all parameters except the first {@code leadingArgCount}
4576      * replaced by a single array of type {@code Object[]}, which will be
4577      * the final parameter.
4578      * <p>
4579      * Before invoking its target, the invoker will spread the final array, apply
4580      * reference casts as necessary, and unbox and widen primitive arguments.
4581      * If, when the invoker is called, the supplied array argument does
4582      * not have the correct number of elements, the invoker will throw
4583      * an {@link IllegalArgumentException} instead of invoking the target.
4584      * <p>
4585      * This method is equivalent to the following code (though it may be more efficient):
4586      * <blockquote><pre>{@code
4587 MethodHandle invoker = MethodHandles.invoker(type);
4588 int spreadArgCount = type.parameterCount() - leadingArgCount;
4589 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4590 return invoker;
4591      * }</pre></blockquote>
4592      * This method throws no reflective or security exceptions.
4593      * @param type the desired target type
4594      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4595      * @return a method handle suitable for invoking any method handle of the given type
4596      * @throws NullPointerException if {@code type} is null
4597      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4598      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4599      *                  or if the resulting method handle's type would have
4600      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4601      */
4602     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4603         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4604             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4605         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4606         return type.invokers().spreadInvoker(leadingArgCount);
4607     }
4608 
4609     /**
4610      * Produces a special <em>invoker method handle</em> which can be used to
4611      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4612      * The resulting invoker will have a type which is
4613      * exactly equal to the desired type, except that it will accept
4614      * an additional leading argument of type {@code MethodHandle}.
4615      * <p>
4616      * This method is equivalent to the following code (though it may be more efficient):
4617      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4618      *
4619      * <p style="font-size:smaller;">
4620      * <em>Discussion:</em>
4621      * Invoker method handles can be useful when working with variable method handles
4622      * of unknown types.
4623      * For example, to emulate an {@code invokeExact} call to a variable method
4624      * handle {@code M}, extract its type {@code T},
4625      * look up the invoker method {@code X} for {@code T},
4626      * and call the invoker method, as {@code X.invoke(T, A...)}.
4627      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4628      * is unknown.)
4629      * If spreading, collecting, or other argument transformations are required,
4630      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4631      * method handle values, as long as they are compatible with the type of {@code X}.
4632      * <p style="font-size:smaller;">
4633      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4634      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4635      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4636      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4637      * <p>
4638      * This method throws no reflective or security exceptions.
4639      * @param type the desired target type
4640      * @return a method handle suitable for invoking any method handle of the given type
4641      * @throws IllegalArgumentException if the resulting method handle's type would have
4642      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4643      */
4644     public static MethodHandle exactInvoker(MethodType type) {
4645         return type.invokers().exactInvoker();
4646     }
4647 
4648     /**
4649      * Produces a special <em>invoker method handle</em> which can be used to
4650      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4651      * The resulting invoker will have a type which is
4652      * exactly equal to the desired type, except that it will accept
4653      * an additional leading argument of type {@code MethodHandle}.
4654      * <p>
4655      * Before invoking its target, if the target differs from the expected type,
4656      * the invoker will apply reference casts as
4657      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4658      * Similarly, the return value will be converted as necessary.
4659      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4660      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4661      * <p>
4662      * This method is equivalent to the following code (though it may be more efficient):
4663      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4664      * <p style="font-size:smaller;">
4665      * <em>Discussion:</em>
4666      * A {@linkplain MethodType#genericMethodType general method type} is one which
4667      * mentions only {@code Object} arguments and return values.
4668      * An invoker for such a type is capable of calling any method handle
4669      * of the same arity as the general type.
4670      * <p style="font-size:smaller;">
4671      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4672      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4673      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4674      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4675      * <p>
4676      * This method throws no reflective or security exceptions.
4677      * @param type the desired target type
4678      * @return a method handle suitable for invoking any method handle convertible to the given type
4679      * @throws IllegalArgumentException if the resulting method handle's type would have
4680      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4681      */
4682     public static MethodHandle invoker(MethodType type) {
4683         return type.invokers().genericInvoker();
4684     }
4685 
4686     /**
4687      * Produces a special <em>invoker method handle</em> which can be used to
4688      * invoke a signature-polymorphic access mode method on any VarHandle whose
4689      * associated access mode type is compatible with the given type.
4690      * The resulting invoker will have a type which is exactly equal to the
4691      * desired given type, except that it will accept an additional leading
4692      * argument of type {@code VarHandle}.
4693      *
4694      * @param accessMode the VarHandle access mode
4695      * @param type the desired target type
4696      * @return a method handle suitable for invoking an access mode method of
4697      *         any VarHandle whose access mode type is of the given type.
4698      * @since 9
4699      */
4700     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4701         return type.invokers().varHandleMethodExactInvoker(accessMode);
4702     }
4703 
4704     /**
4705      * Produces a special <em>invoker method handle</em> which can be used to
4706      * invoke a signature-polymorphic access mode method on any VarHandle whose
4707      * associated access mode type is compatible with the given type.
4708      * The resulting invoker will have a type which is exactly equal to the
4709      * desired given type, except that it will accept an additional leading
4710      * argument of type {@code VarHandle}.
4711      * <p>
4712      * Before invoking its target, if the access mode type differs from the
4713      * desired given type, the invoker will apply reference casts as necessary
4714      * and box, unbox, or widen primitive values, as if by
4715      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4716      * converted as necessary.
4717      * <p>
4718      * This method is equivalent to the following code (though it may be more
4719      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4720      *
4721      * @param accessMode the VarHandle access mode
4722      * @param type the desired target type
4723      * @return a method handle suitable for invoking an access mode method of
4724      *         any VarHandle whose access mode type is convertible to the given
4725      *         type.
4726      * @since 9
4727      */
4728     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4729         return type.invokers().varHandleMethodInvoker(accessMode);
4730     }
4731 
4732     /*non-public*/
4733     static MethodHandle basicInvoker(MethodType type) {
4734         return type.invokers().basicInvoker();
4735     }
4736 
4737      /// method handle modification (creation from other method handles)
4738 
4739     /**
4740      * Produces a method handle which adapts the type of the
4741      * given method handle to a new type by pairwise argument and return type conversion.
4742      * The original type and new type must have the same number of arguments.
4743      * The resulting method handle is guaranteed to report a type
4744      * which is equal to the desired new type.
4745      * <p>
4746      * If the original type and new type are equal, returns target.
4747      * <p>
4748      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4749      * and some additional conversions are also applied if those conversions fail.
4750      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4751      * if possible, before or instead of any conversions done by {@code asType}:
4752      * <ul>
4753      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4754      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4755      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4756      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4757      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4758      *     (This treatment follows the usage of the bytecode verifier.)
4759      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4760      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4761      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4762      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4763      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4764      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4765      *     widening and/or narrowing.)
4766      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4767      *     conversion will be applied at runtime, possibly followed
4768      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4769      *     possibly followed by a conversion from byte to boolean by testing
4770      *     the low-order bit.
4771      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4772      *     and if the reference is null at runtime, a zero value is introduced.
4773      * </ul>
4774      * @param target the method handle to invoke after arguments are retyped
4775      * @param newType the expected type of the new method handle
4776      * @return a method handle which delegates to the target after performing
4777      *           any necessary argument conversions, and arranges for any
4778      *           necessary return value conversions
4779      * @throws NullPointerException if either argument is null
4780      * @throws WrongMethodTypeException if the conversion cannot be made
4781      * @see MethodHandle#asType
4782      */
4783     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4784         explicitCastArgumentsChecks(target, newType);
4785         // use the asTypeCache when possible:
4786         MethodType oldType = target.type();
4787         if (oldType == newType)  return target;
4788         if (oldType.explicitCastEquivalentToAsType(newType)) {
4789             return target.asFixedArity().asType(newType);
4790         }
4791         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4792     }
4793 
4794     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4795         if (target.type().parameterCount() != newType.parameterCount()) {
4796             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4797         }
4798     }
4799 
4800     /**
4801      * Produces a method handle which adapts the calling sequence of the
4802      * given method handle to a new type, by reordering the arguments.
4803      * The resulting method handle is guaranteed to report a type
4804      * which is equal to the desired new type.
4805      * <p>
4806      * The given array controls the reordering.
4807      * Call {@code #I} the number of incoming parameters (the value
4808      * {@code newType.parameterCount()}, and call {@code #O} the number
4809      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4810      * Then the length of the reordering array must be {@code #O},
4811      * and each element must be a non-negative number less than {@code #I}.
4812      * For every {@code N} less than {@code #O}, the {@code N}-th
4813      * outgoing argument will be taken from the {@code I}-th incoming
4814      * argument, where {@code I} is {@code reorder[N]}.
4815      * <p>
4816      * No argument or return value conversions are applied.
4817      * The type of each incoming argument, as determined by {@code newType},
4818      * must be identical to the type of the corresponding outgoing parameter
4819      * or parameters in the target method handle.
4820      * The return type of {@code newType} must be identical to the return
4821      * type of the original target.
4822      * <p>
4823      * The reordering array need not specify an actual permutation.
4824      * An incoming argument will be duplicated if its index appears
4825      * more than once in the array, and an incoming argument will be dropped
4826      * if its index does not appear in the array.
4827      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4828      * incoming arguments which are not mentioned in the reordering array
4829      * may be of any type, as determined only by {@code newType}.
4830      * <blockquote><pre>{@code
4831 import static java.lang.invoke.MethodHandles.*;
4832 import static java.lang.invoke.MethodType.*;
4833 ...
4834 MethodType intfn1 = methodType(int.class, int.class);
4835 MethodType intfn2 = methodType(int.class, int.class, int.class);
4836 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4837 assert(sub.type().equals(intfn2));
4838 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4839 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4840 assert((int)rsub.invokeExact(1, 100) == 99);
4841 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4842 assert(add.type().equals(intfn2));
4843 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4844 assert(twice.type().equals(intfn1));
4845 assert((int)twice.invokeExact(21) == 42);
4846      * }</pre></blockquote>
4847      * <p>
4848      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4849      * variable-arity method handle}, even if the original target method handle was.
4850      * @param target the method handle to invoke after arguments are reordered
4851      * @param newType the expected type of the new method handle
4852      * @param reorder an index array which controls the reordering
4853      * @return a method handle which delegates to the target after it
4854      *           drops unused arguments and moves and/or duplicates the other arguments
4855      * @throws NullPointerException if any argument is null
4856      * @throws IllegalArgumentException if the index array length is not equal to
4857      *                  the arity of the target, or if any index array element
4858      *                  not a valid index for a parameter of {@code newType},
4859      *                  or if two corresponding parameter types in
4860      *                  {@code target.type()} and {@code newType} are not identical,
4861      */
4862     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4863         reorder = reorder.clone();  // get a private copy
4864         MethodType oldType = target.type();
4865         permuteArgumentChecks(reorder, newType, oldType);
4866         // first detect dropped arguments and handle them separately
4867         int[] originalReorder = reorder;
4868         BoundMethodHandle result = target.rebind();
4869         LambdaForm form = result.form;
4870         int newArity = newType.parameterCount();
4871         // Normalize the reordering into a real permutation,
4872         // by removing duplicates and adding dropped elements.
4873         // This somewhat improves lambda form caching, as well
4874         // as simplifying the transform by breaking it up into steps.
4875         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4876             if (ddIdx > 0) {
4877                 // We found a duplicated entry at reorder[ddIdx].
4878                 // Example:  (x,y,z)->asList(x,y,z)
4879                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4880                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4881                 // The starred element corresponds to the argument
4882                 // deleted by the dupArgumentForm transform.
4883                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4884                 boolean killFirst = false;
4885                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4886                     // Set killFirst if the dup is larger than an intervening position.
4887                     // This will remove at least one inversion from the permutation.
4888                     if (dupVal > val) killFirst = true;
4889                 }
4890                 if (!killFirst) {
4891                     srcPos = dstPos;
4892                     dstPos = ddIdx;
4893                 }
4894                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4895                 assert (reorder[srcPos] == reorder[dstPos]);
4896                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4897                 // contract the reordering by removing the element at dstPos
4898                 int tailPos = dstPos + 1;
4899                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4900                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4901             } else {
4902                 int dropVal = ~ddIdx, insPos = 0;
4903                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4904                     // Find first element of reorder larger than dropVal.
4905                     // This is where we will insert the dropVal.
4906                     insPos += 1;
4907                 }
4908                 Class<?> ptype = newType.parameterType(dropVal);
4909                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4910                 oldType = oldType.insertParameterTypes(insPos, ptype);
4911                 // expand the reordering by inserting an element at insPos
4912                 int tailPos = insPos + 1;
4913                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4914                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4915                 reorder[insPos] = dropVal;
4916             }
4917             assert (permuteArgumentChecks(reorder, newType, oldType));
4918         }
4919         assert (reorder.length == newArity);  // a perfect permutation
4920         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4921         form = form.editor().permuteArgumentsForm(1, reorder);
4922         if (newType == result.type() && form == result.internalForm())
4923             return result;
4924         return result.copyWith(newType, form);
4925     }
4926 
4927     /**
4928      * Return an indication of any duplicate or omission in reorder.
4929      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4930      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4931      * Otherwise, return zero.
4932      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4933      */
4934     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4935         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4936         if (newArity < BIT_LIMIT) {
4937             long mask = 0;
4938             for (int i = 0; i < reorder.length; i++) {
4939                 int arg = reorder[i];
4940                 if (arg >= newArity) {
4941                     return reorder.length;
4942                 }
4943                 long bit = 1L << arg;
4944                 if ((mask & bit) != 0) {
4945                     return i;  // >0 indicates a dup
4946                 }
4947                 mask |= bit;
4948             }
4949             if (mask == (1L << newArity) - 1) {
4950                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4951                 return 0;
4952             }
4953             // find first zero
4954             long zeroBit = Long.lowestOneBit(~mask);
4955             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4956             assert(zeroPos <= newArity);
4957             if (zeroPos == newArity) {
4958                 return 0;
4959             }
4960             return ~zeroPos;
4961         } else {
4962             // same algorithm, different bit set
4963             BitSet mask = new BitSet(newArity);
4964             for (int i = 0; i < reorder.length; i++) {
4965                 int arg = reorder[i];
4966                 if (arg >= newArity) {
4967                     return reorder.length;
4968                 }
4969                 if (mask.get(arg)) {
4970                     return i;  // >0 indicates a dup
4971                 }
4972                 mask.set(arg);
4973             }
4974             int zeroPos = mask.nextClearBit(0);
4975             assert(zeroPos <= newArity);
4976             if (zeroPos == newArity) {
4977                 return 0;
4978             }
4979             return ~zeroPos;
4980         }
4981     }
4982 
4983     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4984         if (newType.returnType() != oldType.returnType())
4985             throw newIllegalArgumentException("return types do not match",
4986                     oldType, newType);
4987         if (reorder.length != oldType.parameterCount())
4988             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4989                     oldType, Arrays.toString(reorder));
4990 
4991         int limit = newType.parameterCount();
4992         for (int j = 0; j < reorder.length; j++) {
4993             int i = reorder[j];
4994             if (i < 0 || i >= limit) {
4995                 throw newIllegalArgumentException("index is out of bounds for new type",
4996                         i, newType);
4997             }
4998             Class<?> src = newType.parameterType(i);
4999             Class<?> dst = oldType.parameterType(j);
5000             if (src != dst)
5001                 throw newIllegalArgumentException("parameter types do not match after reorder",
5002                         oldType, newType);
5003         }
5004         return true;
5005     }
5006 
5007     /**
5008      * Produces a method handle of the requested return type which returns the given
5009      * constant value every time it is invoked.
5010      * <p>
5011      * Before the method handle is returned, the passed-in value is converted to the requested type.
5012      * If the requested type is primitive, widening primitive conversions are attempted,
5013      * else reference conversions are attempted.
5014      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5015      * @param type the return type of the desired method handle
5016      * @param value the value to return
5017      * @return a method handle of the given return type and no arguments, which always returns the given value
5018      * @throws NullPointerException if the {@code type} argument is null
5019      * @throws ClassCastException if the value cannot be converted to the required return type
5020      * @throws IllegalArgumentException if the given type is {@code void.class}
5021      */
5022     public static MethodHandle constant(Class<?> type, Object value) {
5023         if (type.isPrimitive()) {
5024             if (type == void.class)
5025                 throw newIllegalArgumentException("void type");
5026             Wrapper w = Wrapper.forPrimitiveType(type);
5027             value = w.convert(value, type);
5028             if (w.zero().equals(value))
5029                 return zero(w, type);
5030             return insertArguments(identity(type), 0, value);
5031         } else {
5032             if (value == null)
5033                 return zero(Wrapper.OBJECT, type);
5034             return identity(type).bindTo(value);
5035         }
5036     }
5037 
5038     /**
5039      * Produces a method handle which returns its sole argument when invoked.
5040      * @param type the type of the sole parameter and return value of the desired method handle
5041      * @return a unary method handle which accepts and returns the given type
5042      * @throws NullPointerException if the argument is null
5043      * @throws IllegalArgumentException if the given type is {@code void.class}
5044      */
5045     public static MethodHandle identity(Class<?> type) {
5046         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5047         int pos = btw.ordinal();
5048         MethodHandle ident = IDENTITY_MHS[pos];
5049         if (ident == null) {
5050             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5051         }
5052         if (ident.type().returnType() == type)
5053             return ident;
5054         // something like identity(Foo.class); do not bother to intern these
5055         assert (btw == Wrapper.OBJECT);
5056         return makeIdentity(type);
5057     }
5058 
5059     /**
5060      * Produces a constant method handle of the requested return type which
5061      * returns the default value for that type every time it is invoked.
5062      * The resulting constant method handle will have no side effects.
5063      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5064      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5065      * since {@code explicitCastArguments} converts {@code null} to default values.
5066      * @param type the expected return type of the desired method handle
5067      * @return a constant method handle that takes no arguments
5068      *         and returns the default value of the given type (or void, if the type is void)
5069      * @throws NullPointerException if the argument is null
5070      * @see MethodHandles#constant
5071      * @see MethodHandles#empty
5072      * @see MethodHandles#explicitCastArguments
5073      * @since 9
5074      */
5075     public static MethodHandle zero(Class<?> type) {
5076         Objects.requireNonNull(type);
5077         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
5078     }
5079 
5080     private static MethodHandle identityOrVoid(Class<?> type) {
5081         return type == void.class ? zero(type) : identity(type);
5082     }
5083 
5084     /**
5085      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5086      * and returns a suitable default depending on the return type.
5087      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
5088      * <p>The returned method handle is equivalent to
5089      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5090      *
5091      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5092      * {@code guardWithTest(pred, target, empty(target.type())}.
5093      * @param type the type of the desired method handle
5094      * @return a constant method handle of the given type, which returns a default value of the given return type
5095      * @throws NullPointerException if the argument is null
5096      * @see MethodHandles#zero
5097      * @see MethodHandles#constant
5098      * @since 9
5099      */
5100     public static  MethodHandle empty(MethodType type) {
5101         Objects.requireNonNull(type);
5102         return dropArguments(zero(type.returnType()), 0, type.parameterList());
5103     }
5104 
5105     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5106     private static MethodHandle makeIdentity(Class<?> ptype) {
5107         MethodType mtype = methodType(ptype, ptype);
5108         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5109         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5110     }
5111 
5112     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5113         int pos = btw.ordinal();
5114         MethodHandle zero = ZERO_MHS[pos];
5115         if (zero == null) {
5116             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5117         }
5118         if (zero.type().returnType() == rtype)
5119             return zero;
5120         assert(btw == Wrapper.OBJECT);
5121         return makeZero(rtype);
5122     }
5123     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5124     private static MethodHandle makeZero(Class<?> rtype) {
5125         MethodType mtype = methodType(rtype);
5126         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5127         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5128     }
5129 
5130     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5131         // Simulate a CAS, to avoid racy duplication of results.
5132         MethodHandle prev = cache[pos];
5133         if (prev != null) return prev;
5134         return cache[pos] = value;
5135     }
5136 
5137     /**
5138      * Provides a target method handle with one or more <em>bound arguments</em>
5139      * in advance of the method handle's invocation.
5140      * The formal parameters to the target corresponding to the bound
5141      * arguments are called <em>bound parameters</em>.
5142      * Returns a new method handle which saves away the bound arguments.
5143      * When it is invoked, it receives arguments for any non-bound parameters,
5144      * binds the saved arguments to their corresponding parameters,
5145      * and calls the original target.
5146      * <p>
5147      * The type of the new method handle will drop the types for the bound
5148      * parameters from the original target type, since the new method handle
5149      * will no longer require those arguments to be supplied by its callers.
5150      * <p>
5151      * Each given argument object must match the corresponding bound parameter type.
5152      * If a bound parameter type is a primitive, the argument object
5153      * must be a wrapper, and will be unboxed to produce the primitive value.
5154      * <p>
5155      * The {@code pos} argument selects which parameters are to be bound.
5156      * It may range between zero and <i>N-L</i> (inclusively),
5157      * where <i>N</i> is the arity of the target method handle
5158      * and <i>L</i> is the length of the values array.
5159      * <p>
5160      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5161      * variable-arity method handle}, even if the original target method handle was.
5162      * @param target the method handle to invoke after the argument is inserted
5163      * @param pos where to insert the argument (zero for the first)
5164      * @param values the series of arguments to insert
5165      * @return a method handle which inserts an additional argument,
5166      *         before calling the original method handle
5167      * @throws NullPointerException if the target or the {@code values} array is null
5168      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5169      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5170      *         is the length of the values array.
5171      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5172      *         type.
5173      * @see MethodHandle#bindTo
5174      */
5175     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5176         int insCount = values.length;
5177         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5178         if (insCount == 0)  return target;
5179         BoundMethodHandle result = target.rebind();
5180         for (int i = 0; i < insCount; i++) {
5181             Object value = values[i];
5182             Class<?> ptype = ptypes[pos+i];
5183             if (ptype.isPrimitive()) {
5184                 result = insertArgumentPrimitive(result, pos, ptype, value);
5185             } else {
5186                 value = ptype.cast(value);  // throw CCE if needed
5187                 result = result.bindArgumentL(pos, value);
5188             }
5189         }
5190         return result;
5191     }
5192 
5193     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5194                                                              Class<?> ptype, Object value) {
5195         Wrapper w = Wrapper.forPrimitiveType(ptype);
5196         // perform unboxing and/or primitive conversion
5197         value = w.convert(value, ptype);
5198         return switch (w) {
5199             case INT    -> result.bindArgumentI(pos, (int) value);
5200             case LONG   -> result.bindArgumentJ(pos, (long) value);
5201             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5202             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5203             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5204         };
5205     }
5206 
5207     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5208         MethodType oldType = target.type();
5209         int outargs = oldType.parameterCount();
5210         int inargs  = outargs - insCount;
5211         if (inargs < 0)
5212             throw newIllegalArgumentException("too many values to insert");
5213         if (pos < 0 || pos > inargs)
5214             throw newIllegalArgumentException("no argument type to append");
5215         return oldType.ptypes();
5216     }
5217 
5218     /**
5219      * Produces a method handle which will discard some dummy arguments
5220      * before calling some other specified <i>target</i> method handle.
5221      * The type of the new method handle will be the same as the target's type,
5222      * except it will also include the dummy argument types,
5223      * at some given position.
5224      * <p>
5225      * The {@code pos} argument may range between zero and <i>N</i>,
5226      * where <i>N</i> is the arity of the target.
5227      * If {@code pos} is zero, the dummy arguments will precede
5228      * the target's real arguments; if {@code pos} is <i>N</i>
5229      * they will come after.
5230      * <p>
5231      * <b>Example:</b>
5232      * <blockquote><pre>{@code
5233 import static java.lang.invoke.MethodHandles.*;
5234 import static java.lang.invoke.MethodType.*;
5235 ...
5236 MethodHandle cat = lookup().findVirtual(String.class,
5237   "concat", methodType(String.class, String.class));
5238 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5239 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5240 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5241 assertEquals(bigType, d0.type());
5242 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5243      * }</pre></blockquote>
5244      * <p>
5245      * This method is also equivalent to the following code:
5246      * <blockquote><pre>
5247      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5248      * </pre></blockquote>
5249      * @param target the method handle to invoke after the arguments are dropped
5250      * @param pos position of first argument to drop (zero for the leftmost)
5251      * @param valueTypes the type(s) of the argument(s) to drop
5252      * @return a method handle which drops arguments of the given types,
5253      *         before calling the original method handle
5254      * @throws NullPointerException if the target is null,
5255      *                              or if the {@code valueTypes} list or any of its elements is null
5256      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5257      *                  or if {@code pos} is negative or greater than the arity of the target,
5258      *                  or if the new method handle's type would have too many parameters
5259      */
5260     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5261         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
5262     }
5263 
5264     private static List<Class<?>> copyTypes(Object[] array) {
5265         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
5266     }
5267 
5268     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5269         MethodType oldType = target.type();  // get NPE
5270         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5271         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5272         if (dropped == 0)  return target;
5273         BoundMethodHandle result = target.rebind();
5274         LambdaForm lform = result.form;
5275         int insertFormArg = 1 + pos;
5276         for (Class<?> ptype : valueTypes) {
5277             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5278         }
5279         result = result.copyWith(newType, lform);
5280         return result;
5281     }
5282 
5283     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
5284         int dropped = valueTypes.size();
5285         MethodType.checkSlotCount(dropped);
5286         int outargs = oldType.parameterCount();
5287         int inargs  = outargs + dropped;
5288         if (pos < 0 || pos > outargs)
5289             throw newIllegalArgumentException("no argument type to remove"
5290                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5291                     );
5292         return dropped;
5293     }
5294 
5295     /**
5296      * Produces a method handle which will discard some dummy arguments
5297      * before calling some other specified <i>target</i> method handle.
5298      * The type of the new method handle will be the same as the target's type,
5299      * except it will also include the dummy argument types,
5300      * at some given position.
5301      * <p>
5302      * The {@code pos} argument may range between zero and <i>N</i>,
5303      * where <i>N</i> is the arity of the target.
5304      * If {@code pos} is zero, the dummy arguments will precede
5305      * the target's real arguments; if {@code pos} is <i>N</i>
5306      * they will come after.
5307      * @apiNote
5308      * <blockquote><pre>{@code
5309 import static java.lang.invoke.MethodHandles.*;
5310 import static java.lang.invoke.MethodType.*;
5311 ...
5312 MethodHandle cat = lookup().findVirtual(String.class,
5313   "concat", methodType(String.class, String.class));
5314 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5315 MethodHandle d0 = dropArguments(cat, 0, String.class);
5316 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5317 MethodHandle d1 = dropArguments(cat, 1, String.class);
5318 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5319 MethodHandle d2 = dropArguments(cat, 2, String.class);
5320 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5321 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5322 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5323      * }</pre></blockquote>
5324      * <p>
5325      * This method is also equivalent to the following code:
5326      * <blockquote><pre>
5327      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5328      * </pre></blockquote>
5329      * @param target the method handle to invoke after the arguments are dropped
5330      * @param pos position of first argument to drop (zero for the leftmost)
5331      * @param valueTypes the type(s) of the argument(s) to drop
5332      * @return a method handle which drops arguments of the given types,
5333      *         before calling the original method handle
5334      * @throws NullPointerException if the target is null,
5335      *                              or if the {@code valueTypes} array or any of its elements is null
5336      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5337      *                  or if {@code pos} is negative or greater than the arity of the target,
5338      *                  or if the new method handle's type would have
5339      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5340      */
5341     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5342         return dropArguments0(target, pos, copyTypes(valueTypes));
5343     }
5344 
5345     // private version which allows caller some freedom with error handling
5346     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
5347                                       boolean nullOnFailure) {
5348         newTypes = copyTypes(newTypes.toArray());
5349         List<Class<?>> oldTypes = target.type().parameterList();
5350         int match = oldTypes.size();
5351         if (skip != 0) {
5352             if (skip < 0 || skip > match) {
5353                 throw newIllegalArgumentException("illegal skip", skip, target);
5354             }
5355             oldTypes = oldTypes.subList(skip, match);
5356             match -= skip;
5357         }
5358         List<Class<?>> addTypes = newTypes;
5359         int add = addTypes.size();
5360         if (pos != 0) {
5361             if (pos < 0 || pos > add) {
5362                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
5363             }
5364             addTypes = addTypes.subList(pos, add);
5365             add -= pos;
5366             assert(addTypes.size() == add);
5367         }
5368         // Do not add types which already match the existing arguments.
5369         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
5370             if (nullOnFailure) {
5371                 return null;
5372             }
5373             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5374         }
5375         addTypes = addTypes.subList(match, add);
5376         add -= match;
5377         assert(addTypes.size() == add);
5378         // newTypes:     (   P*[pos], M*[match], A*[add] )
5379         // target: ( S*[skip],        M*[match]  )
5380         MethodHandle adapter = target;
5381         if (add > 0) {
5382             adapter = dropArguments0(adapter, skip+ match, addTypes);
5383         }
5384         // adapter: (S*[skip],        M*[match], A*[add] )
5385         if (pos > 0) {
5386             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5387         }
5388         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5389         return adapter;
5390     }
5391 
5392     /**
5393      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5394      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5395      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5396      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5397      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5398      * {@link #dropArguments(MethodHandle, int, Class[])}.
5399      * <p>
5400      * The resulting handle will have the same return type as the target handle.
5401      * <p>
5402      * In more formal terms, assume these two type lists:<ul>
5403      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5404      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5405      * {@code newTypes}.
5406      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5407      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5408      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5409      * sub-list.
5410      * </ul>
5411      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5412      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5413      * {@link #dropArguments(MethodHandle, int, Class[])}.
5414      *
5415      * @apiNote
5416      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5417      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5418      * <blockquote><pre>{@code
5419 import static java.lang.invoke.MethodHandles.*;
5420 import static java.lang.invoke.MethodType.*;
5421 ...
5422 ...
5423 MethodHandle h0 = constant(boolean.class, true);
5424 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5425 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5426 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5427 if (h1.type().parameterCount() < h2.type().parameterCount())
5428     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5429 else
5430     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5431 MethodHandle h3 = guardWithTest(h0, h1, h2);
5432 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5433      * }</pre></blockquote>
5434      * @param target the method handle to adapt
5435      * @param skip number of targets parameters to disregard (they will be unchanged)
5436      * @param newTypes the list of types to match {@code target}'s parameter type list to
5437      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5438      * @return a possibly adapted method handle
5439      * @throws NullPointerException if either argument is null
5440      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5441      *         or if {@code skip} is negative or greater than the arity of the target,
5442      *         or if {@code pos} is negative or greater than the newTypes list size,
5443      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5444      *         {@code pos}.
5445      * @since 9
5446      */
5447     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5448         Objects.requireNonNull(target);
5449         Objects.requireNonNull(newTypes);
5450         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5451     }
5452 
5453     /**
5454      * Drop the return value of the target handle (if any).
5455      * The returned method handle will have a {@code void} return type.
5456      *
5457      * @param target the method handle to adapt
5458      * @return a possibly adapted method handle
5459      * @throws NullPointerException if {@code target} is null
5460      * @since 16
5461      */
5462     public static MethodHandle dropReturn(MethodHandle target) {
5463         Objects.requireNonNull(target);
5464         MethodType oldType = target.type();
5465         Class<?> oldReturnType = oldType.returnType();
5466         if (oldReturnType == void.class)
5467             return target;
5468         MethodType newType = oldType.changeReturnType(void.class);
5469         BoundMethodHandle result = target.rebind();
5470         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5471         result = result.copyWith(newType, lform);
5472         return result;
5473     }
5474 
5475     /**
5476      * Adapts a target method handle by pre-processing
5477      * one or more of its arguments, each with its own unary filter function,
5478      * and then calling the target with each pre-processed argument
5479      * replaced by the result of its corresponding filter function.
5480      * <p>
5481      * The pre-processing is performed by one or more method handles,
5482      * specified in the elements of the {@code filters} array.
5483      * The first element of the filter array corresponds to the {@code pos}
5484      * argument of the target, and so on in sequence.
5485      * The filter functions are invoked in left to right order.
5486      * <p>
5487      * Null arguments in the array are treated as identity functions,
5488      * and the corresponding arguments left unchanged.
5489      * (If there are no non-null elements in the array, the original target is returned.)
5490      * Each filter is applied to the corresponding argument of the adapter.
5491      * <p>
5492      * If a filter {@code F} applies to the {@code N}th argument of
5493      * the target, then {@code F} must be a method handle which
5494      * takes exactly one argument.  The type of {@code F}'s sole argument
5495      * replaces the corresponding argument type of the target
5496      * in the resulting adapted method handle.
5497      * The return type of {@code F} must be identical to the corresponding
5498      * parameter type of the target.
5499      * <p>
5500      * It is an error if there are elements of {@code filters}
5501      * (null or not)
5502      * which do not correspond to argument positions in the target.
5503      * <p><b>Example:</b>
5504      * <blockquote><pre>{@code
5505 import static java.lang.invoke.MethodHandles.*;
5506 import static java.lang.invoke.MethodType.*;
5507 ...
5508 MethodHandle cat = lookup().findVirtual(String.class,
5509   "concat", methodType(String.class, String.class));
5510 MethodHandle upcase = lookup().findVirtual(String.class,
5511   "toUpperCase", methodType(String.class));
5512 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5513 MethodHandle f0 = filterArguments(cat, 0, upcase);
5514 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5515 MethodHandle f1 = filterArguments(cat, 1, upcase);
5516 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5517 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5518 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5519      * }</pre></blockquote>
5520      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5521      * denotes the return type of both the {@code target} and resulting adapter.
5522      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5523      * of the parameters and arguments that precede and follow the filter position
5524      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5525      * values of the filtered parameters and arguments; they also represent the
5526      * return types of the {@code filter[i]} handles. The latter accept arguments
5527      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5528      * the resulting adapter.
5529      * <blockquote><pre>{@code
5530      * T target(P... p, A[i]... a[i], B... b);
5531      * A[i] filter[i](V[i]);
5532      * T adapter(P... p, V[i]... v[i], B... b) {
5533      *   return target(p..., filter[i](v[i])..., b...);
5534      * }
5535      * }</pre></blockquote>
5536      * <p>
5537      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5538      * variable-arity method handle}, even if the original target method handle was.
5539      *
5540      * @param target the method handle to invoke after arguments are filtered
5541      * @param pos the position of the first argument to filter
5542      * @param filters method handles to call initially on filtered arguments
5543      * @return method handle which incorporates the specified argument filtering logic
5544      * @throws NullPointerException if the target is null
5545      *                              or if the {@code filters} array is null
5546      * @throws IllegalArgumentException if a non-null element of {@code filters}
5547      *          does not match a corresponding argument type of target as described above,
5548      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5549      *          or if the resulting method handle's type would have
5550      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5551      */
5552     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5553         // In method types arguments start at index 0, while the LF
5554         // editor have the MH receiver at position 0 - adjust appropriately.
5555         final int MH_RECEIVER_OFFSET = 1;
5556         filterArgumentsCheckArity(target, pos, filters);
5557         MethodHandle adapter = target;
5558 
5559         // keep track of currently matched filters, as to optimize repeated filters
5560         int index = 0;
5561         int[] positions = new int[filters.length];
5562         MethodHandle filter = null;
5563 
5564         // process filters in reverse order so that the invocation of
5565         // the resulting adapter will invoke the filters in left-to-right order
5566         for (int i = filters.length - 1; i >= 0; --i) {
5567             MethodHandle newFilter = filters[i];
5568             if (newFilter == null) continue;  // ignore null elements of filters
5569 
5570             // flush changes on update
5571             if (filter != newFilter) {
5572                 if (filter != null) {
5573                     if (index > 1) {
5574                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5575                     } else {
5576                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5577                     }
5578                 }
5579                 filter = newFilter;
5580                 index = 0;
5581             }
5582 
5583             filterArgumentChecks(target, pos + i, newFilter);
5584             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5585         }
5586         if (index > 1) {
5587             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5588         } else if (index == 1) {
5589             adapter = filterArgument(adapter, positions[0] - 1, filter);
5590         }
5591         return adapter;
5592     }
5593 
5594     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5595         MethodType targetType = adapter.type();
5596         MethodType filterType = filter.type();
5597         BoundMethodHandle result = adapter.rebind();
5598         Class<?> newParamType = filterType.parameterType(0);
5599 
5600         Class<?>[] ptypes = targetType.ptypes().clone();
5601         for (int pos : positions) {
5602             ptypes[pos - 1] = newParamType;
5603         }
5604         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5605 
5606         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5607         return result.copyWithExtendL(newType, lform, filter);
5608     }
5609 
5610     /*non-public*/
5611     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5612         filterArgumentChecks(target, pos, filter);
5613         MethodType targetType = target.type();
5614         MethodType filterType = filter.type();
5615         BoundMethodHandle result = target.rebind();
5616         Class<?> newParamType = filterType.parameterType(0);
5617         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5618         MethodType newType = targetType.changeParameterType(pos, newParamType);
5619         result = result.copyWithExtendL(newType, lform, filter);
5620         return result;
5621     }
5622 
5623     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5624         MethodType targetType = target.type();
5625         int maxPos = targetType.parameterCount();
5626         if (pos + filters.length > maxPos)
5627             throw newIllegalArgumentException("too many filters");
5628     }
5629 
5630     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5631         MethodType targetType = target.type();
5632         MethodType filterType = filter.type();
5633         if (filterType.parameterCount() != 1
5634             || filterType.returnType() != targetType.parameterType(pos))
5635             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5636     }
5637 
5638     /**
5639      * Adapts a target method handle by pre-processing
5640      * a sub-sequence of its arguments with a filter (another method handle).
5641      * The pre-processed arguments are replaced by the result (if any) of the
5642      * filter function.
5643      * The target is then called on the modified (usually shortened) argument list.
5644      * <p>
5645      * If the filter returns a value, the target must accept that value as
5646      * its argument in position {@code pos}, preceded and/or followed by
5647      * any arguments not passed to the filter.
5648      * If the filter returns void, the target must accept all arguments
5649      * not passed to the filter.
5650      * No arguments are reordered, and a result returned from the filter
5651      * replaces (in order) the whole subsequence of arguments originally
5652      * passed to the adapter.
5653      * <p>
5654      * The argument types (if any) of the filter
5655      * replace zero or one argument types of the target, at position {@code pos},
5656      * in the resulting adapted method handle.
5657      * The return type of the filter (if any) must be identical to the
5658      * argument type of the target at position {@code pos}, and that target argument
5659      * is supplied by the return value of the filter.
5660      * <p>
5661      * In all cases, {@code pos} must be greater than or equal to zero, and
5662      * {@code pos} must also be less than or equal to the target's arity.
5663      * <p><b>Example:</b>
5664      * <blockquote><pre>{@code
5665 import static java.lang.invoke.MethodHandles.*;
5666 import static java.lang.invoke.MethodType.*;
5667 ...
5668 MethodHandle deepToString = publicLookup()
5669   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5670 
5671 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5672 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5673 
5674 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5675 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5676 
5677 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5678 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5679 assertEquals("[top, [up, down], strange]",
5680              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5681 
5682 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5683 assertEquals("[top, [up, down], [strange]]",
5684              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5685 
5686 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5687 assertEquals("[top, [[up, down, strange], charm], bottom]",
5688              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5689      * }</pre></blockquote>
5690      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5691      * represents the return type of the {@code target} and resulting adapter.
5692      * {@code V}/{@code v} stand for the return type and value of the
5693      * {@code filter}, which are also found in the signature and arguments of
5694      * the {@code target}, respectively, unless {@code V} is {@code void}.
5695      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5696      * and values preceding and following the collection position, {@code pos},
5697      * in the {@code target}'s signature. They also turn up in the resulting
5698      * adapter's signature and arguments, where they surround
5699      * {@code B}/{@code b}, which represent the parameter types and arguments
5700      * to the {@code filter} (if any).
5701      * <blockquote><pre>{@code
5702      * T target(A...,V,C...);
5703      * V filter(B...);
5704      * T adapter(A... a,B... b,C... c) {
5705      *   V v = filter(b...);
5706      *   return target(a...,v,c...);
5707      * }
5708      * // and if the filter has no arguments:
5709      * T target2(A...,V,C...);
5710      * V filter2();
5711      * T adapter2(A... a,C... c) {
5712      *   V v = filter2();
5713      *   return target2(a...,v,c...);
5714      * }
5715      * // and if the filter has a void return:
5716      * T target3(A...,C...);
5717      * void filter3(B...);
5718      * T adapter3(A... a,B... b,C... c) {
5719      *   filter3(b...);
5720      *   return target3(a...,c...);
5721      * }
5722      * }</pre></blockquote>
5723      * <p>
5724      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5725      * one which first "folds" the affected arguments, and then drops them, in separate
5726      * steps as follows:
5727      * <blockquote><pre>{@code
5728      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5729      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5730      * }</pre></blockquote>
5731      * If the target method handle consumes no arguments besides than the result
5732      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5733      * is equivalent to {@code filterReturnValue(coll, mh)}.
5734      * If the filter method handle {@code coll} consumes one argument and produces
5735      * a non-void result, then {@code collectArguments(mh, N, coll)}
5736      * is equivalent to {@code filterArguments(mh, N, coll)}.
5737      * Other equivalences are possible but would require argument permutation.
5738      * <p>
5739      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5740      * variable-arity method handle}, even if the original target method handle was.
5741      *
5742      * @param target the method handle to invoke after filtering the subsequence of arguments
5743      * @param pos the position of the first adapter argument to pass to the filter,
5744      *            and/or the target argument which receives the result of the filter
5745      * @param filter method handle to call on the subsequence of arguments
5746      * @return method handle which incorporates the specified argument subsequence filtering logic
5747      * @throws NullPointerException if either argument is null
5748      * @throws IllegalArgumentException if the return type of {@code filter}
5749      *          is non-void and is not the same as the {@code pos} argument of the target,
5750      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5751      *          or if the resulting method handle's type would have
5752      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5753      * @see MethodHandles#foldArguments
5754      * @see MethodHandles#filterArguments
5755      * @see MethodHandles#filterReturnValue
5756      */
5757     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5758         MethodType newType = collectArgumentsChecks(target, pos, filter);
5759         MethodType collectorType = filter.type();
5760         BoundMethodHandle result = target.rebind();
5761         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5762         return result.copyWithExtendL(newType, lform, filter);
5763     }
5764 
5765     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5766         MethodType targetType = target.type();
5767         MethodType filterType = filter.type();
5768         Class<?> rtype = filterType.returnType();
5769         List<Class<?>> filterArgs = filterType.parameterList();
5770         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5771                        (rtype != void.class && pos >= targetType.parameterCount())) {
5772             throw newIllegalArgumentException("position is out of range for target", target, pos);
5773         }
5774         if (rtype == void.class) {
5775             return targetType.insertParameterTypes(pos, filterArgs);
5776         }
5777         if (rtype != targetType.parameterType(pos)) {
5778             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5779         }
5780         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5781     }
5782 
5783     /**
5784      * Adapts a target method handle by post-processing
5785      * its return value (if any) with a filter (another method handle).
5786      * The result of the filter is returned from the adapter.
5787      * <p>
5788      * If the target returns a value, the filter must accept that value as
5789      * its only argument.
5790      * If the target returns void, the filter must accept no arguments.
5791      * <p>
5792      * The return type of the filter
5793      * replaces the return type of the target
5794      * in the resulting adapted method handle.
5795      * The argument type of the filter (if any) must be identical to the
5796      * return type of the target.
5797      * <p><b>Example:</b>
5798      * <blockquote><pre>{@code
5799 import static java.lang.invoke.MethodHandles.*;
5800 import static java.lang.invoke.MethodType.*;
5801 ...
5802 MethodHandle cat = lookup().findVirtual(String.class,
5803   "concat", methodType(String.class, String.class));
5804 MethodHandle length = lookup().findVirtual(String.class,
5805   "length", methodType(int.class));
5806 System.out.println((String) cat.invokeExact("x", "y")); // xy
5807 MethodHandle f0 = filterReturnValue(cat, length);
5808 System.out.println((int) f0.invokeExact("x", "y")); // 2
5809      * }</pre></blockquote>
5810      * <p>Here is pseudocode for the resulting adapter. In the code,
5811      * {@code T}/{@code t} represent the result type and value of the
5812      * {@code target}; {@code V}, the result type of the {@code filter}; and
5813      * {@code A}/{@code a}, the types and values of the parameters and arguments
5814      * of the {@code target} as well as the resulting adapter.
5815      * <blockquote><pre>{@code
5816      * T target(A...);
5817      * V filter(T);
5818      * V adapter(A... a) {
5819      *   T t = target(a...);
5820      *   return filter(t);
5821      * }
5822      * // and if the target has a void return:
5823      * void target2(A...);
5824      * V filter2();
5825      * V adapter2(A... a) {
5826      *   target2(a...);
5827      *   return filter2();
5828      * }
5829      * // and if the filter has a void return:
5830      * T target3(A...);
5831      * void filter3(V);
5832      * void adapter3(A... a) {
5833      *   T t = target3(a...);
5834      *   filter3(t);
5835      * }
5836      * }</pre></blockquote>
5837      * <p>
5838      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5839      * variable-arity method handle}, even if the original target method handle was.
5840      * @param target the method handle to invoke before filtering the return value
5841      * @param filter method handle to call on the return value
5842      * @return method handle which incorporates the specified return value filtering logic
5843      * @throws NullPointerException if either argument is null
5844      * @throws IllegalArgumentException if the argument list of {@code filter}
5845      *          does not match the return type of target as described above
5846      */
5847     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5848         MethodType targetType = target.type();
5849         MethodType filterType = filter.type();
5850         filterReturnValueChecks(targetType, filterType);
5851         BoundMethodHandle result = target.rebind();
5852         BasicType rtype = BasicType.basicType(filterType.returnType());
5853         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5854         MethodType newType = targetType.changeReturnType(filterType.returnType());
5855         result = result.copyWithExtendL(newType, lform, filter);
5856         return result;
5857     }
5858 
5859     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5860         Class<?> rtype = targetType.returnType();
5861         int filterValues = filterType.parameterCount();
5862         if (filterValues == 0
5863                 ? (rtype != void.class)
5864                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5865             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5866     }
5867 
5868     /**
5869      * Filter the return value of a target method handle with a filter function. The filter function is
5870      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5871      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5872      * as follows:
5873      * <blockquote><pre>{@code
5874      * T target(A...)
5875      * V filter(B... , T)
5876      * V adapter(A... a, B... b) {
5877      *     T t = target(a...);
5878      *     return filter(b..., t);
5879      * }</pre></blockquote>
5880      * <p>
5881      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5882      *
5883      * @param target the target method handle
5884      * @param filter the filter method handle
5885      * @return the adapter method handle
5886      */
5887     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5888         MethodType targetType = target.type();
5889         MethodType filterType = filter.type();
5890         BoundMethodHandle result = target.rebind();
5891         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5892         MethodType newType = targetType.changeReturnType(filterType.returnType());
5893         if (filterType.parameterCount() > 1) {
5894             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5895                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5896             }
5897         }
5898         result = result.copyWithExtendL(newType, lform, filter);
5899         return result;
5900     }
5901 
5902     /**
5903      * Adapts a target method handle by pre-processing
5904      * some of its arguments, and then calling the target with
5905      * the result of the pre-processing, inserted into the original
5906      * sequence of arguments.
5907      * <p>
5908      * The pre-processing is performed by {@code combiner}, a second method handle.
5909      * Of the arguments passed to the adapter, the first {@code N} arguments
5910      * are copied to the combiner, which is then called.
5911      * (Here, {@code N} is defined as the parameter count of the combiner.)
5912      * After this, control passes to the target, with any result
5913      * from the combiner inserted before the original {@code N} incoming
5914      * arguments.
5915      * <p>
5916      * If the combiner returns a value, the first parameter type of the target
5917      * must be identical with the return type of the combiner, and the next
5918      * {@code N} parameter types of the target must exactly match the parameters
5919      * of the combiner.
5920      * <p>
5921      * If the combiner has a void return, no result will be inserted,
5922      * and the first {@code N} parameter types of the target
5923      * must exactly match the parameters of the combiner.
5924      * <p>
5925      * The resulting adapter is the same type as the target, except that the
5926      * first parameter type is dropped,
5927      * if it corresponds to the result of the combiner.
5928      * <p>
5929      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5930      * that either the combiner or the target does not wish to receive.
5931      * If some of the incoming arguments are destined only for the combiner,
5932      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5933      * arguments will not need to be live on the stack on entry to the
5934      * target.)
5935      * <p><b>Example:</b>
5936      * <blockquote><pre>{@code
5937 import static java.lang.invoke.MethodHandles.*;
5938 import static java.lang.invoke.MethodType.*;
5939 ...
5940 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5941   "println", methodType(void.class, String.class))
5942     .bindTo(System.out);
5943 MethodHandle cat = lookup().findVirtual(String.class,
5944   "concat", methodType(String.class, String.class));
5945 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5946 MethodHandle catTrace = foldArguments(cat, trace);
5947 // also prints "boo":
5948 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5949      * }</pre></blockquote>
5950      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5951      * represents the result type of the {@code target} and resulting adapter.
5952      * {@code V}/{@code v} represent the type and value of the parameter and argument
5953      * of {@code target} that precedes the folding position; {@code V} also is
5954      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5955      * types and values of the {@code N} parameters and arguments at the folding
5956      * position. {@code B}/{@code b} represent the types and values of the
5957      * {@code target} parameters and arguments that follow the folded parameters
5958      * and arguments.
5959      * <blockquote><pre>{@code
5960      * // there are N arguments in A...
5961      * T target(V, A[N]..., B...);
5962      * V combiner(A...);
5963      * T adapter(A... a, B... b) {
5964      *   V v = combiner(a...);
5965      *   return target(v, a..., b...);
5966      * }
5967      * // and if the combiner has a void return:
5968      * T target2(A[N]..., B...);
5969      * void combiner2(A...);
5970      * T adapter2(A... a, B... b) {
5971      *   combiner2(a...);
5972      *   return target2(a..., b...);
5973      * }
5974      * }</pre></blockquote>
5975      * <p>
5976      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5977      * variable-arity method handle}, even if the original target method handle was.
5978      * @param target the method handle to invoke after arguments are combined
5979      * @param combiner method handle to call initially on the incoming arguments
5980      * @return method handle which incorporates the specified argument folding logic
5981      * @throws NullPointerException if either argument is null
5982      * @throws IllegalArgumentException if {@code combiner}'s return type
5983      *          is non-void and not the same as the first argument type of
5984      *          the target, or if the initial {@code N} argument types
5985      *          of the target
5986      *          (skipping one matching the {@code combiner}'s return type)
5987      *          are not identical with the argument types of {@code combiner}
5988      */
5989     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5990         return foldArguments(target, 0, combiner);
5991     }
5992 
5993     /**
5994      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5995      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5996      * before the folded arguments.
5997      * <p>
5998      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5999      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6000      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6001      * 0.
6002      *
6003      * @apiNote Example:
6004      * <blockquote><pre>{@code
6005     import static java.lang.invoke.MethodHandles.*;
6006     import static java.lang.invoke.MethodType.*;
6007     ...
6008     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6009     "println", methodType(void.class, String.class))
6010     .bindTo(System.out);
6011     MethodHandle cat = lookup().findVirtual(String.class,
6012     "concat", methodType(String.class, String.class));
6013     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6014     MethodHandle catTrace = foldArguments(cat, 1, trace);
6015     // also prints "jum":
6016     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6017      * }</pre></blockquote>
6018      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6019      * represents the result type of the {@code target} and resulting adapter.
6020      * {@code V}/{@code v} represent the type and value of the parameter and argument
6021      * of {@code target} that precedes the folding position; {@code V} also is
6022      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6023      * types and values of the {@code N} parameters and arguments at the folding
6024      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6025      * and values of the {@code target} parameters and arguments that precede and
6026      * follow the folded parameters and arguments starting at {@code pos},
6027      * respectively.
6028      * <blockquote><pre>{@code
6029      * // there are N arguments in A...
6030      * T target(Z..., V, A[N]..., B...);
6031      * V combiner(A...);
6032      * T adapter(Z... z, A... a, B... b) {
6033      *   V v = combiner(a...);
6034      *   return target(z..., v, a..., b...);
6035      * }
6036      * // and if the combiner has a void return:
6037      * T target2(Z..., A[N]..., B...);
6038      * void combiner2(A...);
6039      * T adapter2(Z... z, A... a, B... b) {
6040      *   combiner2(a...);
6041      *   return target2(z..., a..., b...);
6042      * }
6043      * }</pre></blockquote>
6044      * <p>
6045      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6046      * variable-arity method handle}, even if the original target method handle was.
6047      *
6048      * @param target the method handle to invoke after arguments are combined
6049      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6050      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6051      * @param combiner method handle to call initially on the incoming arguments
6052      * @return method handle which incorporates the specified argument folding logic
6053      * @throws NullPointerException if either argument is null
6054      * @throws IllegalArgumentException if either of the following two conditions holds:
6055      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6056      *              {@code pos} of the target signature;
6057      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6058      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6059      *
6060      * @see #foldArguments(MethodHandle, MethodHandle)
6061      * @since 9
6062      */
6063     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6064         MethodType targetType = target.type();
6065         MethodType combinerType = combiner.type();
6066         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6067         BoundMethodHandle result = target.rebind();
6068         boolean dropResult = rtype == void.class;
6069         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6070         MethodType newType = targetType;
6071         if (!dropResult) {
6072             newType = newType.dropParameterTypes(pos, pos + 1);
6073         }
6074         result = result.copyWithExtendL(newType, lform, combiner);
6075         return result;
6076     }
6077 
6078     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6079         int foldArgs   = combinerType.parameterCount();
6080         Class<?> rtype = combinerType.returnType();
6081         int foldVals = rtype == void.class ? 0 : 1;
6082         int afterInsertPos = foldPos + foldVals;
6083         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6084         if (ok) {
6085             for (int i = 0; i < foldArgs; i++) {
6086                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6087                     ok = false;
6088                     break;
6089                 }
6090             }
6091         }
6092         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6093             ok = false;
6094         if (!ok)
6095             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6096         return rtype;
6097     }
6098 
6099     /**
6100      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6101      * of the pre-processing replacing the argument at the given position.
6102      *
6103      * @param target the method handle to invoke after arguments are combined
6104      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6105      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6106      * @param combiner method handle to call initially on the incoming arguments
6107      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6108      * @return method handle which incorporates the specified argument folding logic
6109      * @throws NullPointerException if either argument is null
6110      * @throws IllegalArgumentException if either of the following two conditions holds:
6111      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6112      *              {@code pos} of the target signature;
6113      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6114      *              not identical with the argument types of {@code combiner}.
6115      */
6116     /*non-public*/
6117     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6118         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6119     }
6120 
6121     /**
6122      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6123      * the pre-processing inserted into the original sequence of arguments at the given position.
6124      *
6125      * @param target the method handle to invoke after arguments are combined
6126      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6127      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6128      * @param combiner method handle to call initially on the incoming arguments
6129      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6130      * @return method handle which incorporates the specified argument folding logic
6131      * @throws NullPointerException if either argument is null
6132      * @throws IllegalArgumentException if either of the following two conditions holds:
6133      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6134      *              {@code pos} of the target signature;
6135      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6136      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6137      *              with the argument types of {@code combiner}.
6138      */
6139     /*non-public*/
6140     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6141         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6142     }
6143 
6144     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6145         MethodType targetType = target.type();
6146         MethodType combinerType = combiner.type();
6147         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6148         BoundMethodHandle result = target.rebind();
6149 
6150         MethodType newType = targetType;
6151         LambdaForm lform;
6152         if (filter) {
6153             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6154         } else {
6155             boolean dropResult = rtype == void.class;
6156             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6157             if (!dropResult) {
6158                 newType = newType.dropParameterTypes(position, position + 1);
6159             }
6160         }
6161         result = result.copyWithExtendL(newType, lform, combiner);
6162         return result;
6163     }
6164 
6165     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6166         int combinerArgs = combinerType.parameterCount();
6167         if (argPos.length != combinerArgs) {
6168             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6169         }
6170         Class<?> rtype = combinerType.returnType();
6171 
6172         for (int i = 0; i < combinerArgs; i++) {
6173             int arg = argPos[i];
6174             if (arg < 0 || arg > targetType.parameterCount()) {
6175                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6176             }
6177             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6178                 throw newIllegalArgumentException("target argument type at position " + arg
6179                         + " must match combiner argument type at index " + i + ": " + targetType
6180                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6181             }
6182         }
6183         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6184             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6185         }
6186         return rtype;
6187     }
6188 
6189     /**
6190      * Makes a method handle which adapts a target method handle,
6191      * by guarding it with a test, a boolean-valued method handle.
6192      * If the guard fails, a fallback handle is called instead.
6193      * All three method handles must have the same corresponding
6194      * argument and return types, except that the return type
6195      * of the test must be boolean, and the test is allowed
6196      * to have fewer arguments than the other two method handles.
6197      * <p>
6198      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6199      * represents the uniform result type of the three involved handles;
6200      * {@code A}/{@code a}, the types and values of the {@code target}
6201      * parameters and arguments that are consumed by the {@code test}; and
6202      * {@code B}/{@code b}, those types and values of the {@code target}
6203      * parameters and arguments that are not consumed by the {@code test}.
6204      * <blockquote><pre>{@code
6205      * boolean test(A...);
6206      * T target(A...,B...);
6207      * T fallback(A...,B...);
6208      * T adapter(A... a,B... b) {
6209      *   if (test(a...))
6210      *     return target(a..., b...);
6211      *   else
6212      *     return fallback(a..., b...);
6213      * }
6214      * }</pre></blockquote>
6215      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6216      * be modified by execution of the test, and so are passed unchanged
6217      * from the caller to the target or fallback as appropriate.
6218      * @param test method handle used for test, must return boolean
6219      * @param target method handle to call if test passes
6220      * @param fallback method handle to call if test fails
6221      * @return method handle which incorporates the specified if/then/else logic
6222      * @throws NullPointerException if any argument is null
6223      * @throws IllegalArgumentException if {@code test} does not return boolean,
6224      *          or if all three method types do not match (with the return
6225      *          type of {@code test} changed to match that of the target).
6226      */
6227     public static MethodHandle guardWithTest(MethodHandle test,
6228                                MethodHandle target,
6229                                MethodHandle fallback) {
6230         MethodType gtype = test.type();
6231         MethodType ttype = target.type();
6232         MethodType ftype = fallback.type();
6233         if (!ttype.equals(ftype))
6234             throw misMatchedTypes("target and fallback types", ttype, ftype);
6235         if (gtype.returnType() != boolean.class)
6236             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6237         List<Class<?>> targs = ttype.parameterList();
6238         test = dropArgumentsToMatch(test, 0, targs, 0, true);
6239         if (test == null) {
6240             throw misMatchedTypes("target and test types", ttype, gtype);
6241         }
6242         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6243     }
6244 
6245     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6246         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6247     }
6248 
6249     /**
6250      * Makes a method handle which adapts a target method handle,
6251      * by running it inside an exception handler.
6252      * If the target returns normally, the adapter returns that value.
6253      * If an exception matching the specified type is thrown, the fallback
6254      * handle is called instead on the exception, plus the original arguments.
6255      * <p>
6256      * The target and handler must have the same corresponding
6257      * argument and return types, except that handler may omit trailing arguments
6258      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6259      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6260      * <p>
6261      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6262      * represents the return type of the {@code target} and {@code handler},
6263      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6264      * the types and values of arguments to the resulting handle consumed by
6265      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6266      * resulting handle discarded by {@code handler}.
6267      * <blockquote><pre>{@code
6268      * T target(A..., B...);
6269      * T handler(ExType, A...);
6270      * T adapter(A... a, B... b) {
6271      *   try {
6272      *     return target(a..., b...);
6273      *   } catch (ExType ex) {
6274      *     return handler(ex, a...);
6275      *   }
6276      * }
6277      * }</pre></blockquote>
6278      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6279      * be modified by execution of the target, and so are passed unchanged
6280      * from the caller to the handler, if the handler is invoked.
6281      * <p>
6282      * The target and handler must return the same type, even if the handler
6283      * always throws.  (This might happen, for instance, because the handler
6284      * is simulating a {@code finally} clause).
6285      * To create such a throwing handler, compose the handler creation logic
6286      * with {@link #throwException throwException},
6287      * in order to create a method handle of the correct return type.
6288      * @param target method handle to call
6289      * @param exType the type of exception which the handler will catch
6290      * @param handler method handle to call if a matching exception is thrown
6291      * @return method handle which incorporates the specified try/catch logic
6292      * @throws NullPointerException if any argument is null
6293      * @throws IllegalArgumentException if {@code handler} does not accept
6294      *          the given exception type, or if the method handle types do
6295      *          not match in their return types and their
6296      *          corresponding parameters
6297      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6298      */
6299     public static MethodHandle catchException(MethodHandle target,
6300                                 Class<? extends Throwable> exType,
6301                                 MethodHandle handler) {
6302         MethodType ttype = target.type();
6303         MethodType htype = handler.type();
6304         if (!Throwable.class.isAssignableFrom(exType))
6305             throw new ClassCastException(exType.getName());
6306         if (htype.parameterCount() < 1 ||
6307             !htype.parameterType(0).isAssignableFrom(exType))
6308             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6309         if (htype.returnType() != ttype.returnType())
6310             throw misMatchedTypes("target and handler return types", ttype, htype);
6311         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
6312         if (handler == null) {
6313             throw misMatchedTypes("target and handler types", ttype, htype);
6314         }
6315         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6316     }
6317 
6318     /**
6319      * Produces a method handle which will throw exceptions of the given {@code exType}.
6320      * The method handle will accept a single argument of {@code exType},
6321      * and immediately throw it as an exception.
6322      * The method type will nominally specify a return of {@code returnType}.
6323      * The return type may be anything convenient:  It doesn't matter to the
6324      * method handle's behavior, since it will never return normally.
6325      * @param returnType the return type of the desired method handle
6326      * @param exType the parameter type of the desired method handle
6327      * @return method handle which can throw the given exceptions
6328      * @throws NullPointerException if either argument is null
6329      */
6330     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6331         if (!Throwable.class.isAssignableFrom(exType))
6332             throw new ClassCastException(exType.getName());
6333         return MethodHandleImpl.throwException(methodType(returnType, exType));
6334     }
6335 
6336     /**
6337      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6338      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6339      * delivers the loop's result, which is the return value of the resulting handle.
6340      * <p>
6341      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6342      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6343      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6344      * terms of method handles, each clause will specify up to four independent actions:<ul>
6345      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6346      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6347      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6348      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6349      * </ul>
6350      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6351      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6352      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6353      * <p>
6354      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6355      * this case. See below for a detailed description.
6356      * <p>
6357      * <em>Parameters optional everywhere:</em>
6358      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6359      * As an exception, the init functions cannot take any {@code v} parameters,
6360      * because those values are not yet computed when the init functions are executed.
6361      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6362      * In fact, any clause function may take no arguments at all.
6363      * <p>
6364      * <em>Loop parameters:</em>
6365      * A clause function may take all the iteration variable values it is entitled to, in which case
6366      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6367      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6368      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6369      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6370      * init function is automatically a loop parameter {@code a}.)
6371      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6372      * These loop parameters act as loop-invariant values visible across the whole loop.
6373      * <p>
6374      * <em>Parameters visible everywhere:</em>
6375      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6376      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6377      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6378      * Most clause functions will not need all of this information, but they will be formally connected to it
6379      * as if by {@link #dropArguments}.
6380      * <a id="astar"></a>
6381      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6382      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6383      * In that notation, the general form of an init function parameter list
6384      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6385      * <p>
6386      * <em>Checking clause structure:</em>
6387      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6388      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6389      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6390      * met by the inputs to the loop combinator.
6391      * <p>
6392      * <em>Effectively identical sequences:</em>
6393      * <a id="effid"></a>
6394      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6395      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6396      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6397      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6398      * that longest list.
6399      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6400      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6401      * <p>
6402      * <em>Step 0: Determine clause structure.</em><ol type="a">
6403      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6404      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6405      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6406      * four. Padding takes place by appending elements to the array.
6407      * <li>Clauses with all {@code null}s are disregarded.
6408      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6409      * </ol>
6410      * <p>
6411      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6412      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6413      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6414      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6415      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6416      * iteration variable type.
6417      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6418      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6419      * </ol>
6420      * <p>
6421      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6422      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6423      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6424      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6425      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6426      * (These types will be checked in step 2, along with all the clause function types.)
6427      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6428      * <li>All of the collected parameter lists must be effectively identical.
6429      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6430      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6431      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6432      * the "internal parameter list".
6433      * </ul>
6434      * <p>
6435      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6436      * <li>Examine fini function return types, disregarding omitted fini functions.
6437      * <li>If there are no fini functions, the loop return type is {@code void}.
6438      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6439      * type.
6440      * </ol>
6441      * <p>
6442      * <em>Step 1D: Check other types.</em><ol type="a">
6443      * <li>There must be at least one non-omitted pred function.
6444      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6445      * </ol>
6446      * <p>
6447      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6448      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6449      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6450      * (Note that their parameter lists are already effectively identical to this list.)
6451      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6452      * effectively identical to the internal parameter list {@code (V... A...)}.
6453      * </ol>
6454      * <p>
6455      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6456      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6457      * type.
6458      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6459      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6460      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6461      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6462      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6463      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6464      * loop return type.
6465      * </ol>
6466      * <p>
6467      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6468      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6469      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6470      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6471      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6472      * pad out the end of the list.
6473      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6474      * </ol>
6475      * <p>
6476      * <em>Final observations.</em><ol type="a">
6477      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6478      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6479      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6480      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6481      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6482      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6483      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6484      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6485      * </ol>
6486      * <p>
6487      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6488      * <ul>
6489      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6490      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6491      * (Only one {@code Pn} has to be non-{@code null}.)
6492      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6493      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6494      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6495      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6496      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6497      * the resulting loop handle's parameter types {@code (A...)}.
6498      * </ul>
6499      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6500      * which is natural if most of the loop computation happens in the steps.  For some loops,
6501      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6502      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6503      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6504      * where the init functions will need the extra parameters.  For such reasons, the rules for
6505      * determining these parameters are as symmetric as possible, across all clause parts.
6506      * In general, the loop parameters function as common invariant values across the whole
6507      * loop, while the iteration variables function as common variant values, or (if there is
6508      * no step function) as internal loop invariant temporaries.
6509      * <p>
6510      * <em>Loop execution.</em><ol type="a">
6511      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6512      * every clause function. These locals are loop invariant.
6513      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6514      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6515      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6516      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6517      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6518      * (in argument order).
6519      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6520      * returns {@code false}.
6521      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6522      * sequence {@code (v...)} of loop variables.
6523      * The updated value is immediately visible to all subsequent function calls.
6524      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6525      * (of type {@code R}) is returned from the loop as a whole.
6526      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6527      * except by throwing an exception.
6528      * </ol>
6529      * <p>
6530      * <em>Usage tips.</em>
6531      * <ul>
6532      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6533      * sometimes a step function only needs to observe the current value of its own variable.
6534      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6535      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6536      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6537      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6538      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6539      * <li>If some of the clause functions are virtual methods on an instance, the instance
6540      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6541      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6542      * will be the first iteration variable value, and it will be easy to use virtual
6543      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6544      * </ul>
6545      * <p>
6546      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6547      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6548      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6549      * <blockquote><pre>{@code
6550      * V... init...(A...);
6551      * boolean pred...(V..., A...);
6552      * V... step...(V..., A...);
6553      * R fini...(V..., A...);
6554      * R loop(A... a) {
6555      *   V... v... = init...(a...);
6556      *   for (;;) {
6557      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6558      *       v = s(v..., a...);
6559      *       if (!p(v..., a...)) {
6560      *         return f(v..., a...);
6561      *       }
6562      *     }
6563      *   }
6564      * }
6565      * }</pre></blockquote>
6566      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6567      * to their full length, even though individual clause functions may neglect to take them all.
6568      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6569      *
6570      * @apiNote Example:
6571      * <blockquote><pre>{@code
6572      * // iterative implementation of the factorial function as a loop handle
6573      * static int one(int k) { return 1; }
6574      * static int inc(int i, int acc, int k) { return i + 1; }
6575      * static int mult(int i, int acc, int k) { return i * acc; }
6576      * static boolean pred(int i, int acc, int k) { return i < k; }
6577      * static int fin(int i, int acc, int k) { return acc; }
6578      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6579      * // null initializer for counter, should initialize to 0
6580      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6581      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6582      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6583      * assertEquals(120, loop.invoke(5));
6584      * }</pre></blockquote>
6585      * The same example, dropping arguments and using combinators:
6586      * <blockquote><pre>{@code
6587      * // simplified implementation of the factorial function as a loop handle
6588      * static int inc(int i) { return i + 1; } // drop acc, k
6589      * static int mult(int i, int acc) { return i * acc; } //drop k
6590      * static boolean cmp(int i, int k) { return i < k; }
6591      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6592      * // null initializer for counter, should initialize to 0
6593      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6594      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6595      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6596      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6597      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6598      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6599      * assertEquals(720, loop.invoke(6));
6600      * }</pre></blockquote>
6601      * A similar example, using a helper object to hold a loop parameter:
6602      * <blockquote><pre>{@code
6603      * // instance-based implementation of the factorial function as a loop handle
6604      * static class FacLoop {
6605      *   final int k;
6606      *   FacLoop(int k) { this.k = k; }
6607      *   int inc(int i) { return i + 1; }
6608      *   int mult(int i, int acc) { return i * acc; }
6609      *   boolean pred(int i) { return i < k; }
6610      *   int fin(int i, int acc) { return acc; }
6611      * }
6612      * // assume MH_FacLoop is a handle to the constructor
6613      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6614      * // null initializer for counter, should initialize to 0
6615      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6616      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6617      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6618      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6619      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6620      * assertEquals(5040, loop.invoke(7));
6621      * }</pre></blockquote>
6622      *
6623      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6624      *
6625      * @return a method handle embodying the looping behavior as defined by the arguments.
6626      *
6627      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6628      *
6629      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6630      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6631      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6632      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6633      * @since 9
6634      */
6635     public static MethodHandle loop(MethodHandle[]... clauses) {
6636         // Step 0: determine clause structure.
6637         loopChecks0(clauses);
6638 
6639         List<MethodHandle> init = new ArrayList<>();
6640         List<MethodHandle> step = new ArrayList<>();
6641         List<MethodHandle> pred = new ArrayList<>();
6642         List<MethodHandle> fini = new ArrayList<>();
6643 
6644         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6645             init.add(clause[0]); // all clauses have at least length 1
6646             step.add(clause.length <= 1 ? null : clause[1]);
6647             pred.add(clause.length <= 2 ? null : clause[2]);
6648             fini.add(clause.length <= 3 ? null : clause[3]);
6649         });
6650 
6651         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6652         final int nclauses = init.size();
6653 
6654         // Step 1A: determine iteration variables (V...).
6655         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6656         for (int i = 0; i < nclauses; ++i) {
6657             MethodHandle in = init.get(i);
6658             MethodHandle st = step.get(i);
6659             if (in == null && st == null) {
6660                 iterationVariableTypes.add(void.class);
6661             } else if (in != null && st != null) {
6662                 loopChecks1a(i, in, st);
6663                 iterationVariableTypes.add(in.type().returnType());
6664             } else {
6665                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6666             }
6667         }
6668         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6669 
6670         // Step 1B: determine loop parameters (A...).
6671         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6672         loopChecks1b(init, commonSuffix);
6673 
6674         // Step 1C: determine loop return type.
6675         // Step 1D: check other types.
6676         // local variable required here; see JDK-8223553
6677         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6678                 .map(MethodType::returnType);
6679         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6680         loopChecks1cd(pred, fini, loopReturnType);
6681 
6682         // Step 2: determine parameter lists.
6683         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6684         commonParameterSequence.addAll(commonSuffix);
6685         loopChecks2(step, pred, fini, commonParameterSequence);
6686 
6687         // Step 3: fill in omitted functions.
6688         for (int i = 0; i < nclauses; ++i) {
6689             Class<?> t = iterationVariableTypes.get(i);
6690             if (init.get(i) == null) {
6691                 init.set(i, empty(methodType(t, commonSuffix)));
6692             }
6693             if (step.get(i) == null) {
6694                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6695             }
6696             if (pred.get(i) == null) {
6697                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6698             }
6699             if (fini.get(i) == null) {
6700                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6701             }
6702         }
6703 
6704         // Step 4: fill in missing parameter types.
6705         // Also convert all handles to fixed-arity handles.
6706         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6707         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6708         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6709         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6710 
6711         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6712                 allMatch(pl -> pl.equals(commonSuffix));
6713         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6714                 allMatch(pl -> pl.equals(commonParameterSequence));
6715 
6716         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6717     }
6718 
6719     private static void loopChecks0(MethodHandle[][] clauses) {
6720         if (clauses == null || clauses.length == 0) {
6721             throw newIllegalArgumentException("null or no clauses passed");
6722         }
6723         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6724             throw newIllegalArgumentException("null clauses are not allowed");
6725         }
6726         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6727             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6728         }
6729     }
6730 
6731     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6732         if (in.type().returnType() != st.type().returnType()) {
6733             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6734                     st.type().returnType());
6735         }
6736     }
6737 
6738     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6739         final List<Class<?>> empty = List.of();
6740         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6741                 // take only those that can contribute to a common suffix because they are longer than the prefix
6742                         map(MethodHandle::type).
6743                         filter(t -> t.parameterCount() > skipSize).
6744                         map(MethodType::parameterList).
6745                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6746         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6747     }
6748 
6749     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6750         final List<Class<?>> empty = List.of();
6751         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6752     }
6753 
6754     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6755         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6756         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6757         return longestParameterList(Arrays.asList(longest1, longest2));
6758     }
6759 
6760     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6761         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6762                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6763             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6764                     " (common suffix: " + commonSuffix + ")");
6765         }
6766     }
6767 
6768     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6769         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6770                 anyMatch(t -> t != loopReturnType)) {
6771             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6772                     loopReturnType + ")");
6773         }
6774 
6775         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6776             throw newIllegalArgumentException("no predicate found", pred);
6777         }
6778         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6779                 anyMatch(t -> t != boolean.class)) {
6780             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6781         }
6782     }
6783 
6784     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6785         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6786                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6787             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6788                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6789         }
6790     }
6791 
6792     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6793         return hs.stream().map(h -> {
6794             int pc = h.type().parameterCount();
6795             int tpsize = targetParams.size();
6796             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6797         }).toList();
6798     }
6799 
6800     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6801         return hs.stream().map(MethodHandle::asFixedArity).toList();
6802     }
6803 
6804     /**
6805      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6806      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6807      * <p>
6808      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6809      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6810      * evaluates to {@code true}).
6811      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6812      * <p>
6813      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6814      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6815      * and updated with the value returned from its invocation. The result of loop execution will be
6816      * the final value of the additional loop-local variable (if present).
6817      * <p>
6818      * The following rules hold for these argument handles:<ul>
6819      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6820      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6821      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6822      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6823      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6824      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6825      * It will constrain the parameter lists of the other loop parts.
6826      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6827      * list {@code (A...)} is called the <em>external parameter list</em>.
6828      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6829      * additional state variable of the loop.
6830      * The body must both accept and return a value of this type {@code V}.
6831      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6832      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6833      * <a href="MethodHandles.html#effid">effectively identical</a>
6834      * to the external parameter list {@code (A...)}.
6835      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6836      * {@linkplain #empty default value}.
6837      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6838      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6839      * effectively identical to the internal parameter list.
6840      * </ul>
6841      * <p>
6842      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6843      * <li>The loop handle's result type is the result type {@code V} of the body.
6844      * <li>The loop handle's parameter types are the types {@code (A...)},
6845      * from the external parameter list.
6846      * </ul>
6847      * <p>
6848      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6849      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6850      * passed to the loop.
6851      * <blockquote><pre>{@code
6852      * V init(A...);
6853      * boolean pred(V, A...);
6854      * V body(V, A...);
6855      * V whileLoop(A... a...) {
6856      *   V v = init(a...);
6857      *   while (pred(v, a...)) {
6858      *     v = body(v, a...);
6859      *   }
6860      *   return v;
6861      * }
6862      * }</pre></blockquote>
6863      *
6864      * @apiNote Example:
6865      * <blockquote><pre>{@code
6866      * // implement the zip function for lists as a loop handle
6867      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6868      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6869      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6870      *   zip.add(a.next());
6871      *   zip.add(b.next());
6872      *   return zip;
6873      * }
6874      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6875      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6876      * List<String> a = Arrays.asList("a", "b", "c", "d");
6877      * List<String> b = Arrays.asList("e", "f", "g", "h");
6878      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6879      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6880      * }</pre></blockquote>
6881      *
6882      *
6883      * @apiNote The implementation of this method can be expressed as follows:
6884      * <blockquote><pre>{@code
6885      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6886      *     MethodHandle fini = (body.type().returnType() == void.class
6887      *                         ? null : identity(body.type().returnType()));
6888      *     MethodHandle[]
6889      *         checkExit = { null, null, pred, fini },
6890      *         varBody   = { init, body };
6891      *     return loop(checkExit, varBody);
6892      * }
6893      * }</pre></blockquote>
6894      *
6895      * @param init optional initializer, providing the initial value of the loop variable.
6896      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6897      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6898      *             above for other constraints.
6899      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6900      *             See above for other constraints.
6901      *
6902      * @return a method handle implementing the {@code while} loop as described by the arguments.
6903      * @throws IllegalArgumentException if the rules for the arguments are violated.
6904      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6905      *
6906      * @see #loop(MethodHandle[][])
6907      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6908      * @since 9
6909      */
6910     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6911         whileLoopChecks(init, pred, body);
6912         MethodHandle fini = identityOrVoid(body.type().returnType());
6913         MethodHandle[] checkExit = { null, null, pred, fini };
6914         MethodHandle[] varBody = { init, body };
6915         return loop(checkExit, varBody);
6916     }
6917 
6918     /**
6919      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6920      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6921      * <p>
6922      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6923      * method will, in each iteration, first execute its body and then evaluate the predicate.
6924      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6925      * <p>
6926      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6927      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6928      * and updated with the value returned from its invocation. The result of loop execution will be
6929      * the final value of the additional loop-local variable (if present).
6930      * <p>
6931      * The following rules hold for these argument handles:<ul>
6932      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6933      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6934      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6935      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6936      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6937      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6938      * It will constrain the parameter lists of the other loop parts.
6939      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6940      * list {@code (A...)} is called the <em>external parameter list</em>.
6941      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6942      * additional state variable of the loop.
6943      * The body must both accept and return a value of this type {@code V}.
6944      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6945      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6946      * <a href="MethodHandles.html#effid">effectively identical</a>
6947      * to the external parameter list {@code (A...)}.
6948      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6949      * {@linkplain #empty default value}.
6950      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6951      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6952      * effectively identical to the internal parameter list.
6953      * </ul>
6954      * <p>
6955      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6956      * <li>The loop handle's result type is the result type {@code V} of the body.
6957      * <li>The loop handle's parameter types are the types {@code (A...)},
6958      * from the external parameter list.
6959      * </ul>
6960      * <p>
6961      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6962      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6963      * passed to the loop.
6964      * <blockquote><pre>{@code
6965      * V init(A...);
6966      * boolean pred(V, A...);
6967      * V body(V, A...);
6968      * V doWhileLoop(A... a...) {
6969      *   V v = init(a...);
6970      *   do {
6971      *     v = body(v, a...);
6972      *   } while (pred(v, a...));
6973      *   return v;
6974      * }
6975      * }</pre></blockquote>
6976      *
6977      * @apiNote Example:
6978      * <blockquote><pre>{@code
6979      * // int i = 0; while (i < limit) { ++i; } return i; => limit
6980      * static int zero(int limit) { return 0; }
6981      * static int step(int i, int limit) { return i + 1; }
6982      * static boolean pred(int i, int limit) { return i < limit; }
6983      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6984      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6985      * assertEquals(23, loop.invoke(23));
6986      * }</pre></blockquote>
6987      *
6988      *
6989      * @apiNote The implementation of this method can be expressed as follows:
6990      * <blockquote><pre>{@code
6991      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6992      *     MethodHandle fini = (body.type().returnType() == void.class
6993      *                         ? null : identity(body.type().returnType()));
6994      *     MethodHandle[] clause = { init, body, pred, fini };
6995      *     return loop(clause);
6996      * }
6997      * }</pre></blockquote>
6998      *
6999      * @param init optional initializer, providing the initial value of the loop variable.
7000      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7001      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7002      *             See above for other constraints.
7003      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7004      *             above for other constraints.
7005      *
7006      * @return a method handle implementing the {@code while} loop as described by the arguments.
7007      * @throws IllegalArgumentException if the rules for the arguments are violated.
7008      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7009      *
7010      * @see #loop(MethodHandle[][])
7011      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7012      * @since 9
7013      */
7014     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7015         whileLoopChecks(init, pred, body);
7016         MethodHandle fini = identityOrVoid(body.type().returnType());
7017         MethodHandle[] clause = {init, body, pred, fini };
7018         return loop(clause);
7019     }
7020 
7021     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7022         Objects.requireNonNull(pred);
7023         Objects.requireNonNull(body);
7024         MethodType bodyType = body.type();
7025         Class<?> returnType = bodyType.returnType();
7026         List<Class<?>> innerList = bodyType.parameterList();
7027         List<Class<?>> outerList = innerList;
7028         if (returnType == void.class) {
7029             // OK
7030         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7031             // leading V argument missing => error
7032             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7033             throw misMatchedTypes("body function", bodyType, expected);
7034         } else {
7035             outerList = innerList.subList(1, innerList.size());
7036         }
7037         MethodType predType = pred.type();
7038         if (predType.returnType() != boolean.class ||
7039                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7040             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7041         }
7042         if (init != null) {
7043             MethodType initType = init.type();
7044             if (initType.returnType() != returnType ||
7045                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7046                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7047             }
7048         }
7049     }
7050 
7051     /**
7052      * Constructs a loop that runs a given number of iterations.
7053      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7054      * <p>
7055      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7056      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7057      * It will be initialized to 0 and incremented by 1 in each iteration.
7058      * <p>
7059      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7060      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7061      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7062      * <p>
7063      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7064      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7065      * iteration variable.
7066      * The result of the loop handle execution will be the final {@code V} value of that variable
7067      * (or {@code void} if there is no {@code V} variable).
7068      * <p>
7069      * The following rules hold for the argument handles:<ul>
7070      * <li>The {@code iterations} handle must not be {@code null}, and must return
7071      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7072      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7073      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7074      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7075      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7076      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7077      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7078      * of types called the <em>internal parameter list</em>.
7079      * It will constrain the parameter lists of the other loop parts.
7080      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7081      * with no additional {@code A} types, then the internal parameter list is extended by
7082      * the argument types {@code A...} of the {@code iterations} handle.
7083      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7084      * list {@code (A...)} is called the <em>external parameter list</em>.
7085      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7086      * additional state variable of the loop.
7087      * The body must both accept a leading parameter and return a value of this type {@code V}.
7088      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7089      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7090      * <a href="MethodHandles.html#effid">effectively identical</a>
7091      * to the external parameter list {@code (A...)}.
7092      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7093      * {@linkplain #empty default value}.
7094      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7095      * effectively identical to the external parameter list {@code (A...)}.
7096      * </ul>
7097      * <p>
7098      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7099      * <li>The loop handle's result type is the result type {@code V} of the body.
7100      * <li>The loop handle's parameter types are the types {@code (A...)},
7101      * from the external parameter list.
7102      * </ul>
7103      * <p>
7104      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7105      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7106      * arguments passed to the loop.
7107      * <blockquote><pre>{@code
7108      * int iterations(A...);
7109      * V init(A...);
7110      * V body(V, int, A...);
7111      * V countedLoop(A... a...) {
7112      *   int end = iterations(a...);
7113      *   V v = init(a...);
7114      *   for (int i = 0; i < end; ++i) {
7115      *     v = body(v, i, a...);
7116      *   }
7117      *   return v;
7118      * }
7119      * }</pre></blockquote>
7120      *
7121      * @apiNote Example with a fully conformant body method:
7122      * <blockquote><pre>{@code
7123      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7124      * // => a variation on a well known theme
7125      * static String step(String v, int counter, String init) { return "na " + v; }
7126      * // assume MH_step is a handle to the method above
7127      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7128      * MethodHandle start = MethodHandles.identity(String.class);
7129      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7130      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7131      * }</pre></blockquote>
7132      *
7133      * @apiNote Example with the simplest possible body method type,
7134      * and passing the number of iterations to the loop invocation:
7135      * <blockquote><pre>{@code
7136      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7137      * // => a variation on a well known theme
7138      * static String step(String v, int counter ) { return "na " + v; }
7139      * // assume MH_step is a handle to the method above
7140      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7141      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7142      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7143      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7144      * }</pre></blockquote>
7145      *
7146      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7147      * as loop parameters:
7148      * <blockquote><pre>{@code
7149      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7150      * // => a variation on a well known theme
7151      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7152      * // assume MH_step is a handle to the method above
7153      * MethodHandle count = MethodHandles.identity(int.class);
7154      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7155      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7156      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7157      * }</pre></blockquote>
7158      *
7159      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7160      * to enforce a loop type:
7161      * <blockquote><pre>{@code
7162      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7163      * // => a variation on a well known theme
7164      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7165      * // assume MH_step is a handle to the method above
7166      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7167      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7168      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7169      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7170      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7171      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7172      * }</pre></blockquote>
7173      *
7174      * @apiNote The implementation of this method can be expressed as follows:
7175      * <blockquote><pre>{@code
7176      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7177      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7178      * }
7179      * }</pre></blockquote>
7180      *
7181      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7182      *                   result type must be {@code int}. See above for other constraints.
7183      * @param init optional initializer, providing the initial value of the loop variable.
7184      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7185      * @param body body of the loop, which may not be {@code null}.
7186      *             It controls the loop parameters and result type in the standard case (see above for details).
7187      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7188      *             and may accept any number of additional types.
7189      *             See above for other constraints.
7190      *
7191      * @return a method handle representing the loop.
7192      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7193      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7194      *
7195      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7196      * @since 9
7197      */
7198     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7199         return countedLoop(empty(iterations.type()), iterations, init, body);
7200     }
7201 
7202     /**
7203      * Constructs a loop that counts over a range of numbers.
7204      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7205      * <p>
7206      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7207      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7208      * values of the loop counter.
7209      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7210      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7211      * <p>
7212      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7213      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7214      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7215      * <p>
7216      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7217      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7218      * iteration variable.
7219      * The result of the loop handle execution will be the final {@code V} value of that variable
7220      * (or {@code void} if there is no {@code V} variable).
7221      * <p>
7222      * The following rules hold for the argument handles:<ul>
7223      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7224      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7225      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7226      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7227      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7228      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7229      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7230      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7231      * of types called the <em>internal parameter list</em>.
7232      * It will constrain the parameter lists of the other loop parts.
7233      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7234      * with no additional {@code A} types, then the internal parameter list is extended by
7235      * the argument types {@code A...} of the {@code end} handle.
7236      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7237      * list {@code (A...)} is called the <em>external parameter list</em>.
7238      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7239      * additional state variable of the loop.
7240      * The body must both accept a leading parameter and return a value of this type {@code V}.
7241      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7242      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7243      * <a href="MethodHandles.html#effid">effectively identical</a>
7244      * to the external parameter list {@code (A...)}.
7245      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7246      * {@linkplain #empty default value}.
7247      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7248      * effectively identical to the external parameter list {@code (A...)}.
7249      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7250      * to the external parameter list.
7251      * </ul>
7252      * <p>
7253      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7254      * <li>The loop handle's result type is the result type {@code V} of the body.
7255      * <li>The loop handle's parameter types are the types {@code (A...)},
7256      * from the external parameter list.
7257      * </ul>
7258      * <p>
7259      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7260      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7261      * arguments passed to the loop.
7262      * <blockquote><pre>{@code
7263      * int start(A...);
7264      * int end(A...);
7265      * V init(A...);
7266      * V body(V, int, A...);
7267      * V countedLoop(A... a...) {
7268      *   int e = end(a...);
7269      *   int s = start(a...);
7270      *   V v = init(a...);
7271      *   for (int i = s; i < e; ++i) {
7272      *     v = body(v, i, a...);
7273      *   }
7274      *   return v;
7275      * }
7276      * }</pre></blockquote>
7277      *
7278      * @apiNote The implementation of this method can be expressed as follows:
7279      * <blockquote><pre>{@code
7280      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7281      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7282      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7283      *     // the following semantics:
7284      *     // MH_increment: (int limit, int counter) -> counter + 1
7285      *     // MH_predicate: (int limit, int counter) -> counter < limit
7286      *     Class<?> counterType = start.type().returnType();  // int
7287      *     Class<?> returnType = body.type().returnType();
7288      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7289      *     if (returnType != void.class) {  // ignore the V variable
7290      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7291      *         pred = dropArguments(pred, 1, returnType);  // ditto
7292      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7293      *     }
7294      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7295      *     MethodHandle[]
7296      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7297      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7298      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7299      *     return loop(loopLimit, bodyClause, indexVar);
7300      * }
7301      * }</pre></blockquote>
7302      *
7303      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7304      *              See above for other constraints.
7305      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7306      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7307      * @param init optional initializer, providing the initial value of the loop variable.
7308      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7309      * @param body body of the loop, which may not be {@code null}.
7310      *             It controls the loop parameters and result type in the standard case (see above for details).
7311      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7312      *             and may accept any number of additional types.
7313      *             See above for other constraints.
7314      *
7315      * @return a method handle representing the loop.
7316      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7317      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7318      *
7319      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7320      * @since 9
7321      */
7322     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7323         countedLoopChecks(start, end, init, body);
7324         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7325         Class<?> limitType   = end.type().returnType();    // yes, int again
7326         Class<?> returnType  = body.type().returnType();
7327         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7328         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7329         MethodHandle retv = null;
7330         if (returnType != void.class) {
7331             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7332             pred = dropArguments(pred, 1, returnType);  // ditto
7333             retv = dropArguments(identity(returnType), 0, counterType);
7334         }
7335         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7336         MethodHandle[]
7337             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7338             bodyClause = { init, body },            // v = init(); v = body(v, i)
7339             indexVar   = { start, incr };           // i = start(); i = i + 1
7340         return loop(loopLimit, bodyClause, indexVar);
7341     }
7342 
7343     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7344         Objects.requireNonNull(start);
7345         Objects.requireNonNull(end);
7346         Objects.requireNonNull(body);
7347         Class<?> counterType = start.type().returnType();
7348         if (counterType != int.class) {
7349             MethodType expected = start.type().changeReturnType(int.class);
7350             throw misMatchedTypes("start function", start.type(), expected);
7351         } else if (end.type().returnType() != counterType) {
7352             MethodType expected = end.type().changeReturnType(counterType);
7353             throw misMatchedTypes("end function", end.type(), expected);
7354         }
7355         MethodType bodyType = body.type();
7356         Class<?> returnType = bodyType.returnType();
7357         List<Class<?>> innerList = bodyType.parameterList();
7358         // strip leading V value if present
7359         int vsize = (returnType == void.class ? 0 : 1);
7360         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7361             // argument list has no "V" => error
7362             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7363             throw misMatchedTypes("body function", bodyType, expected);
7364         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7365             // missing I type => error
7366             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7367             throw misMatchedTypes("body function", bodyType, expected);
7368         }
7369         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7370         if (outerList.isEmpty()) {
7371             // special case; take lists from end handle
7372             outerList = end.type().parameterList();
7373             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7374         }
7375         MethodType expected = methodType(counterType, outerList);
7376         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7377             throw misMatchedTypes("start parameter types", start.type(), expected);
7378         }
7379         if (end.type() != start.type() &&
7380             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7381             throw misMatchedTypes("end parameter types", end.type(), expected);
7382         }
7383         if (init != null) {
7384             MethodType initType = init.type();
7385             if (initType.returnType() != returnType ||
7386                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7387                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7388             }
7389         }
7390     }
7391 
7392     /**
7393      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7394      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7395      * <p>
7396      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7397      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7398      * <p>
7399      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7400      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7401      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7402      * <p>
7403      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7404      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7405      * iteration variable.
7406      * The result of the loop handle execution will be the final {@code V} value of that variable
7407      * (or {@code void} if there is no {@code V} variable).
7408      * <p>
7409      * The following rules hold for the argument handles:<ul>
7410      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7411      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7412      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7413      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7414      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7415      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7416      * of types called the <em>internal parameter list</em>.
7417      * It will constrain the parameter lists of the other loop parts.
7418      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7419      * with no additional {@code A} types, then the internal parameter list is extended by
7420      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7421      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7422      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7423      * list {@code (A...)} is called the <em>external parameter list</em>.
7424      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7425      * additional state variable of the loop.
7426      * The body must both accept a leading parameter and return a value of this type {@code V}.
7427      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7428      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7429      * <a href="MethodHandles.html#effid">effectively identical</a>
7430      * to the external parameter list {@code (A...)}.
7431      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7432      * {@linkplain #empty default value}.
7433      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7434      * type {@code java.util.Iterator} or a subtype thereof.
7435      * The iterator it produces when the loop is executed will be assumed
7436      * to yield values which can be converted to type {@code T}.
7437      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7438      * effectively identical to the external parameter list {@code (A...)}.
7439      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7440      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7441      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7442      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7443      * the {@link MethodHandle#asType asType} conversion method.
7444      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7445      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7446      * </ul>
7447      * <p>
7448      * The type {@code T} may be either a primitive or reference.
7449      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7450      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7451      * as if by the {@link MethodHandle#asType asType} conversion method.
7452      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7453      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7454      * <p>
7455      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7456      * <li>The loop handle's result type is the result type {@code V} of the body.
7457      * <li>The loop handle's parameter types are the types {@code (A...)},
7458      * from the external parameter list.
7459      * </ul>
7460      * <p>
7461      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7462      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7463      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7464      * <blockquote><pre>{@code
7465      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7466      * V init(A...);
7467      * V body(V,T,A...);
7468      * V iteratedLoop(A... a...) {
7469      *   Iterator<T> it = iterator(a...);
7470      *   V v = init(a...);
7471      *   while (it.hasNext()) {
7472      *     T t = it.next();
7473      *     v = body(v, t, a...);
7474      *   }
7475      *   return v;
7476      * }
7477      * }</pre></blockquote>
7478      *
7479      * @apiNote Example:
7480      * <blockquote><pre>{@code
7481      * // get an iterator from a list
7482      * static List<String> reverseStep(List<String> r, String e) {
7483      *   r.add(0, e);
7484      *   return r;
7485      * }
7486      * static List<String> newArrayList() { return new ArrayList<>(); }
7487      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7488      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7489      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7490      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7491      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7492      * }</pre></blockquote>
7493      *
7494      * @apiNote The implementation of this method can be expressed approximately as follows:
7495      * <blockquote><pre>{@code
7496      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7497      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7498      *     Class<?> returnType = body.type().returnType();
7499      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7500      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7501      *     MethodHandle retv = null, step = body, startIter = iterator;
7502      *     if (returnType != void.class) {
7503      *         // the simple thing first:  in (I V A...), drop the I to get V
7504      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7505      *         // body type signature (V T A...), internal loop types (I V A...)
7506      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7507      *     }
7508      *     if (startIter == null)  startIter = MH_getIter;
7509      *     MethodHandle[]
7510      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7511      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7512      *     return loop(iterVar, bodyClause);
7513      * }
7514      * }</pre></blockquote>
7515      *
7516      * @param iterator an optional handle to return the iterator to start the loop.
7517      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7518      *                 See above for other constraints.
7519      * @param init optional initializer, providing the initial value of the loop variable.
7520      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7521      * @param body body of the loop, which may not be {@code null}.
7522      *             It controls the loop parameters and result type in the standard case (see above for details).
7523      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7524      *             and may accept any number of additional types.
7525      *             See above for other constraints.
7526      *
7527      * @return a method handle embodying the iteration loop functionality.
7528      * @throws NullPointerException if the {@code body} handle is {@code null}.
7529      * @throws IllegalArgumentException if any argument violates the above requirements.
7530      *
7531      * @since 9
7532      */
7533     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7534         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7535         Class<?> returnType = body.type().returnType();
7536         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7537         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7538         MethodHandle startIter;
7539         MethodHandle nextVal;
7540         {
7541             MethodType iteratorType;
7542             if (iterator == null) {
7543                 // derive argument type from body, if available, else use Iterable
7544                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7545                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7546             } else {
7547                 // force return type to the internal iterator class
7548                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7549                 startIter = iterator;
7550             }
7551             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7552             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7553 
7554             // perform the asType transforms under an exception transformer, as per spec.:
7555             try {
7556                 startIter = startIter.asType(iteratorType);
7557                 nextVal = nextRaw.asType(nextValType);
7558             } catch (WrongMethodTypeException ex) {
7559                 throw new IllegalArgumentException(ex);
7560             }
7561         }
7562 
7563         MethodHandle retv = null, step = body;
7564         if (returnType != void.class) {
7565             // the simple thing first:  in (I V A...), drop the I to get V
7566             retv = dropArguments(identity(returnType), 0, Iterator.class);
7567             // body type signature (V T A...), internal loop types (I V A...)
7568             step = swapArguments(body, 0, 1);  // swap V <-> T
7569         }
7570 
7571         MethodHandle[]
7572             iterVar    = { startIter, null, hasNext, retv },
7573             bodyClause = { init, filterArgument(step, 0, nextVal) };
7574         return loop(iterVar, bodyClause);
7575     }
7576 
7577     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7578         Objects.requireNonNull(body);
7579         MethodType bodyType = body.type();
7580         Class<?> returnType = bodyType.returnType();
7581         List<Class<?>> internalParamList = bodyType.parameterList();
7582         // strip leading V value if present
7583         int vsize = (returnType == void.class ? 0 : 1);
7584         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7585             // argument list has no "V" => error
7586             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7587             throw misMatchedTypes("body function", bodyType, expected);
7588         } else if (internalParamList.size() <= vsize) {
7589             // missing T type => error
7590             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7591             throw misMatchedTypes("body function", bodyType, expected);
7592         }
7593         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7594         Class<?> iterableType = null;
7595         if (iterator != null) {
7596             // special case; if the body handle only declares V and T then
7597             // the external parameter list is obtained from iterator handle
7598             if (externalParamList.isEmpty()) {
7599                 externalParamList = iterator.type().parameterList();
7600             }
7601             MethodType itype = iterator.type();
7602             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7603                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7604             }
7605             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7606                 MethodType expected = methodType(itype.returnType(), externalParamList);
7607                 throw misMatchedTypes("iterator parameters", itype, expected);
7608             }
7609         } else {
7610             if (externalParamList.isEmpty()) {
7611                 // special case; if the iterator handle is null and the body handle
7612                 // only declares V and T then the external parameter list consists
7613                 // of Iterable
7614                 externalParamList = Arrays.asList(Iterable.class);
7615                 iterableType = Iterable.class;
7616             } else {
7617                 // special case; if the iterator handle is null and the external
7618                 // parameter list is not empty then the first parameter must be
7619                 // assignable to Iterable
7620                 iterableType = externalParamList.get(0);
7621                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7622                     throw newIllegalArgumentException(
7623                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7624                 }
7625             }
7626         }
7627         if (init != null) {
7628             MethodType initType = init.type();
7629             if (initType.returnType() != returnType ||
7630                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7631                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7632             }
7633         }
7634         return iterableType;  // help the caller a bit
7635     }
7636 
7637     /*non-public*/
7638     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7639         // there should be a better way to uncross my wires
7640         int arity = mh.type().parameterCount();
7641         int[] order = new int[arity];
7642         for (int k = 0; k < arity; k++)  order[k] = k;
7643         order[i] = j; order[j] = i;
7644         Class<?>[] types = mh.type().parameterArray();
7645         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7646         MethodType swapType = methodType(mh.type().returnType(), types);
7647         return permuteArguments(mh, swapType, order);
7648     }
7649 
7650     /**
7651      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7652      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7653      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7654      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7655      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7656      * {@code try-finally} handle.
7657      * <p>
7658      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7659      * The first is the exception thrown during the
7660      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7661      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7662      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7663      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7664      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7665      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7666      * <p>
7667      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7668      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7669      * two extra leading parameters:<ul>
7670      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7671      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7672      * the result from the execution of the {@code target} handle.
7673      * This parameter is not present if the {@code target} returns {@code void}.
7674      * </ul>
7675      * <p>
7676      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7677      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7678      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7679      * the cleanup.
7680      * <blockquote><pre>{@code
7681      * V target(A..., B...);
7682      * V cleanup(Throwable, V, A...);
7683      * V adapter(A... a, B... b) {
7684      *   V result = (zero value for V);
7685      *   Throwable throwable = null;
7686      *   try {
7687      *     result = target(a..., b...);
7688      *   } catch (Throwable t) {
7689      *     throwable = t;
7690      *     throw t;
7691      *   } finally {
7692      *     result = cleanup(throwable, result, a...);
7693      *   }
7694      *   return result;
7695      * }
7696      * }</pre></blockquote>
7697      * <p>
7698      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7699      * be modified by execution of the target, and so are passed unchanged
7700      * from the caller to the cleanup, if it is invoked.
7701      * <p>
7702      * The target and cleanup must return the same type, even if the cleanup
7703      * always throws.
7704      * To create such a throwing cleanup, compose the cleanup logic
7705      * with {@link #throwException throwException},
7706      * in order to create a method handle of the correct return type.
7707      * <p>
7708      * Note that {@code tryFinally} never converts exceptions into normal returns.
7709      * In rare cases where exceptions must be converted in that way, first wrap
7710      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7711      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7712      * <p>
7713      * It is recommended that the first parameter type of {@code cleanup} be
7714      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7715      * {@code cleanup} will always be invoked with whatever exception that
7716      * {@code target} throws.  Declaring a narrower type may result in a
7717      * {@code ClassCastException} being thrown by the {@code try-finally}
7718      * handle if the type of the exception thrown by {@code target} is not
7719      * assignable to the first parameter type of {@code cleanup}.  Note that
7720      * various exception types of {@code VirtualMachineError},
7721      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7722      * thrown by almost any kind of Java code, and a finally clause that
7723      * catches (say) only {@code IOException} would mask any of the others
7724      * behind a {@code ClassCastException}.
7725      *
7726      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7727      * @param cleanup the handle that is invoked in the finally block.
7728      *
7729      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7730      * @throws NullPointerException if any argument is null
7731      * @throws IllegalArgumentException if {@code cleanup} does not accept
7732      *          the required leading arguments, or if the method handle types do
7733      *          not match in their return types and their
7734      *          corresponding trailing parameters
7735      *
7736      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7737      * @since 9
7738      */
7739     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7740         List<Class<?>> targetParamTypes = target.type().parameterList();
7741         Class<?> rtype = target.type().returnType();
7742 
7743         tryFinallyChecks(target, cleanup);
7744 
7745         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7746         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7747         // target parameter list.
7748         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7749 
7750         // Ensure that the intrinsic type checks the instance thrown by the
7751         // target against the first parameter of cleanup
7752         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7753 
7754         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7755         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7756     }
7757 
7758     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7759         Class<?> rtype = target.type().returnType();
7760         if (rtype != cleanup.type().returnType()) {
7761             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7762         }
7763         MethodType cleanupType = cleanup.type();
7764         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7765             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7766         }
7767         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7768             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7769         }
7770         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7771         // target parameter list.
7772         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7773         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7774             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7775                     cleanup.type(), target.type());
7776         }
7777     }
7778 
7779     /**
7780      * Creates a table switch method handle, which can be used to switch over a set of target
7781      * method handles, based on a given target index, called selector.
7782      * <p>
7783      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7784      * and where {@code N} is the number of target method handles, the table switch method
7785      * handle will invoke the n-th target method handle from the list of target method handles.
7786      * <p>
7787      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7788      * method handle will invoke the given fallback method handle.
7789      * <p>
7790      * All method handles passed to this method must have the same type, with the additional
7791      * requirement that the leading parameter be of type {@code int}. The leading parameter
7792      * represents the selector.
7793      * <p>
7794      * Any trailing parameters present in the type will appear on the returned table switch
7795      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7796      * together with the selector value, to the selected method handle when invoking it.
7797      *
7798      * @apiNote Example:
7799      * The cases each drop the {@code selector} value they are given, and take an additional
7800      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7801      * to a specific constant label string for each case:
7802      * <blockquote><pre>{@code
7803      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7804      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7805      *         MethodType.methodType(String.class, String.class));
7806      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7807      *
7808      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7809      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7810      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7811      *
7812      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7813      *     caseDefault,
7814      *     case0,
7815      *     case1
7816      * );
7817      *
7818      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7819      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7820      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7821      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7822      * }</pre></blockquote>
7823      *
7824      * @param fallback the fallback method handle that is called when the selector is not
7825      *                 within the range {@code [0, N)}.
7826      * @param targets array of target method handles.
7827      * @return the table switch method handle.
7828      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7829      *                              any of the elements of the {@code targets} array are
7830      *                              {@code null}.
7831      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7832      *                                  parameter of the fallback handle or any of the target
7833      *                                  handles is not {@code int}, or if the types of
7834      *                                  the fallback handle and all of target handles are
7835      *                                  not the same.
7836      */
7837     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7838         Objects.requireNonNull(fallback);
7839         Objects.requireNonNull(targets);
7840         targets = targets.clone();
7841         MethodType type = tableSwitchChecks(fallback, targets);
7842         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7843     }
7844 
7845     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7846         if (caseActions.length == 0)
7847             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7848 
7849         MethodType expectedType = defaultCase.type();
7850 
7851         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7852             throw new IllegalArgumentException(
7853                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7854 
7855         for (MethodHandle mh : caseActions) {
7856             Objects.requireNonNull(mh);
7857             if (mh.type() != expectedType)
7858                 throw new IllegalArgumentException(
7859                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7860         }
7861 
7862         return expectedType;
7863     }
7864 
7865 }