1 /*
   2  * Copyright (c) 2008, 2026, 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.reflect.CallerSensitive;
  32 import jdk.internal.reflect.CallerSensitiveAdapter;
  33 import jdk.internal.reflect.Reflection;
  34 import jdk.internal.util.ClassFileDumper;
  35 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 import jdk.internal.vm.annotation.Stable;
  38 import sun.invoke.util.ValueConversions;
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.Wrapper;
  41 
  42 import java.lang.classfile.ClassFile;
  43 import java.lang.classfile.ClassModel;
  44 import java.lang.constant.ClassDesc;
  45 import java.lang.constant.ConstantDescs;
  46 import java.lang.invoke.LambdaForm.BasicType;
  47 import java.lang.invoke.MethodHandleImpl.Intrinsic;
  48 import java.lang.reflect.Constructor;
  49 import java.lang.reflect.Field;
  50 import java.lang.reflect.Member;
  51 import java.lang.reflect.Method;
  52 import java.lang.reflect.Modifier;
  53 import java.nio.ByteOrder;
  54 import java.security.ProtectionDomain;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.BitSet;
  58 import java.util.Comparator;
  59 import java.util.Iterator;
  60 import java.util.List;
  61 import java.util.Objects;
  62 import java.util.Set;
  63 import java.util.concurrent.ConcurrentHashMap;
  64 import java.util.stream.Stream;
  65 
  66 import static java.lang.classfile.ClassFile.*;
  67 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  68 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  69 import static java.lang.invoke.MethodHandleStatics.*;
  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 @AOTSafeClassInitializer
  88 public final class MethodHandles {
  89 
  90     private MethodHandles() { }  // do not instantiate
  91 
  92     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  93 
  94     // See IMPL_LOOKUP below.
  95 
  96     //--- Method handle creation from ordinary methods.
  97 
  98     /**
  99      * Returns a {@link Lookup lookup object} with
 100      * full capabilities to emulate all supported bytecode behaviors of the caller.
 101      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 102      * Factory methods on the lookup object can create
 103      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 104      * for any member that the caller has access to via bytecodes,
 105      * including protected and private fields and methods.
 106      * This lookup object is created by the original lookup class
 107      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 108      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 109      * Do not store it in place where untrusted code can access it.
 110      * <p>
 111      * This method is caller sensitive, which means that it may return different
 112      * values to different callers.
 113      * In cases where {@code MethodHandles.lookup} is called from a context where
 114      * there is no caller frame on the stack (e.g. when called directly
 115      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 116      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 117      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 118      * to obtain a low-privileged lookup instead.
 119      * @return a lookup object for the caller of this method, with
 120      * {@linkplain Lookup#ORIGINAL original} and
 121      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 122      * @throws IllegalCallerException if there is no caller frame on the stack.
 123      */
 124     @CallerSensitive
 125     @ForceInline // to ensure Reflection.getCallerClass optimization
 126     public static Lookup lookup() {
 127         final Class<?> c = Reflection.getCallerClass();
 128         if (c == null) {
 129             throw new IllegalCallerException("no caller frame");
 130         }
 131         return new Lookup(c);
 132     }
 133 
 134     /**
 135      * This lookup method is the alternate implementation of
 136      * the lookup method with a leading caller class argument which is
 137      * non-caller-sensitive.  This method is only invoked by reflection
 138      * and method handle.
 139      */
 140     @CallerSensitiveAdapter
 141     private static Lookup lookup(Class<?> caller) {
 142         if (caller.getClassLoader() == null) {
 143             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 144         }
 145         return new Lookup(caller);
 146     }
 147 
 148     /**
 149      * Returns a {@link Lookup lookup object} which is trusted minimally.
 150      * The lookup has the {@code UNCONDITIONAL} mode.
 151      * It can only be used to create method handles to public members of
 152      * public classes in packages that are exported unconditionally.
 153      * <p>
 154      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 155      * of this lookup object will be {@link java.lang.Object}.
 156      *
 157      * @apiNote The use of Object is conventional, and because the lookup modes are
 158      * limited, there is no special access provided to the internals of Object, its package
 159      * or its module.  This public lookup object or other lookup object with
 160      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 161      * is not used to determine the lookup context.
 162      *
 163      * <p style="font-size:smaller;">
 164      * <em>Discussion:</em>
 165      * The lookup class can be changed to any other class {@code C} using an expression of the form
 166      * {@link Lookup#in publicLookup().in(C.class)}.
 167      * Also, it cannot access
 168      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 169      * @return a lookup object which is trusted minimally
 170      */
 171     public static Lookup publicLookup() {
 172         return Lookup.PUBLIC_LOOKUP;
 173     }
 174 
 175     /**
 176      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 177      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 178      * The returned lookup object can provide access to classes in modules and packages,
 179      * and members of those classes, outside the normal rules of Java access control,
 180      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 181      * <p>
 182      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 183      * allowed to do deep reflection on module {@code M2} and package of the target class
 184      * if and only if all of the following conditions are {@code true}:
 185      * <ul>
 186      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 187      * full privilege access}.  Specifically:
 188      *   <ul>
 189      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 190      *         (This is because otherwise there would be no way to ensure the original lookup
 191      *         creator was a member of any particular module, and so any subsequent checks
 192      *         for readability and qualified exports would become ineffective.)
 193      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 194      *         (This is because an application intending to share intra-module access
 195      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 196      *         deep reflection to its own module.)
 197      *   </ul>
 198      * <li>The target class must be a proper class, not a primitive or array class.
 199      * (Thus, {@code M2} is well-defined.)
 200      * <li>If the caller module {@code M1} differs from
 201      * the target module {@code M2} then both of the following must be true:
 202      *   <ul>
 203      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 204      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 205      *         containing the target class to at least {@code M1}.</li>
 206      *   </ul>
 207      * </ul>
 208      * <p>
 209      * If any of the above checks is violated, this method fails with an
 210      * exception.
 211      * <p>
 212      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 213      * returns a {@code Lookup} on {@code targetClass} with
 214      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 215      * with {@code null} previous lookup class.
 216      * <p>
 217      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 218      * returns a {@code Lookup} on {@code targetClass} that records
 219      * the lookup class of the caller as the new previous lookup class with
 220      * {@code PRIVATE} access but no {@code MODULE} access.
 221      * <p>
 222      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 223      *
 224      * @apiNote The {@code Lookup} object returned by this method is allowed to
 225      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 226      * of {@code targetClass}. Extreme caution should be taken when opening a package
 227      * to another module as such defined classes have the same full privilege
 228      * access as other members in {@code targetClass}'s module.
 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 IllegalAccessException if any of the other access checks specified above fails
 236      * @since 9
 237      * @see Lookup#dropLookupMode
 238      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 239      */
 240     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 241         if (caller.allowedModes == Lookup.TRUSTED) {
 242             return new Lookup(targetClass);
 243         }
 244 
 245         if (targetClass.isPrimitive())
 246             throw new IllegalArgumentException(targetClass + " is a primitive class");
 247         if (targetClass.isArray())
 248             throw new IllegalArgumentException(targetClass + " is an array class");
 249         // Ensure that we can reason accurately about private and module access.
 250         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 251         if ((caller.lookupModes() & requireAccess) != requireAccess)
 252             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 253 
 254         // previous lookup class is never set if it has MODULE access
 255         assert caller.previousLookupClass() == null;
 256 
 257         Class<?> callerClass = caller.lookupClass();
 258         Module callerModule = callerClass.getModule();  // M1
 259         Module targetModule = targetClass.getModule();  // M2
 260         Class<?> newPreviousClass = null;
 261         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 262 
 263         if (targetModule != callerModule) {
 264             if (!callerModule.canRead(targetModule))
 265                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 266             if (targetModule.isNamed()) {
 267                 String pn = targetClass.getPackageName();
 268                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 269                 if (!targetModule.isOpen(pn, callerModule))
 270                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 271             }
 272 
 273             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 274             newPreviousClass = callerClass;
 275             newModes &= ~Lookup.MODULE;
 276         }
 277         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 278     }
 279 
 280     /**
 281      * Returns the <em>class data</em> associated with the lookup class
 282      * of the given {@code caller} lookup object, or {@code null}.
 283      *
 284      * <p> A hidden class with class data can be created by calling
 285      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 286      * Lookup::defineHiddenClassWithClassData}.
 287      * This method will cause the static class initializer of the lookup
 288      * class of the given {@code caller} lookup object be executed if
 289      * it has not been initialized.
 290      *
 291      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 292      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 293      * {@code null} is returned if this method is called on the lookup object
 294      * on these classes.
 295      *
 296      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 297      * must have {@linkplain Lookup#ORIGINAL original access}
 298      * in order to retrieve the class data.
 299      *
 300      * @apiNote
 301      * This method can be called as a bootstrap method for a dynamically computed
 302      * constant.  A framework can create a hidden class with class data, for
 303      * example that can be {@code Class} or {@code MethodHandle} object.
 304      * The class data is accessible only to the lookup object
 305      * created by the original caller but inaccessible to other members
 306      * in the same nest.  If a framework passes security sensitive objects
 307      * to a hidden class via class data, it is recommended to load the value
 308      * of class data as a dynamically computed constant instead of storing
 309      * the class data in private static field(s) which are accessible to
 310      * other nestmates.
 311      *
 312      * @param <T> the type to cast the class data object to
 313      * @param caller the lookup context describing the class performing the
 314      * operation (normally stacked by the JVM)
 315      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 316      *             ({@code "_"})
 317      * @param type the type of the class data
 318      * @return the value of the class data if present in the lookup class;
 319      * otherwise {@code null}
 320      * @throws IllegalArgumentException if name is not {@code "_"}
 321      * @throws IllegalAccessException if the lookup context does not have
 322      * {@linkplain Lookup#ORIGINAL original} access
 323      * @throws ClassCastException if the class data cannot be converted to
 324      * the given {@code type}
 325      * @throws NullPointerException if {@code caller} or {@code type} argument
 326      * is {@code null}
 327      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 328      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 329      * @since 16
 330      * @jvms 5.5 Initialization
 331      */
 332      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 333          Objects.requireNonNull(caller);
 334          Objects.requireNonNull(type);
 335          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 336              throw new IllegalArgumentException("name must be \"_\": " + name);
 337          }
 338 
 339          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 340              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 341          }
 342 
 343          Object classdata = classData(caller.lookupClass());
 344          if (classdata == null) return null;
 345 
 346          try {
 347              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 348          } catch (RuntimeException|Error e) {
 349              throw e; // let CCE and other runtime exceptions through
 350          } catch (Throwable e) {
 351              throw new InternalError(e);
 352          }
 353     }
 354 
 355     /*
 356      * Returns the class data set by the VM in the Class::classData field.
 357      *
 358      * This is also invoked by LambdaForms as it cannot use condy via
 359      * MethodHandles::classData due to bootstrapping issue.
 360      */
 361     static Object classData(Class<?> c) {
 362         UNSAFE.ensureClassInitialized(c);
 363         return SharedSecrets.getJavaLangAccess().classData(c);
 364     }
 365 
 366     /**
 367      * Returns the element at the specified index in the
 368      * {@linkplain #classData(Lookup, String, Class) class data},
 369      * if the class data associated with the lookup class
 370      * of the given {@code caller} lookup object is a {@code List}.
 371      * If the class data is not present in this lookup class, this method
 372      * returns {@code null}.
 373      *
 374      * <p> A hidden class with class data can be created by calling
 375      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 376      * Lookup::defineHiddenClassWithClassData}.
 377      * This method will cause the static class initializer of the lookup
 378      * class of the given {@code caller} lookup object be executed if
 379      * it has not been initialized.
 380      *
 381      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 382      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 383      * {@code null} is returned if this method is called on the lookup object
 384      * on these classes.
 385      *
 386      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 387      * must have {@linkplain Lookup#ORIGINAL original access}
 388      * in order to retrieve the class data.
 389      *
 390      * @apiNote
 391      * This method can be called as a bootstrap method for a dynamically computed
 392      * constant.  A framework can create a hidden class with class data, for
 393      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 394      * one object and use this method to load one element at a specific index.
 395      * The class data is accessible only to the lookup object
 396      * created by the original caller but inaccessible to other members
 397      * in the same nest.  If a framework passes security sensitive objects
 398      * to a hidden class via class data, it is recommended to load the value
 399      * of class data as a dynamically computed constant instead of storing
 400      * the class data in private static field(s) which are accessible to other
 401      * nestmates.
 402      *
 403      * @param <T> the type to cast the result object to
 404      * @param caller the lookup context describing the class performing the
 405      * operation (normally stacked by the JVM)
 406      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 407      *             ({@code "_"})
 408      * @param type the type of the element at the given index in the class data
 409      * @param index index of the element in the class data
 410      * @return the element at the given index in the class data
 411      * if the class data is present; otherwise {@code null}
 412      * @throws IllegalArgumentException if name is not {@code "_"}
 413      * @throws IllegalAccessException if the lookup context does not have
 414      * {@linkplain Lookup#ORIGINAL original} access
 415      * @throws ClassCastException if the class data cannot be converted to {@code List}
 416      * or the element at the specified index cannot be converted to the given type
 417      * @throws IndexOutOfBoundsException if the index is out of range
 418      * @throws NullPointerException if {@code caller} or {@code type} argument is
 419      * {@code null}; or if unboxing operation fails because
 420      * the element at the given index is {@code null}
 421      *
 422      * @since 16
 423      * @see #classData(Lookup, String, Class)
 424      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 425      */
 426     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 427             throws IllegalAccessException
 428     {
 429         @SuppressWarnings("unchecked")
 430         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 431         if (classdata == null) return null;
 432 
 433         try {
 434             Object element = classdata.get(index);
 435             return BootstrapMethodInvoker.widenAndCast(element, type);
 436         } catch (RuntimeException|Error e) {
 437             throw e; // let specified exceptions and other runtime exceptions/errors through
 438         } catch (Throwable e) {
 439             throw new InternalError(e);
 440         }
 441     }
 442 
 443     /**
 444      * Performs an unchecked "crack" of a
 445      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 446      * The result is as if the user had obtained a lookup object capable enough
 447      * to crack the target method handle, called
 448      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 449      * on the target to obtain its symbolic reference, and then called
 450      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 451      * to resolve the symbolic reference to a member.
 452      * @param <T> the desired type of the result, either {@link Member} or a subtype
 453      * @param expected a class object representing the desired result type {@code T}
 454      * @param target a direct method handle to crack into symbolic reference components
 455      * @return a reference to the method, constructor, or field object
 456      * @throws    NullPointerException if either argument is {@code null}
 457      * @throws    IllegalArgumentException if the target is not a direct method handle
 458      * @throws    ClassCastException if the member is not of the expected type
 459      * @since 1.8
 460      */
 461     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 462         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 463         return lookup.revealDirect(target).reflectAs(expected, lookup);
 464     }
 465 
 466     /**
 467      * A <em>lookup object</em> is a factory for creating method handles,
 468      * when the creation requires access checking.
 469      * Method handles do not perform
 470      * access checks when they are called, but rather when they are created.
 471      * Therefore, method handle access
 472      * restrictions must be enforced when a method handle is created.
 473      * The caller class against which those restrictions are enforced
 474      * is known as the {@linkplain #lookupClass() lookup class}.
 475      * <p>
 476      * A lookup class which needs to create method handles will call
 477      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 478      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 479      * determined, and securely stored in the {@code Lookup} object.
 480      * The lookup class (or its delegates) may then use factory methods
 481      * on the {@code Lookup} object to create method handles for access-checked members.
 482      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 483      * even private ones.
 484      *
 485      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 486      * The factory methods on a {@code Lookup} object correspond to all major
 487      * use cases for methods, constructors, and fields.
 488      * Each method handle created by a factory method is the functional
 489      * equivalent of a particular <em>bytecode behavior</em>.
 490      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 491      * the Java Virtual Machine Specification.)
 492      * Here is a summary of the correspondence between these factory methods and
 493      * the behavior of the resulting method handles:
 494      * <table class="striped">
 495      * <caption style="display:none">lookup method behaviors</caption>
 496      * <thead>
 497      * <tr>
 498      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 499      *     <th scope="col">member</th>
 500      *     <th scope="col">bytecode behavior</th>
 501      * </tr>
 502      * </thead>
 503      * <tbody>
 504      * <tr>
 505      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 506      *     <td>{@code FT f;}</td><td>{@code (FT) this.f;}</td>
 507      * </tr>
 508      * <tr>
 509      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 510      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 511      * </tr>
 512      * <tr>
 513      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 514      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 515      * </tr>
 516      * <tr>
 517      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 518      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 519      * </tr>
 520      * <tr>
 521      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 522      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 523      * </tr>
 524      * <tr>
 525      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 526      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 527      * </tr>
 528      * <tr>
 529      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 530      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 531      * </tr>
 532      * <tr>
 533      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 534      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 535      * </tr>
 536      * <tr>
 537      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 538      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 539      * </tr>
 540      * <tr>
 541      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 542      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 543      * </tr>
 544      * <tr>
 545      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 546      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 547      * </tr>
 548      * <tr>
 549      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 550      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 551      * </tr>
 552      * <tr>
 553      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 554      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 555      * </tr>
 556      * <tr>
 557      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 558      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 559      * </tr>
 560      * </tbody>
 561      * </table>
 562      *
 563      * Here, the type {@code C} is the class or interface being searched for a member,
 564      * documented as a parameter named {@code refc} in the lookup methods.
 565      * The method type {@code MT} is composed from the return type {@code T}
 566      * and the sequence of argument types {@code A*}.
 567      * The constructor also has a sequence of argument types {@code A*} and
 568      * is deemed to return the newly-created object of type {@code C}.
 569      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 570      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 571      * if it is present, it is always the leading argument to the method handle invocation.
 572      * (In the case of some {@code protected} members, {@code this} may be
 573      * restricted in type to the lookup class; see below.)
 574      * The name {@code arg} stands for all the other method handle arguments.
 575      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 576      * stands for a null reference if the accessed method or field is static,
 577      * and {@code this} otherwise.
 578      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 579      * for reflective objects corresponding to the given members declared in type {@code C}.
 580      * <p>
 581      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 582      * as if by {@code ldc CONSTANT_Class}.
 583      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 584      * <p>
 585      * In cases where the given member is of variable arity (i.e., a method or constructor)
 586      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 587      * In all other cases, the returned method handle will be of fixed arity.
 588      * <p style="font-size:smaller;">
 589      * <em>Discussion:</em>
 590      * The equivalence between looked-up method handles and underlying
 591      * class members and bytecode behaviors
 592      * can break down in a few ways:
 593      * <ul style="font-size:smaller;">
 594      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 595      * the lookup can still succeed, even when there is no equivalent
 596      * Java expression or bytecoded constant.
 597      * <li>Likewise, if {@code T} or {@code MT}
 598      * is not symbolically accessible from the lookup class's loader,
 599      * the lookup can still succeed.
 600      * For example, lookups for {@code MethodHandle.invokeExact} and
 601      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 602      * <li>If the looked-up method has a
 603      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 604      * the method handle creation may fail with an
 605      * {@code IllegalArgumentException}, due to the method handle type having
 606      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 607      * </ul>
 608      *
 609      * <h2><a id="access"></a>Access checking</h2>
 610      * Access checks are applied in the factory methods of {@code Lookup},
 611      * when a method handle is created.
 612      * This is a key difference from the Core Reflection API, since
 613      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 614      * performs access checking against every caller, on every call.
 615      * <p>
 616      * All access checks start from a {@code Lookup} object, which
 617      * compares its recorded lookup class against all requests to
 618      * create method handles.
 619      * A single {@code Lookup} object can be used to create any number
 620      * of access-checked method handles, all checked against a single
 621      * lookup class.
 622      * <p>
 623      * A {@code Lookup} object can be shared with other trusted code,
 624      * such as a metaobject protocol.
 625      * A shared {@code Lookup} object delegates the capability
 626      * to create method handles on private members of the lookup class.
 627      * Even if privileged code uses the {@code Lookup} object,
 628      * the access checking is confined to the privileges of the
 629      * original lookup class.
 630      * <p>
 631      * A lookup can fail, because
 632      * the containing class is not accessible to the lookup class, or
 633      * because the desired class member is missing, or because the
 634      * desired class member is not accessible to the lookup class, or
 635      * because the lookup object is not trusted enough to access the member.
 636      * In the case of a field setter function on a {@code final} field,
 637      * finality enforcement is treated as a kind of access control,
 638      * and the lookup will fail, except in special cases of
 639      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 640      * In any of these cases, a {@code ReflectiveOperationException} will be
 641      * thrown from the attempted lookup.  The exact class will be one of
 642      * the following:
 643      * <ul>
 644      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 645      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 646      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 647      * </ul>
 648      * <p>
 649      * In general, the conditions under which a method handle may be
 650      * looked up for a method {@code M} are no more restrictive than the conditions
 651      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 652      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 653      * a method handle lookup will generally raise a corresponding
 654      * checked exception, such as {@code NoSuchMethodException}.
 655      * And the effect of invoking the method handle resulting from the lookup
 656      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 657      * to executing the compiled, verified, and resolved call to {@code M}.
 658      * The same point is true of fields and constructors.
 659      * <p style="font-size:smaller;">
 660      * <em>Discussion:</em>
 661      * Access checks only apply to named and reflected methods,
 662      * constructors, and fields.
 663      * Other method handle creation methods, such as
 664      * {@link MethodHandle#asType MethodHandle.asType},
 665      * do not require any access checks, and are used
 666      * independently of any {@code Lookup} object.
 667      * <p>
 668      * If the desired member is {@code protected}, the usual JVM rules apply,
 669      * including the requirement that the lookup class must either be in the
 670      * same package as the desired member, or must inherit that member.
 671      * (See the Java Virtual Machine Specification, sections {@jvms
 672      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 673      * In addition, if the desired member is a non-static field or method
 674      * in a different package, the resulting method handle may only be applied
 675      * to objects of the lookup class or one of its subclasses.
 676      * This requirement is enforced by narrowing the type of the leading
 677      * {@code this} parameter from {@code C}
 678      * (which will necessarily be a superclass of the lookup class)
 679      * to the lookup class itself.
 680      * <p>
 681      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 682      * that the receiver argument must match both the resolved method <em>and</em>
 683      * the current class.  Again, this requirement is enforced by narrowing the
 684      * type of the leading parameter to the resulting method handle.
 685      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 686      * <p>
 687      * The JVM represents constructors and static initializer blocks as internal methods
 688      * with special names ({@value ConstantDescs#INIT_NAME} and {@value
 689      * ConstantDescs#CLASS_INIT_NAME}).
 690      * The internal syntax of invocation instructions allows them to refer to such internal
 691      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 692      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 693      * <p>
 694      * If the relationship between nested types is expressed directly through the
 695      * {@code NestHost} and {@code NestMembers} attributes
 696      * (see the Java Virtual Machine Specification, sections {@jvms
 697      * 4.7.28} and {@jvms 4.7.29}),
 698      * then the associated {@code Lookup} object provides direct access to
 699      * the lookup class and all of its nestmates
 700      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 701      * Otherwise, access between nested classes is obtained by the Java compiler creating
 702      * a wrapper method to access a private method of another class in the same nest.
 703      * For example, a nested class {@code C.D}
 704      * can access private members within other related classes such as
 705      * {@code C}, {@code C.D.E}, or {@code C.B},
 706      * but the Java compiler may need to generate wrapper methods in
 707      * those related classes.  In such cases, a {@code Lookup} object on
 708      * {@code C.E} would be unable to access those private members.
 709      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 710      * which can transform a lookup on {@code C.E} into one on any of those other
 711      * classes, without special elevation of privilege.
 712      * <p>
 713      * The accesses permitted to a given lookup object may be limited,
 714      * according to its set of {@link #lookupModes lookupModes},
 715      * to a subset of members normally accessible to the lookup class.
 716      * For example, the {@link MethodHandles#publicLookup publicLookup}
 717      * method produces a lookup object which is only allowed to access
 718      * public members in public classes of exported packages.
 719      * The caller sensitive method {@link MethodHandles#lookup lookup}
 720      * produces a lookup object with full capabilities relative to
 721      * its caller class, to emulate all supported bytecode behaviors.
 722      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 723      * with fewer access modes than the original lookup object.
 724      *
 725      * <p style="font-size:smaller;">
 726      * <a id="privacc"></a>
 727      * <em>Discussion of private and module access:</em>
 728      * We say that a lookup has <em>private access</em>
 729      * if its {@linkplain #lookupModes lookup modes}
 730      * include the possibility of accessing {@code private} members
 731      * (which includes the private members of nestmates).
 732      * As documented in the relevant methods elsewhere,
 733      * only lookups with private access possess the following capabilities:
 734      * <ul style="font-size:smaller;">
 735      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 736      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 737      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 738      *     within the same package member
 739      * </ul>
 740      * <p style="font-size:smaller;">
 741      * Similarly, a lookup with module access ensures that the original lookup creator was
 742      * a member in the same module as the lookup class.
 743      * <p style="font-size:smaller;">
 744      * Private and module access are independently determined modes; a lookup may have
 745      * either or both or neither.  A lookup which possesses both access modes is said to
 746      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 747      * <p style="font-size:smaller;">
 748      * A lookup with <em>original access</em> ensures that this lookup is created by
 749      * the original lookup class and the bootstrap method invoked by the VM.
 750      * Such a lookup with original access also has private and module access
 751      * which has the following additional capability:
 752      * <ul style="font-size:smaller;">
 753      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 754      *     such as {@code Class.forName}
 755      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 756      * class data} associated with the lookup class</li>
 757      * </ul>
 758      * <p style="font-size:smaller;">
 759      * Each of these permissions is a consequence of the fact that a lookup object
 760      * with private access can be securely traced back to an originating class,
 761      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 762      * can be reliably determined and emulated by method handles.
 763      *
 764      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 765      * When a lookup class in one module {@code M1} accesses a class in another module
 766      * {@code M2}, extra access checking is performed beyond the access mode bits.
 767      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 768      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 769      * and when the type is in a package of {@code M2} that is exported to
 770      * at least {@code M1}.
 771      * <p>
 772      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 773      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 774      * MethodHandles.privateLookupIn} methods.
 775      * Teleporting across modules will always record the original lookup class as
 776      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 777      * and drops {@link Lookup#MODULE MODULE} access.
 778      * If the target class is in the same module as the lookup class {@code C},
 779      * then the target class becomes the new lookup class
 780      * and there is no change to the previous lookup class.
 781      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 782      * {@code C} becomes the new previous lookup class
 783      * and the target class becomes the new lookup class.
 784      * In that case, if there was already a previous lookup class in {@code M0},
 785      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 786      * drops all privileges.
 787      * For example,
 788      * {@snippet lang="java" :
 789      * Lookup lookup = MethodHandles.lookup();   // in class C
 790      * Lookup lookup2 = lookup.in(D.class);
 791      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 792      * }
 793      * <p>
 794      * The {@link #lookup()} factory method produces a {@code Lookup} object
 795      * with {@code null} previous lookup class.
 796      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 797      * to class {@code D} without elevation of privileges.
 798      * If {@code C} and {@code D} are in the same module,
 799      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 800      * same previous lookup class as the original {@code lookup}, or
 801      * {@code null} if not present.
 802      * <p>
 803      * When a {@code Lookup} teleports from a class
 804      * in one nest to another nest, {@code PRIVATE} access is dropped.
 805      * When a {@code Lookup} teleports from a class in one package to
 806      * another package, {@code PACKAGE} access is dropped.
 807      * When a {@code Lookup} teleports from a class in one module to another module,
 808      * {@code MODULE} access is dropped.
 809      * Teleporting across modules drops the ability to access non-exported classes
 810      * in both the module of the new lookup class and the module of the old lookup class
 811      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 812      * A {@code Lookup} can teleport back and forth to a class in the module of
 813      * the lookup class and the module of the previous class lookup.
 814      * Teleporting across modules can only decrease access but cannot increase it.
 815      * Teleporting to some third module drops all accesses.
 816      * <p>
 817      * In the above example, if {@code C} and {@code D} are in different modules,
 818      * {@code lookup2} records {@code D} as its lookup class and
 819      * {@code C} as its previous lookup class and {@code lookup2} has only
 820      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 821      * {@code C}'s module and {@code D}'s module.
 822      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 823      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 824      * class {@code D} is recorded as its previous lookup class.
 825      * <p>
 826      * Teleporting across modules restricts access to the public types that
 827      * both the lookup class and the previous lookup class can equally access
 828      * (see below).
 829      * <p>
 830      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 831      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 832      * and produce a new {@code Lookup} with <a href="#privacc">private access</a>
 833      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 834      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 835      * to call {@code privateLookupIn}.
 836      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 837      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 838      * produces a new {@code Lookup} on {@code T} with full capabilities.
 839      * A {@code lookup} on {@code C} is also allowed
 840      * to do deep reflection on {@code T} in another module {@code M2} if
 841      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 842      * the package containing {@code T} to at least {@code M1}.
 843      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 844      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 845      * The resulting {@code Lookup} can be used to do member lookup or teleport
 846      * to another lookup class by calling {@link #in Lookup::in}.  But
 847      * it cannot be used to obtain another private {@code Lookup} by calling
 848      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 849      * because it has no {@code MODULE} access.
 850      * <p>
 851      * The {@code Lookup} object returned by {@code privateLookupIn} is allowed to
 852      * {@linkplain Lookup#defineClass(byte[]) define classes} in the runtime package
 853      * of {@code T}. Extreme caution should be taken when opening a package
 854      * to another module as such defined classes have the same full privilege
 855      * access as other members in {@code M2}.
 856      *
 857      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 858      *
 859      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 860      * allows cross-module access. The access checking is performed with respect
 861      * to both the lookup class and the previous lookup class if present.
 862      * <p>
 863      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 864      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 865      * exported unconditionally}.
 866      * <p>
 867      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 868      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 869      * that are readable to {@code M1} and the type is in a package that is exported
 870      * at least to {@code M1}.
 871      * <p>
 872      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 873      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 874      * the intersection of all public types that are accessible to {@code M1}
 875      * with all public types that are accessible to {@code M0}. {@code M0}
 876      * reads {@code M1} and hence the set of accessible types includes:
 877      *
 878      * <ul>
 879      * <li>unconditional-exported packages from {@code M1}</li>
 880      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 881      * <li>
 882      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 883      *     and {@code M1} read {@code M2}
 884      * </li>
 885      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 886      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 887      * <li>
 888      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 889      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 890      * </li>
 891      * </ul>
 892      *
 893      * <h2><a id="access-modes"></a>Access modes</h2>
 894      *
 895      * The table below shows the access modes of a {@code Lookup} produced by
 896      * any of the following factory or transformation methods:
 897      * <ul>
 898      * <li>{@link #lookup() MethodHandles::lookup}</li>
 899      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 900      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 901      * <li>{@link Lookup#in Lookup::in}</li>
 902      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 903      * </ul>
 904      *
 905      * <table class="striped">
 906      * <caption style="display:none">
 907      * Access mode summary
 908      * </caption>
 909      * <thead>
 910      * <tr>
 911      * <th scope="col">Lookup object</th>
 912      * <th style="text-align:center">original</th>
 913      * <th style="text-align:center">protected</th>
 914      * <th style="text-align:center">private</th>
 915      * <th style="text-align:center">package</th>
 916      * <th style="text-align:center">module</th>
 917      * <th style="text-align:center">public</th>
 918      * </tr>
 919      * </thead>
 920      * <tbody>
 921      * <tr>
 922      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 923      * <td style="text-align:center">ORI</td>
 924      * <td style="text-align:center">PRO</td>
 925      * <td style="text-align:center">PRI</td>
 926      * <td style="text-align:center">PAC</td>
 927      * <td style="text-align:center">MOD</td>
 928      * <td style="text-align:center">1R</td>
 929      * </tr>
 930      * <tr>
 931      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 932      * <td></td>
 933      * <td></td>
 934      * <td></td>
 935      * <td style="text-align:center">PAC</td>
 936      * <td style="text-align:center">MOD</td>
 937      * <td style="text-align:center">1R</td>
 938      * </tr>
 939      * <tr>
 940      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 941      * <td></td>
 942      * <td></td>
 943      * <td></td>
 944      * <td></td>
 945      * <td style="text-align:center">MOD</td>
 946      * <td style="text-align:center">1R</td>
 947      * </tr>
 948      * <tr>
 949      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 950      * <td></td>
 951      * <td></td>
 952      * <td></td>
 953      * <td></td>
 954      * <td></td>
 955      * <td style="text-align:center">2R</td>
 956      * </tr>
 957      * <tr>
 958      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 959      * <td></td>
 960      * <td></td>
 961      * <td></td>
 962      * <td></td>
 963      * <td></td>
 964      * <td style="text-align:center">2R</td>
 965      * </tr>
 966      * <tr>
 967      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 968      * <td></td>
 969      * <td style="text-align:center">PRO</td>
 970      * <td style="text-align:center">PRI</td>
 971      * <td style="text-align:center">PAC</td>
 972      * <td style="text-align:center">MOD</td>
 973      * <td style="text-align:center">1R</td>
 974      * </tr>
 975      * <tr>
 976      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 977      * <td></td>
 978      * <td style="text-align:center">PRO</td>
 979      * <td style="text-align:center">PRI</td>
 980      * <td style="text-align:center">PAC</td>
 981      * <td style="text-align:center">MOD</td>
 982      * <td style="text-align:center">1R</td>
 983      * </tr>
 984      * <tr>
 985      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
 986      * <td></td>
 987      * <td></td>
 988      * <td></td>
 989      * <td style="text-align:center">PAC</td>
 990      * <td style="text-align:center">MOD</td>
 991      * <td style="text-align:center">1R</td>
 992      * </tr>
 993      * <tr>
 994      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
 995      * <td></td>
 996      * <td></td>
 997      * <td></td>
 998      * <td></td>
 999      * <td style="text-align:center">MOD</td>
1000      * <td style="text-align:center">1R</td>
1001      * </tr>
1002      * <tr>
1003      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1004      * <td></td>
1005      * <td></td>
1006      * <td></td>
1007      * <td></td>
1008      * <td></td>
1009      * <td style="text-align:center">2R</td>
1010      * </tr>
1011      * <tr>
1012      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1013      * <td></td>
1014      * <td></td>
1015      * <td style="text-align:center">PRI</td>
1016      * <td style="text-align:center">PAC</td>
1017      * <td style="text-align:center">MOD</td>
1018      * <td style="text-align:center">1R</td>
1019      * </tr>
1020      * <tr>
1021      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1022      * <td></td>
1023      * <td></td>
1024      * <td></td>
1025      * <td style="text-align:center">PAC</td>
1026      * <td style="text-align:center">MOD</td>
1027      * <td style="text-align:center">1R</td>
1028      * </tr>
1029      * <tr>
1030      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1031      * <td></td>
1032      * <td></td>
1033      * <td></td>
1034      * <td></td>
1035      * <td style="text-align:center">MOD</td>
1036      * <td style="text-align:center">1R</td>
1037      * </tr>
1038      * <tr>
1039      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1040      * <td></td>
1041      * <td></td>
1042      * <td></td>
1043      * <td></td>
1044      * <td></td>
1045      * <td style="text-align:center">1R</td>
1046      * </tr>
1047      * <tr>
1048      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1049      * <td></td>
1050      * <td></td>
1051      * <td></td>
1052      * <td></td>
1053      * <td></td>
1054      * <td style="text-align:center">none</td>
1055      * <tr>
1056      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1057      * <td></td>
1058      * <td style="text-align:center">PRO</td>
1059      * <td style="text-align:center">PRI</td>
1060      * <td style="text-align:center">PAC</td>
1061      * <td></td>
1062      * <td style="text-align:center">2R</td>
1063      * </tr>
1064      * <tr>
1065      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1066      * <td></td>
1067      * <td style="text-align:center">PRO</td>
1068      * <td style="text-align:center">PRI</td>
1069      * <td style="text-align:center">PAC</td>
1070      * <td></td>
1071      * <td style="text-align:center">2R</td>
1072      * </tr>
1073      * <tr>
1074      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1075      * <td></td>
1076      * <td></td>
1077      * <td></td>
1078      * <td></td>
1079      * <td></td>
1080      * <td style="text-align:center">IAE</td>
1081      * </tr>
1082      * <tr>
1083      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1084      * <td></td>
1085      * <td></td>
1086      * <td></td>
1087      * <td style="text-align:center">PAC</td>
1088      * <td></td>
1089      * <td style="text-align:center">2R</td>
1090      * </tr>
1091      * <tr>
1092      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1093      * <td></td>
1094      * <td></td>
1095      * <td></td>
1096      * <td></td>
1097      * <td></td>
1098      * <td style="text-align:center">2R</td>
1099      * </tr>
1100      * <tr>
1101      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1102      * <td></td>
1103      * <td></td>
1104      * <td></td>
1105      * <td></td>
1106      * <td></td>
1107      * <td style="text-align:center">2R</td>
1108      * </tr>
1109      * <tr>
1110      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1111      * <td></td>
1112      * <td></td>
1113      * <td></td>
1114      * <td></td>
1115      * <td></td>
1116      * <td style="text-align:center">none</td>
1117      * </tr>
1118      * <tr>
1119      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1120      * <td></td>
1121      * <td></td>
1122      * <td style="text-align:center">PRI</td>
1123      * <td style="text-align:center">PAC</td>
1124      * <td></td>
1125      * <td style="text-align:center">2R</td>
1126      * </tr>
1127      * <tr>
1128      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1129      * <td></td>
1130      * <td></td>
1131      * <td></td>
1132      * <td style="text-align:center">PAC</td>
1133      * <td></td>
1134      * <td style="text-align:center">2R</td>
1135      * </tr>
1136      * <tr>
1137      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1138      * <td></td>
1139      * <td></td>
1140      * <td></td>
1141      * <td></td>
1142      * <td></td>
1143      * <td style="text-align:center">2R</td>
1144      * </tr>
1145      * <tr>
1146      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1147      * <td></td>
1148      * <td></td>
1149      * <td></td>
1150      * <td></td>
1151      * <td></td>
1152      * <td style="text-align:center">2R</td>
1153      * </tr>
1154      * <tr>
1155      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1156      * <td></td>
1157      * <td></td>
1158      * <td></td>
1159      * <td></td>
1160      * <td></td>
1161      * <td style="text-align:center">none</td>
1162      * </tr>
1163      * <tr>
1164      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1165      * <td></td>
1166      * <td></td>
1167      * <td style="text-align:center">PRI</td>
1168      * <td style="text-align:center">PAC</td>
1169      * <td style="text-align:center">MOD</td>
1170      * <td style="text-align:center">1R</td>
1171      * </tr>
1172      * <tr>
1173      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1174      * <td></td>
1175      * <td></td>
1176      * <td></td>
1177      * <td style="text-align:center">PAC</td>
1178      * <td style="text-align:center">MOD</td>
1179      * <td style="text-align:center">1R</td>
1180      * </tr>
1181      * <tr>
1182      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1183      * <td></td>
1184      * <td></td>
1185      * <td></td>
1186      * <td></td>
1187      * <td style="text-align:center">MOD</td>
1188      * <td style="text-align:center">1R</td>
1189      * </tr>
1190      * <tr>
1191      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1192      * <td></td>
1193      * <td></td>
1194      * <td></td>
1195      * <td></td>
1196      * <td></td>
1197      * <td style="text-align:center">1R</td>
1198      * </tr>
1199      * <tr>
1200      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1201      * <td></td>
1202      * <td></td>
1203      * <td></td>
1204      * <td></td>
1205      * <td></td>
1206      * <td style="text-align:center">none</td>
1207      * </tr>
1208      * <tr>
1209      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1210      * <td></td>
1211      * <td></td>
1212      * <td></td>
1213      * <td></td>
1214      * <td></td>
1215      * <td style="text-align:center">U</td>
1216      * </tr>
1217      * <tr>
1218      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1219      * <td></td>
1220      * <td></td>
1221      * <td></td>
1222      * <td></td>
1223      * <td></td>
1224      * <td style="text-align:center">U</td>
1225      * </tr>
1226      * <tr>
1227      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1228      * <td></td>
1229      * <td></td>
1230      * <td></td>
1231      * <td></td>
1232      * <td></td>
1233      * <td style="text-align:center">U</td>
1234      * </tr>
1235      * <tr>
1236      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1237      * <td></td>
1238      * <td></td>
1239      * <td></td>
1240      * <td></td>
1241      * <td></td>
1242      * <td style="text-align:center">none</td>
1243      * </tr>
1244      * <tr>
1245      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1246      * <td></td>
1247      * <td></td>
1248      * <td></td>
1249      * <td></td>
1250      * <td></td>
1251      * <td style="text-align:center">IAE</td>
1252      * </tr>
1253      * <tr>
1254      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1255      * <td></td>
1256      * <td></td>
1257      * <td></td>
1258      * <td></td>
1259      * <td></td>
1260      * <td style="text-align:center">none</td>
1261      * </tr>
1262      * </tbody>
1263      * </table>
1264      *
1265      * <p>
1266      * Notes:
1267      * <ul>
1268      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1269      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1270      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1271      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1272      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1273      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1274      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1275      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1276      *     {@code MOD} indicates {@link #MODULE} bit set,
1277      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1278      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1279      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1280      * <li>Public access comes in three kinds:
1281      * <ul>
1282      * <li>unconditional ({@code U}): the lookup assumes readability.
1283      *     The lookup has {@code null} previous lookup class.
1284      * <li>one-module-reads ({@code 1R}): the module access checking is
1285      *     performed with respect to the lookup class.  The lookup has {@code null}
1286      *     previous lookup class.
1287      * <li>two-module-reads ({@code 2R}): the module access checking is
1288      *     performed with respect to the lookup class and the previous lookup class.
1289      *     The lookup has a non-null previous lookup class which is in a
1290      *     different module from the current lookup class.
1291      * </ul>
1292      * <li>Any attempt to reach a third module loses all access.</li>
1293      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1294      * all access modes are dropped.</li>
1295      * </ul>
1296      *
1297      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1298      * A small number of Java methods have a special property called caller sensitivity.
1299      * A <em>caller-sensitive</em> method can behave differently depending on the
1300      * identity of its immediate caller.
1301      * <p>
1302      * If a method handle for a caller-sensitive method is requested,
1303      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1304      * but they take account of the lookup class in a special way.
1305      * The resulting method handle behaves as if it were called
1306      * from an instruction contained in the lookup class,
1307      * so that the caller-sensitive method detects the lookup class.
1308      * (By contrast, the invoker of the method handle is disregarded.)
1309      * Thus, in the case of caller-sensitive methods,
1310      * different lookup classes may give rise to
1311      * differently behaving method handles.
1312      * <p>
1313      * In cases where the lookup object is
1314      * {@link MethodHandles#publicLookup() publicLookup()},
1315      * or some other lookup object without the
1316      * {@linkplain #ORIGINAL original access},
1317      * the lookup class is disregarded.
1318      * In such cases, no caller-sensitive method handle can be created,
1319      * access is forbidden, and the lookup fails with an
1320      * {@code IllegalAccessException}.
1321      * <p style="font-size:smaller;">
1322      * <em>Discussion:</em>
1323      * For example, the caller-sensitive method
1324      * {@link java.lang.Class#forName(String) Class.forName(x)}
1325      * can return varying classes or throw varying exceptions,
1326      * depending on the class loader of the class that calls it.
1327      * A public lookup of {@code Class.forName} will fail, because
1328      * there is no reasonable way to determine its bytecode behavior.
1329      * <p style="font-size:smaller;">
1330      * If an application caches method handles for broad sharing,
1331      * it should use {@code publicLookup()} to create them.
1332      * If there is a lookup of {@code Class.forName}, it will fail,
1333      * and the application must take appropriate action in that case.
1334      * It may be that a later lookup, perhaps during the invocation of a
1335      * bootstrap method, can incorporate the specific identity
1336      * of the caller, making the method accessible.
1337      * <p style="font-size:smaller;">
1338      * The function {@code MethodHandles.lookup} is caller sensitive
1339      * so that there can be a secure foundation for lookups.
1340      * Nearly all other methods in the JSR 292 API rely on lookup
1341      * objects to check access requests.
1342      */
1343     public static final
1344     class Lookup {
1345         /** The class on behalf of whom the lookup is being performed. */
1346         private final Class<?> lookupClass;
1347 
1348         /** previous lookup class */
1349         private final Class<?> prevLookupClass;
1350 
1351         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1352         private final int allowedModes;
1353 
1354         static {
1355             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1356         }
1357 
1358         /** A single-bit mask representing {@code public} access,
1359          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1360          *  The value, {@code 0x01}, happens to be the same as the value of the
1361          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1362          *  <p>
1363          *  A {@code Lookup} with this lookup mode performs cross-module access check
1364          *  with respect to the {@linkplain #lookupClass() lookup class} and
1365          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1366          */
1367         public static final int PUBLIC = Modifier.PUBLIC;
1368 
1369         /** A single-bit mask representing {@code private} access,
1370          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1371          *  The value, {@code 0x02}, happens to be the same as the value of the
1372          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1373          */
1374         public static final int PRIVATE = Modifier.PRIVATE;
1375 
1376         /** A single-bit mask representing {@code protected} access,
1377          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1378          *  The value, {@code 0x04}, happens to be the same as the value of the
1379          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1380          */
1381         public static final int PROTECTED = Modifier.PROTECTED;
1382 
1383         /** A single-bit mask representing {@code package} access (default access),
1384          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1385          *  The value is {@code 0x08}, which does not correspond meaningfully to
1386          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1387          */
1388         public static final int PACKAGE = Modifier.STATIC;
1389 
1390         /** A single-bit mask representing {@code module} access,
1391          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1392          *  The value is {@code 0x10}, which does not correspond meaningfully to
1393          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1394          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1395          *  with this lookup mode can access all public types in the module of the
1396          *  lookup class and public types in packages exported by other modules
1397          *  to the module of the lookup class.
1398          *  <p>
1399          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1400          *  previous lookup class} is always {@code null}.
1401          *
1402          *  @since 9
1403          */
1404         public static final int MODULE = PACKAGE << 1;
1405 
1406         /** A single-bit mask representing {@code unconditional} access
1407          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1408          *  The value is {@code 0x20}, which does not correspond meaningfully to
1409          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1410          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1411          *  java.lang.Module#canRead(java.lang.Module) readability}.
1412          *  This lookup mode can access all public members of public types
1413          *  of all modules when the type is in a package that is {@link
1414          *  java.lang.Module#isExported(String) exported unconditionally}.
1415          *
1416          *  <p>
1417          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1418          *  previous lookup class} is always {@code null}.
1419          *
1420          *  @since 9
1421          *  @see #publicLookup()
1422          */
1423         public static final int UNCONDITIONAL = PACKAGE << 2;
1424 
1425         /** A single-bit mask representing {@code original} access
1426          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1427          *  The value is {@code 0x40}, which does not correspond meaningfully to
1428          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1429          *
1430          *  <p>
1431          *  If this lookup mode is set, the {@code Lookup} object must be
1432          *  created by the original lookup class by calling
1433          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1434          *  invoked by the VM.  The {@code Lookup} object with this lookup
1435          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1436          *
1437          *  @since 16
1438          */
1439         public static final int ORIGINAL = PACKAGE << 3;
1440 
1441         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1442         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1443         private static final int TRUSTED   = -1;
1444 
1445         /*
1446          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1447          * Adjust 0 => PACKAGE
1448          */
1449         private static int fixmods(int mods) {
1450             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1451             if (Modifier.isPublic(mods))
1452                 mods |= UNCONDITIONAL;
1453             return (mods != 0) ? mods : PACKAGE;
1454         }
1455 
1456         /** Tells which class is performing the lookup.  It is this class against
1457          *  which checks are performed for visibility and access permissions.
1458          *  <p>
1459          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1460          *  access checks are performed against both the lookup class and the previous lookup class.
1461          *  <p>
1462          *  The class implies a maximum level of access permission,
1463          *  but the permissions may be additionally limited by the bitmask
1464          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1465          *  can be accessed.
1466          *  @return the lookup class, on behalf of which this lookup object finds members
1467          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1468          */
1469         public Class<?> lookupClass() {
1470             return lookupClass;
1471         }
1472 
1473         /** Reports a lookup class in another module that this lookup object
1474          * was previously teleported from, or {@code null}.
1475          * <p>
1476          * A {@code Lookup} object produced by the factory methods, such as the
1477          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1478          * has {@code null} previous lookup class.
1479          * A {@code Lookup} object has a non-null previous lookup class
1480          * when this lookup was teleported from an old lookup class
1481          * in one module to a new lookup class in another module.
1482          *
1483          * @return the lookup class in another module that this lookup object was
1484          *         previously teleported from, or {@code null}
1485          * @since 14
1486          * @see #in(Class)
1487          * @see MethodHandles#privateLookupIn(Class, Lookup)
1488          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1489          */
1490         public Class<?> previousLookupClass() {
1491             return prevLookupClass;
1492         }
1493 
1494         // This is just for calling out to MethodHandleImpl.
1495         private Class<?> lookupClassOrNull() {
1496             return (allowedModes == TRUSTED) ? null : lookupClass;
1497         }
1498 
1499         /** Tells which access-protection classes of members this lookup object can produce.
1500          *  The result is a bit-mask of the bits
1501          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1502          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1503          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1504          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1505          *  {@linkplain #MODULE MODULE (0x10)},
1506          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1507          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1508          *  <p>
1509          *  A freshly-created lookup object
1510          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1511          *  all possible bits set, except {@code UNCONDITIONAL}.
1512          *  A lookup object on a new lookup class
1513          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1514          *  may have some mode bits set to zero.
1515          *  Mode bits can also be
1516          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1517          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1518          *  The purpose of this is to restrict access via the new lookup object,
1519          *  so that it can access only names which can be reached by the original
1520          *  lookup object, and also by the new lookup class.
1521          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1522          *  @see #in
1523          *  @see #dropLookupMode
1524          */
1525         public int lookupModes() {
1526             return allowedModes & ALL_MODES;
1527         }
1528 
1529         /** Embody the current class (the lookupClass) as a lookup class
1530          * for method handle creation.
1531          * Must be called by from a method in this package,
1532          * which in turn is called by a method not in this package.
1533          */
1534         Lookup(Class<?> lookupClass) {
1535             this(lookupClass, null, FULL_POWER_MODES);
1536         }
1537 
1538         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1539             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1540                     && prevLookupClass.getModule() != lookupClass.getModule());
1541             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1542             this.lookupClass = lookupClass;
1543             this.prevLookupClass = prevLookupClass;
1544             this.allowedModes = allowedModes;
1545         }
1546 
1547         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1548             // make sure we haven't accidentally picked up a privileged class:
1549             checkUnprivilegedlookupClass(lookupClass);
1550             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1551         }
1552 
1553         /**
1554          * Creates a lookup on the specified new lookup class.
1555          * The resulting object will report the specified
1556          * class as its own {@link #lookupClass() lookupClass}.
1557          *
1558          * <p>
1559          * However, the resulting {@code Lookup} object is guaranteed
1560          * to have no more access capabilities than the original.
1561          * In particular, access capabilities can be lost as follows:<ul>
1562          * <li>If the new lookup class is different from the old lookup class,
1563          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1564          * <li>If the new lookup class is in a different module from the old one,
1565          * i.e. {@link #MODULE MODULE} access is lost.
1566          * <li>If the new lookup class is in a different package
1567          * than the old one, protected and default (package) members will not be accessible,
1568          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1569          * <li>If the new lookup class is not within the same package member
1570          * as the old one, private members will not be accessible, and protected members
1571          * will not be accessible by virtue of inheritance,
1572          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1573          * (Protected members may continue to be accessible because of package sharing.)
1574          * <li>If the new lookup class is not
1575          * {@linkplain #accessClass(Class) accessible} to this lookup,
1576          * then no members, not even public members, will be accessible
1577          * i.e. all access modes are lost.
1578          * <li>If the new lookup class, the old lookup class and the previous lookup class
1579          * are all in different modules i.e. teleporting to a third module,
1580          * all access modes are lost.
1581          * </ul>
1582          * <p>
1583          * The new previous lookup class is chosen as follows:
1584          * <ul>
1585          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1586          * the new previous lookup class is {@code null}.
1587          * <li>If the new lookup class is in the same module as the old lookup class,
1588          * the new previous lookup class is the old previous lookup class.
1589          * <li>If the new lookup class is in a different module from the old lookup class,
1590          * the new previous lookup class is the old lookup class.
1591          *</ul>
1592          * <p>
1593          * The resulting lookup's capabilities for loading classes
1594          * (used during {@link #findClass} invocations)
1595          * are determined by the lookup class' loader,
1596          * which may change due to this operation.
1597          *
1598          * @param requestedLookupClass the desired lookup class for the new lookup object
1599          * @return a lookup object which reports the desired lookup class, or the same object
1600          * if there is no change
1601          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1602          * @throws NullPointerException if the argument is null
1603          *
1604          * @see #accessClass(Class)
1605          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1606          */
1607         public Lookup in(Class<?> requestedLookupClass) {
1608             Objects.requireNonNull(requestedLookupClass);
1609             if (requestedLookupClass.isPrimitive())
1610                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1611             if (requestedLookupClass.isArray())
1612                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1613 
1614             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1615                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1616             if (requestedLookupClass == this.lookupClass)
1617                 return this;  // keep same capabilities
1618             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1619             Module fromModule = this.lookupClass.getModule();
1620             Module targetModule = requestedLookupClass.getModule();
1621             Class<?> plc = this.previousLookupClass();
1622             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1623                 assert plc == null;
1624                 newModes = UNCONDITIONAL;
1625             } else if (fromModule != targetModule) {
1626                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1627                     // allow hopping back and forth between fromModule and plc's module
1628                     // but not the third module
1629                     newModes = 0;
1630                 }
1631                 // drop MODULE access
1632                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1633                 // teleport from this lookup class
1634                 plc = this.lookupClass;
1635             }
1636             if ((newModes & PACKAGE) != 0
1637                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1638                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1639             }
1640             // Allow nestmate lookups to be created without special privilege:
1641             if ((newModes & PRIVATE) != 0
1642                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1643                 newModes &= ~(PRIVATE|PROTECTED);
1644             }
1645             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1646                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1647                 // The requested class it not accessible from the lookup class.
1648                 // No permissions.
1649                 newModes = 0;
1650             }
1651             return newLookup(requestedLookupClass, plc, newModes);
1652         }
1653 
1654         /**
1655          * Creates a lookup on the same lookup class which this lookup object
1656          * finds members, but with a lookup mode that has lost the given lookup mode.
1657          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1658          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1659          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1660          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1661          *
1662          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1663          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1664          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1665          * lookup has no access.
1666          *
1667          * <p> If this lookup is not a public lookup, then the following applies
1668          * regardless of its {@linkplain #lookupModes() lookup modes}.
1669          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1670          * dropped and so the resulting lookup mode will never have these access
1671          * capabilities. When dropping {@code PACKAGE}
1672          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1673          * access. When dropping {@code MODULE} then the resulting lookup will not
1674          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1675          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1676          *
1677          * @apiNote
1678          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1679          * delegate non-public access within the package of the lookup class without
1680          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1681          * A lookup with {@code MODULE} but not
1682          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1683          * the module of the lookup class without conferring package access.
1684          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1685          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1686          * to public classes accessible to both the module of the lookup class
1687          * and the module of the previous lookup class.
1688          *
1689          * @param modeToDrop the lookup mode to drop
1690          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1691          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1692          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1693          * or {@code UNCONDITIONAL}
1694          * @see MethodHandles#privateLookupIn
1695          * @since 9
1696          */
1697         public Lookup dropLookupMode(int modeToDrop) {
1698             int oldModes = lookupModes();
1699             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1700             switch (modeToDrop) {
1701                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1702                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1703                 case PACKAGE: newModes &= ~(PRIVATE); break;
1704                 case PROTECTED:
1705                 case PRIVATE:
1706                 case ORIGINAL:
1707                 case UNCONDITIONAL: break;
1708                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1709             }
1710             if (newModes == oldModes) return this;  // return self if no change
1711             return newLookup(lookupClass(), previousLookupClass(), newModes);
1712         }
1713 
1714         /**
1715          * Creates and links a class or interface from {@code bytes}
1716          * with the same class loader and in the same runtime package and
1717          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1718          * {@linkplain #lookupClass() lookup class} as if calling
1719          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1720          * ClassLoader::defineClass}.
1721          *
1722          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1723          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1724          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1725          * that the lookup object was created by a caller in the runtime package (or derived
1726          * from a lookup originally created by suitably privileged code to a target class in
1727          * the runtime package). </p>
1728          *
1729          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1730          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1731          * same package as the lookup class. </p>
1732          *
1733          * <p> This method does not run the class initializer. The class initializer may
1734          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1735          * Specification</em>. </p>
1736          *
1737          * @param bytes the class bytes
1738          * @return the {@code Class} object for the class
1739          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1740          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1741          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1742          * than the lookup class or {@code bytes} is not a class or interface
1743          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1744          * @throws VerifyError if the newly created class cannot be verified
1745          * @throws LinkageError if the newly created class cannot be linked for any other reason
1746          * @throws NullPointerException if {@code bytes} is {@code null}
1747          * @since 9
1748          * @see MethodHandles#privateLookupIn
1749          * @see Lookup#dropLookupMode
1750          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1751          */
1752         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1753             if ((lookupModes() & PACKAGE) == 0)
1754                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1755             return makeClassDefiner(bytes.clone()).defineClass(false);
1756         }
1757 
1758         /**
1759          * The set of class options that specify whether a hidden class created by
1760          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1761          * Lookup::defineHiddenClass} method is dynamically added as a new member
1762          * to the nest of a lookup class and/or whether a hidden class has
1763          * a strong relationship with the class loader marked as its defining loader.
1764          *
1765          * @since 15
1766          */
1767         public enum ClassOption {
1768             /**
1769              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1770              * of a lookup class as a nestmate.
1771              *
1772              * <p> A hidden nestmate class has access to the private members of all
1773              * classes and interfaces in the same nest.
1774              *
1775              * @see Class#getNestHost()
1776              */
1777             NESTMATE(NESTMATE_CLASS),
1778 
1779             /**
1780              * Specifies that a hidden class has a <em>strong</em>
1781              * relationship with the class loader marked as its defining loader,
1782              * as a normal class or interface has with its own defining loader.
1783              * This means that the hidden class may be unloaded if and only if
1784              * its defining loader is not reachable and thus may be reclaimed
1785              * by a garbage collector (JLS {@jls 12.7}).
1786              *
1787              * <p> By default, a hidden class or interface may be unloaded
1788              * even if the class loader that is marked as its defining loader is
1789              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1790 
1791              *
1792              * @jls 12.7 Unloading of Classes and Interfaces
1793              */
1794             STRONG(STRONG_LOADER_LINK);
1795 
1796             /* the flag value is used by VM at define class time */
1797             private final int flag;
1798             ClassOption(int flag) {
1799                 this.flag = flag;
1800             }
1801 
1802             static int optionsToFlag(ClassOption[] options) {
1803                 int flags = 0;
1804                 for (ClassOption cp : options) {
1805                     if ((flags & cp.flag) != 0) {
1806                         throw new IllegalArgumentException("Duplicate ClassOption " + cp);
1807                     }
1808                     flags |= cp.flag;
1809                 }
1810                 return flags;
1811             }
1812         }
1813 
1814         /**
1815          * Creates a <em>hidden</em> class or interface from {@code bytes},
1816          * returning a {@code Lookup} on the newly created class or interface.
1817          *
1818          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1819          * which either defines {@code C} directly or delegates to another class loader.
1820          * A class loader defines {@code C} directly by invoking
1821          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1822          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1823          * to derive {@code C} from a purported representation in {@code class} file format.
1824          * In situations where use of a class loader is undesirable, a class or interface
1825          * {@code C} can be created by this method instead. This method is capable of
1826          * defining {@code C}, and thereby creating it, without invoking
1827          * {@code ClassLoader::defineClass}.
1828          * Instead, this method defines {@code C} as if by arranging for
1829          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1830          * from a purported representation in {@code class} file format
1831          * using the following rules:
1832          *
1833          * <ol>
1834          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1835          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1836          * This level of access is needed to create {@code C} in the module
1837          * of the lookup class of this {@code Lookup}.</li>
1838          *
1839          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1840          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1841          * The major and minor version may differ from the {@code class} file version
1842          * of the lookup class of this {@code Lookup}.</li>
1843          *
1844          * <li> The value of {@code this_class} must be a valid index in the
1845          * {@code constant_pool} table, and the entry at that index must be a valid
1846          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1847          * encoded in internal form that is specified by this structure. {@code N} must
1848          * denote a class or interface in the same package as the lookup class.</li>
1849          *
1850          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1851          * where {@code <suffix>} is an unqualified name.
1852          *
1853          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1854          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1855          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1856          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1857          * refers to the new {@code CONSTANT_Utf8_info} structure.
1858          *
1859          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1860          *
1861          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1862          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1863          * with the following adjustments:
1864          * <ul>
1865          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1866          * that includes a single {@code "."} character, even though this is not a valid
1867          * binary class or interface name in internal form.</li>
1868          *
1869          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1870          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1871          *
1872          * <li> {@code C} is considered to have the same runtime
1873          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1874          * and {@linkplain java.security.ProtectionDomain protection domain}
1875          * as the lookup class of this {@code Lookup}.
1876          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1877          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1878          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1879          * <ul>
1880          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1881          *      even though this is not a valid binary class or interface name.</li>
1882          * <li> {@link Class#descriptorString()} returns the string
1883          *      {@code "L" + N + "." + <suffix> + ";"},
1884          *      even though this is not a valid type descriptor name.</li>
1885          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1886          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1887          * </ul>
1888          * </ul>
1889          * </li>
1890          * </ol>
1891          *
1892          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1893          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1894          * <ul>
1895          * <li> During verification, whenever it is necessary to load the class named
1896          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1897          * made of any class loader.</li>
1898          *
1899          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1900          * by {@code this_class}, the symbolic reference is considered to be resolved to
1901          * {@code C} and resolution always succeeds immediately.</li>
1902          * </ul>
1903          *
1904          * <p> If the {@code initialize} parameter is {@code true},
1905          * then {@code C} is initialized by the Java Virtual Machine.
1906          *
1907          * <p> The newly created class or interface {@code C} serves as the
1908          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
1909          * returned by this method. {@code C} is <em>hidden</em> in the sense that
1910          * no other class or interface can refer to {@code C} via a constant pool entry.
1911          * That is, a hidden class or interface cannot be named as a supertype, a field type,
1912          * a method parameter type, or a method return type by any other class.
1913          * This is because a hidden class or interface does not have a binary name, so
1914          * there is no internal form available to record in any class's constant pool.
1915          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1916          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1917          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
1918          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1919          * JVM Tool Interface</a>.
1920          *
1921          * <p> A class or interface created by
1922          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1923          * a class loader} has a strong relationship with that class loader.
1924          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1925          * that {@linkplain Class#getClassLoader() defined it}.
1926          * This means that a class created by a class loader may be unloaded if and
1927          * only if its defining loader is not reachable and thus may be reclaimed
1928          * by a garbage collector (JLS {@jls 12.7}).
1929          *
1930          * By default, however, a hidden class or interface may be unloaded even if
1931          * the class loader that is marked as its defining loader is
1932          * <a href="../ref/package-summary.html#reachability">reachable</a>.
1933          * This behavior is useful when a hidden class or interface serves multiple
1934          * classes defined by arbitrary class loaders.  In other cases, a hidden
1935          * class or interface may be linked to a single class (or a small number of classes)
1936          * with the same defining loader as the hidden class or interface.
1937          * In such cases, where the hidden class or interface must be coterminous
1938          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1939          * option may be passed in {@code options}.
1940          * This arranges for a hidden class to have the same strong relationship
1941          * with the class loader marked as its defining loader,
1942          * as a normal class or interface has with its own defining loader.
1943          *
1944          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1945          * may still prevent a hidden class or interface from being
1946          * unloaded by ensuring that the {@code Class} object is reachable.
1947          *
1948          * <p> The unloading characteristics are set for each hidden class when it is
1949          * defined, and cannot be changed later.  An advantage of allowing hidden classes
1950          * to be unloaded independently of the class loader marked as their defining loader
1951          * is that a very large number of hidden classes may be created by an application.
1952          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1953          * just as if normal classes were created by class loaders.
1954          *
1955          * <p> Classes and interfaces in a nest are allowed to have mutual access to
1956          * their private members.  The nest relationship is determined by
1957          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
1958          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
1959          * By default, a hidden class belongs to a nest consisting only of itself
1960          * because a hidden class has no binary name.
1961          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1962          * to create a hidden class or interface {@code C} as a member of a nest.
1963          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1964          * in the {@code ClassFile} structure from which {@code C} was derived.
1965          * Instead, the following rules determine the nest host of {@code C}:
1966          * <ul>
1967          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1968          *     been determined, then let {@code H} be the nest host of the lookup class.
1969          *     Otherwise, the nest host of the lookup class is determined using the
1970          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
1971          * <li>The nest host of {@code C} is determined to be {@code H},
1972          *     the nest host of the lookup class.</li>
1973          * </ul>
1974          *
1975          * <p> A hidden class or interface may be serializable, but this requires a custom
1976          * serialization mechanism in order to ensure that instances are properly serialized
1977          * and deserialized. The default serialization mechanism supports only classes and
1978          * interfaces that are discoverable by their class name.
1979          *
1980          * @param bytes the bytes that make up the class data,
1981          * in the format of a valid {@code class} file as defined by
1982          * <cite>The Java Virtual Machine Specification</cite>.
1983          * @param initialize if {@code true} the class will be initialized.
1984          * @param options {@linkplain ClassOption class options}
1985          * @return the {@code Lookup} object on the hidden class,
1986          * with {@linkplain #ORIGINAL original} and
1987          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
1988          *
1989          * @throws IllegalAccessException if this {@code Lookup} does not have
1990          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1991          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1992          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1993          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1994          * than the lookup class or {@code bytes} is not a class or interface
1995          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1996          * @throws IncompatibleClassChangeError if the class or interface named as
1997          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1998          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1999          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2000          * {@code C} is {@code C} itself
2001          * @throws VerifyError if the newly created class cannot be verified
2002          * @throws LinkageError if the newly created class cannot be linked for any other reason
2003          * @throws NullPointerException if any parameter is {@code null}
2004          *
2005          * @since 15
2006          * @see Class#isHidden()
2007          * @jvms 4.2.1 Binary Class and Interface Names
2008          * @jvms 4.2.2 Unqualified Names
2009          * @jvms 4.7.28 The {@code NestHost} Attribute
2010          * @jvms 4.7.29 The {@code NestMembers} Attribute
2011          * @jvms 5.4.3.1 Class and Interface Resolution
2012          * @jvms 5.4.4 Access Control
2013          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2014          * @jvms 5.4 Linking
2015          * @jvms 5.5 Initialization
2016          * @jls 12.7 Unloading of Classes and Interfaces
2017          */
2018         @SuppressWarnings("doclint:reference") // cross-module links
2019         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2020                 throws IllegalAccessException
2021         {
2022             Objects.requireNonNull(bytes);
2023             int flags = ClassOption.optionsToFlag(options);
2024             if (!hasFullPrivilegeAccess()) {
2025                 throw new IllegalAccessException(this + " does not have full privilege access");
2026             }
2027 
2028             return makeHiddenClassDefiner(bytes.clone(), false, flags).defineClassAsLookup(initialize);
2029         }
2030 
2031         /**
2032          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2033          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2034          * returning a {@code Lookup} on the newly created class or interface.
2035          *
2036          * <p> This method is equivalent to calling
2037          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2038          * as if the hidden class is injected with a private static final <i>unnamed</i>
2039          * field which is initialized with the given {@code classData} at
2040          * the first instruction of the class initializer.
2041          * The newly created class is linked by the Java Virtual Machine.
2042          *
2043          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2044          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2045          * methods can be used to retrieve the {@code classData}.
2046          *
2047          * @apiNote
2048          * A framework can create a hidden class with class data with one or more
2049          * objects and load the class data as dynamically-computed constant(s)
2050          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2051          * Class data} is accessible only to the lookup object created by the newly
2052          * defined hidden class but inaccessible to other members in the same nest
2053          * (unlike private static fields that are accessible to nestmates).
2054          * Care should be taken w.r.t. mutability for example when passing
2055          * an array or other mutable structure through the class data.
2056          * Changing any value stored in the class data at runtime may lead to
2057          * unpredictable behavior.
2058          * If the class data is a {@code List}, it is good practice to make it
2059          * unmodifiable for example via {@link List#of List::of}.
2060          *
2061          * @param bytes     the class bytes
2062          * @param classData pre-initialized class data
2063          * @param initialize if {@code true} the class will be initialized.
2064          * @param options   {@linkplain ClassOption class options}
2065          * @return the {@code Lookup} object on the hidden class,
2066          * with {@linkplain #ORIGINAL original} and
2067          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2068          *
2069          * @throws IllegalAccessException if this {@code Lookup} does not have
2070          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2071          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2072          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2073          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2074          * than the lookup class or {@code bytes} is not a class or interface
2075          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2076          * @throws IncompatibleClassChangeError if the class or interface named as
2077          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2078          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2079          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2080          * {@code C} is {@code C} itself
2081          * @throws VerifyError if the newly created class cannot be verified
2082          * @throws LinkageError if the newly created class cannot be linked for any other reason
2083          * @throws NullPointerException if any parameter is {@code null}
2084          *
2085          * @since 16
2086          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2087          * @see Class#isHidden()
2088          * @see MethodHandles#classData(Lookup, String, Class)
2089          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2090          * @jvms 4.2.1 Binary Class and Interface Names
2091          * @jvms 4.2.2 Unqualified Names
2092          * @jvms 4.7.28 The {@code NestHost} Attribute
2093          * @jvms 4.7.29 The {@code NestMembers} Attribute
2094          * @jvms 5.4.3.1 Class and Interface Resolution
2095          * @jvms 5.4.4 Access Control
2096          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2097          * @jvms 5.4 Linking
2098          * @jvms 5.5 Initialization
2099          * @jls 12.7 Unloading of Classes and Interfaces
2100          */
2101         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2102                 throws IllegalAccessException
2103         {
2104             Objects.requireNonNull(bytes);
2105             Objects.requireNonNull(classData);
2106 
2107             int flags = ClassOption.optionsToFlag(options);
2108 
2109             if (!hasFullPrivilegeAccess()) {
2110                 throw new IllegalAccessException(this + " does not have full privilege access");
2111             }
2112 
2113             return makeHiddenClassDefiner(bytes.clone(), false, flags)
2114                        .defineClassAsLookup(initialize, classData);
2115         }
2116 
2117         // A default dumper for writing class files passed to Lookup::defineClass
2118         // and Lookup::defineHiddenClass to disk for debugging purposes.  To enable,
2119         // set -Djdk.invoke.MethodHandle.dumpHiddenClassFiles or
2120         //     -Djdk.invoke.MethodHandle.dumpHiddenClassFiles=true
2121         //
2122         // This default dumper does not dump hidden classes defined by LambdaMetafactory
2123         // and LambdaForms and method handle internals.  They are dumped via
2124         // different ClassFileDumpers.
2125         private static ClassFileDumper defaultDumper() {
2126             return DEFAULT_DUMPER;
2127         }
2128 
2129         private static final ClassFileDumper DEFAULT_DUMPER = ClassFileDumper.getInstance(
2130                 "jdk.invoke.MethodHandle.dumpClassFiles", "DUMP_CLASS_FILES");
2131 
2132         /**
2133          * This method checks the class file version and the structure of `this_class`.
2134          * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2135          * that is in the named package.
2136          *
2137          * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2138          * or the class is not in the given package name.
2139          */
2140         static String validateAndFindInternalName(byte[] bytes, String pkgName) {
2141             int magic = readInt(bytes, 0);
2142             if (magic != ClassFile.MAGIC_NUMBER) {
2143                 throw new ClassFormatError("Incompatible magic value: " + magic);
2144             }
2145             // We have to read major and minor this way as ClassFile API throws IAE
2146             // yet we want distinct ClassFormatError and UnsupportedClassVersionError
2147             int minor = readUnsignedShort(bytes, 4);
2148             int major = readUnsignedShort(bytes, 6);
2149 
2150             if (!VM.isSupportedClassFileVersion(major, minor)) {
2151                 throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2152             }
2153 
2154             String name;
2155             ClassDesc sym;
2156             int accessFlags;
2157             try {
2158                 ClassModel cm = ClassFile.of().parse(bytes);
2159                 var thisClass = cm.thisClass();
2160                 name = thisClass.asInternalName();
2161                 sym = thisClass.asSymbol();
2162                 accessFlags = cm.flags().flagsMask();
2163             } catch (IllegalArgumentException e) {
2164                 ClassFormatError cfe = new ClassFormatError();
2165                 cfe.initCause(e);
2166                 throw cfe;
2167             }
2168             // must be a class or interface
2169             if ((accessFlags & ACC_MODULE) != 0) {
2170                 throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2171             }
2172 
2173             String pn = sym.packageName();
2174             if (!pn.equals(pkgName)) {
2175                 throw newIllegalArgumentException(name + " not in same package as lookup class");
2176             }
2177 
2178             return name;
2179         }
2180 
2181         private static int readInt(byte[] bytes, int offset) {
2182             if ((offset + 4) > bytes.length) {
2183                 throw new ClassFormatError("Invalid ClassFile structure");
2184             }
2185             return ((bytes[offset] & 0xFF) << 24)
2186                     | ((bytes[offset + 1] & 0xFF) << 16)
2187                     | ((bytes[offset + 2] & 0xFF) << 8)
2188                     | (bytes[offset + 3] & 0xFF);
2189         }
2190 
2191         private static int readUnsignedShort(byte[] bytes, int offset) {
2192             if ((offset+2) > bytes.length) {
2193                 throw new ClassFormatError("Invalid ClassFile structure");
2194             }
2195             return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2196         }
2197 
2198         /*
2199          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2200          * from the given bytes.
2201          *
2202          * Caller should make a defensive copy of the arguments if needed
2203          * before calling this factory method.
2204          *
2205          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2206          * {@code bytes} denotes a class in a different package than the lookup class
2207          */
2208         private ClassDefiner makeClassDefiner(byte[] bytes) {
2209             var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2210             return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, defaultDumper());
2211         }
2212 
2213         /**
2214          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2215          * from the given bytes.  No package name check on the given bytes.
2216          *
2217          * @param internalName internal name
2218          * @param bytes   class bytes
2219          * @param dumper  dumper to write the given bytes to the dumper's output directory
2220          * @return ClassDefiner that defines a normal class of the given bytes.
2221          */
2222         ClassDefiner makeClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) {
2223             // skip package name validation
2224             return new ClassDefiner(this, internalName, bytes, STRONG_LOADER_LINK, dumper);
2225         }
2226 
2227         /**
2228          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2229          * from the given bytes.  The name must be in the same package as the lookup class.
2230          *
2231          * Caller should make a defensive copy of the arguments if needed
2232          * before calling this factory method.
2233          *
2234          * @param bytes   class bytes
2235          * @param dumper dumper to write the given bytes to the dumper's output directory
2236          * @return ClassDefiner that defines a hidden class of the given bytes.
2237          *
2238          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2239          * {@code bytes} denotes a class in a different package than the lookup class
2240          */
2241         ClassDefiner makeHiddenClassDefiner(byte[] bytes, ClassFileDumper dumper) {
2242             var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2243             return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0);
2244         }
2245 
2246         /**
2247          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2248          * from the given bytes and options.
2249          * The name must be in the same package as the lookup class.
2250          *
2251          * Caller should make a defensive copy of the arguments if needed
2252          * before calling this factory method.
2253          *
2254          * @param bytes   class bytes
2255          * @param flags   class option flag mask
2256          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2257          * @return ClassDefiner that defines a hidden class of the given bytes and options
2258          *
2259          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2260          * {@code bytes} denotes a class in a different package than the lookup class
2261          */
2262         private ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2263                                                     boolean accessVmAnnotations,
2264                                                     int flags) {
2265             var internalName = validateAndFindInternalName(bytes, lookupClass().getPackageName());
2266             return makeHiddenClassDefiner(internalName, bytes, accessVmAnnotations, defaultDumper(), flags);
2267         }
2268 
2269         /**
2270          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2271          * from the given bytes and the given options.  No package name check on the given bytes.
2272          *
2273          * @param internalName internal name that specifies the prefix of the hidden class
2274          * @param bytes   class bytes
2275          * @param dumper  dumper to write the given bytes to the dumper's output directory
2276          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2277          */
2278         ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper) {
2279             Objects.requireNonNull(dumper);
2280             // skip name and access flags validation
2281             return makeHiddenClassDefiner(internalName, bytes, false, dumper, 0);
2282         }
2283 
2284         /**
2285          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2286          * from the given bytes and the given options.  No package name check on the given bytes.
2287          *
2288          * @param internalName internal name that specifies the prefix of the hidden class
2289          * @param bytes   class bytes
2290          * @param flags   class options flag mask
2291          * @param dumper  dumper to write the given bytes to the dumper's output directory
2292          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2293          */
2294         ClassDefiner makeHiddenClassDefiner(String internalName, byte[] bytes, ClassFileDumper dumper, int flags) {
2295             Objects.requireNonNull(dumper);
2296             // skip name and access flags validation
2297             return makeHiddenClassDefiner(internalName, bytes, false, dumper, flags);
2298         }
2299 
2300         /**
2301          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2302          * from the given class file and options.
2303          *
2304          * @param internalName internal name
2305          * @param bytes Class byte array
2306          * @param flags class option flag mask
2307          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2308          * @param dumper dumper to write the given bytes to the dumper's output directory
2309          */
2310         private ClassDefiner makeHiddenClassDefiner(String internalName,
2311                                                     byte[] bytes,
2312                                                     boolean accessVmAnnotations,
2313                                                     ClassFileDumper dumper,
2314                                                     int flags) {
2315             flags |= HIDDEN_CLASS;
2316             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2317                 // jdk.internal.vm.annotations are permitted for classes
2318                 // defined to boot loader and platform loader
2319                 flags |= ACCESS_VM_ANNOTATIONS;
2320             }
2321 
2322             return new ClassDefiner(this, internalName, bytes, flags, dumper);
2323         }
2324 
2325         record ClassDefiner(Lookup lookup, String internalName, byte[] bytes, int classFlags, ClassFileDumper dumper) {
2326             ClassDefiner {
2327                 assert ((classFlags & HIDDEN_CLASS) != 0 || (classFlags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2328             }
2329 
2330             Class<?> defineClass(boolean initialize) {
2331                 return defineClass(initialize, null);
2332             }
2333 
2334             Lookup defineClassAsLookup(boolean initialize) {
2335                 Class<?> c = defineClass(initialize, null);
2336                 return new Lookup(c, null, FULL_POWER_MODES);
2337             }
2338 
2339             /**
2340              * Defines the class of the given bytes and the given classData.
2341              * If {@code initialize} parameter is true, then the class will be initialized.
2342              *
2343              * @param initialize true if the class to be initialized
2344              * @param classData classData or null
2345              * @return the class
2346              *
2347              * @throws LinkageError linkage error
2348              */
2349             Class<?> defineClass(boolean initialize, Object classData) {
2350                 Class<?> lookupClass = lookup.lookupClass();
2351                 ClassLoader loader = lookupClass.getClassLoader();
2352                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2353                 Class<?> c = null;
2354                 try {
2355                     c = SharedSecrets.getJavaLangAccess()
2356                             .defineClass(loader, lookupClass, internalName, bytes, pd, initialize, classFlags, classData);
2357                     assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2358                     return c;
2359                 } finally {
2360                     // dump the classfile for debugging
2361                     if (dumper.isEnabled()) {
2362                         String name = internalName();
2363                         if (c != null) {
2364                             dumper.dumpClass(name, c, bytes);
2365                         } else {
2366                             dumper.dumpFailedClass(name, bytes);
2367                         }
2368                     }
2369                 }
2370             }
2371 
2372             /**
2373              * Defines the class of the given bytes and the given classData.
2374              * If {@code initialize} parameter is true, then the class will be initialized.
2375              *
2376              * @param initialize true if the class to be initialized
2377              * @param classData classData or null
2378              * @return a Lookup for the defined class
2379              *
2380              * @throws LinkageError linkage error
2381              */
2382             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2383                 Class<?> c = defineClass(initialize, classData);
2384                 return new Lookup(c, null, FULL_POWER_MODES);
2385             }
2386 
2387             private boolean isNestmate() {
2388                 return (classFlags & NESTMATE_CLASS) != 0;
2389             }
2390         }
2391 
2392         private ProtectionDomain lookupClassProtectionDomain() {
2393             ProtectionDomain pd = cachedProtectionDomain;
2394             if (pd == null) {
2395                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2396             }
2397             return pd;
2398         }
2399 
2400         // cached protection domain
2401         private volatile ProtectionDomain cachedProtectionDomain;
2402 
2403         // Make sure outer class is initialized first.
2404         static { IMPL_NAMES.getClass(); }
2405 
2406         /** Package-private version of lookup which is trusted. */
2407         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2408 
2409         /** Version of lookup which is trusted minimally.
2410          *  It can only be used to create method handles to publicly accessible
2411          *  members in packages that are exported unconditionally.
2412          */
2413         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2414 
2415         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2416             String name = lookupClass.getName();
2417             if (name.startsWith("java.lang.invoke."))
2418                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2419         }
2420 
2421         /**
2422          * Displays the name of the class from which lookups are to be made,
2423          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2424          * previous lookup class} if present.
2425          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2426          * If there are restrictions on the access permitted to this lookup,
2427          * this is indicated by adding a suffix to the class name, consisting
2428          * of a slash and a keyword.  The keyword represents the strongest
2429          * allowed access, and is chosen as follows:
2430          * <ul>
2431          * <li>If no access is allowed, the suffix is "/noaccess".
2432          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2433          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2434          * <li>If only public and module access are allowed, the suffix is "/module".
2435          * <li>If public and package access are allowed, the suffix is "/package".
2436          * <li>If public, package, and private access are allowed, the suffix is "/private".
2437          * </ul>
2438          * If none of the above cases apply, it is the case that
2439          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2440          * (public, module, package, private, and protected) is allowed.
2441          * In this case, no suffix is added.
2442          * This is true only of an object obtained originally from
2443          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2444          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2445          * always have restricted access, and will display a suffix.
2446          * <p>
2447          * (It may seem strange that protected access should be
2448          * stronger than private access.  Viewed independently from
2449          * package access, protected access is the first to be lost,
2450          * because it requires a direct subclass relationship between
2451          * caller and callee.)
2452          * @see #in
2453          */
2454         @Override
2455         public String toString() {
2456             String cname = lookupClass.getName();
2457             if (prevLookupClass != null)
2458                 cname += "/" + prevLookupClass.getName();
2459             switch (allowedModes) {
2460             case 0:  // no privileges
2461                 return cname + "/noaccess";
2462             case UNCONDITIONAL:
2463                 return cname + "/publicLookup";
2464             case PUBLIC:
2465                 return cname + "/public";
2466             case PUBLIC|MODULE:
2467                 return cname + "/module";
2468             case PUBLIC|PACKAGE:
2469             case PUBLIC|MODULE|PACKAGE:
2470                 return cname + "/package";
2471             case PUBLIC|PACKAGE|PRIVATE:
2472             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2473                     return cname + "/private";
2474             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2475             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2476             case FULL_POWER_MODES:
2477                     return cname;
2478             case TRUSTED:
2479                 return "/trusted";  // internal only; not exported
2480             default:  // Should not happen, but it's a bitfield...
2481                 cname = cname + "/" + Integer.toHexString(allowedModes);
2482                 assert(false) : cname;
2483                 return cname;
2484             }
2485         }
2486 
2487         /**
2488          * Produces a method handle for a static method.
2489          * The type of the method handle will be that of the method.
2490          * (Since static methods do not take receivers, there is no
2491          * additional receiver argument inserted into the method handle type,
2492          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2493          * The method and all its argument types must be accessible to the lookup object.
2494          * <p>
2495          * The returned method handle will have
2496          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2497          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2498          * <p>
2499          * If the returned method handle is invoked, the method's class will
2500          * be initialized, if it has not already been initialized.
2501          * <p><b>Example:</b>
2502          * {@snippet lang="java" :
2503 import static java.lang.invoke.MethodHandles.*;
2504 import static java.lang.invoke.MethodType.*;
2505 ...
2506 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2507   "asList", methodType(List.class, Object[].class));
2508 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2509          * }
2510          * @param refc the class from which the method is accessed
2511          * @param name the name of the method
2512          * @param type the type of the method
2513          * @return the desired method handle
2514          * @throws NoSuchMethodException if the method does not exist
2515          * @throws IllegalAccessException if access checking fails,
2516          *                                or if the method is not {@code static},
2517          *                                or if the method's variable arity modifier bit
2518          *                                is set and {@code asVarargsCollector} fails
2519          * @throws NullPointerException if any argument is null
2520          */
2521         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2522             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2523             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2524         }
2525 
2526         /**
2527          * Produces a method handle for a virtual method.
2528          * The type of the method handle will be that of the method,
2529          * with the receiver type (usually {@code refc}) prepended.
2530          * The method and all its argument types must be accessible to the lookup object.
2531          * <p>
2532          * When called, the handle will treat the first argument as a receiver
2533          * and, for non-private methods, dispatch on the receiver's type to determine which method
2534          * implementation to enter.
2535          * For private methods the named method in {@code refc} will be invoked on the receiver.
2536          * (The dispatching action is identical with that performed by an
2537          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2538          * <p>
2539          * The first argument will be of type {@code refc} if the lookup
2540          * class has full privileges to access the member.  Otherwise
2541          * the member must be {@code protected} and the first argument
2542          * will be restricted in type to the lookup class.
2543          * <p>
2544          * The returned method handle will have
2545          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2546          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2547          * <p>
2548          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2549          * instructions and method handles produced by {@code findVirtual},
2550          * if the class is {@code MethodHandle} and the name string is
2551          * {@code invokeExact} or {@code invoke}, the resulting
2552          * method handle is equivalent to one produced by
2553          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2554          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2555          * with the same {@code type} argument.
2556          * <p>
2557          * If the class is {@code VarHandle} and the name string corresponds to
2558          * the name of a signature-polymorphic access mode method, the resulting
2559          * method handle is equivalent to one produced by
2560          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2561          * the access mode corresponding to the name string and with the same
2562          * {@code type} arguments.
2563          * <p>
2564          * <b>Example:</b>
2565          * {@snippet lang="java" :
2566 import static java.lang.invoke.MethodHandles.*;
2567 import static java.lang.invoke.MethodType.*;
2568 ...
2569 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2570   "concat", methodType(String.class, String.class));
2571 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2572   "hashCode", methodType(int.class));
2573 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2574   "hashCode", methodType(int.class));
2575 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2576 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2577 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2578 // interface method:
2579 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2580   "subSequence", methodType(CharSequence.class, int.class, int.class));
2581 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2582 // constructor "internal method" must be accessed differently:
2583 MethodType MT_newString = methodType(void.class); //()V for new String()
2584 try { assertEquals("impossible", lookup()
2585         .findVirtual(String.class, "<init>", MT_newString));
2586  } catch (NoSuchMethodException ex) { } // OK
2587 MethodHandle MH_newString = publicLookup()
2588   .findConstructor(String.class, MT_newString);
2589 assertEquals("", (String) MH_newString.invokeExact());
2590          * }
2591          *
2592          * @param refc the class or interface from which the method is accessed
2593          * @param name the name of the method
2594          * @param type the type of the method, with the receiver argument omitted
2595          * @return the desired method handle
2596          * @throws NoSuchMethodException if the method does not exist
2597          * @throws IllegalAccessException if access checking fails,
2598          *                                or if the method is {@code static},
2599          *                                or if the method's variable arity modifier bit
2600          *                                is set and {@code asVarargsCollector} fails
2601          * @throws NullPointerException if any argument is null
2602          */
2603         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2604             if (refc == MethodHandle.class) {
2605                 MethodHandle mh = findVirtualForMH(name, type);
2606                 if (mh != null)  return mh;
2607             } else if (refc == VarHandle.class) {
2608                 MethodHandle mh = findVirtualForVH(name, type);
2609                 if (mh != null)  return mh;
2610             }
2611             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2612             MemberName method = resolveOrFail(refKind, refc, name, type);
2613             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2614         }
2615         private MethodHandle findVirtualForMH(String name, MethodType type) {
2616             // these names require special lookups because of the implicit MethodType argument
2617             if ("invoke".equals(name))
2618                 return invoker(type);
2619             if ("invokeExact".equals(name))
2620                 return exactInvoker(type);
2621             assert(!MemberName.isMethodHandleInvokeName(name));
2622             return null;
2623         }
2624         private MethodHandle findVirtualForVH(String name, MethodType type) {
2625             try {
2626                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2627             } catch (IllegalArgumentException e) {
2628                 return null;
2629             }
2630         }
2631 
2632         /**
2633          * Produces a method handle which creates an object and initializes it, using
2634          * the constructor of the specified type.
2635          * The parameter types of the method handle will be those of the constructor,
2636          * while the return type will be a reference to the constructor's class.
2637          * The constructor and all its argument types must be accessible to the lookup object.
2638          * <p>
2639          * The requested type must have a return type of {@code void}.
2640          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2641          * <p>
2642          * The returned method handle will have
2643          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2644          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2645          * <p>
2646          * If the returned method handle is invoked, the constructor's class will
2647          * be initialized, if it has not already been initialized.
2648          * <p><b>Example:</b>
2649          * {@snippet lang="java" :
2650 import static java.lang.invoke.MethodHandles.*;
2651 import static java.lang.invoke.MethodType.*;
2652 ...
2653 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2654   ArrayList.class, methodType(void.class, Collection.class));
2655 Collection orig = Arrays.asList("x", "y");
2656 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2657 assert(orig != copy);
2658 assertEquals(orig, copy);
2659 // a variable-arity constructor:
2660 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2661   ProcessBuilder.class, methodType(void.class, String[].class));
2662 ProcessBuilder pb = (ProcessBuilder)
2663   MH_newProcessBuilder.invoke("x", "y", "z");
2664 assertEquals("[x, y, z]", pb.command().toString());
2665          * }
2666          *
2667          *
2668          * @param refc the class or interface from which the method is accessed
2669          * @param type the type of the method, with the receiver argument omitted, and a void return type
2670          * @return the desired method handle
2671          * @throws NoSuchMethodException if the constructor does not exist
2672          * @throws IllegalAccessException if access checking fails
2673          *                                or if the method's variable arity modifier bit
2674          *                                is set and {@code asVarargsCollector} fails
2675          * @throws NullPointerException if any argument is null
2676          */
2677         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2678             if (refc.isArray()) {
2679                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2680             }
2681             if (type.returnType() != void.class) {
2682                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2683             }
2684             String name = ConstantDescs.INIT_NAME;
2685             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2686             return getDirectConstructor(refc, ctor);
2687         }
2688 
2689         /**
2690          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2691          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2692          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2693          * and then determines whether the class is accessible to this lookup object.
2694          * <p>
2695          * For a class or an interface, the name is the {@linkplain ClassLoader##binary-name binary name}.
2696          * For an array class of {@code n} dimensions, the name begins with {@code n} occurrences
2697          * of {@code '['} and followed by the element type as encoded in the
2698          * {@linkplain Class##nameFormat table} specified in {@link Class#getName}.
2699          * <p>
2700          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2701          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2702          *
2703          * @param targetName the {@linkplain ClassLoader##binary-name binary name} of the class
2704          *                   or the string representing an array class
2705          * @return the requested class.
2706          * @throws LinkageError if the linkage fails
2707          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2708          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2709          * modes.
2710          * @throws NullPointerException if {@code targetName} is null
2711          * @since 9
2712          * @jvms 5.4.3.1 Class and Interface Resolution
2713          */
2714         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2715             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2716             return accessClass(targetClass);
2717         }
2718 
2719         /**
2720          * Ensures that {@code targetClass} has been initialized. The class
2721          * to be initialized must be {@linkplain #accessClass accessible}
2722          * to this {@code Lookup} object.  This method causes {@code targetClass}
2723          * to be initialized if it has not been already initialized,
2724          * as specified in JVMS {@jvms 5.5}.
2725          *
2726          * <p>
2727          * This method returns when {@code targetClass} is fully initialized, or
2728          * when {@code targetClass} is being initialized by the current thread.
2729          *
2730          * @param <T> the type of the class to be initialized
2731          * @param targetClass the class to be initialized
2732          * @return {@code targetClass} that has been initialized, or that is being
2733          *         initialized by the current thread.
2734          *
2735          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2736          *          or array class
2737          * @throws  IllegalAccessException if {@code targetClass} is not
2738          *          {@linkplain #accessClass accessible} to this lookup
2739          * @throws  ExceptionInInitializerError if the class initialization provoked
2740          *          by this method fails
2741          * @since 15
2742          * @jvms 5.5 Initialization
2743          */
2744         public <T> Class<T> ensureInitialized(Class<T> targetClass) throws IllegalAccessException {
2745             if (targetClass.isPrimitive())
2746                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2747             if (targetClass.isArray())
2748                 throw new IllegalArgumentException(targetClass + " is an array class");
2749 
2750             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2751                 throw makeAccessException(targetClass);
2752             }
2753 
2754             // ensure class initialization
2755             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2756             return targetClass;
2757         }
2758 
2759         /*
2760          * Returns IllegalAccessException due to access violation to the given targetClass.
2761          *
2762          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2763          * which verifies access to a class rather a member.
2764          */
2765         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2766             String message = "access violation: "+ targetClass;
2767             if (this == MethodHandles.publicLookup()) {
2768                 message += ", from public Lookup";
2769             } else {
2770                 Module m = lookupClass().getModule();
2771                 message += ", from " + lookupClass() + " (" + m + ")";
2772                 if (prevLookupClass != null) {
2773                     message += ", previous lookup " +
2774                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2775                 }
2776             }
2777             return new IllegalAccessException(message);
2778         }
2779 
2780         /**
2781          * Determines if a class can be accessed from the lookup context defined by
2782          * this {@code Lookup} object. The static initializer of the class is not run.
2783          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2784          * if the element type of the array class is accessible.  Otherwise,
2785          * {@code targetClass} is determined as accessible as follows.
2786          *
2787          * <p>
2788          * If {@code targetClass} is in the same module as the lookup class,
2789          * the lookup class is {@code LC} in module {@code M1} and
2790          * the previous lookup class is in module {@code M0} or
2791          * {@code null} if not present,
2792          * {@code targetClass} is accessible if and only if one of the following is true:
2793          * <ul>
2794          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2795          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2796          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2797          *     in the same runtime package of {@code LC}.</li>
2798          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2799          *     a public type in {@code M1}.</li>
2800          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2801          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2802          *     if the previous lookup class is present; otherwise, {@code targetClass}
2803          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2804          * </ul>
2805          *
2806          * <p>
2807          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2808          * can access public types in all modules when the type is in a package
2809          * that is exported unconditionally.
2810          * <p>
2811          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2812          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2813          * is inaccessible.
2814          * <p>
2815          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2816          * {@code M1} is the module containing {@code lookupClass} and
2817          * {@code M2} is the module containing {@code targetClass},
2818          * then {@code targetClass} is accessible if and only if
2819          * <ul>
2820          * <li>{@code M1} reads {@code M2}, and
2821          * <li>{@code targetClass} is public and in a package exported by
2822          *     {@code M2} at least to {@code M1}.
2823          * </ul>
2824          * <p>
2825          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2826          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2827          * containing the previous lookup class, then {@code targetClass} is accessible
2828          * if and only if one of the following is true:
2829          * <ul>
2830          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2831          *     {@linkplain Module#canRead(Module)}  reads} {@code M0} and the type is
2832          *     in a package that is exported to at least {@code M1}.
2833          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2834          *     {@linkplain Module#canRead(Module)}  reads} {@code M1} and the type is
2835          *     in a package that is exported to at least {@code M0}.
2836          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2837          *     and {@code M1} reads {@code M2} and the type is in a package
2838          *     that is exported to at least both {@code M0} and {@code M2}.
2839          * </ul>
2840          * <p>
2841          * Otherwise, {@code targetClass} is not accessible.
2842          *
2843          * @param <T> the type of the class to be access-checked
2844          * @param targetClass the class to be access-checked
2845          * @return {@code targetClass} that has been access-checked
2846          * @throws IllegalAccessException if the class is not accessible from the lookup class
2847          * and previous lookup class, if present, using the allowed access modes.
2848          * @throws NullPointerException if {@code targetClass} is {@code null}
2849          * @since 9
2850          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2851          */
2852         public <T> Class<T> accessClass(Class<T> targetClass) throws IllegalAccessException {
2853             if (!isClassAccessible(targetClass)) {
2854                 throw makeAccessException(targetClass);
2855             }
2856             return targetClass;
2857         }
2858 
2859         /**
2860          * Produces an early-bound method handle for a virtual method.
2861          * It will bypass checks for overriding methods on the receiver,
2862          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2863          * instruction from within the explicitly specified {@code specialCaller}.
2864          * The type of the method handle will be that of the method,
2865          * with a suitably restricted receiver type prepended.
2866          * (The receiver type will be {@code specialCaller} or a subtype.)
2867          * The method and all its argument types must be accessible
2868          * to the lookup object.
2869          * <p>
2870          * Before method resolution,
2871          * if the explicitly specified caller class is not identical with the
2872          * lookup class, or if this lookup object does not have
2873          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2874          * privileges, the access fails.
2875          * <p>
2876          * The returned method handle will have
2877          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2878          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2879          * <p style="font-size:smaller;">
2880          * <em>(Note:  JVM internal methods named {@value ConstantDescs#INIT_NAME}
2881          * are not visible to this API,
2882          * even though the {@code invokespecial} instruction can refer to them
2883          * in special circumstances.  Use {@link #findConstructor findConstructor}
2884          * to access instance initialization methods in a safe manner.)</em>
2885          * <p><b>Example:</b>
2886          * {@snippet lang="java" :
2887 import static java.lang.invoke.MethodHandles.*;
2888 import static java.lang.invoke.MethodType.*;
2889 ...
2890 static class Listie extends ArrayList {
2891   public String toString() { return "[wee Listie]"; }
2892   static Lookup lookup() { return MethodHandles.lookup(); }
2893 }
2894 ...
2895 // no access to constructor via invokeSpecial:
2896 MethodHandle MH_newListie = Listie.lookup()
2897   .findConstructor(Listie.class, methodType(void.class));
2898 Listie l = (Listie) MH_newListie.invokeExact();
2899 try { assertEquals("impossible", Listie.lookup().findSpecial(
2900         Listie.class, "<init>", methodType(void.class), Listie.class));
2901  } catch (NoSuchMethodException ex) { } // OK
2902 // access to super and self methods via invokeSpecial:
2903 MethodHandle MH_super = Listie.lookup().findSpecial(
2904   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2905 MethodHandle MH_this = Listie.lookup().findSpecial(
2906   Listie.class, "toString" , methodType(String.class), Listie.class);
2907 MethodHandle MH_duper = Listie.lookup().findSpecial(
2908   Object.class, "toString" , methodType(String.class), Listie.class);
2909 assertEquals("[]", (String) MH_super.invokeExact(l));
2910 assertEquals(""+l, (String) MH_this.invokeExact(l));
2911 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2912 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2913         String.class, "toString", methodType(String.class), Listie.class));
2914  } catch (IllegalAccessException ex) { } // OK
2915 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
2916 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
2917          * }
2918          *
2919          * @param refc the class or interface from which the method is accessed
2920          * @param name the name of the method (which must not be "&lt;init&gt;")
2921          * @param type the type of the method, with the receiver argument omitted
2922          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
2923          * @return the desired method handle
2924          * @throws NoSuchMethodException if the method does not exist
2925          * @throws IllegalAccessException if access checking fails,
2926          *                                or if the method is {@code static},
2927          *                                or if the method's variable arity modifier bit
2928          *                                is set and {@code asVarargsCollector} fails
2929          * @throws NullPointerException if any argument is null
2930          */
2931         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
2932                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
2933             checkSpecialCaller(specialCaller, refc);
2934             Lookup specialLookup = this.in(specialCaller);
2935             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
2936             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
2937         }
2938 
2939         /**
2940          * Produces a method handle giving read access to a non-static field.
2941          * The type of the method handle will have a return type of the field's
2942          * value type.
2943          * The method handle's single argument will be the instance containing
2944          * the field.
2945          * Access checking is performed immediately on behalf of the lookup class.
2946          * @param refc the class or interface from which the method is accessed
2947          * @param name the field's name
2948          * @param type the field's type
2949          * @return a method handle which can load values from the field
2950          * @throws NoSuchFieldException if the field does not exist
2951          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2952          * @throws NullPointerException if any argument is null
2953          * @see #findVarHandle(Class, String, Class)
2954          */
2955         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2956             MemberName field = resolveOrFail(REF_getField, refc, name, type);
2957             return getDirectField(REF_getField, refc, field);
2958         }
2959 
2960         /**
2961          * Produces a method handle giving write access to a non-static field.
2962          * The type of the method handle will have a void return type.
2963          * The method handle will take two arguments, the instance containing
2964          * the field, and the value to be stored.
2965          * The second argument will be of the field's value type.
2966          * Access checking is performed immediately on behalf of the lookup class.
2967          * @param refc the class or interface from which the method is accessed
2968          * @param name the field's name
2969          * @param type the field's type
2970          * @return a method handle which can store values into the field
2971          * @throws NoSuchFieldException if the field does not exist
2972          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
2973          *                                or {@code final}
2974          * @throws NullPointerException if any argument is null
2975          * @see #findVarHandle(Class, String, Class)
2976          */
2977         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
2978             MemberName field = resolveOrFail(REF_putField, refc, name, type);
2979             return getDirectField(REF_putField, refc, field);
2980         }
2981 
2982         /**
2983          * Produces a VarHandle giving access to a non-static field {@code name}
2984          * of type {@code type} declared in a class of type {@code recv}.
2985          * The VarHandle's variable type is {@code type} and it has one
2986          * coordinate type, {@code recv}.
2987          * <p>
2988          * Access checking is performed immediately on behalf of the lookup
2989          * class.
2990          * <p>
2991          * Certain access modes of the returned VarHandle are unsupported under
2992          * the following conditions:
2993          * <ul>
2994          * <li>if the field is declared {@code final}, then the write, atomic
2995          *     update, numeric atomic update, and bitwise atomic update access
2996          *     modes are unsupported.
2997          * <li>if the field type is anything other than {@code byte},
2998          *     {@code short}, {@code char}, {@code int}, {@code long},
2999          *     {@code float}, or {@code double} then numeric atomic update
3000          *     access modes are unsupported.
3001          * <li>if the field type is anything other than {@code boolean},
3002          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3003          *     {@code long} then bitwise atomic update access modes are
3004          *     unsupported.
3005          * </ul>
3006          * <p>
3007          * If the field is declared {@code volatile} then the returned VarHandle
3008          * will override access to the field (effectively ignore the
3009          * {@code volatile} declaration) in accordance to its specified
3010          * access modes.
3011          * <p>
3012          * If the field type is {@code float} or {@code double} then numeric
3013          * and atomic update access modes compare values using their bitwise
3014          * representation (see {@link Float#floatToRawIntBits} and
3015          * {@link Double#doubleToRawLongBits}, respectively).
3016          * @apiNote
3017          * Bitwise comparison of {@code float} values or {@code double} values,
3018          * as performed by the numeric and atomic update access modes, differ
3019          * from the primitive {@code ==} operator and the {@link Float#equals}
3020          * and {@link Double#equals} methods, specifically with respect to
3021          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3022          * Care should be taken when performing a compare and set or a compare
3023          * and exchange operation with such values since the operation may
3024          * unexpectedly fail.
3025          * There are many possible NaN values that are considered to be
3026          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3027          * provided by Java can distinguish between them.  Operation failure can
3028          * occur if the expected or witness value is a NaN value and it is
3029          * transformed (perhaps in a platform specific manner) into another NaN
3030          * value, and thus has a different bitwise representation (see
3031          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3032          * details).
3033          * The values {@code -0.0} and {@code +0.0} have different bitwise
3034          * representations but are considered equal when using the primitive
3035          * {@code ==} operator.  Operation failure can occur if, for example, a
3036          * numeric algorithm computes an expected value to be say {@code -0.0}
3037          * and previously computed the witness value to be say {@code +0.0}.
3038          * @param recv the receiver class, of type {@code R}, that declares the
3039          * non-static field
3040          * @param name the field's name
3041          * @param type the field's type, of type {@code T}
3042          * @return a VarHandle giving access to non-static fields.
3043          * @throws NoSuchFieldException if the field does not exist
3044          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3045          * @throws NullPointerException if any argument is null
3046          * @since 9
3047          */
3048         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3049             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3050             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3051             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3052         }
3053 
3054         /**
3055          * Produces a method handle giving read access to a static field.
3056          * The type of the method handle will have a return type of the field's
3057          * value type.
3058          * The method handle will take no arguments.
3059          * Access checking is performed immediately on behalf of the lookup class.
3060          * <p>
3061          * If the returned method handle is invoked, the field's class will
3062          * be initialized, if it has not already been initialized.
3063          * @param refc the class or interface from which the method is accessed
3064          * @param name the field's name
3065          * @param type the field's type
3066          * @return a method handle which can load values from the field
3067          * @throws NoSuchFieldException if the field does not exist
3068          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3069          * @throws NullPointerException if any argument is null
3070          */
3071         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3072             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3073             return getDirectField(REF_getStatic, refc, field);
3074         }
3075 
3076         /**
3077          * Produces a method handle giving write access to a static field.
3078          * The type of the method handle will have a void return type.
3079          * The method handle will take a single
3080          * argument, of the field's value type, the value to be stored.
3081          * Access checking is performed immediately on behalf of the lookup class.
3082          * <p>
3083          * If the returned method handle is invoked, the field's class will
3084          * be initialized, if it has not already been initialized.
3085          * @param refc the class or interface from which the method is accessed
3086          * @param name the field's name
3087          * @param type the field's type
3088          * @return a method handle which can store values into the field
3089          * @throws NoSuchFieldException if the field does not exist
3090          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3091          *                                or is {@code final}
3092          * @throws NullPointerException if any argument is null
3093          */
3094         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3095             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3096             return getDirectField(REF_putStatic, refc, field);
3097         }
3098 
3099         /**
3100          * Produces a VarHandle giving access to a static field {@code name} of
3101          * type {@code type} declared in a class of type {@code decl}.
3102          * The VarHandle's variable type is {@code type} and it has no
3103          * coordinate types.
3104          * <p>
3105          * Access checking is performed immediately on behalf of the lookup
3106          * class.
3107          * <p>
3108          * If the returned VarHandle is operated on, the declaring class will be
3109          * initialized, if it has not already been initialized.
3110          * <p>
3111          * Certain access modes of the returned VarHandle are unsupported under
3112          * the following conditions:
3113          * <ul>
3114          * <li>if the field is declared {@code final}, then the write, atomic
3115          *     update, numeric atomic update, and bitwise atomic update access
3116          *     modes are unsupported.
3117          * <li>if the field type is anything other than {@code byte},
3118          *     {@code short}, {@code char}, {@code int}, {@code long},
3119          *     {@code float}, or {@code double}, then numeric atomic update
3120          *     access modes are unsupported.
3121          * <li>if the field type is anything other than {@code boolean},
3122          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3123          *     {@code long} then bitwise atomic update access modes are
3124          *     unsupported.
3125          * </ul>
3126          * <p>
3127          * If the field is declared {@code volatile} then the returned VarHandle
3128          * will override access to the field (effectively ignore the
3129          * {@code volatile} declaration) in accordance to its specified
3130          * access modes.
3131          * <p>
3132          * If the field type is {@code float} or {@code double} then numeric
3133          * and atomic update access modes compare values using their bitwise
3134          * representation (see {@link Float#floatToRawIntBits} and
3135          * {@link Double#doubleToRawLongBits}, respectively).
3136          * @apiNote
3137          * Bitwise comparison of {@code float} values or {@code double} values,
3138          * as performed by the numeric and atomic update access modes, differ
3139          * from the primitive {@code ==} operator and the {@link Float#equals}
3140          * and {@link Double#equals} methods, specifically with respect to
3141          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3142          * Care should be taken when performing a compare and set or a compare
3143          * and exchange operation with such values since the operation may
3144          * unexpectedly fail.
3145          * There are many possible NaN values that are considered to be
3146          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3147          * provided by Java can distinguish between them.  Operation failure can
3148          * occur if the expected or witness value is a NaN value and it is
3149          * transformed (perhaps in a platform specific manner) into another NaN
3150          * value, and thus has a different bitwise representation (see
3151          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3152          * details).
3153          * The values {@code -0.0} and {@code +0.0} have different bitwise
3154          * representations but are considered equal when using the primitive
3155          * {@code ==} operator.  Operation failure can occur if, for example, a
3156          * numeric algorithm computes an expected value to be say {@code -0.0}
3157          * and previously computed the witness value to be say {@code +0.0}.
3158          * @param decl the class that declares the static field
3159          * @param name the field's name
3160          * @param type the field's type, of type {@code T}
3161          * @return a VarHandle giving access to a static field
3162          * @throws NoSuchFieldException if the field does not exist
3163          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3164          * @throws NullPointerException if any argument is null
3165          * @since 9
3166          */
3167         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3168             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3169             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3170             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3171         }
3172 
3173         /**
3174          * Produces an early-bound method handle for a non-static method.
3175          * The receiver must have a supertype {@code defc} in which a method
3176          * of the given name and type is accessible to the lookup class.
3177          * The method and all its argument types must be accessible to the lookup object.
3178          * The type of the method handle will be that of the method,
3179          * without any insertion of an additional receiver parameter.
3180          * The given receiver will be bound into the method handle,
3181          * so that every call to the method handle will invoke the
3182          * requested method on the given receiver.
3183          * <p>
3184          * The returned method handle will have
3185          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3186          * the method's variable arity modifier bit ({@code 0x0080}) is set
3187          * <em>and</em> the trailing array argument is not the only argument.
3188          * (If the trailing array argument is the only argument,
3189          * the given receiver value will be bound to it.)
3190          * <p>
3191          * This is almost equivalent to the following code, with some differences noted below:
3192          * {@snippet lang="java" :
3193 import static java.lang.invoke.MethodHandles.*;
3194 import static java.lang.invoke.MethodType.*;
3195 ...
3196 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3197 MethodHandle mh1 = mh0.bindTo(receiver);
3198 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3199 return mh1;
3200          * }
3201          * where {@code defc} is either {@code receiver.getClass()} or a super
3202          * type of that class, in which the requested method is accessible
3203          * to the lookup class.
3204          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3205          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3206          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3207          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3208          * @param receiver the object from which the method is accessed
3209          * @param name the name of the method
3210          * @param type the type of the method, with the receiver argument omitted
3211          * @return the desired method handle
3212          * @throws NoSuchMethodException if the method does not exist
3213          * @throws IllegalAccessException if access checking fails
3214          *                                or if the method's variable arity modifier bit
3215          *                                is set and {@code asVarargsCollector} fails
3216          * @throws NullPointerException if any argument is null
3217          * @see MethodHandle#bindTo
3218          * @see #findVirtual
3219          */
3220         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3221             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3222             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3223             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3224             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3225                 throw new IllegalAccessException("The restricted defining class " +
3226                                                  mh.type().leadingReferenceParameter().getName() +
3227                                                  " is not assignable from receiver class " +
3228                                                  receiver.getClass().getName());
3229             }
3230             return mh.bindArgumentL(0, receiver).setVarargs(method);
3231         }
3232 
3233         /**
3234          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3235          * to <i>m</i>, if the lookup class has permission.
3236          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3237          * If <i>m</i> is virtual, overriding is respected on every call.
3238          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3239          * The type of the method handle will be that of the method,
3240          * with the receiver type prepended (but only if it is non-static).
3241          * If the method's {@code accessible} flag is not set,
3242          * access checking is performed immediately on behalf of the lookup class.
3243          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3244          * <p>
3245          * The returned method handle will have
3246          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3247          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3248          * <p>
3249          * If <i>m</i> is static, and
3250          * if the returned method handle is invoked, the method's class will
3251          * be initialized, if it has not already been initialized.
3252          * @param m the reflected method
3253          * @return a method handle which can invoke the reflected method
3254          * @throws IllegalAccessException if access checking fails
3255          *                                or if the method's variable arity modifier bit
3256          *                                is set and {@code asVarargsCollector} fails
3257          * @throws NullPointerException if the argument is null
3258          */
3259         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3260             if (m.getDeclaringClass() == MethodHandle.class) {
3261                 MethodHandle mh = unreflectForMH(m);
3262                 if (mh != null)  return mh;
3263             }
3264             if (m.getDeclaringClass() == VarHandle.class) {
3265                 MethodHandle mh = unreflectForVH(m);
3266                 if (mh != null)  return mh;
3267             }
3268             MemberName method = new MemberName(m);
3269             byte refKind = method.getReferenceKind();
3270             if (refKind == REF_invokeSpecial)
3271                 refKind = REF_invokeVirtual;
3272             assert(method.isMethod());
3273             @SuppressWarnings("deprecation")
3274             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3275             return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3276         }
3277         private MethodHandle unreflectForMH(Method m) {
3278             // these names require special lookups because they throw UnsupportedOperationException
3279             if (MemberName.isMethodHandleInvokeName(m.getName()))
3280                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3281             return null;
3282         }
3283         private MethodHandle unreflectForVH(Method m) {
3284             // these names require special lookups because they throw UnsupportedOperationException
3285             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3286                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3287             return null;
3288         }
3289 
3290         /**
3291          * Produces a method handle for a reflected method.
3292          * It will bypass checks for overriding methods on the receiver,
3293          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3294          * instruction from within the explicitly specified {@code specialCaller}.
3295          * The type of the method handle will be that of the method,
3296          * with a suitably restricted receiver type prepended.
3297          * (The receiver type will be {@code specialCaller} or a subtype.)
3298          * If the method's {@code accessible} flag is not set,
3299          * access checking is performed immediately on behalf of the lookup class,
3300          * as if {@code invokespecial} instruction were being linked.
3301          * <p>
3302          * Before method resolution,
3303          * if the explicitly specified caller class is not identical with the
3304          * lookup class, or if this lookup object does not have
3305          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3306          * privileges, the access fails.
3307          * <p>
3308          * The returned method handle will have
3309          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3310          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3311          * @param m the reflected method
3312          * @param specialCaller the class nominally calling the method
3313          * @return a method handle which can invoke the reflected method
3314          * @throws IllegalAccessException if access checking fails,
3315          *                                or if the method is {@code static},
3316          *                                or if the method's variable arity modifier bit
3317          *                                is set and {@code asVarargsCollector} fails
3318          * @throws NullPointerException if any argument is null
3319          */
3320         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3321             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3322             Lookup specialLookup = this.in(specialCaller);
3323             MemberName method = new MemberName(m, true);
3324             assert(method.isMethod());
3325             // ignore m.isAccessible:  this is a new kind of access
3326             return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3327         }
3328 
3329         /**
3330          * Produces a method handle for a reflected constructor.
3331          * The type of the method handle will be that of the constructor,
3332          * with the return type changed to the declaring class.
3333          * The method handle will perform a {@code newInstance} operation,
3334          * creating a new instance of the constructor's class on the
3335          * arguments passed to the method handle.
3336          * <p>
3337          * If the constructor's {@code accessible} flag is not set,
3338          * access checking is performed immediately on behalf of the lookup class.
3339          * <p>
3340          * The returned method handle will have
3341          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3342          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3343          * <p>
3344          * If the returned method handle is invoked, the constructor's class will
3345          * be initialized, if it has not already been initialized.
3346          * @param c the reflected constructor
3347          * @return a method handle which can invoke the reflected constructor
3348          * @throws IllegalAccessException if access checking fails
3349          *                                or if the method's variable arity modifier bit
3350          *                                is set and {@code asVarargsCollector} fails
3351          * @throws NullPointerException if the argument is null
3352          */
3353         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3354             MemberName ctor = new MemberName(c);
3355             assert(ctor.isConstructor());
3356             @SuppressWarnings("deprecation")
3357             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3358             return lookup.getDirectConstructor(ctor.getDeclaringClass(), ctor);
3359         }
3360 
3361         /*
3362          * Produces a method handle that is capable of creating instances of the given class
3363          * and instantiated by the given constructor.
3364          *
3365          * This method should only be used by ReflectionFactory::newConstructorForSerialization.
3366          */
3367         /* package-private */ MethodHandle serializableConstructor(Class<?> decl, Constructor<?> c) throws IllegalAccessException {
3368             MemberName ctor = new MemberName(c);
3369             assert(ctor.isConstructor() && constructorInSuperclass(decl, c));
3370             checkAccess(REF_newInvokeSpecial, decl, ctor);
3371             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3372             return DirectMethodHandle.makeAllocator(decl, ctor).setVarargs(ctor);
3373         }
3374 
3375         private static boolean constructorInSuperclass(Class<?> decl, Constructor<?> ctor) {
3376             if (decl == ctor.getDeclaringClass())
3377                 return true;
3378 
3379             Class<?> cl = decl;
3380             while ((cl = cl.getSuperclass()) != null) {
3381                 if (cl == ctor.getDeclaringClass()) {
3382                     return true;
3383                 }
3384             }
3385             return false;
3386         }
3387 
3388         /**
3389          * Produces a method handle giving read access to a reflected field.
3390          * The type of the method handle will have a return type of the field's
3391          * value type.
3392          * If the field is {@code static}, the method handle will take no arguments.
3393          * Otherwise, its single argument will be the instance containing
3394          * the field.
3395          * If the {@code Field} object's {@code accessible} flag is not set,
3396          * access checking is performed immediately on behalf of the lookup class.
3397          * <p>
3398          * If the field is static, and
3399          * if the returned method handle is invoked, the field's class will
3400          * be initialized, if it has not already been initialized.
3401          * @param f the reflected field
3402          * @return a method handle which can load values from the reflected field
3403          * @throws IllegalAccessException if access checking fails
3404          * @throws NullPointerException if the argument is null
3405          */
3406         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3407             return unreflectField(f, false);
3408         }
3409 
3410         /**
3411          * Produces a method handle giving write access to a reflected field.
3412          * The type of the method handle will have a void return type.
3413          * If the field is {@code static}, the method handle will take a single
3414          * argument, of the field's value type, the value to be stored.
3415          * Otherwise, the two arguments will be the instance containing
3416          * the field, and the value to be stored.
3417          * If the {@code Field} object's {@code accessible} flag is not set,
3418          * access checking is performed immediately on behalf of the lookup class.
3419          * <p>
3420          * If the field is {@code final}, write access will not be
3421          * allowed and access checking will fail, except under certain
3422          * narrow circumstances documented for {@link Field#set Field.set}.
3423          * A method handle is returned only if a corresponding call to
3424          * the {@code Field} object's {@code set} method could return
3425          * normally.  In particular, fields which are both {@code static}
3426          * and {@code final} may never be set.
3427          * <p>
3428          * If the field is {@code static}, and
3429          * if the returned method handle is invoked, the field's class will
3430          * be initialized, if it has not already been initialized.
3431          * @param f the reflected field
3432          * @return a method handle which can store values into the reflected field
3433          * @throws IllegalAccessException if access checking fails,
3434          *         or if the field is {@code final} and write access
3435          *         is not enabled on the {@code Field} object
3436          * @throws NullPointerException if the argument is null
3437          * @see <a href="{@docRoot}/java.base/java/lang/reflect/doc-files/MutationMethods.html">Mutation methods</a>
3438          */
3439         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3440             return unreflectField(f, true);
3441         }
3442 
3443         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3444             @SuppressWarnings("deprecation")
3445             boolean isAccessible = f.isAccessible();
3446             MemberName field = new MemberName(f, isSetter);
3447             if (isSetter && field.isFinal()) {
3448                 if (field.isTrustedFinalField()) {
3449                     String msg = field.isStatic() ? "static final field has no write access"
3450                                                   : "final field has no write access";
3451                     throw field.makeAccessException(msg, this);
3452                 }
3453                 // check if write access to final field allowed
3454                 if (!field.isStatic() && isAccessible) {
3455                     SharedSecrets.getJavaLangReflectAccess().checkAllowedToUnreflectFinalSetter(lookupClass, f);
3456                 }
3457             }
3458             assert(isSetter
3459                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3460                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3461             Lookup lookup = isAccessible ? IMPL_LOOKUP : this;
3462             return lookup.getDirectField(field.getReferenceKind(), f.getDeclaringClass(), field);
3463         }
3464 
3465         /**
3466          * Produces a VarHandle giving access to a reflected field {@code f}
3467          * of type {@code T} declared in a class of type {@code R}.
3468          * The VarHandle's variable type is {@code T}.
3469          * If the field is non-static the VarHandle has one coordinate type,
3470          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3471          * coordinate types.
3472          * <p>
3473          * Access checking is performed immediately on behalf of the lookup
3474          * class, regardless of the value of the field's {@code accessible}
3475          * flag.
3476          * <p>
3477          * If the field is static, and if the returned VarHandle is operated
3478          * on, the field's declaring class will be initialized, if it has not
3479          * already been initialized.
3480          * <p>
3481          * Certain access modes of the returned VarHandle are unsupported under
3482          * the following conditions:
3483          * <ul>
3484          * <li>if the field is declared {@code final}, then the write, atomic
3485          *     update, numeric atomic update, and bitwise atomic update access
3486          *     modes are unsupported.
3487          * <li>if the field type is anything other than {@code byte},
3488          *     {@code short}, {@code char}, {@code int}, {@code long},
3489          *     {@code float}, or {@code double} then numeric atomic update
3490          *     access modes are unsupported.
3491          * <li>if the field type is anything other than {@code boolean},
3492          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3493          *     {@code long} then bitwise atomic update access modes are
3494          *     unsupported.
3495          * </ul>
3496          * <p>
3497          * If the field is declared {@code volatile} then the returned VarHandle
3498          * will override access to the field (effectively ignore the
3499          * {@code volatile} declaration) in accordance to its specified
3500          * access modes.
3501          * <p>
3502          * If the field type is {@code float} or {@code double} then numeric
3503          * and atomic update access modes compare values using their bitwise
3504          * representation (see {@link Float#floatToRawIntBits} and
3505          * {@link Double#doubleToRawLongBits}, respectively).
3506          * @apiNote
3507          * Bitwise comparison of {@code float} values or {@code double} values,
3508          * as performed by the numeric and atomic update access modes, differ
3509          * from the primitive {@code ==} operator and the {@link Float#equals}
3510          * and {@link Double#equals} methods, specifically with respect to
3511          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3512          * Care should be taken when performing a compare and set or a compare
3513          * and exchange operation with such values since the operation may
3514          * unexpectedly fail.
3515          * There are many possible NaN values that are considered to be
3516          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3517          * provided by Java can distinguish between them.  Operation failure can
3518          * occur if the expected or witness value is a NaN value and it is
3519          * transformed (perhaps in a platform specific manner) into another NaN
3520          * value, and thus has a different bitwise representation (see
3521          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3522          * details).
3523          * The values {@code -0.0} and {@code +0.0} have different bitwise
3524          * representations but are considered equal when using the primitive
3525          * {@code ==} operator.  Operation failure can occur if, for example, a
3526          * numeric algorithm computes an expected value to be say {@code -0.0}
3527          * and previously computed the witness value to be say {@code +0.0}.
3528          * @param f the reflected field, with a field of type {@code T}, and
3529          * a declaring class of type {@code R}
3530          * @return a VarHandle giving access to non-static fields or a static
3531          * field
3532          * @throws IllegalAccessException if access checking fails
3533          * @throws NullPointerException if the argument is null
3534          * @since 9
3535          */
3536         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3537             MemberName getField = new MemberName(f, false);
3538             MemberName putField = new MemberName(f, true);
3539             return getFieldVarHandle(getField.getReferenceKind(), putField.getReferenceKind(),
3540                                      f.getDeclaringClass(), getField, putField);
3541         }
3542 
3543         /**
3544          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3545          * created by this lookup object or a similar one.
3546          * Security and access checks are performed to ensure that this lookup object
3547          * is capable of reproducing the target method handle.
3548          * This means that the cracking may fail if target is a direct method handle
3549          * but was created by an unrelated lookup object.
3550          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3551          * and was created by a lookup object for a different class.
3552          * @param target a direct method handle to crack into symbolic reference components
3553          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3554          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3555          * @throws    NullPointerException if the target is {@code null}
3556          * @see MethodHandleInfo
3557          * @since 1.8
3558          */
3559         public MethodHandleInfo revealDirect(MethodHandle target) {
3560             if (!target.isCrackable()) {
3561                 throw newIllegalArgumentException("not a direct method handle");
3562             }
3563             MemberName member = target.internalMemberName();
3564             Class<?> defc = member.getDeclaringClass();
3565             byte refKind = member.getReferenceKind();
3566             assert(MethodHandleNatives.refKindIsValid(refKind));
3567             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3568                 // Devirtualized method invocation is usually formally virtual.
3569                 // To avoid creating extra MemberName objects for this common case,
3570                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3571                 refKind = REF_invokeVirtual;
3572             if (refKind == REF_invokeVirtual && defc.isInterface())
3573                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3574                 refKind = REF_invokeInterface;
3575             // Check member access before cracking.
3576             try {
3577                 checkAccess(refKind, defc, member);
3578             } catch (IllegalAccessException ex) {
3579                 throw new IllegalArgumentException(ex);
3580             }
3581             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3582                 Class<?> callerClass = target.internalCallerClass();
3583                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3584                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3585             }
3586             // Produce the handle to the results.
3587             return new InfoFromMemberName(this, member, refKind);
3588         }
3589 
3590         //--- Helper methods, all package-private.
3591 
3592         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3593             checkSymbolicClass(refc);  // do this before attempting to resolve
3594             Objects.requireNonNull(name);
3595             Objects.requireNonNull(type);
3596             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3597                                             NoSuchFieldException.class);
3598         }
3599 
3600         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3601             checkSymbolicClass(refc);  // do this before attempting to resolve
3602             Objects.requireNonNull(type);
3603             checkMethodName(refKind, name);  // implicit null-check of name
3604             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3605                                             NoSuchMethodException.class);
3606         }
3607 
3608         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3609             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3610             Objects.requireNonNull(member.getName());
3611             Objects.requireNonNull(member.getType());
3612             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3613                                             ReflectiveOperationException.class);
3614         }
3615 
3616         MemberName resolveOrNull(byte refKind, MemberName member) {
3617             // do this before attempting to resolve
3618             if (!isClassAccessible(member.getDeclaringClass())) {
3619                 return null;
3620             }
3621             Objects.requireNonNull(member.getName());
3622             Objects.requireNonNull(member.getType());
3623             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3624         }
3625 
3626         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3627             // do this before attempting to resolve
3628             if (!isClassAccessible(refc)) {
3629                 return null;
3630             }
3631             Objects.requireNonNull(type);
3632             // implicit null-check of name
3633             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3634                 return null;
3635             }
3636             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3637         }
3638 
3639         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3640             if (!isClassAccessible(refc)) {
3641                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3642             }
3643         }
3644 
3645         boolean isClassAccessible(Class<?> refc) {
3646             Objects.requireNonNull(refc);
3647             Class<?> caller = lookupClassOrNull();
3648             Class<?> type = refc;
3649             while (type.isArray()) {
3650                 type = type.getComponentType();
3651             }
3652             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3653         }
3654 
3655         /** Check name for an illegal leading "&lt;" character. */
3656         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3657             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
3658                 throw new NoSuchMethodException("illegal method name: "+name);
3659         }
3660 
3661         /**
3662          * Find my trustable caller class if m is a caller sensitive method.
3663          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3664          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3665          */
3666         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3667             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3668                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3669                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3670             }
3671             return this;
3672         }
3673 
3674         /**
3675          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3676          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3677          *
3678          * @deprecated This method was originally designed to test {@code PRIVATE} access
3679          * that implies full privilege access but {@code MODULE} access has since become
3680          * independent of {@code PRIVATE} access.  It is recommended to call
3681          * {@link #hasFullPrivilegeAccess()} instead.
3682          * @since 9
3683          */
3684         @Deprecated(since="14")
3685         public boolean hasPrivateAccess() {
3686             return hasFullPrivilegeAccess();
3687         }
3688 
3689         /**
3690          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3691          * i.e. {@code PRIVATE} and {@code MODULE} access.
3692          * A {@code Lookup} object must have full privilege access in order to
3693          * access all members that are allowed to the
3694          * {@linkplain #lookupClass() lookup class}.
3695          *
3696          * @return {@code true} if this lookup has full privilege access.
3697          * @since 14
3698          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3699          */
3700         public boolean hasFullPrivilegeAccess() {
3701             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3702         }
3703 
3704         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3705             boolean wantStatic = (refKind == REF_invokeStatic);
3706             String message;
3707             if (m.isConstructor())
3708                 message = "expected a method, not a constructor";
3709             else if (!m.isMethod())
3710                 message = "expected a method";
3711             else if (wantStatic != m.isStatic())
3712                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3713             else
3714                 { checkAccess(refKind, refc, m); return; }
3715             throw m.makeAccessException(message, this);
3716         }
3717 
3718         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3719             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3720             String message;
3721             if (wantStatic != m.isStatic())
3722                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3723             else
3724                 { checkAccess(refKind, refc, m); return; }
3725             throw m.makeAccessException(message, this);
3726         }
3727 
3728         private boolean isArrayClone(byte refKind, Class<?> refc, MemberName m) {
3729             return Modifier.isProtected(m.getModifiers()) &&
3730                     refKind == REF_invokeVirtual &&
3731                     m.getDeclaringClass() == Object.class &&
3732                     m.getName().equals("clone") &&
3733                     refc.isArray();
3734         }
3735 
3736         /** Check public/protected/private bits on the symbolic reference class and its member. */
3737         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3738             assert(m.referenceKindIsConsistentWith(refKind) &&
3739                    MethodHandleNatives.refKindIsValid(refKind) &&
3740                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3741             int allowedModes = this.allowedModes;
3742             if (allowedModes == TRUSTED)  return;
3743             int mods = m.getModifiers();
3744             if (isArrayClone(refKind, refc, m)) {
3745                 // The JVM does this hack also.
3746                 // (See ClassVerifier::verify_invoke_instructions
3747                 // and LinkResolver::check_method_accessability.)
3748                 // Because the JVM does not allow separate methods on array types,
3749                 // there is no separate method for int[].clone.
3750                 // All arrays simply inherit Object.clone.
3751                 // But for access checking logic, we make Object.clone
3752                 // (normally protected) appear to be public.
3753                 // Later on, when the DirectMethodHandle is created,
3754                 // its leading argument will be restricted to the
3755                 // requested array type.
3756                 // N.B. The return type is not adjusted, because
3757                 // that is *not* the bytecode behavior.
3758                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3759             }
3760             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3761                 // cannot "new" a protected ctor in a different package
3762                 mods ^= Modifier.PROTECTED;
3763             }
3764             if (Modifier.isFinal(mods) &&
3765                     MethodHandleNatives.refKindIsSetter(refKind))
3766                 throw m.makeAccessException("unexpected set of a final field", this);
3767             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3768             if ((requestedModes & allowedModes) != 0) {
3769                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3770                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3771                     return;
3772             } else {
3773                 // Protected members can also be checked as if they were package-private.
3774                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3775                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3776                     return;
3777             }
3778             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3779         }
3780 
3781         String accessFailedMessage(Class<?> refc, MemberName m) {
3782             Class<?> defc = m.getDeclaringClass();
3783             int mods = m.getModifiers();
3784             // check the class first:
3785             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3786                                (defc == refc ||
3787                                 Modifier.isPublic(refc.getModifiers())));
3788             if (!classOK && (allowedModes & PACKAGE) != 0) {
3789                 // ignore previous lookup class to check if default package access
3790                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3791                            (defc == refc ||
3792                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3793             }
3794             if (!classOK)
3795                 return "class is not public";
3796             if (Modifier.isPublic(mods))
3797                 return "access to public member failed";  // (how?, module not readable?)
3798             if (Modifier.isPrivate(mods))
3799                 return "member is private";
3800             if (Modifier.isProtected(mods))
3801                 return "member is protected";
3802             return "member is private to package";
3803         }
3804 
3805         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3806             int allowedModes = this.allowedModes;
3807             if (allowedModes == TRUSTED)  return;
3808             if ((lookupModes() & PRIVATE) == 0
3809                 || (specialCaller != lookupClass()
3810                        // ensure non-abstract methods in superinterfaces can be special-invoked
3811                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3812                 throw new MemberName(specialCaller).
3813                     makeAccessException("no private access for invokespecial", this);
3814         }
3815 
3816         private boolean restrictProtectedReceiver(MemberName method) {
3817             // The accessing class only has the right to use a protected member
3818             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3819             if (!method.isProtected() || method.isStatic()
3820                 || allowedModes == TRUSTED
3821                 || method.getDeclaringClass() == lookupClass()
3822                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3823                 return false;
3824             return true;
3825         }
3826         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3827             assert(!method.isStatic());
3828             // receiver type of mh is too wide; narrow to caller
3829             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3830                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3831             }
3832             MethodType rawType = mh.type();
3833             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3834             MethodType narrowType = rawType.changeParameterType(0, caller);
3835             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3836             assert(mh.viewAsTypeChecks(narrowType, true));
3837             return mh.copyWith(narrowType, mh.form);
3838         }
3839 
3840         /** Check access and get the requested method. */
3841         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3842             final boolean doRestrict    = true;
3843             return getDirectMethodCommon(refKind, refc, method, doRestrict, callerLookup);
3844         }
3845         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3846         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3847             final boolean doRestrict    = false;
3848             return getDirectMethodCommon(REF_invokeSpecial, refc, method, doRestrict, callerLookup);
3849         }
3850         /** Common code for all methods; do not call directly except from immediately above. */
3851         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
3852                                                    boolean doRestrict,
3853                                                    Lookup boundCaller) throws IllegalAccessException {
3854             checkMethod(refKind, refc, method);
3855             assert(!method.isMethodHandleInvoke());
3856             if (refKind == REF_invokeSpecial &&
3857                 refc != lookupClass() &&
3858                 !refc.isInterface() && !lookupClass().isInterface() &&
3859                 refc != lookupClass().getSuperclass() &&
3860                 refc.isAssignableFrom(lookupClass())) {
3861                 assert(!method.getName().equals(ConstantDescs.INIT_NAME));  // not this code path
3862 
3863                 // Per JVMS 6.5, desc. of invokespecial instruction:
3864                 // If the method is in a superclass of the LC,
3865                 // and if our original search was above LC.super,
3866                 // repeat the search (symbolic lookup) from LC.super
3867                 // and continue with the direct superclass of that class,
3868                 // and so forth, until a match is found or no further superclasses exist.
3869                 // FIXME: MemberName.resolve should handle this instead.
3870                 Class<?> refcAsSuper = lookupClass();
3871                 MemberName m2;
3872                 do {
3873                     refcAsSuper = refcAsSuper.getSuperclass();
3874                     m2 = new MemberName(refcAsSuper,
3875                                         method.getName(),
3876                                         method.getMethodType(),
3877                                         REF_invokeSpecial);
3878                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
3879                 } while (m2 == null &&         // no method is found yet
3880                          refc != refcAsSuper); // search up to refc
3881                 if (m2 == null)  throw new InternalError(method.toString());
3882                 method = m2;
3883                 refc = refcAsSuper;
3884                 // redo basic checks
3885                 checkMethod(refKind, refc, method);
3886             }
3887             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
3888             MethodHandle mh = dmh;
3889             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
3890             if ((doRestrict && refKind == REF_invokeSpecial) ||
3891                     (MethodHandleNatives.refKindHasReceiver(refKind) &&
3892                             restrictProtectedReceiver(method) &&
3893                             // All arrays simply inherit the protected Object.clone method.
3894                             // The leading argument is already restricted to the requested
3895                             // array type (not the lookup class).
3896                             !isArrayClone(refKind, refc, method))) {
3897                 mh = restrictReceiver(method, dmh, lookupClass());
3898             }
3899             mh = maybeBindCaller(method, mh, boundCaller);
3900             mh = mh.setVarargs(method);
3901             return mh;
3902         }
3903         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
3904                                              throws IllegalAccessException {
3905             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
3906                 return mh;
3907 
3908             // boundCaller must have full privilege access.
3909             // It should have been checked by findBoundCallerLookup. Safe to check this again.
3910             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
3911                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3912 
3913             assert boundCaller.hasFullPrivilegeAccess();
3914 
3915             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
3916             // Note: caller will apply varargs after this step happens.
3917             return cbmh;
3918         }
3919 
3920         /** Check access and get the requested field. */
3921         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3922             return getDirectFieldCommon(refKind, refc, field);
3923         }
3924         /** Common code for all fields; do not call directly except from immediately above. */
3925         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
3926             checkField(refKind, refc, field);
3927             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
3928             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
3929                                     restrictProtectedReceiver(field));
3930             if (doRestrict)
3931                 return restrictReceiver(field, dmh, lookupClass());
3932             return dmh;
3933         }
3934         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
3935                                             Class<?> refc, MemberName getField, MemberName putField)
3936                 throws IllegalAccessException {
3937             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField);
3938         }
3939         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
3940                                                   Class<?> refc, MemberName getField,
3941                                                   MemberName putField) throws IllegalAccessException {
3942             assert getField.isStatic() == putField.isStatic();
3943             assert getField.isGetter() && putField.isSetter();
3944             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
3945             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
3946 
3947             checkField(getRefKind, refc, getField);
3948 
3949             if (!putField.isFinal()) {
3950                 // A VarHandle does not support updates to final fields, any
3951                 // such VarHandle to a final field will be read-only and
3952                 // therefore the following write-based accessibility checks are
3953                 // only required for non-final fields
3954                 checkField(putRefKind, refc, putField);
3955             }
3956 
3957             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
3958                                   restrictProtectedReceiver(getField));
3959             if (doRestrict) {
3960                 assert !getField.isStatic();
3961                 // receiver type of VarHandle is too wide; narrow to caller
3962                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
3963                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
3964                 }
3965                 refc = lookupClass();
3966             }
3967             return VarHandles.makeFieldHandle(getField, refc,
3968                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
3969         }
3970         /** Check access and get the requested constructor. */
3971         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3972             return getDirectConstructorCommon(refc, ctor);
3973         }
3974         /** Common code for all constructors; do not call directly except from immediately above. */
3975         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor) throws IllegalAccessException {
3976             assert(ctor.isConstructor());
3977             checkAccess(REF_newInvokeSpecial, refc, ctor);
3978             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
3979             return DirectMethodHandle.make(ctor).setVarargs(ctor);
3980         }
3981 
3982         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
3983          */
3984         /*non-public*/
3985         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
3986                 throws ReflectiveOperationException {
3987             if (!(type instanceof Class || type instanceof MethodType))
3988                 throw new InternalError("unresolved MemberName");
3989             MemberName member = new MemberName(refKind, defc, name, type);
3990             MethodHandle mh = LOOKASIDE_TABLE.get(member);
3991             if (mh != null) {
3992                 checkSymbolicClass(defc);
3993                 return mh;
3994             }
3995             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
3996                 // Treat MethodHandle.invoke and invokeExact specially.
3997                 mh = findVirtualForMH(member.getName(), member.getMethodType());
3998                 if (mh != null) {
3999                     return mh;
4000                 }
4001             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4002                 // Treat signature-polymorphic methods on VarHandle specially.
4003                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4004                 if (mh != null) {
4005                     return mh;
4006                 }
4007             }
4008             MemberName resolved = resolveOrFail(refKind, member);
4009             mh = getDirectMethodForConstant(refKind, defc, resolved);
4010             if (mh instanceof DirectMethodHandle dmh
4011                     && canBeCached(refKind, defc, resolved)) {
4012                 MemberName key = mh.internalMemberName();
4013                 if (key != null) {
4014                     key = key.asNormalOriginal();
4015                 }
4016                 if (member.equals(key)) {  // better safe than sorry
4017                     LOOKASIDE_TABLE.put(key, dmh);
4018                 }
4019             }
4020             return mh;
4021         }
4022         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4023             if (refKind == REF_invokeSpecial) {
4024                 return false;
4025             }
4026             if (!Modifier.isPublic(defc.getModifiers()) ||
4027                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4028                     !member.isPublic() ||
4029                     member.isCallerSensitive()) {
4030                 return false;
4031             }
4032             ClassLoader loader = defc.getClassLoader();
4033             if (loader != null) {
4034                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4035                 boolean found = false;
4036                 while (sysl != null) {
4037                     if (loader == sysl) { found = true; break; }
4038                     sysl = sysl.getParent();
4039                 }
4040                 if (!found) {
4041                     return false;
4042                 }
4043             }
4044             MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4045                     new MemberName(refKind, defc, member.getName(), member.getType()));
4046             if (resolved2 == null) {
4047                 return false;
4048             }
4049             return true;
4050         }
4051         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4052                 throws ReflectiveOperationException {
4053             if (MethodHandleNatives.refKindIsField(refKind)) {
4054                 return getDirectField(refKind, defc, member);
4055             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4056                 return getDirectMethod(refKind, defc, member, findBoundCallerLookup(member));
4057             } else if (refKind == REF_newInvokeSpecial) {
4058                 return getDirectConstructor(defc, member);
4059             }
4060             // oops
4061             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4062         }
4063 
4064         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4065     }
4066 
4067     /**
4068      * Produces a method handle constructing arrays of a desired type,
4069      * as if by the {@code anewarray} bytecode.
4070      * The return type of the method handle will be the array type.
4071      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4072      *
4073      * <p> If the returned method handle is invoked with a negative
4074      * array size, a {@code NegativeArraySizeException} will be thrown.
4075      *
4076      * @param arrayClass an array type
4077      * @return a method handle which can create arrays of the given type
4078      * @throws NullPointerException if the argument is {@code null}
4079      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4080      * @see java.lang.reflect.Array#newInstance(Class, int)
4081      * @jvms 6.5 {@code anewarray} Instruction
4082      * @since 9
4083      */
4084     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4085         if (!arrayClass.isArray()) {
4086             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4087         }
4088         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4089                 bindTo(arrayClass.getComponentType());
4090         return ani.asType(ani.type().changeReturnType(arrayClass));
4091     }
4092 
4093     /**
4094      * Produces a method handle returning the length of an array,
4095      * as if by the {@code arraylength} bytecode.
4096      * The type of the method handle will have {@code int} as return type,
4097      * and its sole argument will be the array type.
4098      *
4099      * <p> If the returned method handle is invoked with a {@code null}
4100      * array reference, a {@code NullPointerException} will be thrown.
4101      *
4102      * @param arrayClass an array type
4103      * @return a method handle which can retrieve the length of an array of the given array type
4104      * @throws NullPointerException if the argument is {@code null}
4105      * @throws IllegalArgumentException if arrayClass is not an array type
4106      * @jvms 6.5 {@code arraylength} Instruction
4107      * @since 9
4108      */
4109     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4110         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4111     }
4112 
4113     /**
4114      * Produces a method handle giving read access to elements of an array,
4115      * as if by the {@code aaload} bytecode.
4116      * The type of the method handle will have a return type of the array's
4117      * element type.  Its first argument will be the array type,
4118      * and the second will be {@code int}.
4119      *
4120      * <p> When the returned method handle is invoked,
4121      * the array reference and array index are checked.
4122      * A {@code NullPointerException} will be thrown if the array reference
4123      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4124      * thrown if the index is negative or if it is greater than or equal to
4125      * the length of the array.
4126      *
4127      * @param arrayClass an array type
4128      * @return a method handle which can load values from the given array type
4129      * @throws NullPointerException if the argument is null
4130      * @throws  IllegalArgumentException if arrayClass is not an array type
4131      * @jvms 6.5 {@code aaload} Instruction
4132      */
4133     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4134         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4135     }
4136 
4137     /**
4138      * Produces a method handle giving write access to elements of an array,
4139      * as if by the {@code astore} bytecode.
4140      * The type of the method handle will have a void return type.
4141      * Its last argument will be the array's element type.
4142      * The first and second arguments will be the array type and int.
4143      *
4144      * <p> When the returned method handle is invoked,
4145      * the array reference and array index are checked.
4146      * A {@code NullPointerException} will be thrown if the array reference
4147      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4148      * thrown if the index is negative or if it is greater than or equal to
4149      * the length of the array.
4150      *
4151      * @param arrayClass the class of an array
4152      * @return a method handle which can store values into the array type
4153      * @throws NullPointerException if the argument is null
4154      * @throws IllegalArgumentException if arrayClass is not an array type
4155      * @jvms 6.5 {@code aastore} Instruction
4156      */
4157     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4158         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4159     }
4160 
4161     /**
4162      * Produces a VarHandle giving access to elements of an array of type
4163      * {@code arrayClass}.  The VarHandle's variable type is the component type
4164      * of {@code arrayClass} and the list of coordinate types is
4165      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4166      * corresponds to an argument that is an index into an array.
4167      * <p>
4168      * Certain access modes of the returned VarHandle are unsupported under
4169      * the following conditions:
4170      * <ul>
4171      * <li>if the component type is anything other than {@code byte},
4172      *     {@code short}, {@code char}, {@code int}, {@code long},
4173      *     {@code float}, or {@code double} then numeric atomic update access
4174      *     modes are unsupported.
4175      * <li>if the component type is anything other than {@code boolean},
4176      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4177      *     {@code long} then bitwise atomic update access modes are
4178      *     unsupported.
4179      * </ul>
4180      * <p>
4181      * If the component type is {@code float} or {@code double} then numeric
4182      * and atomic update access modes compare values using their bitwise
4183      * representation (see {@link Float#floatToRawIntBits} and
4184      * {@link Double#doubleToRawLongBits}, respectively).
4185      *
4186      * <p> When the returned {@code VarHandle} is invoked,
4187      * the array reference and array index are checked.
4188      * A {@code NullPointerException} will be thrown if the array reference
4189      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4190      * thrown if the index is negative or if it is greater than or equal to
4191      * the length of the array.
4192      *
4193      * @apiNote
4194      * Bitwise comparison of {@code float} values or {@code double} values,
4195      * as performed by the numeric and atomic update access modes, differ
4196      * from the primitive {@code ==} operator and the {@link Float#equals}
4197      * and {@link Double#equals} methods, specifically with respect to
4198      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4199      * Care should be taken when performing a compare and set or a compare
4200      * and exchange operation with such values since the operation may
4201      * unexpectedly fail.
4202      * There are many possible NaN values that are considered to be
4203      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4204      * provided by Java can distinguish between them.  Operation failure can
4205      * occur if the expected or witness value is a NaN value and it is
4206      * transformed (perhaps in a platform specific manner) into another NaN
4207      * value, and thus has a different bitwise representation (see
4208      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4209      * details).
4210      * The values {@code -0.0} and {@code +0.0} have different bitwise
4211      * representations but are considered equal when using the primitive
4212      * {@code ==} operator.  Operation failure can occur if, for example, a
4213      * numeric algorithm computes an expected value to be say {@code -0.0}
4214      * and previously computed the witness value to be say {@code +0.0}.
4215      * @param arrayClass the class of an array, of type {@code T[]}
4216      * @return a VarHandle giving access to elements of an array
4217      * @throws NullPointerException if the arrayClass is null
4218      * @throws IllegalArgumentException if arrayClass is not an array type
4219      * @since 9
4220      */
4221     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4222         return VarHandles.makeArrayElementHandle(arrayClass);
4223     }
4224 
4225     /**
4226      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4227      * viewed as if it were a different primitive array type, such as
4228      * {@code int[]} or {@code long[]}.
4229      * The VarHandle's variable type is the component type of
4230      * {@code viewArrayClass} and the list of coordinate types is
4231      * {@code (byte[], int)}, where the {@code int} coordinate type
4232      * corresponds to an argument that is an index into a {@code byte[]} array.
4233      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4234      * array, composing bytes to or from a value of the component type of
4235      * {@code viewArrayClass} according to the given endianness.
4236      * <p>
4237      * The supported component types (variables types) are {@code short},
4238      * {@code char}, {@code int}, {@code long}, {@code float} and
4239      * {@code double}.
4240      * <p>
4241      * Access of bytes at a given index will result in an
4242      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4243      * or greater than the {@code byte[]} array length minus the size (in bytes)
4244      * of {@code T}.
4245      * <p>
4246      * Only plain {@linkplain VarHandle.AccessMode#GET get} and {@linkplain VarHandle.AccessMode#SET set}
4247      * access modes are supported by the returned var handle. For all other access modes, an
4248      * {@link UnsupportedOperationException} will be thrown.
4249      *
4250      * @apiNote if access modes other than plain access are required, clients should
4251      * consider using off-heap memory through
4252      * {@linkplain java.nio.ByteBuffer#allocateDirect(int) direct byte buffers} or
4253      * off-heap {@linkplain java.lang.foreign.MemorySegment memory segments},
4254      * or memory segments backed by a
4255      * {@linkplain java.lang.foreign.MemorySegment#ofArray(long[]) {@code long[]}},
4256      * for which stronger alignment guarantees can be made.
4257      *
4258      * @param viewArrayClass the view array class, with a component type of
4259      * type {@code T}
4260      * @param byteOrder the endianness of the view array elements, as
4261      * stored in the underlying {@code byte} array
4262      * @return a VarHandle giving access to elements of a {@code byte[]} array
4263      * viewed as if elements corresponding to the components type of the view
4264      * array class
4265      * @throws NullPointerException if viewArrayClass or byteOrder is null
4266      * @throws IllegalArgumentException if viewArrayClass is not an array type
4267      * @throws UnsupportedOperationException if the component type of
4268      * viewArrayClass is not supported as a variable type
4269      * @since 9
4270      */
4271     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4272                                      ByteOrder byteOrder) throws IllegalArgumentException {
4273         Objects.requireNonNull(byteOrder);
4274         return VarHandles.byteArrayViewHandle(viewArrayClass,
4275                                               byteOrder == ByteOrder.BIG_ENDIAN);
4276     }
4277 
4278     /**
4279      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4280      * viewed as if it were an array of elements of a different primitive
4281      * component type to that of {@code byte}, such as {@code int[]} or
4282      * {@code long[]}.
4283      * The VarHandle's variable type is the component type of
4284      * {@code viewArrayClass} and the list of coordinate types is
4285      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4286      * corresponds to an argument that is an index into a {@code byte[]} array.
4287      * The returned VarHandle accesses bytes at an index in a
4288      * {@code ByteBuffer}, composing bytes to or from a value of the component
4289      * type of {@code viewArrayClass} according to the given endianness.
4290      * <p>
4291      * The supported component types (variables types) are {@code short},
4292      * {@code char}, {@code int}, {@code long}, {@code float} and
4293      * {@code double}.
4294      * <p>
4295      * Access will result in a {@code ReadOnlyBufferException} for anything
4296      * other than the read access modes if the {@code ByteBuffer} is read-only.
4297      * <p>
4298      * Access of bytes at a given index will result in an
4299      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4300      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4301      * {@code T}.
4302      * <p>
4303      * For heap byte buffers, access is always unaligned. As a result, only the plain
4304      * {@linkplain VarHandle.AccessMode#GET get}
4305      * and {@linkplain VarHandle.AccessMode#SET set} access modes are supported by the
4306      * returned var handle. For all other access modes, an {@link IllegalStateException}
4307      * will be thrown.
4308      * <p>
4309      * For direct buffers only, access of bytes at an index may be aligned or misaligned for {@code T},
4310      * with respect to the underlying memory address, {@code A} say, associated
4311      * with the {@code ByteBuffer} and index.
4312      * If access is misaligned then access for anything other than the
4313      * {@code get} and {@code set} access modes will result in an
4314      * {@code IllegalStateException}.  In such cases atomic access is only
4315      * guaranteed with respect to the largest power of two that divides the GCD
4316      * of {@code A} and the size (in bytes) of {@code T}.
4317      * If access is aligned then following access modes are supported and are
4318      * guaranteed to support atomic access:
4319      * <ul>
4320      * <li>read write access modes for all {@code T}.  Access modes {@code get}
4321      *     and {@code set} for {@code long} and {@code double} are supported but
4322      *     have no atomicity guarantee, as described in Section {@jls 17.7} of
4323      *     <cite>The Java Language Specification</cite>.
4324      * <li>atomic update access modes for {@code int}, {@code long},
4325      *     {@code float} or {@code double}.
4326      *     (Future major platform releases of the JDK may support additional
4327      *     types for certain currently unsupported access modes.)
4328      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4329      *     (Future major platform releases of the JDK may support additional
4330      *     numeric types for certain currently unsupported access modes.)
4331      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4332      *     (Future major platform releases of the JDK may support additional
4333      *     numeric types for certain currently unsupported access modes.)
4334      * </ul>
4335      * <p>
4336      * Misaligned access, and therefore atomicity guarantees, may be determined
4337      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4338      * {@code index}, {@code T} and its corresponding boxed type,
4339      * {@code T_BOX}, as follows:
4340      * <pre>{@code
4341      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4342      * ByteBuffer bb = ...
4343      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4344      * boolean isMisaligned = misalignedAtIndex != 0;
4345      * }</pre>
4346      * <p>
4347      * If the variable type is {@code float} or {@code double} then atomic
4348      * update access modes compare values using their bitwise representation
4349      * (see {@link Float#floatToRawIntBits} and
4350      * {@link Double#doubleToRawLongBits}, respectively).
4351      * @param viewArrayClass the view array class, with a component type of
4352      * type {@code T}
4353      * @param byteOrder the endianness of the view array elements, as
4354      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4355      * endianness of a {@code ByteBuffer})
4356      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4357      * viewed as if elements corresponding to the components type of the view
4358      * array class
4359      * @throws NullPointerException if viewArrayClass or byteOrder is null
4360      * @throws IllegalArgumentException if viewArrayClass is not an array type
4361      * @throws UnsupportedOperationException if the component type of
4362      * viewArrayClass is not supported as a variable type
4363      * @since 9
4364      */
4365     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4366                                       ByteOrder byteOrder) throws IllegalArgumentException {
4367         Objects.requireNonNull(byteOrder);
4368         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4369                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4370     }
4371 
4372 
4373     //--- method handle invocation (reflective style)
4374 
4375     /**
4376      * Produces a method handle which will invoke any method handle of the
4377      * given {@code type}, with a given number of trailing arguments replaced by
4378      * a single trailing {@code Object[]} array.
4379      * The resulting invoker will be a method handle with the following
4380      * arguments:
4381      * <ul>
4382      * <li>a single {@code MethodHandle} target
4383      * <li>zero or more leading values (counted by {@code leadingArgCount})
4384      * <li>an {@code Object[]} array containing trailing arguments
4385      * </ul>
4386      * <p>
4387      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4388      * the indicated {@code type}.
4389      * That is, if the target is exactly of the given {@code type}, it will behave
4390      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4391      * is used to convert the target to the required {@code type}.
4392      * <p>
4393      * The type of the returned invoker will not be the given {@code type}, but rather
4394      * will have all parameters except the first {@code leadingArgCount}
4395      * replaced by a single array of type {@code Object[]}, which will be
4396      * the final parameter.
4397      * <p>
4398      * Before invoking its target, the invoker will spread the final array, apply
4399      * reference casts as necessary, and unbox and widen primitive arguments.
4400      * If, when the invoker is called, the supplied array argument does
4401      * not have the correct number of elements, the invoker will throw
4402      * an {@link IllegalArgumentException} instead of invoking the target.
4403      * <p>
4404      * This method is equivalent to the following code (though it may be more efficient):
4405      * {@snippet lang="java" :
4406 MethodHandle invoker = MethodHandles.invoker(type);
4407 int spreadArgCount = type.parameterCount() - leadingArgCount;
4408 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4409 return invoker;
4410      * }
4411      * This method throws no reflective exceptions.
4412      * @param type the desired target type
4413      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4414      * @return a method handle suitable for invoking any method handle of the given type
4415      * @throws NullPointerException if {@code type} is null
4416      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4417      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4418      *                  or if the resulting method handle's type would have
4419      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4420      */
4421     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4422         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4423             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4424         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4425         return type.invokers().spreadInvoker(leadingArgCount);
4426     }
4427 
4428     /**
4429      * Produces a special <em>invoker method handle</em> which can be used to
4430      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4431      * The resulting invoker will have a type which is
4432      * exactly equal to the desired type, except that it will accept
4433      * an additional leading argument of type {@code MethodHandle}.
4434      * <p>
4435      * This method is equivalent to the following code (though it may be more efficient):
4436      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4437      *
4438      * <p style="font-size:smaller;">
4439      * <em>Discussion:</em>
4440      * Invoker method handles can be useful when working with variable method handles
4441      * of unknown types.
4442      * For example, to emulate an {@code invokeExact} call to a variable method
4443      * handle {@code M}, extract its type {@code T},
4444      * look up the invoker method {@code X} for {@code T},
4445      * and call the invoker method, as {@code X.invoke(T, A...)}.
4446      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4447      * is unknown.)
4448      * If spreading, collecting, or other argument transformations are required,
4449      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4450      * method handle values, as long as they are compatible with the type of {@code X}.
4451      * <p style="font-size:smaller;">
4452      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4453      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4454      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4455      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4456      * <p>
4457      * This method throws no reflective exceptions.
4458      * @param type the desired target type
4459      * @return a method handle suitable for invoking any method handle of the given type
4460      * @throws IllegalArgumentException if the resulting method handle's type would have
4461      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4462      */
4463     public static MethodHandle exactInvoker(MethodType type) {
4464         return type.invokers().exactInvoker();
4465     }
4466 
4467     /**
4468      * Produces a special <em>invoker method handle</em> which can be used to
4469      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4470      * The resulting invoker will have a type which is
4471      * exactly equal to the desired type, except that it will accept
4472      * an additional leading argument of type {@code MethodHandle}.
4473      * <p>
4474      * Before invoking its target, if the target differs from the expected type,
4475      * the invoker will apply reference casts as
4476      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4477      * Similarly, the return value will be converted as necessary.
4478      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4479      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4480      * <p>
4481      * This method is equivalent to the following code (though it may be more efficient):
4482      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4483      * <p style="font-size:smaller;">
4484      * <em>Discussion:</em>
4485      * A {@linkplain MethodType#genericMethodType general method type} is one which
4486      * mentions only {@code Object} arguments and return values.
4487      * An invoker for such a type is capable of calling any method handle
4488      * of the same arity as the general type.
4489      * <p style="font-size:smaller;">
4490      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4491      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4492      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4493      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4494      * <p>
4495      * This method throws no reflective exceptions.
4496      * @param type the desired target type
4497      * @return a method handle suitable for invoking any method handle convertible to the given type
4498      * @throws IllegalArgumentException if the resulting method handle's type would have
4499      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4500      */
4501     public static MethodHandle invoker(MethodType type) {
4502         return type.invokers().genericInvoker();
4503     }
4504 
4505     /**
4506      * Produces a special <em>invoker method handle</em> which can be used to
4507      * invoke a signature-polymorphic access mode method on any VarHandle whose
4508      * associated access mode type is compatible with the given type.
4509      * The resulting invoker will have a type which is exactly equal to the
4510      * desired given type, except that it will accept an additional leading
4511      * argument of type {@code VarHandle}.
4512      *
4513      * @param accessMode the VarHandle access mode
4514      * @param type the desired target type
4515      * @return a method handle suitable for invoking an access mode method of
4516      *         any VarHandle whose access mode type is of the given type.
4517      * @since 9
4518      */
4519     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4520         return type.invokers().varHandleMethodExactInvoker(accessMode);
4521     }
4522 
4523     /**
4524      * Produces a special <em>invoker method handle</em> which can be used to
4525      * invoke a signature-polymorphic access mode method on any VarHandle whose
4526      * associated access mode type is compatible with the given type.
4527      * The resulting invoker will have a type which is exactly equal to the
4528      * desired given type, except that it will accept an additional leading
4529      * argument of type {@code VarHandle}.
4530      * <p>
4531      * Before invoking its target, if the access mode type differs from the
4532      * desired given type, the invoker will apply reference casts as necessary
4533      * and box, unbox, or widen primitive values, as if by
4534      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4535      * converted as necessary.
4536      * <p>
4537      * This method is equivalent to the following code (though it may be more
4538      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4539      *
4540      * @param accessMode the VarHandle access mode
4541      * @param type the desired target type
4542      * @return a method handle suitable for invoking an access mode method of
4543      *         any VarHandle whose access mode type is convertible to the given
4544      *         type.
4545      * @since 9
4546      */
4547     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4548         return type.invokers().varHandleMethodInvoker(accessMode);
4549     }
4550 
4551     /*non-public*/
4552     static MethodHandle basicInvoker(MethodType type) {
4553         return type.invokers().basicInvoker();
4554     }
4555 
4556      //--- method handle modification (creation from other method handles)
4557 
4558     /**
4559      * Produces a method handle which adapts the type of the
4560      * given method handle to a new type by pairwise argument and return type conversion.
4561      * The original type and new type must have the same number of arguments.
4562      * The resulting method handle is guaranteed to report a type
4563      * which is equal to the desired new type.
4564      * <p>
4565      * If the original type and new type are equal, returns target.
4566      * <p>
4567      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4568      * and some additional conversions are also applied if those conversions fail.
4569      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4570      * if possible, before or instead of any conversions done by {@code asType}:
4571      * <ul>
4572      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4573      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4574      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4575      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4576      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4577      *     (This treatment follows the usage of the bytecode verifier.)
4578      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4579      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4580      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4581      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4582      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4583      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4584      *     widening and/or narrowing.)
4585      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4586      *     conversion will be applied at runtime, possibly followed
4587      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4588      *     possibly followed by a conversion from byte to boolean by testing
4589      *     the low-order bit.
4590      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4591      *     and if the reference is null at runtime, a zero value is introduced.
4592      * </ul>
4593      * @param target the method handle to invoke after arguments are retyped
4594      * @param newType the expected type of the new method handle
4595      * @return a method handle which delegates to the target after performing
4596      *           any necessary argument conversions, and arranges for any
4597      *           necessary return value conversions
4598      * @throws NullPointerException if either argument is null
4599      * @throws WrongMethodTypeException if the conversion cannot be made
4600      * @see MethodHandle#asType
4601      */
4602     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4603         explicitCastArgumentsChecks(target, newType);
4604         // use the asTypeCache when possible:
4605         MethodType oldType = target.type();
4606         if (oldType == newType)  return target;
4607         if (oldType.explicitCastEquivalentToAsType(newType)) {
4608             return target.asFixedArity().asType(newType);
4609         }
4610         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4611     }
4612 
4613     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4614         if (target.type().parameterCount() != newType.parameterCount()) {
4615             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4616         }
4617     }
4618 
4619     /**
4620      * Produces a method handle which adapts the calling sequence of the
4621      * given method handle to a new type, by reordering the arguments.
4622      * The resulting method handle is guaranteed to report a type
4623      * which is equal to the desired new type.
4624      * <p>
4625      * The given array controls the reordering.
4626      * Call {@code #I} the number of incoming parameters (the value
4627      * {@code newType.parameterCount()}, and call {@code #O} the number
4628      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4629      * Then the length of the reordering array must be {@code #O},
4630      * and each element must be a non-negative number less than {@code #I}.
4631      * For every {@code N} less than {@code #O}, the {@code N}-th
4632      * outgoing argument will be taken from the {@code I}-th incoming
4633      * argument, where {@code I} is {@code reorder[N]}.
4634      * <p>
4635      * No argument or return value conversions are applied.
4636      * The type of each incoming argument, as determined by {@code newType},
4637      * must be identical to the type of the corresponding outgoing parameter
4638      * or parameters in the target method handle.
4639      * The return type of {@code newType} must be identical to the return
4640      * type of the original target.
4641      * <p>
4642      * The reordering array need not specify an actual permutation.
4643      * An incoming argument will be duplicated if its index appears
4644      * more than once in the array, and an incoming argument will be dropped
4645      * if its index does not appear in the array.
4646      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4647      * incoming arguments which are not mentioned in the reordering array
4648      * may be of any type, as determined only by {@code newType}.
4649      * {@snippet lang="java" :
4650 import static java.lang.invoke.MethodHandles.*;
4651 import static java.lang.invoke.MethodType.*;
4652 ...
4653 MethodType intfn1 = methodType(int.class, int.class);
4654 MethodType intfn2 = methodType(int.class, int.class, int.class);
4655 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4656 assert(sub.type().equals(intfn2));
4657 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4658 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4659 assert((int)rsub.invokeExact(1, 100) == 99);
4660 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4661 assert(add.type().equals(intfn2));
4662 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4663 assert(twice.type().equals(intfn1));
4664 assert((int)twice.invokeExact(21) == 42);
4665      * }
4666      * <p>
4667      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4668      * variable-arity method handle}, even if the original target method handle was.
4669      * @param target the method handle to invoke after arguments are reordered
4670      * @param newType the expected type of the new method handle
4671      * @param reorder an index array which controls the reordering
4672      * @return a method handle which delegates to the target after it
4673      *           drops unused arguments and moves and/or duplicates the other arguments
4674      * @throws NullPointerException if any argument is null
4675      * @throws IllegalArgumentException if the index array length is not equal to
4676      *                  the arity of the target, or if any index array element
4677      *                  not a valid index for a parameter of {@code newType},
4678      *                  or if two corresponding parameter types in
4679      *                  {@code target.type()} and {@code newType} are not identical,
4680      */
4681     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4682         reorder = reorder.clone();  // get a private copy
4683         MethodType oldType = target.type();
4684         permuteArgumentChecks(reorder, newType, oldType);
4685         // first detect dropped arguments and handle them separately
4686         int[] originalReorder = reorder;
4687         BoundMethodHandle result = target.rebind();
4688         LambdaForm form = result.form;
4689         int newArity = newType.parameterCount();
4690         // Normalize the reordering into a real permutation,
4691         // by removing duplicates and adding dropped elements.
4692         // This somewhat improves lambda form caching, as well
4693         // as simplifying the transform by breaking it up into steps.
4694         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4695             if (ddIdx > 0) {
4696                 // We found a duplicated entry at reorder[ddIdx].
4697                 // Example:  (x,y,z)->asList(x,y,z)
4698                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4699                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4700                 // The starred element corresponds to the argument
4701                 // deleted by the dupArgumentForm transform.
4702                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4703                 boolean killFirst = false;
4704                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4705                     // Set killFirst if the dup is larger than an intervening position.
4706                     // This will remove at least one inversion from the permutation.
4707                     if (dupVal > val) killFirst = true;
4708                 }
4709                 if (!killFirst) {
4710                     srcPos = dstPos;
4711                     dstPos = ddIdx;
4712                 }
4713                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4714                 assert (reorder[srcPos] == reorder[dstPos]);
4715                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4716                 // contract the reordering by removing the element at dstPos
4717                 int tailPos = dstPos + 1;
4718                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4719                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4720             } else {
4721                 int dropVal = ~ddIdx, insPos = 0;
4722                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4723                     // Find first element of reorder larger than dropVal.
4724                     // This is where we will insert the dropVal.
4725                     insPos += 1;
4726                 }
4727                 Class<?> ptype = newType.parameterType(dropVal);
4728                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4729                 oldType = oldType.insertParameterTypes(insPos, ptype);
4730                 // expand the reordering by inserting an element at insPos
4731                 int tailPos = insPos + 1;
4732                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4733                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4734                 reorder[insPos] = dropVal;
4735             }
4736             assert (permuteArgumentChecks(reorder, newType, oldType));
4737         }
4738         assert (reorder.length == newArity);  // a perfect permutation
4739         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4740         form = form.editor().permuteArgumentsForm(1, reorder);
4741         if (newType == result.type() && form == result.internalForm())
4742             return result;
4743         return result.copyWith(newType, form);
4744     }
4745 
4746     /**
4747      * Return an indication of any duplicate or omission in reorder.
4748      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4749      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4750      * Otherwise, return zero.
4751      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4752      */
4753     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4754         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4755         if (newArity < BIT_LIMIT) {
4756             long mask = 0;
4757             for (int i = 0; i < reorder.length; i++) {
4758                 int arg = reorder[i];
4759                 if (arg >= newArity) {
4760                     return reorder.length;
4761                 }
4762                 long bit = 1L << arg;
4763                 if ((mask & bit) != 0) {
4764                     return i;  // >0 indicates a dup
4765                 }
4766                 mask |= bit;
4767             }
4768             if (mask == (1L << newArity) - 1) {
4769                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4770                 return 0;
4771             }
4772             // find first zero
4773             long zeroBit = Long.lowestOneBit(~mask);
4774             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4775             assert(zeroPos <= newArity);
4776             if (zeroPos == newArity) {
4777                 return 0;
4778             }
4779             return ~zeroPos;
4780         } else {
4781             // same algorithm, different bit set
4782             BitSet mask = new BitSet(newArity);
4783             for (int i = 0; i < reorder.length; i++) {
4784                 int arg = reorder[i];
4785                 if (arg >= newArity) {
4786                     return reorder.length;
4787                 }
4788                 if (mask.get(arg)) {
4789                     return i;  // >0 indicates a dup
4790                 }
4791                 mask.set(arg);
4792             }
4793             int zeroPos = mask.nextClearBit(0);
4794             assert(zeroPos <= newArity);
4795             if (zeroPos == newArity) {
4796                 return 0;
4797             }
4798             return ~zeroPos;
4799         }
4800     }
4801 
4802     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
4803         if (newType.returnType() != oldType.returnType())
4804             throw newIllegalArgumentException("return types do not match",
4805                     oldType, newType);
4806         if (reorder.length != oldType.parameterCount())
4807             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
4808                     oldType, Arrays.toString(reorder));
4809 
4810         int limit = newType.parameterCount();
4811         for (int j = 0; j < reorder.length; j++) {
4812             int i = reorder[j];
4813             if (i < 0 || i >= limit) {
4814                 throw newIllegalArgumentException("index is out of bounds for new type",
4815                         i, newType);
4816             }
4817             Class<?> src = newType.parameterType(i);
4818             Class<?> dst = oldType.parameterType(j);
4819             if (src != dst)
4820                 throw newIllegalArgumentException("parameter types do not match after reorder",
4821                         oldType, newType);
4822         }
4823         return true;
4824     }
4825 
4826     /**
4827      * Produces a method handle of the requested return type which returns the given
4828      * constant value every time it is invoked.
4829      * <p>
4830      * Before the method handle is returned, the passed-in value is converted to the requested type.
4831      * If the requested type is primitive, widening primitive conversions are attempted,
4832      * else reference conversions are attempted.
4833      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)},
4834      * for reference types.  For all types it is equivalent to
4835      * {@code insertArguments(identity(type), 0, value)}.
4836      * @param type the return type of the desired method handle
4837      * @param value the value to return
4838      * @return a method handle of the given return type and no arguments, which always returns the given value
4839      * @throws NullPointerException if the {@code type} argument is null
4840      * @throws ClassCastException if the value cannot be converted to the required return type
4841      * @throws IllegalArgumentException if the given type is {@code void.class}
4842      */
4843     public static MethodHandle constant(Class<?> type, Object value) {
4844         if (Objects.requireNonNull(type) == void.class)
4845             throw newIllegalArgumentException("void type");
4846         return MethodHandleImpl.makeConstantReturning(type, value);
4847     }
4848 
4849     /**
4850      * Produces a method handle which returns its sole argument when invoked.
4851      * @param type the type of the sole parameter and return value of the desired method handle
4852      * @return a unary method handle which accepts and returns the given type
4853      * @throws NullPointerException if the argument is null
4854      * @throws IllegalArgumentException if the given type is {@code void.class}
4855      */
4856     public static MethodHandle identity(Class<?> type) {
4857         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
4858         int pos = btw.ordinal();
4859         MethodHandle ident = IDENTITY_MHS[pos];
4860         if (ident == null) {
4861             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
4862         }
4863         if (ident.type().returnType() == type)
4864             return ident;
4865         // something like identity(Foo.class); do not bother to intern these
4866         assert (btw == Wrapper.OBJECT);
4867         return makeIdentity(type);
4868     }
4869 
4870     /**
4871      * Produces a constant method handle of the requested return type which
4872      * returns the default value for that type every time it is invoked.
4873      * The resulting constant method handle will have no side effects.
4874      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
4875      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
4876      * since {@code explicitCastArguments} converts {@code null} to default values.
4877      * @param type the expected return type of the desired method handle
4878      * @return a constant method handle that takes no arguments
4879      *         and returns the default value of the given type (or void, if the type is void)
4880      * @throws NullPointerException if the argument is null
4881      * @see MethodHandles#constant
4882      * @see MethodHandles#empty
4883      * @see MethodHandles#explicitCastArguments
4884      * @since 9
4885      */
4886     public static MethodHandle zero(Class<?> type) {
4887         Objects.requireNonNull(type);
4888         return type.isPrimitive() ? primitiveZero(Wrapper.forPrimitiveType(type))
4889                 : MethodHandleImpl.makeConstantReturning(type, null);
4890     }
4891 
4892     private static MethodHandle identityOrVoid(Class<?> type) {
4893         return type == void.class ? zero(type) : identity(type);
4894     }
4895 
4896     /**
4897      * Produces a method handle of the requested type which ignores any arguments, does nothing,
4898      * and returns a suitable default depending on the return type.
4899      * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
4900      * <p>The returned method handle is equivalent to
4901      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
4902      *
4903      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
4904      * {@code guardWithTest(pred, target, empty(target.type())}.
4905      * @param type the type of the desired method handle
4906      * @return a constant method handle of the given type, which returns a default value of the given return type
4907      * @throws NullPointerException if the argument is null
4908      * @see MethodHandles#zero(Class)
4909      * @see MethodHandles#constant
4910      * @since 9
4911      */
4912     public static  MethodHandle empty(MethodType type) {
4913         Objects.requireNonNull(type);
4914         return dropArgumentsTrusted(zero(type.returnType()), 0, type.ptypes());
4915     }
4916 
4917     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
4918     private static MethodHandle makeIdentity(Class<?> ptype) {
4919         MethodType mtype = methodType(ptype, ptype); // throws IAE for void
4920         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
4921         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
4922     }
4923 
4924     private static MethodHandle primitiveZero(Wrapper w) {
4925         assert w != Wrapper.OBJECT : w;
4926         int pos = w.ordinal();
4927         MethodHandle mh = PRIMITIVE_ZERO_MHS[pos];
4928         if (mh == null) {
4929             mh = setCachedMethodHandle(PRIMITIVE_ZERO_MHS, pos, makePrimitiveZero(w));
4930         }
4931         assert (mh.type().returnType() == w.primitiveType()) : mh;
4932         return mh;
4933     }
4934 
4935     private static MethodHandle makePrimitiveZero(Wrapper w) {
4936         if (w == Wrapper.VOID) {
4937             var lf = LambdaForm.identityForm(V_TYPE); // ensures BMH & SimpleMH are initialized
4938             return SimpleMethodHandle.make(MethodType.methodType(void.class), lf);
4939         } else {
4940             return MethodHandleImpl.makeConstantReturning(w.primitiveType(), w.zero());
4941         }
4942     }
4943 
4944     private static final @Stable MethodHandle[] PRIMITIVE_ZERO_MHS = new MethodHandle[Wrapper.COUNT];
4945 
4946     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
4947         // Simulate a CAS, to avoid racy duplication of results.
4948         MethodHandle prev = cache[pos];
4949         if (prev != null) return prev;
4950         return cache[pos] = value;
4951     }
4952 
4953     /**
4954      * Provides a target method handle with one or more <em>bound arguments</em>
4955      * in advance of the method handle's invocation.
4956      * The formal parameters to the target corresponding to the bound
4957      * arguments are called <em>bound parameters</em>.
4958      * Returns a new method handle which saves away the bound arguments.
4959      * When it is invoked, it receives arguments for any non-bound parameters,
4960      * binds the saved arguments to their corresponding parameters,
4961      * and calls the original target.
4962      * <p>
4963      * The type of the new method handle will drop the types for the bound
4964      * parameters from the original target type, since the new method handle
4965      * will no longer require those arguments to be supplied by its callers.
4966      * <p>
4967      * Each given argument object must match the corresponding bound parameter type.
4968      * If a bound parameter type is a primitive, the argument object
4969      * must be a wrapper, and will be unboxed to produce the primitive value.
4970      * <p>
4971      * The {@code pos} argument selects which parameters are to be bound.
4972      * It may range between zero and <i>N-L</i> (inclusively),
4973      * where <i>N</i> is the arity of the target method handle
4974      * and <i>L</i> is the length of the values array.
4975      * <p>
4976      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4977      * variable-arity method handle}, even if the original target method handle was.
4978      * @param target the method handle to invoke after the argument is inserted
4979      * @param pos where to insert the argument (zero for the first)
4980      * @param values the series of arguments to insert
4981      * @return a method handle which inserts an additional argument,
4982      *         before calling the original method handle
4983      * @throws NullPointerException if the target or the {@code values} array is null
4984      * @throws IllegalArgumentException if {@code pos} is less than {@code 0} or greater than
4985      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
4986      *         is the length of the values array.
4987      * @throws ClassCastException if an argument does not match the corresponding bound parameter
4988      *         type.
4989      * @see MethodHandle#bindTo
4990      */
4991     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
4992         int insCount = values.length;
4993         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
4994         if (insCount == 0)  return target;
4995         BoundMethodHandle result = target.rebind();
4996         for (int i = 0; i < insCount; i++) {
4997             Object value = values[i];
4998             Class<?> ptype = ptypes[pos+i];
4999             if (ptype.isPrimitive()) {
5000                 result = insertArgumentPrimitive(result, pos, ptype, value);
5001             } else {
5002                 value = ptype.cast(value);  // throw CCE if needed
5003                 result = result.bindArgumentL(pos, value);
5004             }
5005         }
5006         return result;
5007     }
5008 
5009     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5010                                                              Class<?> ptype, Object value) {
5011         Wrapper w = Wrapper.forPrimitiveType(ptype);
5012         // perform unboxing and/or primitive conversion
5013         value = w.convert(value, ptype);
5014         return switch (w) {
5015             case INT    -> result.bindArgumentI(pos, (int) value);
5016             case LONG   -> result.bindArgumentJ(pos, (long) value);
5017             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5018             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5019             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5020         };
5021     }
5022 
5023     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5024         MethodType oldType = target.type();
5025         int outargs = oldType.parameterCount();
5026         int inargs  = outargs - insCount;
5027         if (inargs < 0)
5028             throw newIllegalArgumentException("too many values to insert");
5029         if (pos < 0 || pos > inargs)
5030             throw newIllegalArgumentException("no argument type to append");
5031         return oldType.ptypes();
5032     }
5033 
5034     /**
5035      * Produces a method handle which will discard some dummy arguments
5036      * before calling some other specified <i>target</i> method handle.
5037      * The type of the new method handle will be the same as the target's type,
5038      * except it will also include the dummy argument types,
5039      * at some given position.
5040      * <p>
5041      * The {@code pos} argument may range between zero and <i>N</i>,
5042      * where <i>N</i> is the arity of the target.
5043      * If {@code pos} is zero, the dummy arguments will precede
5044      * the target's real arguments; if {@code pos} is <i>N</i>
5045      * they will come after.
5046      * <p>
5047      * <b>Example:</b>
5048      * {@snippet lang="java" :
5049 import static java.lang.invoke.MethodHandles.*;
5050 import static java.lang.invoke.MethodType.*;
5051 ...
5052 MethodHandle cat = lookup().findVirtual(String.class,
5053   "concat", methodType(String.class, String.class));
5054 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5055 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5056 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5057 assertEquals(bigType, d0.type());
5058 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5059      * }
5060      * <p>
5061      * This method is also equivalent to the following code:
5062      * <blockquote><pre>
5063      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5064      * </pre></blockquote>
5065      * @param target the method handle to invoke after the arguments are dropped
5066      * @param pos position of first argument to drop (zero for the leftmost)
5067      * @param valueTypes the type(s) of the argument(s) to drop
5068      * @return a method handle which drops arguments of the given types,
5069      *         before calling the original method handle
5070      * @throws NullPointerException if the target is null,
5071      *                              or if the {@code valueTypes} list or any of its elements is null
5072      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5073      *                  or if {@code pos} is negative or greater than the arity of the target,
5074      *                  or if the new method handle's type would have too many parameters
5075      */
5076     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5077         return dropArgumentsTrusted(target, pos, valueTypes.toArray(new Class<?>[0]).clone());
5078     }
5079 
5080     static MethodHandle dropArgumentsTrusted(MethodHandle target, int pos, Class<?>[] valueTypes) {
5081         MethodType oldType = target.type();  // get NPE
5082         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5083         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5084         if (dropped == 0)  return target;
5085         BoundMethodHandle result = target.rebind();
5086         LambdaForm lform = result.form;
5087         int insertFormArg = 1 + pos;
5088         for (Class<?> ptype : valueTypes) {
5089             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5090         }
5091         result = result.copyWith(newType, lform);
5092         return result;
5093     }
5094 
5095     private static int dropArgumentChecks(MethodType oldType, int pos, Class<?>[] valueTypes) {
5096         int dropped = valueTypes.length;
5097         MethodType.checkSlotCount(dropped);
5098         int outargs = oldType.parameterCount();
5099         int inargs  = outargs + dropped;
5100         if (pos < 0 || pos > outargs)
5101             throw newIllegalArgumentException("no argument type to remove"
5102                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5103                     );
5104         return dropped;
5105     }
5106 
5107     /**
5108      * Produces a method handle which will discard some dummy arguments
5109      * before calling some other specified <i>target</i> method handle.
5110      * The type of the new method handle will be the same as the target's type,
5111      * except it will also include the dummy argument types,
5112      * at some given position.
5113      * <p>
5114      * The {@code pos} argument may range between zero and <i>N</i>,
5115      * where <i>N</i> is the arity of the target.
5116      * If {@code pos} is zero, the dummy arguments will precede
5117      * the target's real arguments; if {@code pos} is <i>N</i>
5118      * they will come after.
5119      * @apiNote
5120      * {@snippet lang="java" :
5121 import static java.lang.invoke.MethodHandles.*;
5122 import static java.lang.invoke.MethodType.*;
5123 ...
5124 MethodHandle cat = lookup().findVirtual(String.class,
5125   "concat", methodType(String.class, String.class));
5126 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5127 MethodHandle d0 = dropArguments(cat, 0, String.class);
5128 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5129 MethodHandle d1 = dropArguments(cat, 1, String.class);
5130 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5131 MethodHandle d2 = dropArguments(cat, 2, String.class);
5132 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5133 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5134 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5135      * }
5136      * <p>
5137      * This method is also equivalent to the following code:
5138      * <blockquote><pre>
5139      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5140      * </pre></blockquote>
5141      * @param target the method handle to invoke after the arguments are dropped
5142      * @param pos position of first argument to drop (zero for the leftmost)
5143      * @param valueTypes the type(s) of the argument(s) to drop
5144      * @return a method handle which drops arguments of the given types,
5145      *         before calling the original method handle
5146      * @throws NullPointerException if the target is null,
5147      *                              or if the {@code valueTypes} array or any of its elements is null
5148      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5149      *                  or if {@code pos} is negative or greater than the arity of the target,
5150      *                  or if the new method handle's type would have
5151      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5152      */
5153     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5154         return dropArgumentsTrusted(target, pos, valueTypes.clone());
5155     }
5156 
5157     /* Convenience overloads for trusting internal low-arity call-sites */
5158     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1) {
5159         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1 });
5160     }
5161     static MethodHandle dropArguments(MethodHandle target, int pos, Class<?> valueType1, Class<?> valueType2) {
5162         return dropArgumentsTrusted(target, pos, new Class<?>[] { valueType1, valueType2 });
5163     }
5164 
5165     // private version which allows caller some freedom with error handling
5166     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, Class<?>[] newTypes, int pos,
5167                                       boolean nullOnFailure) {
5168         Class<?>[] oldTypes = target.type().ptypes();
5169         int match = oldTypes.length;
5170         if (skip != 0) {
5171             if (skip < 0 || skip > match) {
5172                 throw newIllegalArgumentException("illegal skip", skip, target);
5173             }
5174             oldTypes = Arrays.copyOfRange(oldTypes, skip, match);
5175             match -= skip;
5176         }
5177         Class<?>[] addTypes = newTypes;
5178         int add = addTypes.length;
5179         if (pos != 0) {
5180             if (pos < 0 || pos > add) {
5181                 throw newIllegalArgumentException("illegal pos", pos, Arrays.toString(newTypes));
5182             }
5183             addTypes = Arrays.copyOfRange(addTypes, pos, add);
5184             add -= pos;
5185             assert(addTypes.length == add);
5186         }
5187         // Do not add types which already match the existing arguments.
5188         if (match > add || !Arrays.equals(oldTypes, 0, oldTypes.length, addTypes, 0, match)) {
5189             if (nullOnFailure) {
5190                 return null;
5191             }
5192             throw newIllegalArgumentException("argument lists do not match",
5193                 Arrays.toString(oldTypes), Arrays.toString(newTypes));
5194         }
5195         addTypes = Arrays.copyOfRange(addTypes, match, add);
5196         add -= match;
5197         assert(addTypes.length == add);
5198         // newTypes:     (   P*[pos], M*[match], A*[add] )
5199         // target: ( S*[skip],        M*[match]  )
5200         MethodHandle adapter = target;
5201         if (add > 0) {
5202             adapter = dropArgumentsTrusted(adapter, skip+ match, addTypes);
5203         }
5204         // adapter: (S*[skip],        M*[match], A*[add] )
5205         if (pos > 0) {
5206             adapter = dropArgumentsTrusted(adapter, skip, Arrays.copyOfRange(newTypes, 0, pos));
5207         }
5208         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5209         return adapter;
5210     }
5211 
5212     /**
5213      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5214      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5215      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5216      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5217      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5218      * {@link #dropArguments(MethodHandle, int, Class[])}.
5219      * <p>
5220      * The resulting handle will have the same return type as the target handle.
5221      * <p>
5222      * In more formal terms, assume these two type lists:<ul>
5223      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5224      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5225      * {@code newTypes}.
5226      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5227      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5228      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5229      * sub-list.
5230      * </ul>
5231      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5232      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5233      * {@link #dropArguments(MethodHandle, int, Class[])}.
5234      *
5235      * @apiNote
5236      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5237      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5238      * {@snippet lang="java" :
5239 import static java.lang.invoke.MethodHandles.*;
5240 import static java.lang.invoke.MethodType.*;
5241 ...
5242 ...
5243 MethodHandle h0 = constant(boolean.class, true);
5244 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5245 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5246 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5247 if (h1.type().parameterCount() < h2.type().parameterCount())
5248     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5249 else
5250     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5251 MethodHandle h3 = guardWithTest(h0, h1, h2);
5252 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5253      * }
5254      * @param target the method handle to adapt
5255      * @param skip number of targets parameters to disregard (they will be unchanged)
5256      * @param newTypes the list of types to match {@code target}'s parameter type list to
5257      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5258      * @return a possibly adapted method handle
5259      * @throws NullPointerException if either argument is null
5260      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5261      *         or if {@code skip} is negative or greater than the arity of the target,
5262      *         or if {@code pos} is negative or greater than the newTypes list size,
5263      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5264      *         {@code pos}.
5265      * @since 9
5266      */
5267     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5268         Objects.requireNonNull(target);
5269         Objects.requireNonNull(newTypes);
5270         return dropArgumentsToMatch(target, skip, newTypes.toArray(new Class<?>[0]).clone(), pos, false);
5271     }
5272 
5273     /**
5274      * Drop the return value of the target handle (if any).
5275      * The returned method handle will have a {@code void} return type.
5276      *
5277      * @param target the method handle to adapt
5278      * @return a possibly adapted method handle
5279      * @throws NullPointerException if {@code target} is null
5280      * @since 16
5281      */
5282     public static MethodHandle dropReturn(MethodHandle target) {
5283         Objects.requireNonNull(target);
5284         MethodType oldType = target.type();
5285         Class<?> oldReturnType = oldType.returnType();
5286         if (oldReturnType == void.class)
5287             return target;
5288         MethodType newType = oldType.changeReturnType(void.class);
5289         BoundMethodHandle result = target.rebind();
5290         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5291         result = result.copyWith(newType, lform);
5292         return result;
5293     }
5294 
5295     /**
5296      * Adapts a target method handle by pre-processing
5297      * one or more of its arguments, each with its own unary filter function,
5298      * and then calling the target with each pre-processed argument
5299      * replaced by the result of its corresponding filter function.
5300      * <p>
5301      * The pre-processing is performed by one or more method handles,
5302      * specified in the elements of the {@code filters} array.
5303      * The first element of the filter array corresponds to the {@code pos}
5304      * argument of the target, and so on in sequence.
5305      * The filter functions are invoked in left to right order.
5306      * <p>
5307      * Null arguments in the array are treated as identity functions,
5308      * and the corresponding arguments left unchanged.
5309      * (If there are no non-null elements in the array, the original target is returned.)
5310      * Each filter is applied to the corresponding argument of the adapter.
5311      * <p>
5312      * If a filter {@code F} applies to the {@code N}th argument of
5313      * the target, then {@code F} must be a method handle which
5314      * takes exactly one argument.  The type of {@code F}'s sole argument
5315      * replaces the corresponding argument type of the target
5316      * in the resulting adapted method handle.
5317      * The return type of {@code F} must be identical to the corresponding
5318      * parameter type of the target.
5319      * <p>
5320      * It is an error if there are elements of {@code filters}
5321      * (null or not)
5322      * which do not correspond to argument positions in the target.
5323      * <p><b>Example:</b>
5324      * {@snippet lang="java" :
5325 import static java.lang.invoke.MethodHandles.*;
5326 import static java.lang.invoke.MethodType.*;
5327 ...
5328 MethodHandle cat = lookup().findVirtual(String.class,
5329   "concat", methodType(String.class, String.class));
5330 MethodHandle upcase = lookup().findVirtual(String.class,
5331   "toUpperCase", methodType(String.class));
5332 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5333 MethodHandle f0 = filterArguments(cat, 0, upcase);
5334 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5335 MethodHandle f1 = filterArguments(cat, 1, upcase);
5336 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5337 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5338 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5339      * }
5340      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5341      * denotes the return type of both the {@code target} and resulting adapter.
5342      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5343      * of the parameters and arguments that precede and follow the filter position
5344      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5345      * values of the filtered parameters and arguments; they also represent the
5346      * return types of the {@code filter[i]} handles. The latter accept arguments
5347      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5348      * the resulting adapter.
5349      * {@snippet lang="java" :
5350      * T target(P... p, A[i]... a[i], B... b);
5351      * A[i] filter[i](V[i]);
5352      * T adapter(P... p, V[i]... v[i], B... b) {
5353      *   return target(p..., filter[i](v[i])..., b...);
5354      * }
5355      * }
5356      * <p>
5357      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5358      * variable-arity method handle}, even if the original target method handle was.
5359      *
5360      * @param target the method handle to invoke after arguments are filtered
5361      * @param pos the position of the first argument to filter
5362      * @param filters method handles to call initially on filtered arguments
5363      * @return method handle which incorporates the specified argument filtering logic
5364      * @throws NullPointerException if the target is null
5365      *                              or if the {@code filters} array is null
5366      * @throws IllegalArgumentException if a non-null element of {@code filters}
5367      *          does not match a corresponding argument type of target as described above,
5368      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5369      *          or if the resulting method handle's type would have
5370      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5371      */
5372     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5373         // In method types arguments start at index 0, while the LF
5374         // editor have the MH receiver at position 0 - adjust appropriately.
5375         final int MH_RECEIVER_OFFSET = 1;
5376         filterArgumentsCheckArity(target, pos, filters);
5377         MethodHandle adapter = target;
5378 
5379         // keep track of currently matched filters, as to optimize repeated filters
5380         int index = 0;
5381         int[] positions = new int[filters.length];
5382         MethodHandle filter = null;
5383 
5384         // process filters in reverse order so that the invocation of
5385         // the resulting adapter will invoke the filters in left-to-right order
5386         for (int i = filters.length - 1; i >= 0; --i) {
5387             MethodHandle newFilter = filters[i];
5388             if (newFilter == null) continue;  // ignore null elements of filters
5389 
5390             // flush changes on update
5391             if (filter != newFilter) {
5392                 if (filter != null) {
5393                     if (index > 1) {
5394                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5395                     } else {
5396                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5397                     }
5398                 }
5399                 filter = newFilter;
5400                 index = 0;
5401             }
5402 
5403             filterArgumentChecks(target, pos + i, newFilter);
5404             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5405         }
5406         if (index > 1) {
5407             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5408         } else if (index == 1) {
5409             adapter = filterArgument(adapter, positions[0] - 1, filter);
5410         }
5411         return adapter;
5412     }
5413 
5414     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5415         MethodType targetType = adapter.type();
5416         MethodType filterType = filter.type();
5417         BoundMethodHandle result = adapter.rebind();
5418         Class<?> newParamType = filterType.parameterType(0);
5419 
5420         Class<?>[] ptypes = targetType.ptypes().clone();
5421         for (int pos : positions) {
5422             ptypes[pos - 1] = newParamType;
5423         }
5424         MethodType newType = MethodType.methodType(targetType.rtype(), ptypes, true);
5425 
5426         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5427         return result.copyWithExtendL(newType, lform, filter);
5428     }
5429 
5430     /*non-public*/
5431     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5432         filterArgumentChecks(target, pos, filter);
5433         MethodType targetType = target.type();
5434         MethodType filterType = filter.type();
5435         BoundMethodHandle result = target.rebind();
5436         Class<?> newParamType = filterType.parameterType(0);
5437         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5438         MethodType newType = targetType.changeParameterType(pos, newParamType);
5439         result = result.copyWithExtendL(newType, lform, filter);
5440         return result;
5441     }
5442 
5443     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5444         MethodType targetType = target.type();
5445         int maxPos = targetType.parameterCount();
5446         if (pos + filters.length > maxPos)
5447             throw newIllegalArgumentException("too many filters");
5448     }
5449 
5450     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5451         MethodType targetType = target.type();
5452         MethodType filterType = filter.type();
5453         if (filterType.parameterCount() != 1
5454             || filterType.returnType() != targetType.parameterType(pos))
5455             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5456     }
5457 
5458     /**
5459      * Adapts a target method handle by pre-processing
5460      * a sub-sequence of its arguments with a filter (another method handle).
5461      * The pre-processed arguments are replaced by the result (if any) of the
5462      * filter function.
5463      * The target is then called on the modified (usually shortened) argument list.
5464      * <p>
5465      * If the filter returns a value, the target must accept that value as
5466      * its argument in position {@code pos}, preceded and/or followed by
5467      * any arguments not passed to the filter.
5468      * If the filter returns void, the target must accept all arguments
5469      * not passed to the filter.
5470      * No arguments are reordered, and a result returned from the filter
5471      * replaces (in order) the whole subsequence of arguments originally
5472      * passed to the adapter.
5473      * <p>
5474      * The argument types (if any) of the filter
5475      * replace zero or one argument types of the target, at position {@code pos},
5476      * in the resulting adapted method handle.
5477      * The return type of the filter (if any) must be identical to the
5478      * argument type of the target at position {@code pos}, and that target argument
5479      * is supplied by the return value of the filter.
5480      * <p>
5481      * In all cases, {@code pos} must be greater than or equal to zero, and
5482      * {@code pos} must also be less than or equal to the target's arity.
5483      * <p><b>Example:</b>
5484      * {@snippet lang="java" :
5485 import static java.lang.invoke.MethodHandles.*;
5486 import static java.lang.invoke.MethodType.*;
5487 ...
5488 MethodHandle deepToString = publicLookup()
5489   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5490 
5491 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5492 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5493 
5494 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5495 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5496 
5497 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5498 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5499 assertEquals("[top, [up, down], strange]",
5500              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5501 
5502 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5503 assertEquals("[top, [up, down], [strange]]",
5504              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5505 
5506 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5507 assertEquals("[top, [[up, down, strange], charm], bottom]",
5508              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5509      * }
5510      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5511      * represents the return type of the {@code target} and resulting adapter.
5512      * {@code V}/{@code v} stand for the return type and value of the
5513      * {@code filter}, which are also found in the signature and arguments of
5514      * the {@code target}, respectively, unless {@code V} is {@code void}.
5515      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5516      * and values preceding and following the collection position, {@code pos},
5517      * in the {@code target}'s signature. They also turn up in the resulting
5518      * adapter's signature and arguments, where they surround
5519      * {@code B}/{@code b}, which represent the parameter types and arguments
5520      * to the {@code filter} (if any).
5521      * {@snippet lang="java" :
5522      * T target(A...,V,C...);
5523      * V filter(B...);
5524      * T adapter(A... a,B... b,C... c) {
5525      *   V v = filter(b...);
5526      *   return target(a...,v,c...);
5527      * }
5528      * // and if the filter has no arguments:
5529      * T target2(A...,V,C...);
5530      * V filter2();
5531      * T adapter2(A... a,C... c) {
5532      *   V v = filter2();
5533      *   return target2(a...,v,c...);
5534      * }
5535      * // and if the filter has a void return:
5536      * T target3(A...,C...);
5537      * void filter3(B...);
5538      * T adapter3(A... a,B... b,C... c) {
5539      *   filter3(b...);
5540      *   return target3(a...,c...);
5541      * }
5542      * }
5543      * <p>
5544      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5545      * one which first "folds" the affected arguments, and then drops them, in separate
5546      * steps as follows:
5547      * {@snippet lang="java" :
5548      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5549      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5550      * }
5551      * If the target method handle consumes no arguments besides than the result
5552      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5553      * is equivalent to {@code filterReturnValue(coll, mh)}.
5554      * If the filter method handle {@code coll} consumes one argument and produces
5555      * a non-void result, then {@code collectArguments(mh, N, coll)}
5556      * is equivalent to {@code filterArguments(mh, N, coll)}.
5557      * Other equivalences are possible but would require argument permutation.
5558      * <p>
5559      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5560      * variable-arity method handle}, even if the original target method handle was.
5561      *
5562      * @param target the method handle to invoke after filtering the subsequence of arguments
5563      * @param pos the position of the first adapter argument to pass to the filter,
5564      *            and/or the target argument which receives the result of the filter
5565      * @param filter method handle to call on the subsequence of arguments
5566      * @return method handle which incorporates the specified argument subsequence filtering logic
5567      * @throws NullPointerException if either argument is null
5568      * @throws IllegalArgumentException if the return type of {@code filter}
5569      *          is non-void and is not the same as the {@code pos} argument of the target,
5570      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5571      *          or if the resulting method handle's type would have
5572      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5573      * @see MethodHandles#foldArguments
5574      * @see MethodHandles#filterArguments
5575      * @see MethodHandles#filterReturnValue
5576      */
5577     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5578         MethodType newType = collectArgumentsChecks(target, pos, filter);
5579         MethodType collectorType = filter.type();
5580         BoundMethodHandle result = target.rebind();
5581         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5582         return result.copyWithExtendL(newType, lform, filter);
5583     }
5584 
5585     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5586         MethodType targetType = target.type();
5587         MethodType filterType = filter.type();
5588         Class<?> rtype = filterType.returnType();
5589         Class<?>[] filterArgs = filterType.ptypes();
5590         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5591                        (rtype != void.class && pos >= targetType.parameterCount())) {
5592             throw newIllegalArgumentException("position is out of range for target", target, pos);
5593         }
5594         if (rtype == void.class) {
5595             return targetType.insertParameterTypes(pos, filterArgs);
5596         }
5597         if (rtype != targetType.parameterType(pos)) {
5598             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5599         }
5600         return targetType.dropParameterTypes(pos, pos + 1).insertParameterTypes(pos, filterArgs);
5601     }
5602 
5603     /**
5604      * Adapts a target method handle by post-processing
5605      * its return value (if any) with a filter (another method handle).
5606      * The result of the filter is returned from the adapter.
5607      * <p>
5608      * If the target returns a value, the filter must accept that value as
5609      * its only argument.
5610      * If the target returns void, the filter must accept no arguments.
5611      * <p>
5612      * The return type of the filter
5613      * replaces the return type of the target
5614      * in the resulting adapted method handle.
5615      * The argument type of the filter (if any) must be identical to the
5616      * return type of the target.
5617      * <p><b>Example:</b>
5618      * {@snippet lang="java" :
5619 import static java.lang.invoke.MethodHandles.*;
5620 import static java.lang.invoke.MethodType.*;
5621 ...
5622 MethodHandle cat = lookup().findVirtual(String.class,
5623   "concat", methodType(String.class, String.class));
5624 MethodHandle length = lookup().findVirtual(String.class,
5625   "length", methodType(int.class));
5626 System.out.println((String) cat.invokeExact("x", "y")); // xy
5627 MethodHandle f0 = filterReturnValue(cat, length);
5628 System.out.println((int) f0.invokeExact("x", "y")); // 2
5629      * }
5630      * <p>Here is pseudocode for the resulting adapter. In the code,
5631      * {@code T}/{@code t} represent the result type and value of the
5632      * {@code target}; {@code V}, the result type of the {@code filter}; and
5633      * {@code A}/{@code a}, the types and values of the parameters and arguments
5634      * of the {@code target} as well as the resulting adapter.
5635      * {@snippet lang="java" :
5636      * T target(A...);
5637      * V filter(T);
5638      * V adapter(A... a) {
5639      *   T t = target(a...);
5640      *   return filter(t);
5641      * }
5642      * // and if the target has a void return:
5643      * void target2(A...);
5644      * V filter2();
5645      * V adapter2(A... a) {
5646      *   target2(a...);
5647      *   return filter2();
5648      * }
5649      * // and if the filter has a void return:
5650      * T target3(A...);
5651      * void filter3(V);
5652      * void adapter3(A... a) {
5653      *   T t = target3(a...);
5654      *   filter3(t);
5655      * }
5656      * }
5657      * <p>
5658      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5659      * variable-arity method handle}, even if the original target method handle was.
5660      * @param target the method handle to invoke before filtering the return value
5661      * @param filter method handle to call on the return value
5662      * @return method handle which incorporates the specified return value filtering logic
5663      * @throws NullPointerException if either argument is null
5664      * @throws IllegalArgumentException if the argument list of {@code filter}
5665      *          does not match the return type of target as described above
5666      */
5667     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5668         MethodType targetType = target.type();
5669         MethodType filterType = filter.type();
5670         filterReturnValueChecks(targetType, filterType);
5671         BoundMethodHandle result = target.rebind();
5672         BasicType rtype = BasicType.basicType(filterType.returnType());
5673         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5674         MethodType newType = targetType.changeReturnType(filterType.returnType());
5675         result = result.copyWithExtendL(newType, lform, filter);
5676         return result;
5677     }
5678 
5679     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5680         Class<?> rtype = targetType.returnType();
5681         int filterValues = filterType.parameterCount();
5682         if (filterValues == 0
5683                 ? (rtype != void.class)
5684                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5685             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5686     }
5687 
5688     /**
5689      * Filter the return value of a target method handle with a filter function. The filter function is
5690      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5691      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5692      * as follows:
5693      * {@snippet lang="java" :
5694      * T target(A...)
5695      * V filter(B... , T)
5696      * V adapter(A... a, B... b) {
5697      *     T t = target(a...);
5698      *     return filter(b..., t);
5699      * }
5700      * }
5701      * <p>
5702      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5703      *
5704      * @param target the target method handle
5705      * @param filter the filter method handle
5706      * @return the adapter method handle
5707      */
5708     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5709         MethodType targetType = target.type();
5710         MethodType filterType = filter.type();
5711         BoundMethodHandle result = target.rebind();
5712         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5713         MethodType newType = targetType.changeReturnType(filterType.returnType());
5714         if (filterType.parameterCount() > 1) {
5715             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5716                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5717             }
5718         }
5719         result = result.copyWithExtendL(newType, lform, filter);
5720         return result;
5721     }
5722 
5723     /**
5724      * Adapts a target method handle by pre-processing
5725      * some of its arguments, and then calling the target with
5726      * the result of the pre-processing, inserted into the original
5727      * sequence of arguments.
5728      * <p>
5729      * The pre-processing is performed by {@code combiner}, a second method handle.
5730      * Of the arguments passed to the adapter, the first {@code N} arguments
5731      * are copied to the combiner, which is then called.
5732      * (Here, {@code N} is defined as the parameter count of the combiner.)
5733      * After this, control passes to the target, with any result
5734      * from the combiner inserted before the original {@code N} incoming
5735      * arguments.
5736      * <p>
5737      * If the combiner returns a value, the first parameter type of the target
5738      * must be identical with the return type of the combiner, and the next
5739      * {@code N} parameter types of the target must exactly match the parameters
5740      * of the combiner.
5741      * <p>
5742      * If the combiner has a void return, no result will be inserted,
5743      * and the first {@code N} parameter types of the target
5744      * must exactly match the parameters of the combiner.
5745      * <p>
5746      * The resulting adapter is the same type as the target, except that the
5747      * first parameter type is dropped,
5748      * if it corresponds to the result of the combiner.
5749      * <p>
5750      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5751      * that either the combiner or the target does not wish to receive.
5752      * If some of the incoming arguments are destined only for the combiner,
5753      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5754      * arguments will not need to be live on the stack on entry to the
5755      * target.)
5756      * <p><b>Example:</b>
5757      * {@snippet lang="java" :
5758 import static java.lang.invoke.MethodHandles.*;
5759 import static java.lang.invoke.MethodType.*;
5760 ...
5761 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5762   "println", methodType(void.class, String.class))
5763     .bindTo(System.out);
5764 MethodHandle cat = lookup().findVirtual(String.class,
5765   "concat", methodType(String.class, String.class));
5766 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5767 MethodHandle catTrace = foldArguments(cat, trace);
5768 // also prints "boo":
5769 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5770      * }
5771      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5772      * represents the result type of the {@code target} and resulting adapter.
5773      * {@code V}/{@code v} represent the type and value of the parameter and argument
5774      * of {@code target} that precedes the folding position; {@code V} also is
5775      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5776      * types and values of the {@code N} parameters and arguments at the folding
5777      * position. {@code B}/{@code b} represent the types and values of the
5778      * {@code target} parameters and arguments that follow the folded parameters
5779      * and arguments.
5780      * {@snippet lang="java" :
5781      * // there are N arguments in A...
5782      * T target(V, A[N]..., B...);
5783      * V combiner(A...);
5784      * T adapter(A... a, B... b) {
5785      *   V v = combiner(a...);
5786      *   return target(v, a..., b...);
5787      * }
5788      * // and if the combiner has a void return:
5789      * T target2(A[N]..., B...);
5790      * void combiner2(A...);
5791      * T adapter2(A... a, B... b) {
5792      *   combiner2(a...);
5793      *   return target2(a..., b...);
5794      * }
5795      * }
5796      * <p>
5797      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5798      * variable-arity method handle}, even if the original target method handle was.
5799      * @param target the method handle to invoke after arguments are combined
5800      * @param combiner method handle to call initially on the incoming arguments
5801      * @return method handle which incorporates the specified argument folding logic
5802      * @throws NullPointerException if either argument is null
5803      * @throws IllegalArgumentException if {@code combiner}'s return type
5804      *          is non-void and not the same as the first argument type of
5805      *          the target, or if the initial {@code N} argument types
5806      *          of the target
5807      *          (skipping one matching the {@code combiner}'s return type)
5808      *          are not identical with the argument types of {@code combiner}
5809      */
5810     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
5811         return foldArguments(target, 0, combiner);
5812     }
5813 
5814     /**
5815      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
5816      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
5817      * before the folded arguments.
5818      * <p>
5819      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
5820      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
5821      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
5822      * 0.
5823      *
5824      * @apiNote Example:
5825      * {@snippet lang="java" :
5826     import static java.lang.invoke.MethodHandles.*;
5827     import static java.lang.invoke.MethodType.*;
5828     ...
5829     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5830     "println", methodType(void.class, String.class))
5831     .bindTo(System.out);
5832     MethodHandle cat = lookup().findVirtual(String.class,
5833     "concat", methodType(String.class, String.class));
5834     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5835     MethodHandle catTrace = foldArguments(cat, 1, trace);
5836     // also prints "jum":
5837     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5838      * }
5839      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5840      * represents the result type of the {@code target} and resulting adapter.
5841      * {@code V}/{@code v} represent the type and value of the parameter and argument
5842      * of {@code target} that precedes the folding position; {@code V} also is
5843      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5844      * types and values of the {@code N} parameters and arguments at the folding
5845      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
5846      * and values of the {@code target} parameters and arguments that precede and
5847      * follow the folded parameters and arguments starting at {@code pos},
5848      * respectively.
5849      * {@snippet lang="java" :
5850      * // there are N arguments in A...
5851      * T target(Z..., V, A[N]..., B...);
5852      * V combiner(A...);
5853      * T adapter(Z... z, A... a, B... b) {
5854      *   V v = combiner(a...);
5855      *   return target(z..., v, a..., b...);
5856      * }
5857      * // and if the combiner has a void return:
5858      * T target2(Z..., A[N]..., B...);
5859      * void combiner2(A...);
5860      * T adapter2(Z... z, A... a, B... b) {
5861      *   combiner2(a...);
5862      *   return target2(z..., a..., b...);
5863      * }
5864      * }
5865      * <p>
5866      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5867      * variable-arity method handle}, even if the original target method handle was.
5868      *
5869      * @param target the method handle to invoke after arguments are combined
5870      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
5871      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5872      * @param combiner method handle to call initially on the incoming arguments
5873      * @return method handle which incorporates the specified argument folding logic
5874      * @throws NullPointerException if either argument is null
5875      * @throws IllegalArgumentException if either of the following two conditions holds:
5876      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5877      *              {@code pos} of the target signature;
5878      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
5879      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
5880      *
5881      * @see #foldArguments(MethodHandle, MethodHandle)
5882      * @since 9
5883      */
5884     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
5885         MethodType targetType = target.type();
5886         MethodType combinerType = combiner.type();
5887         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
5888         BoundMethodHandle result = target.rebind();
5889         boolean dropResult = rtype == void.class;
5890         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
5891         MethodType newType = targetType;
5892         if (!dropResult) {
5893             newType = newType.dropParameterTypes(pos, pos + 1);
5894         }
5895         result = result.copyWithExtendL(newType, lform, combiner);
5896         return result;
5897     }
5898 
5899     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
5900         int foldArgs   = combinerType.parameterCount();
5901         Class<?> rtype = combinerType.returnType();
5902         int foldVals = rtype == void.class ? 0 : 1;
5903         int afterInsertPos = foldPos + foldVals;
5904         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
5905         if (ok) {
5906             for (int i = 0; i < foldArgs; i++) {
5907                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
5908                     ok = false;
5909                     break;
5910                 }
5911             }
5912         }
5913         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
5914             ok = false;
5915         if (!ok)
5916             throw misMatchedTypes("target and combiner types", targetType, combinerType);
5917         return rtype;
5918     }
5919 
5920     /**
5921      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
5922      * of the pre-processing replacing the argument at the given position.
5923      *
5924      * @param target the method handle to invoke after arguments are combined
5925      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5926      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5927      * @param combiner method handle to call initially on the incoming arguments
5928      * @param argPositions indexes of the target to pick arguments sent to the combiner from
5929      * @return method handle which incorporates the specified argument folding logic
5930      * @throws NullPointerException if either argument is null
5931      * @throws IllegalArgumentException if either of the following two conditions holds:
5932      *          (1) {@code combiner}'s return type is not the same as the argument type at position
5933      *              {@code pos} of the target signature;
5934      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
5935      *              not identical with the argument types of {@code combiner}.
5936      */
5937     /*non-public*/
5938     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5939         return argumentsWithCombiner(true, target, position, combiner, argPositions);
5940     }
5941 
5942     /**
5943      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
5944      * the pre-processing inserted into the original sequence of arguments at the given position.
5945      *
5946      * @param target the method handle to invoke after arguments are combined
5947      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
5948      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
5949      * @param combiner method handle to call initially on the incoming arguments
5950      * @param argPositions indexes of the target to pick arguments sent to the combiner from
5951      * @return method handle which incorporates the specified argument folding logic
5952      * @throws NullPointerException if either argument is null
5953      * @throws IllegalArgumentException if either of the following two conditions holds:
5954      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
5955      *              {@code pos} of the target signature;
5956      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
5957      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
5958      *              with the argument types of {@code combiner}.
5959      */
5960     /*non-public*/
5961     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5962         return argumentsWithCombiner(false, target, position, combiner, argPositions);
5963     }
5964 
5965     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
5966         MethodType targetType = target.type();
5967         MethodType combinerType = combiner.type();
5968         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
5969         BoundMethodHandle result = target.rebind();
5970 
5971         MethodType newType = targetType;
5972         LambdaForm lform;
5973         if (filter) {
5974             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
5975         } else {
5976             boolean dropResult = rtype == void.class;
5977             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
5978             if (!dropResult) {
5979                 newType = newType.dropParameterTypes(position, position + 1);
5980             }
5981         }
5982         result = result.copyWithExtendL(newType, lform, combiner);
5983         return result;
5984     }
5985 
5986     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
5987         int combinerArgs = combinerType.parameterCount();
5988         if (argPos.length != combinerArgs) {
5989             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
5990         }
5991         Class<?> rtype = combinerType.returnType();
5992 
5993         for (int i = 0; i < combinerArgs; i++) {
5994             int arg = argPos[i];
5995             if (arg < 0 || arg > targetType.parameterCount()) {
5996                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
5997             }
5998             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
5999                 throw newIllegalArgumentException("target argument type at position " + arg
6000                         + " must match combiner argument type at index " + i + ": " + targetType
6001                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6002             }
6003         }
6004         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6005             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6006         }
6007         return rtype;
6008     }
6009 
6010     /**
6011      * Makes a method handle which adapts a target method handle,
6012      * by guarding it with a test, a boolean-valued method handle.
6013      * If the guard fails, a fallback handle is called instead.
6014      * All three method handles must have the same corresponding
6015      * argument and return types, except that the return type
6016      * of the test must be boolean, and the test is allowed
6017      * to have fewer arguments than the other two method handles.
6018      * <p>
6019      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6020      * represents the uniform result type of the three involved handles;
6021      * {@code A}/{@code a}, the types and values of the {@code target}
6022      * parameters and arguments that are consumed by the {@code test}; and
6023      * {@code B}/{@code b}, those types and values of the {@code target}
6024      * parameters and arguments that are not consumed by the {@code test}.
6025      * {@snippet lang="java" :
6026      * boolean test(A...);
6027      * T target(A...,B...);
6028      * T fallback(A...,B...);
6029      * T adapter(A... a,B... b) {
6030      *   if (test(a...))
6031      *     return target(a..., b...);
6032      *   else
6033      *     return fallback(a..., b...);
6034      * }
6035      * }
6036      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6037      * be modified by execution of the test, and so are passed unchanged
6038      * from the caller to the target or fallback as appropriate.
6039      * @param test method handle used for test, must return boolean
6040      * @param target method handle to call if test passes
6041      * @param fallback method handle to call if test fails
6042      * @return method handle which incorporates the specified if/then/else logic
6043      * @throws NullPointerException if any argument is null
6044      * @throws IllegalArgumentException if {@code test} does not return boolean,
6045      *          or if all three method types do not match (with the return
6046      *          type of {@code test} changed to match that of the target).
6047      */
6048     public static MethodHandle guardWithTest(MethodHandle test,
6049                                MethodHandle target,
6050                                MethodHandle fallback) {
6051         MethodType gtype = test.type();
6052         MethodType ttype = target.type();
6053         MethodType ftype = fallback.type();
6054         if (!ttype.equals(ftype))
6055             throw misMatchedTypes("target and fallback types", ttype, ftype);
6056         if (gtype.returnType() != boolean.class)
6057             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6058 
6059         test = dropArgumentsToMatch(test, 0, ttype.ptypes(), 0, true);
6060         if (test == null) {
6061             throw misMatchedTypes("target and test types", ttype, gtype);
6062         }
6063         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6064     }
6065 
6066     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6067         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6068     }
6069 
6070     /**
6071      * Makes a method handle which adapts a target method handle,
6072      * by running it inside an exception handler.
6073      * If the target returns normally, the adapter returns that value.
6074      * If an exception matching the specified type is thrown, the fallback
6075      * handle is called instead on the exception, plus the original arguments.
6076      * <p>
6077      * The target and handler must have the same corresponding
6078      * argument and return types, except that handler may omit trailing arguments
6079      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6080      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6081      * <p>
6082      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6083      * represents the return type of the {@code target} and {@code handler},
6084      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6085      * the types and values of arguments to the resulting handle consumed by
6086      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6087      * resulting handle discarded by {@code handler}.
6088      * {@snippet lang="java" :
6089      * T target(A..., B...);
6090      * T handler(ExType, A...);
6091      * T adapter(A... a, B... b) {
6092      *   try {
6093      *     return target(a..., b...);
6094      *   } catch (ExType ex) {
6095      *     return handler(ex, a...);
6096      *   }
6097      * }
6098      * }
6099      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6100      * be modified by execution of the target, and so are passed unchanged
6101      * from the caller to the handler, if the handler is invoked.
6102      * <p>
6103      * The target and handler must return the same type, even if the handler
6104      * always throws.  (This might happen, for instance, because the handler
6105      * is simulating a {@code finally} clause).
6106      * To create such a throwing handler, compose the handler creation logic
6107      * with {@link #throwException throwException},
6108      * in order to create a method handle of the correct return type.
6109      * @param target method handle to call
6110      * @param exType the type of exception which the handler will catch
6111      * @param handler method handle to call if a matching exception is thrown
6112      * @return method handle which incorporates the specified try/catch logic
6113      * @throws NullPointerException if any argument is null
6114      * @throws IllegalArgumentException if {@code handler} does not accept
6115      *          the given exception type, or if the method handle types do
6116      *          not match in their return types and their
6117      *          corresponding parameters
6118      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6119      */
6120     public static MethodHandle catchException(MethodHandle target,
6121                                 Class<? extends Throwable> exType,
6122                                 MethodHandle handler) {
6123         MethodType ttype = target.type();
6124         MethodType htype = handler.type();
6125         if (!Throwable.class.isAssignableFrom(exType))
6126             throw new ClassCastException(exType.getName());
6127         if (htype.parameterCount() < 1 ||
6128             !htype.parameterType(0).isAssignableFrom(exType))
6129             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6130         if (htype.returnType() != ttype.returnType())
6131             throw misMatchedTypes("target and handler return types", ttype, htype);
6132         handler = dropArgumentsToMatch(handler, 1, ttype.ptypes(), 0, true);
6133         if (handler == null) {
6134             throw misMatchedTypes("target and handler types", ttype, htype);
6135         }
6136         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6137     }
6138 
6139     /**
6140      * Produces a method handle which will throw exceptions of the given {@code exType}.
6141      * The method handle will accept a single argument of {@code exType},
6142      * and immediately throw it as an exception.
6143      * The method type will nominally specify a return of {@code returnType}.
6144      * The return type may be anything convenient:  It doesn't matter to the
6145      * method handle's behavior, since it will never return normally.
6146      * @param returnType the return type of the desired method handle
6147      * @param exType the parameter type of the desired method handle
6148      * @return method handle which can throw the given exceptions
6149      * @throws NullPointerException if either argument is null
6150      */
6151     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6152         if (!Throwable.class.isAssignableFrom(exType))
6153             throw new ClassCastException(exType.getName());
6154         return MethodHandleImpl.throwException(methodType(returnType, exType));
6155     }
6156 
6157     /**
6158      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6159      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6160      * delivers the loop's result, which is the return value of the resulting handle.
6161      * <p>
6162      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6163      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6164      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6165      * terms of method handles, each clause will specify up to four independent actions:<ul>
6166      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6167      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6168      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6169      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6170      * </ul>
6171      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6172      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6173      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6174      * <p>
6175      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6176      * this case. See below for a detailed description.
6177      * <p>
6178      * <em>Parameters optional everywhere:</em>
6179      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6180      * As an exception, the init functions cannot take any {@code v} parameters,
6181      * because those values are not yet computed when the init functions are executed.
6182      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6183      * In fact, any clause function may take no arguments at all.
6184      * <p>
6185      * <em>Loop parameters:</em>
6186      * A clause function may take all the iteration variable values it is entitled to, in which case
6187      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6188      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6189      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6190      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6191      * init function is automatically a loop parameter {@code a}.)
6192      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6193      * These loop parameters act as loop-invariant values visible across the whole loop.
6194      * <p>
6195      * <em>Parameters visible everywhere:</em>
6196      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6197      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6198      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6199      * Most clause functions will not need all of this information, but they will be formally connected to it
6200      * as if by {@link #dropArguments}.
6201      * <a id="astar"></a>
6202      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6203      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6204      * In that notation, the general form of an init function parameter list
6205      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6206      * <p>
6207      * <em>Checking clause structure:</em>
6208      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6209      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6210      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6211      * met by the inputs to the loop combinator.
6212      * <p>
6213      * <em>Effectively identical sequences:</em>
6214      * <a id="effid"></a>
6215      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6216      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6217      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6218      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6219      * that longest list.
6220      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6221      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6222      * <p>
6223      * <em>Step 0: Determine clause structure.</em><ol type="a">
6224      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6225      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6226      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6227      * four. Padding takes place by appending elements to the array.
6228      * <li>Clauses with all {@code null}s are disregarded.
6229      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6230      * </ol>
6231      * <p>
6232      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6233      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6234      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6235      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6236      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6237      * iteration variable type.
6238      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6239      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6240      * </ol>
6241      * <p>
6242      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6243      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6244      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6245      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6246      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6247      * (These types will be checked in step 2, along with all the clause function types.)
6248      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6249      * <li>All of the collected parameter lists must be effectively identical.
6250      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6251      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6252      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6253      * the "internal parameter list".
6254      * </ul>
6255      * <p>
6256      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6257      * <li>Examine fini function return types, disregarding omitted fini functions.
6258      * <li>If there are no fini functions, the loop return type is {@code void}.
6259      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6260      * type.
6261      * </ol>
6262      * <p>
6263      * <em>Step 1D: Check other types.</em><ol type="a">
6264      * <li>There must be at least one non-omitted pred function.
6265      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6266      * </ol>
6267      * <p>
6268      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6269      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6270      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6271      * (Note that their parameter lists are already effectively identical to this list.)
6272      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6273      * effectively identical to the internal parameter list {@code (V... A...)}.
6274      * </ol>
6275      * <p>
6276      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6277      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6278      * type.
6279      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6280      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6281      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6282      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6283      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6284      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6285      * loop return type.
6286      * </ol>
6287      * <p>
6288      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6289      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6290      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6291      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6292      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6293      * pad out the end of the list.
6294      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6295      * </ol>
6296      * <p>
6297      * <em>Final observations.</em><ol type="a">
6298      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6299      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6300      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6301      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6302      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6303      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6304      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6305      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6306      * </ol>
6307      * <p>
6308      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6309      * <ul>
6310      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6311      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6312      * (Only one {@code Pn} has to be non-{@code null}.)
6313      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6314      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6315      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6316      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6317      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6318      * the resulting loop handle's parameter types {@code (A...)}.
6319      * </ul>
6320      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6321      * which is natural if most of the loop computation happens in the steps.  For some loops,
6322      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6323      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6324      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6325      * where the init functions will need the extra parameters.  For such reasons, the rules for
6326      * determining these parameters are as symmetric as possible, across all clause parts.
6327      * In general, the loop parameters function as common invariant values across the whole
6328      * loop, while the iteration variables function as common variant values, or (if there is
6329      * no step function) as internal loop invariant temporaries.
6330      * <p>
6331      * <em>Loop execution.</em><ol type="a">
6332      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6333      * every clause function. These locals are loop invariant.
6334      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6335      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6336      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6337      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6338      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6339      * (in argument order).
6340      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6341      * returns {@code false}.
6342      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6343      * sequence {@code (v...)} of loop variables.
6344      * The updated value is immediately visible to all subsequent function calls.
6345      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6346      * (of type {@code R}) is returned from the loop as a whole.
6347      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6348      * except by throwing an exception.
6349      * </ol>
6350      * <p>
6351      * <em>Usage tips.</em>
6352      * <ul>
6353      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6354      * sometimes a step function only needs to observe the current value of its own variable.
6355      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6356      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6357      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6358      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6359      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6360      * <li>If some of the clause functions are virtual methods on an instance, the instance
6361      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6362      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6363      * will be the first iteration variable value, and it will be easy to use virtual
6364      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6365      * </ul>
6366      * <p>
6367      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6368      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6369      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6370      * {@snippet lang="java" :
6371      * V... init...(A...);
6372      * boolean pred...(V..., A...);
6373      * V... step...(V..., A...);
6374      * R fini...(V..., A...);
6375      * R loop(A... a) {
6376      *   V... v... = init...(a...);
6377      *   for (;;) {
6378      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6379      *       v = s(v..., a...);
6380      *       if (!p(v..., a...)) {
6381      *         return f(v..., a...);
6382      *       }
6383      *     }
6384      *   }
6385      * }
6386      * }
6387      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6388      * to their full length, even though individual clause functions may neglect to take them all.
6389      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6390      *
6391      * @apiNote Example:
6392      * {@snippet lang="java" :
6393      * // iterative implementation of the factorial function as a loop handle
6394      * static int one(int k) { return 1; }
6395      * static int inc(int i, int acc, int k) { return i + 1; }
6396      * static int mult(int i, int acc, int k) { return i * acc; }
6397      * static boolean pred(int i, int acc, int k) { return i < k; }
6398      * static int fin(int i, int acc, int k) { return acc; }
6399      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6400      * // null initializer for counter, should initialize to 0
6401      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6402      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6403      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6404      * assertEquals(120, loop.invoke(5));
6405      * }
6406      * The same example, dropping arguments and using combinators:
6407      * {@snippet lang="java" :
6408      * // simplified implementation of the factorial function as a loop handle
6409      * static int inc(int i) { return i + 1; } // drop acc, k
6410      * static int mult(int i, int acc) { return i * acc; } //drop k
6411      * static boolean cmp(int i, int k) { return i < k; }
6412      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6413      * // null initializer for counter, should initialize to 0
6414      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6415      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6416      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6417      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6418      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6419      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6420      * assertEquals(720, loop.invoke(6));
6421      * }
6422      * A similar example, using a helper object to hold a loop parameter:
6423      * {@snippet lang="java" :
6424      * // instance-based implementation of the factorial function as a loop handle
6425      * static class FacLoop {
6426      *   final int k;
6427      *   FacLoop(int k) { this.k = k; }
6428      *   int inc(int i) { return i + 1; }
6429      *   int mult(int i, int acc) { return i * acc; }
6430      *   boolean pred(int i) { return i < k; }
6431      *   int fin(int i, int acc) { return acc; }
6432      * }
6433      * // assume MH_FacLoop is a handle to the constructor
6434      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6435      * // null initializer for counter, should initialize to 0
6436      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6437      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6438      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6439      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6440      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6441      * assertEquals(5040, loop.invoke(7));
6442      * }
6443      *
6444      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6445      *
6446      * @return a method handle embodying the looping behavior as defined by the arguments.
6447      *
6448      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6449      *
6450      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6451      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6452      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6453      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6454      * @since 9
6455      */
6456     public static MethodHandle loop(MethodHandle[]... clauses) {
6457         // Step 0: determine clause structure.
6458         loopChecks0(clauses);
6459 
6460         List<MethodHandle> init = new ArrayList<>();
6461         List<MethodHandle> step = new ArrayList<>();
6462         List<MethodHandle> pred = new ArrayList<>();
6463         List<MethodHandle> fini = new ArrayList<>();
6464 
6465         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6466             init.add(clause[0]); // all clauses have at least length 1
6467             step.add(clause.length <= 1 ? null : clause[1]);
6468             pred.add(clause.length <= 2 ? null : clause[2]);
6469             fini.add(clause.length <= 3 ? null : clause[3]);
6470         });
6471 
6472         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6473         final int nclauses = init.size();
6474 
6475         // Step 1A: determine iteration variables (V...).
6476         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6477         for (int i = 0; i < nclauses; ++i) {
6478             MethodHandle in = init.get(i);
6479             MethodHandle st = step.get(i);
6480             if (in == null && st == null) {
6481                 iterationVariableTypes.add(void.class);
6482             } else if (in != null && st != null) {
6483                 loopChecks1a(i, in, st);
6484                 iterationVariableTypes.add(in.type().returnType());
6485             } else {
6486                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6487             }
6488         }
6489         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6490 
6491         // Step 1B: determine loop parameters (A...).
6492         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6493         loopChecks1b(init, commonSuffix);
6494 
6495         // Step 1C: determine loop return type.
6496         // Step 1D: check other types.
6497         // local variable required here; see JDK-8223553
6498         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6499                 .map(MethodType::returnType);
6500         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6501         loopChecks1cd(pred, fini, loopReturnType);
6502 
6503         // Step 2: determine parameter lists.
6504         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6505         commonParameterSequence.addAll(commonSuffix);
6506         loopChecks2(step, pred, fini, commonParameterSequence);
6507         // Step 3: fill in omitted functions.
6508         for (int i = 0; i < nclauses; ++i) {
6509             Class<?> t = iterationVariableTypes.get(i);
6510             if (init.get(i) == null) {
6511                 init.set(i, empty(methodType(t, commonSuffix)));
6512             }
6513             if (step.get(i) == null) {
6514                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6515             }
6516             if (pred.get(i) == null) {
6517                 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
6518             }
6519             if (fini.get(i) == null) {
6520                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6521             }
6522         }
6523 
6524         // Step 4: fill in missing parameter types.
6525         // Also convert all handles to fixed-arity handles.
6526         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6527         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6528         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6529         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6530 
6531         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6532                 allMatch(pl -> pl.equals(commonSuffix));
6533         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6534                 allMatch(pl -> pl.equals(commonParameterSequence));
6535 
6536         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6537     }
6538 
6539     private static void loopChecks0(MethodHandle[][] clauses) {
6540         if (clauses == null || clauses.length == 0) {
6541             throw newIllegalArgumentException("null or no clauses passed");
6542         }
6543         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6544             throw newIllegalArgumentException("null clauses are not allowed");
6545         }
6546         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6547             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6548         }
6549     }
6550 
6551     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6552         if (in.type().returnType() != st.type().returnType()) {
6553             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6554                     st.type().returnType());
6555         }
6556     }
6557 
6558     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6559         return mhs.filter(Objects::nonNull)
6560                 // take only those that can contribute to a common suffix because they are longer than the prefix
6561                 .map(MethodHandle::type)
6562                 .filter(t -> t.parameterCount() > skipSize)
6563                 .max(Comparator.comparingInt(MethodType::parameterCount))
6564                 .map(methodType -> List.of(Arrays.copyOfRange(methodType.ptypes(), skipSize, methodType.parameterCount())))
6565                 .orElse(List.of());
6566     }
6567 
6568     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6569         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6570         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6571         return longest1.size() >= longest2.size() ? longest1 : longest2;
6572     }
6573 
6574     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6575         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6576                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6577             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6578                     " (common suffix: " + commonSuffix + ")");
6579         }
6580     }
6581 
6582     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6583         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6584                 anyMatch(t -> t != loopReturnType)) {
6585             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6586                     loopReturnType + ")");
6587         }
6588 
6589         if (pred.stream().noneMatch(Objects::nonNull)) {
6590             throw newIllegalArgumentException("no predicate found", pred);
6591         }
6592         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6593                 anyMatch(t -> t != boolean.class)) {
6594             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6595         }
6596     }
6597 
6598     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6599         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6600                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6601             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6602                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6603         }
6604     }
6605 
6606     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6607         return hs.stream().map(h -> {
6608             int pc = h.type().parameterCount();
6609             int tpsize = targetParams.size();
6610             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
6611         }).toList();
6612     }
6613 
6614     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6615         return hs.stream().map(MethodHandle::asFixedArity).toList();
6616     }
6617 
6618     /**
6619      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6620      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6621      * <p>
6622      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6623      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6624      * evaluates to {@code true}).
6625      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6626      * <p>
6627      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6628      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6629      * and updated with the value returned from its invocation. The result of loop execution will be
6630      * the final value of the additional loop-local variable (if present).
6631      * <p>
6632      * The following rules hold for these argument handles:<ul>
6633      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6634      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6635      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6636      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6637      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6638      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6639      * It will constrain the parameter lists of the other loop parts.
6640      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6641      * list {@code (A...)} is called the <em>external parameter list</em>.
6642      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6643      * additional state variable of the loop.
6644      * The body must both accept and return a value of this type {@code V}.
6645      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6646      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6647      * <a href="MethodHandles.html#effid">effectively identical</a>
6648      * to the external parameter list {@code (A...)}.
6649      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6650      * {@linkplain #empty default value}.
6651      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6652      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6653      * effectively identical to the internal parameter list.
6654      * </ul>
6655      * <p>
6656      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6657      * <li>The loop handle's result type is the result type {@code V} of the body.
6658      * <li>The loop handle's parameter types are the types {@code (A...)},
6659      * from the external parameter list.
6660      * </ul>
6661      * <p>
6662      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6663      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6664      * passed to the loop.
6665      * {@snippet lang="java" :
6666      * V init(A...);
6667      * boolean pred(V, A...);
6668      * V body(V, A...);
6669      * V whileLoop(A... a...) {
6670      *   V v = init(a...);
6671      *   while (pred(v, a...)) {
6672      *     v = body(v, a...);
6673      *   }
6674      *   return v;
6675      * }
6676      * }
6677      *
6678      * @apiNote Example:
6679      * {@snippet lang="java" :
6680      * // implement the zip function for lists as a loop handle
6681      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6682      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6683      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6684      *   zip.add(a.next());
6685      *   zip.add(b.next());
6686      *   return zip;
6687      * }
6688      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6689      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6690      * List<String> a = Arrays.asList("a", "b", "c", "d");
6691      * List<String> b = Arrays.asList("e", "f", "g", "h");
6692      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6693      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6694      * }
6695      *
6696      *
6697      * @apiNote The implementation of this method can be expressed as follows:
6698      * {@snippet lang="java" :
6699      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6700      *     MethodHandle fini = (body.type().returnType() == void.class
6701      *                         ? null : identity(body.type().returnType()));
6702      *     MethodHandle[]
6703      *         checkExit = { null, null, pred, fini },
6704      *         varBody   = { init, body };
6705      *     return loop(checkExit, varBody);
6706      * }
6707      * }
6708      *
6709      * @param init optional initializer, providing the initial value of the loop variable.
6710      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6711      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6712      *             above for other constraints.
6713      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6714      *             See above for other constraints.
6715      *
6716      * @return a method handle implementing the {@code while} loop as described by the arguments.
6717      * @throws IllegalArgumentException if the rules for the arguments are violated.
6718      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6719      *
6720      * @see #loop(MethodHandle[][])
6721      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6722      * @since 9
6723      */
6724     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6725         whileLoopChecks(init, pred, body);
6726         MethodHandle fini = identityOrVoid(body.type().returnType());
6727         MethodHandle[] checkExit = { null, null, pred, fini };
6728         MethodHandle[] varBody = { init, body };
6729         return loop(checkExit, varBody);
6730     }
6731 
6732     /**
6733      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6734      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6735      * <p>
6736      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6737      * method will, in each iteration, first execute its body and then evaluate the predicate.
6738      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6739      * <p>
6740      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6741      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6742      * and updated with the value returned from its invocation. The result of loop execution will be
6743      * the final value of the additional loop-local variable (if present).
6744      * <p>
6745      * The following rules hold for these argument handles:<ul>
6746      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6747      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6748      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6749      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6750      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6751      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6752      * It will constrain the parameter lists of the other loop parts.
6753      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6754      * list {@code (A...)} is called the <em>external parameter list</em>.
6755      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6756      * additional state variable of the loop.
6757      * The body must both accept and return a value of this type {@code V}.
6758      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6759      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6760      * <a href="MethodHandles.html#effid">effectively identical</a>
6761      * to the external parameter list {@code (A...)}.
6762      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6763      * {@linkplain #empty default value}.
6764      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6765      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6766      * effectively identical to the internal parameter list.
6767      * </ul>
6768      * <p>
6769      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6770      * <li>The loop handle's result type is the result type {@code V} of the body.
6771      * <li>The loop handle's parameter types are the types {@code (A...)},
6772      * from the external parameter list.
6773      * </ul>
6774      * <p>
6775      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6776      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6777      * passed to the loop.
6778      * {@snippet lang="java" :
6779      * V init(A...);
6780      * boolean pred(V, A...);
6781      * V body(V, A...);
6782      * V doWhileLoop(A... a...) {
6783      *   V v = init(a...);
6784      *   do {
6785      *     v = body(v, a...);
6786      *   } while (pred(v, a...));
6787      *   return v;
6788      * }
6789      * }
6790      *
6791      * @apiNote Example:
6792      * {@snippet lang="java" :
6793      * // int i = 0; while (i < limit) { ++i; } return i; => limit
6794      * static int zero(int limit) { return 0; }
6795      * static int step(int i, int limit) { return i + 1; }
6796      * static boolean pred(int i, int limit) { return i < limit; }
6797      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
6798      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
6799      * assertEquals(23, loop.invoke(23));
6800      * }
6801      *
6802      *
6803      * @apiNote The implementation of this method can be expressed as follows:
6804      * {@snippet lang="java" :
6805      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6806      *     MethodHandle fini = (body.type().returnType() == void.class
6807      *                         ? null : identity(body.type().returnType()));
6808      *     MethodHandle[] clause = { init, body, pred, fini };
6809      *     return loop(clause);
6810      * }
6811      * }
6812      *
6813      * @param init optional initializer, providing the initial value of the loop variable.
6814      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6815      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6816      *             See above for other constraints.
6817      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6818      *             above for other constraints.
6819      *
6820      * @return a method handle implementing the {@code while} loop as described by the arguments.
6821      * @throws IllegalArgumentException if the rules for the arguments are violated.
6822      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6823      *
6824      * @see #loop(MethodHandle[][])
6825      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
6826      * @since 9
6827      */
6828     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
6829         whileLoopChecks(init, pred, body);
6830         MethodHandle fini = identityOrVoid(body.type().returnType());
6831         MethodHandle[] clause = {init, body, pred, fini };
6832         return loop(clause);
6833     }
6834 
6835     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
6836         Objects.requireNonNull(pred);
6837         Objects.requireNonNull(body);
6838         MethodType bodyType = body.type();
6839         Class<?> returnType = bodyType.returnType();
6840         List<Class<?>> innerList = bodyType.parameterList();
6841         List<Class<?>> outerList = innerList;
6842         if (returnType == void.class) {
6843             // OK
6844         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
6845             // leading V argument missing => error
6846             MethodType expected = bodyType.insertParameterTypes(0, returnType);
6847             throw misMatchedTypes("body function", bodyType, expected);
6848         } else {
6849             outerList = innerList.subList(1, innerList.size());
6850         }
6851         MethodType predType = pred.type();
6852         if (predType.returnType() != boolean.class ||
6853                 !predType.effectivelyIdenticalParameters(0, innerList)) {
6854             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
6855         }
6856         if (init != null) {
6857             MethodType initType = init.type();
6858             if (initType.returnType() != returnType ||
6859                     !initType.effectivelyIdenticalParameters(0, outerList)) {
6860                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
6861             }
6862         }
6863     }
6864 
6865     /**
6866      * Constructs a loop that runs a given number of iterations.
6867      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6868      * <p>
6869      * The number of iterations is determined by the {@code iterations} handle evaluation result.
6870      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
6871      * It will be initialized to 0 and incremented by 1 in each iteration.
6872      * <p>
6873      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
6874      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
6875      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
6876      * <p>
6877      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
6878      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
6879      * iteration variable.
6880      * The result of the loop handle execution will be the final {@code V} value of that variable
6881      * (or {@code void} if there is no {@code V} variable).
6882      * <p>
6883      * The following rules hold for the argument handles:<ul>
6884      * <li>The {@code iterations} handle must not be {@code null}, and must return
6885      * the type {@code int}, referred to here as {@code I} in parameter type lists.
6886      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6887      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
6888      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6889      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
6890      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
6891      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
6892      * of types called the <em>internal parameter list</em>.
6893      * It will constrain the parameter lists of the other loop parts.
6894      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
6895      * with no additional {@code A} types, then the internal parameter list is extended by
6896      * the argument types {@code A...} of the {@code iterations} handle.
6897      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
6898      * list {@code (A...)} is called the <em>external parameter list</em>.
6899      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6900      * additional state variable of the loop.
6901      * The body must both accept a leading parameter and return a value of this type {@code V}.
6902      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6903      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6904      * <a href="MethodHandles.html#effid">effectively identical</a>
6905      * to the external parameter list {@code (A...)}.
6906      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6907      * {@linkplain #empty default value}.
6908      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
6909      * effectively identical to the external parameter list {@code (A...)}.
6910      * </ul>
6911      * <p>
6912      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6913      * <li>The loop handle's result type is the result type {@code V} of the body.
6914      * <li>The loop handle's parameter types are the types {@code (A...)},
6915      * from the external parameter list.
6916      * </ul>
6917      * <p>
6918      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6919      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
6920      * arguments passed to the loop.
6921      * {@snippet lang="java" :
6922      * int iterations(A...);
6923      * V init(A...);
6924      * V body(V, int, A...);
6925      * V countedLoop(A... a...) {
6926      *   int end = iterations(a...);
6927      *   V v = init(a...);
6928      *   for (int i = 0; i < end; ++i) {
6929      *     v = body(v, i, a...);
6930      *   }
6931      *   return v;
6932      * }
6933      * }
6934      *
6935      * @apiNote Example with a fully conformant body method:
6936      * {@snippet lang="java" :
6937      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6938      * // => a variation on a well known theme
6939      * static String step(String v, int counter, String init) { return "na " + v; }
6940      * // assume MH_step is a handle to the method above
6941      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
6942      * MethodHandle start = MethodHandles.identity(String.class);
6943      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
6944      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
6945      * }
6946      *
6947      * @apiNote Example with the simplest possible body method type,
6948      * and passing the number of iterations to the loop invocation:
6949      * {@snippet lang="java" :
6950      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
6951      * // => a variation on a well known theme
6952      * static String step(String v, int counter ) { return "na " + v; }
6953      * // assume MH_step is a handle to the method above
6954      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
6955      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
6956      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
6957      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
6958      * }
6959      *
6960      * @apiNote Example that treats the number of iterations, string to append to, and string to append
6961      * as loop parameters:
6962      * {@snippet lang="java" :
6963      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6964      * // => a variation on a well known theme
6965      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
6966      * // assume MH_step is a handle to the method above
6967      * MethodHandle count = MethodHandles.identity(int.class);
6968      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
6969      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
6970      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
6971      * }
6972      *
6973      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
6974      * to enforce a loop type:
6975      * {@snippet lang="java" :
6976      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
6977      * // => a variation on a well known theme
6978      * static String step(String v, int counter, String pre) { return pre + " " + v; }
6979      * // assume MH_step is a handle to the method above
6980      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
6981      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
6982      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
6983      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
6984      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
6985      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
6986      * }
6987      *
6988      * @apiNote The implementation of this method can be expressed as follows:
6989      * {@snippet lang="java" :
6990      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
6991      *     return countedLoop(empty(iterations.type()), iterations, init, body);
6992      * }
6993      * }
6994      *
6995      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
6996      *                   result type must be {@code int}. See above for other constraints.
6997      * @param init optional initializer, providing the initial value of the loop variable.
6998      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6999      * @param body body of the loop, which may not be {@code null}.
7000      *             It controls the loop parameters and result type in the standard case (see above for details).
7001      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7002      *             and may accept any number of additional types.
7003      *             See above for other constraints.
7004      *
7005      * @return a method handle representing the loop.
7006      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7007      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7008      *
7009      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7010      * @since 9
7011      */
7012     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7013         return countedLoop(empty(iterations.type()), iterations, init, body);
7014     }
7015 
7016     /**
7017      * Constructs a loop that counts over a range of numbers.
7018      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7019      * <p>
7020      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7021      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7022      * values of the loop counter.
7023      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7024      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7025      * <p>
7026      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7027      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7028      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7029      * <p>
7030      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7031      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7032      * iteration variable.
7033      * The result of the loop handle execution will be the final {@code V} value of that variable
7034      * (or {@code void} if there is no {@code V} variable).
7035      * <p>
7036      * The following rules hold for the argument handles:<ul>
7037      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7038      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7039      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7040      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7041      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7042      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7043      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7044      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7045      * of types called the <em>internal parameter list</em>.
7046      * It will constrain the parameter lists of the other loop parts.
7047      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7048      * with no additional {@code A} types, then the internal parameter list is extended by
7049      * the argument types {@code A...} of the {@code end} handle.
7050      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7051      * list {@code (A...)} is called the <em>external parameter list</em>.
7052      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7053      * additional state variable of the loop.
7054      * The body must both accept a leading parameter and return a value of this type {@code V}.
7055      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7056      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7057      * <a href="MethodHandles.html#effid">effectively identical</a>
7058      * to the external parameter list {@code (A...)}.
7059      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7060      * {@linkplain #empty default value}.
7061      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7062      * effectively identical to the external parameter list {@code (A...)}.
7063      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7064      * to the external parameter list.
7065      * </ul>
7066      * <p>
7067      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7068      * <li>The loop handle's result type is the result type {@code V} of the body.
7069      * <li>The loop handle's parameter types are the types {@code (A...)},
7070      * from the external parameter list.
7071      * </ul>
7072      * <p>
7073      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7074      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7075      * arguments passed to the loop.
7076      * {@snippet lang="java" :
7077      * int start(A...);
7078      * int end(A...);
7079      * V init(A...);
7080      * V body(V, int, A...);
7081      * V countedLoop(A... a...) {
7082      *   int e = end(a...);
7083      *   int s = start(a...);
7084      *   V v = init(a...);
7085      *   for (int i = s; i < e; ++i) {
7086      *     v = body(v, i, a...);
7087      *   }
7088      *   return v;
7089      * }
7090      * }
7091      *
7092      * @apiNote The implementation of this method can be expressed as follows:
7093      * {@snippet lang="java" :
7094      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7095      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7096      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7097      *     // the following semantics:
7098      *     // MH_increment: (int limit, int counter) -> counter + 1
7099      *     // MH_predicate: (int limit, int counter) -> counter < limit
7100      *     Class<?> counterType = start.type().returnType();  // int
7101      *     Class<?> returnType = body.type().returnType();
7102      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7103      *     if (returnType != void.class) {  // ignore the V variable
7104      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7105      *         pred = dropArguments(pred, 1, returnType);  // ditto
7106      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7107      *     }
7108      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7109      *     MethodHandle[]
7110      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7111      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7112      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7113      *     return loop(loopLimit, bodyClause, indexVar);
7114      * }
7115      * }
7116      *
7117      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7118      *              See above for other constraints.
7119      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7120      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7121      * @param init optional initializer, providing the initial value of the loop variable.
7122      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7123      * @param body body of the loop, which may not be {@code null}.
7124      *             It controls the loop parameters and result type in the standard case (see above for details).
7125      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7126      *             and may accept any number of additional types.
7127      *             See above for other constraints.
7128      *
7129      * @return a method handle representing the loop.
7130      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7131      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7132      *
7133      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7134      * @since 9
7135      */
7136     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7137         countedLoopChecks(start, end, init, body);
7138         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7139         Class<?> limitType   = end.type().returnType();    // yes, int again
7140         Class<?> returnType  = body.type().returnType();
7141         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7142         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7143         MethodHandle retv = null;
7144         if (returnType != void.class) {
7145             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7146             pred = dropArguments(pred, 1, returnType);  // ditto
7147             retv = dropArguments(identity(returnType), 0, counterType);
7148         }
7149         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7150         MethodHandle[]
7151             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7152             bodyClause = { init, body },            // v = init(); v = body(v, i)
7153             indexVar   = { start, incr };           // i = start(); i = i + 1
7154         return loop(loopLimit, bodyClause, indexVar);
7155     }
7156 
7157     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7158         Objects.requireNonNull(start);
7159         Objects.requireNonNull(end);
7160         Objects.requireNonNull(body);
7161         Class<?> counterType = start.type().returnType();
7162         if (counterType != int.class) {
7163             MethodType expected = start.type().changeReturnType(int.class);
7164             throw misMatchedTypes("start function", start.type(), expected);
7165         } else if (end.type().returnType() != counterType) {
7166             MethodType expected = end.type().changeReturnType(counterType);
7167             throw misMatchedTypes("end function", end.type(), expected);
7168         }
7169         MethodType bodyType = body.type();
7170         Class<?> returnType = bodyType.returnType();
7171         List<Class<?>> innerList = bodyType.parameterList();
7172         // strip leading V value if present
7173         int vsize = (returnType == void.class ? 0 : 1);
7174         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7175             // argument list has no "V" => error
7176             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7177             throw misMatchedTypes("body function", bodyType, expected);
7178         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7179             // missing I type => error
7180             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7181             throw misMatchedTypes("body function", bodyType, expected);
7182         }
7183         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7184         if (outerList.isEmpty()) {
7185             // special case; take lists from end handle
7186             outerList = end.type().parameterList();
7187             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7188         }
7189         MethodType expected = methodType(counterType, outerList);
7190         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7191             throw misMatchedTypes("start parameter types", start.type(), expected);
7192         }
7193         if (end.type() != start.type() &&
7194             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7195             throw misMatchedTypes("end parameter types", end.type(), expected);
7196         }
7197         if (init != null) {
7198             MethodType initType = init.type();
7199             if (initType.returnType() != returnType ||
7200                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7201                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7202             }
7203         }
7204     }
7205 
7206     /**
7207      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7208      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7209      * <p>
7210      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7211      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7212      * <p>
7213      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7214      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7215      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7216      * <p>
7217      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7218      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7219      * iteration variable.
7220      * The result of the loop handle execution will be the final {@code V} value of that variable
7221      * (or {@code void} if there is no {@code V} variable).
7222      * <p>
7223      * The following rules hold for the argument handles:<ul>
7224      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7225      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7226      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7227      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7228      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7229      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7230      * of types called the <em>internal parameter list</em>.
7231      * It will constrain the parameter lists of the other loop parts.
7232      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7233      * with no additional {@code A} types, then the internal parameter list is extended by
7234      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7235      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7236      * <li>If the iteration variable types {@code (V T)} 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>If the {@code iterator} handle is non-{@code null}, it must have the return
7248      * type {@code java.util.Iterator} or a subtype thereof.
7249      * The iterator it produces when the loop is executed will be assumed
7250      * to yield values which can be converted to type {@code T}.
7251      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7252      * effectively identical to the external parameter list {@code (A...)}.
7253      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7254      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7255      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7256      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7257      * the {@link MethodHandle#asType asType} conversion method.
7258      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7259      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7260      * </ul>
7261      * <p>
7262      * The type {@code T} may be either a primitive or reference.
7263      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7264      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7265      * as if by the {@link MethodHandle#asType asType} conversion method.
7266      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7267      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7268      * <p>
7269      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7270      * <li>The loop handle's result type is the result type {@code V} of the body.
7271      * <li>The loop handle's parameter types are the types {@code (A...)},
7272      * from the external parameter list.
7273      * </ul>
7274      * <p>
7275      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7276      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7277      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7278      * {@snippet lang="java" :
7279      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7280      * V init(A...);
7281      * V body(V,T,A...);
7282      * V iteratedLoop(A... a...) {
7283      *   Iterator<T> it = iterator(a...);
7284      *   V v = init(a...);
7285      *   while (it.hasNext()) {
7286      *     T t = it.next();
7287      *     v = body(v, t, a...);
7288      *   }
7289      *   return v;
7290      * }
7291      * }
7292      *
7293      * @apiNote Example:
7294      * {@snippet lang="java" :
7295      * // get an iterator from a list
7296      * static List<String> reverseStep(List<String> r, String e) {
7297      *   r.add(0, e);
7298      *   return r;
7299      * }
7300      * static List<String> newArrayList() { return new ArrayList<>(); }
7301      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7302      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7303      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7304      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7305      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7306      * }
7307      *
7308      * @apiNote The implementation of this method can be expressed approximately as follows:
7309      * {@snippet lang="java" :
7310      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7311      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7312      *     Class<?> returnType = body.type().returnType();
7313      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7314      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7315      *     MethodHandle retv = null, step = body, startIter = iterator;
7316      *     if (returnType != void.class) {
7317      *         // the simple thing first:  in (I V A...), drop the I to get V
7318      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7319      *         // body type signature (V T A...), internal loop types (I V A...)
7320      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7321      *     }
7322      *     if (startIter == null)  startIter = MH_getIter;
7323      *     MethodHandle[]
7324      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7325      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7326      *     return loop(iterVar, bodyClause);
7327      * }
7328      * }
7329      *
7330      * @param iterator an optional handle to return the iterator to start the loop.
7331      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7332      *                 See above for other constraints.
7333      * @param init optional initializer, providing the initial value of the loop variable.
7334      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7335      * @param body body of the loop, which may not be {@code null}.
7336      *             It controls the loop parameters and result type in the standard case (see above for details).
7337      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7338      *             and may accept any number of additional types.
7339      *             See above for other constraints.
7340      *
7341      * @return a method handle embodying the iteration loop functionality.
7342      * @throws NullPointerException if the {@code body} handle is {@code null}.
7343      * @throws IllegalArgumentException if any argument violates the above requirements.
7344      *
7345      * @since 9
7346      */
7347     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7348         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7349         Class<?> returnType = body.type().returnType();
7350         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7351         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7352         MethodHandle startIter;
7353         MethodHandle nextVal;
7354         {
7355             MethodType iteratorType;
7356             if (iterator == null) {
7357                 // derive argument type from body, if available, else use Iterable
7358                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7359                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7360             } else {
7361                 // force return type to the internal iterator class
7362                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7363                 startIter = iterator;
7364             }
7365             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7366             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7367 
7368             // perform the asType transforms under an exception transformer, as per spec.:
7369             try {
7370                 startIter = startIter.asType(iteratorType);
7371                 nextVal = nextRaw.asType(nextValType);
7372             } catch (WrongMethodTypeException ex) {
7373                 throw new IllegalArgumentException(ex);
7374             }
7375         }
7376 
7377         MethodHandle retv = null, step = body;
7378         if (returnType != void.class) {
7379             // the simple thing first:  in (I V A...), drop the I to get V
7380             retv = dropArguments(identity(returnType), 0, Iterator.class);
7381             // body type signature (V T A...), internal loop types (I V A...)
7382             step = swapArguments(body, 0, 1);  // swap V <-> T
7383         }
7384 
7385         MethodHandle[]
7386             iterVar    = { startIter, null, hasNext, retv },
7387             bodyClause = { init, filterArgument(step, 0, nextVal) };
7388         return loop(iterVar, bodyClause);
7389     }
7390 
7391     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7392         Objects.requireNonNull(body);
7393         MethodType bodyType = body.type();
7394         Class<?> returnType = bodyType.returnType();
7395         List<Class<?>> internalParamList = bodyType.parameterList();
7396         // strip leading V value if present
7397         int vsize = (returnType == void.class ? 0 : 1);
7398         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7399             // argument list has no "V" => error
7400             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7401             throw misMatchedTypes("body function", bodyType, expected);
7402         } else if (internalParamList.size() <= vsize) {
7403             // missing T type => error
7404             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7405             throw misMatchedTypes("body function", bodyType, expected);
7406         }
7407         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7408         Class<?> iterableType = null;
7409         if (iterator != null) {
7410             // special case; if the body handle only declares V and T then
7411             // the external parameter list is obtained from iterator handle
7412             if (externalParamList.isEmpty()) {
7413                 externalParamList = iterator.type().parameterList();
7414             }
7415             MethodType itype = iterator.type();
7416             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7417                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7418             }
7419             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7420                 MethodType expected = methodType(itype.returnType(), externalParamList);
7421                 throw misMatchedTypes("iterator parameters", itype, expected);
7422             }
7423         } else {
7424             if (externalParamList.isEmpty()) {
7425                 // special case; if the iterator handle is null and the body handle
7426                 // only declares V and T then the external parameter list consists
7427                 // of Iterable
7428                 externalParamList = List.of(Iterable.class);
7429                 iterableType = Iterable.class;
7430             } else {
7431                 // special case; if the iterator handle is null and the external
7432                 // parameter list is not empty then the first parameter must be
7433                 // assignable to Iterable
7434                 iterableType = externalParamList.get(0);
7435                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7436                     throw newIllegalArgumentException(
7437                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7438                 }
7439             }
7440         }
7441         if (init != null) {
7442             MethodType initType = init.type();
7443             if (initType.returnType() != returnType ||
7444                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7445                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7446             }
7447         }
7448         return iterableType;  // help the caller a bit
7449     }
7450 
7451     /*non-public*/
7452     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7453         // there should be a better way to uncross my wires
7454         int arity = mh.type().parameterCount();
7455         int[] order = new int[arity];
7456         for (int k = 0; k < arity; k++)  order[k] = k;
7457         order[i] = j; order[j] = i;
7458         Class<?>[] types = mh.type().parameterArray();
7459         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7460         MethodType swapType = methodType(mh.type().returnType(), types);
7461         return permuteArguments(mh, swapType, order);
7462     }
7463 
7464     /**
7465      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7466      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7467      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7468      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7469      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7470      * {@code try-finally} handle.
7471      * <p>
7472      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7473      * The first is the exception thrown during the
7474      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7475      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7476      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7477      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7478      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7479      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7480      * <p>
7481      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7482      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7483      * two extra leading parameters:<ul>
7484      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7485      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7486      * the result from the execution of the {@code target} handle.
7487      * This parameter is not present if the {@code target} returns {@code void}.
7488      * </ul>
7489      * <p>
7490      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7491      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7492      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7493      * the cleanup.
7494      * {@snippet lang="java" :
7495      * V target(A..., B...);
7496      * V cleanup(Throwable, V, A...);
7497      * V adapter(A... a, B... b) {
7498      *   V result = (zero value for V);
7499      *   Throwable throwable = null;
7500      *   try {
7501      *     result = target(a..., b...);
7502      *   } catch (Throwable t) {
7503      *     throwable = t;
7504      *     throw t;
7505      *   } finally {
7506      *     result = cleanup(throwable, result, a...);
7507      *   }
7508      *   return result;
7509      * }
7510      * }
7511      * <p>
7512      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7513      * be modified by execution of the target, and so are passed unchanged
7514      * from the caller to the cleanup, if it is invoked.
7515      * <p>
7516      * The target and cleanup must return the same type, even if the cleanup
7517      * always throws.
7518      * To create such a throwing cleanup, compose the cleanup logic
7519      * with {@link #throwException throwException},
7520      * in order to create a method handle of the correct return type.
7521      * <p>
7522      * Note that {@code tryFinally} never converts exceptions into normal returns.
7523      * In rare cases where exceptions must be converted in that way, first wrap
7524      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7525      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7526      * <p>
7527      * It is recommended that the first parameter type of {@code cleanup} be
7528      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7529      * {@code cleanup} will always be invoked with whatever exception that
7530      * {@code target} throws.  Declaring a narrower type may result in a
7531      * {@code ClassCastException} being thrown by the {@code try-finally}
7532      * handle if the type of the exception thrown by {@code target} is not
7533      * assignable to the first parameter type of {@code cleanup}.  Note that
7534      * various exception types of {@code VirtualMachineError},
7535      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7536      * thrown by almost any kind of Java code, and a finally clause that
7537      * catches (say) only {@code IOException} would mask any of the others
7538      * behind a {@code ClassCastException}.
7539      *
7540      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7541      * @param cleanup the handle that is invoked in the finally block.
7542      *
7543      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7544      * @throws NullPointerException if any argument is null
7545      * @throws IllegalArgumentException if {@code cleanup} does not accept
7546      *          the required leading arguments, or if the method handle types do
7547      *          not match in their return types and their
7548      *          corresponding trailing parameters
7549      *
7550      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7551      * @since 9
7552      */
7553     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7554         Class<?>[] targetParamTypes = target.type().ptypes();
7555         Class<?> rtype = target.type().returnType();
7556 
7557         tryFinallyChecks(target, cleanup);
7558 
7559         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7560         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7561         // target parameter list.
7562         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0, false);
7563 
7564         // Ensure that the intrinsic type checks the instance thrown by the
7565         // target against the first parameter of cleanup
7566         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7567 
7568         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7569         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7570     }
7571 
7572     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7573         Class<?> rtype = target.type().returnType();
7574         if (rtype != cleanup.type().returnType()) {
7575             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7576         }
7577         MethodType cleanupType = cleanup.type();
7578         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7579             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7580         }
7581         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7582             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7583         }
7584         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7585         // target parameter list.
7586         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7587         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7588             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7589                     cleanup.type(), target.type());
7590         }
7591     }
7592 
7593     /**
7594      * Creates a table switch method handle, which can be used to switch over a set of target
7595      * method handles, based on a given target index, called selector.
7596      * <p>
7597      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7598      * and where {@code N} is the number of target method handles, the table switch method
7599      * handle will invoke the n-th target method handle from the list of target method handles.
7600      * <p>
7601      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7602      * method handle will invoke the given fallback method handle.
7603      * <p>
7604      * All method handles passed to this method must have the same type, with the additional
7605      * requirement that the leading parameter be of type {@code int}. The leading parameter
7606      * represents the selector.
7607      * <p>
7608      * Any trailing parameters present in the type will appear on the returned table switch
7609      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7610      * together with the selector value, to the selected method handle when invoking it.
7611      *
7612      * @apiNote Example:
7613      * The cases each drop the {@code selector} value they are given, and take an additional
7614      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7615      * to a specific constant label string for each case:
7616      * {@snippet lang="java" :
7617      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7618      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7619      *         MethodType.methodType(String.class, String.class));
7620      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7621      *
7622      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7623      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7624      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7625      *
7626      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7627      *     caseDefault,
7628      *     case0,
7629      *     case1
7630      * );
7631      *
7632      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7633      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7634      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7635      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7636      * }
7637      *
7638      * @param fallback the fallback method handle that is called when the selector is not
7639      *                 within the range {@code [0, N)}.
7640      * @param targets array of target method handles.
7641      * @return the table switch method handle.
7642      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7643      *                              any of the elements of the {@code targets} array are
7644      *                              {@code null}.
7645      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7646      *                                  parameter of the fallback handle or any of the target
7647      *                                  handles is not {@code int}, or if the types of
7648      *                                  the fallback handle and all of target handles are
7649      *                                  not the same.
7650      *
7651      * @since 17
7652      */
7653     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7654         Objects.requireNonNull(fallback);
7655         Objects.requireNonNull(targets);
7656         targets = targets.clone();
7657         MethodType type = tableSwitchChecks(fallback, targets);
7658         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7659     }
7660 
7661     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7662         if (caseActions.length == 0)
7663             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7664 
7665         MethodType expectedType = defaultCase.type();
7666 
7667         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7668             throw new IllegalArgumentException(
7669                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7670 
7671         for (MethodHandle mh : caseActions) {
7672             Objects.requireNonNull(mh);
7673             if (mh.type() != expectedType)
7674                 throw new IllegalArgumentException(
7675                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7676         }
7677 
7678         return expectedType;
7679     }
7680 
7681     /**
7682      * Adapts a target var handle by pre-processing incoming and outgoing values using a pair of filter functions.
7683      * <p>
7684      * When calling e.g. {@link VarHandle#set(Object...)} on the resulting var handle, the incoming value (of type {@code T}, where
7685      * {@code T} is the <em>last</em> parameter type of the first filter function) is processed using the first filter and then passed
7686      * to the target var handle.
7687      * Conversely, when calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the return value obtained from
7688      * the target var handle (of type {@code T}, where {@code T} is the <em>last</em> parameter type of the second filter function)
7689      * is processed using the second filter and returned to the caller. More advanced access mode types, such as
7690      * {@link VarHandle.AccessMode#COMPARE_AND_EXCHANGE} might apply both filters at the same time.
7691      * <p>
7692      * For the boxing and unboxing filters to be well-formed, their types must be of the form {@code (A... , S) -> T} and
7693      * {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle. If this is the case,
7694      * the resulting var handle will have type {@code S} and will feature the additional coordinates {@code A...} (which
7695      * will be appended to the coordinates of the target var handle).
7696      * <p>
7697      * If the boxing and unboxing filters throw any checked exceptions when invoked, the resulting var handle will
7698      * throw an {@link IllegalStateException}.
7699      * <p>
7700      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7701      * atomic access guarantees as those featured by the target var handle.
7702      *
7703      * @param target the target var handle
7704      * @param filterToTarget a filter to convert some type {@code S} into the type of {@code target}
7705      * @param filterFromTarget a filter to convert the type of {@code target} to some type {@code S}
7706      * @return an adapter var handle which accepts a new type, performing the provided boxing/unboxing conversions.
7707      * @throws IllegalArgumentException if {@code filterFromTarget} and {@code filterToTarget} are not well-formed, that is, they have types
7708      * other than {@code (A... , S) -> T} and {@code (A... , T) -> S}, respectively, where {@code T} is the type of the target var handle,
7709      * or if it's determined that either {@code filterFromTarget} or {@code filterToTarget} throws any checked exceptions.
7710      * @throws NullPointerException if any of the arguments is {@code null}.
7711      * @since 22
7712      */
7713     public static VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
7714         return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
7715     }
7716 
7717     /**
7718      * Adapts a target var handle by pre-processing incoming coordinate values using unary filter functions.
7719      * <p>
7720      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, the incoming coordinate values
7721      * starting at position {@code pos} (of type {@code C1, C2 ... Cn}, where {@code C1, C2 ... Cn} are the return types
7722      * of the unary filter functions) are transformed into new values (of type {@code S1, S2 ... Sn}, where {@code S1, S2 ... Sn} are the
7723      * parameter types of the unary filter functions), and then passed (along with any coordinate that was left unaltered
7724      * by the adaptation) to the target var handle.
7725      * <p>
7726      * For the coordinate filters to be well-formed, their types must be of the form {@code S1 -> T1, S2 -> T1 ... Sn -> Tn},
7727      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7728      * <p>
7729      * If any of the filters throws a checked exception when invoked, the resulting var handle will
7730      * throw an {@link IllegalStateException}.
7731      * <p>
7732      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7733      * atomic access guarantees as those featured by the target var handle.
7734      *
7735      * @param target the target var handle
7736      * @param pos the position of the first coordinate to be transformed
7737      * @param filters the unary functions which are used to transform coordinates starting at position {@code pos}
7738      * @return an adapter var handle which accepts new coordinate types, applying the provided transformation
7739      * to the new coordinate values.
7740      * @throws IllegalArgumentException if the handles in {@code filters} are not well-formed, that is, they have types
7741      * other than {@code S1 -> T1, S2 -> T2, ... Sn -> Tn} where {@code T1, T2 ... Tn} are the coordinate types starting
7742      * at position {@code pos} of the target var handle, if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7743      * or if more filters are provided than the actual number of coordinate types available starting at {@code pos},
7744      * or if it's determined that any of the filters throws any checked exceptions.
7745      * @throws NullPointerException if any of the arguments is {@code null} or {@code filters} contains {@code null}.
7746      * @since 22
7747      */
7748     public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
7749         return VarHandles.filterCoordinates(target, pos, filters);
7750     }
7751 
7752     /**
7753      * Provides a target var handle with one or more <em>bound coordinates</em>
7754      * in advance of the var handle's invocation. As a consequence, the resulting var handle will feature less
7755      * coordinate types than the target var handle.
7756      * <p>
7757      * When calling e.g. {@link VarHandle#get(Object...)} on the resulting var handle, incoming coordinate values
7758      * are joined with bound coordinate values, and then passed to the target var handle.
7759      * <p>
7760      * For the bound coordinates to be well-formed, their types must be {@code T1, T2 ... Tn },
7761      * where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos} of the target var handle.
7762      * <p>
7763      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7764      * atomic access guarantees as those featured by the target var handle.
7765      *
7766      * @param target the var handle to invoke after the bound coordinates are inserted
7767      * @param pos the position of the first coordinate to be inserted
7768      * @param values the series of bound coordinates to insert
7769      * @return an adapter var handle which inserts additional coordinates,
7770      *         before calling the target var handle
7771      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7772      * or if more values are provided than the actual number of coordinate types available starting at {@code pos}.
7773      * @throws ClassCastException if the bound coordinates in {@code values} are not well-formed, that is, they have types
7774      * other than {@code T1, T2 ... Tn }, where {@code T1, T2 ... Tn} are the coordinate types starting at position {@code pos}
7775      * of the target var handle.
7776      * @throws NullPointerException if any of the arguments is {@code null} or {@code values} contains {@code null}.
7777      * @since 22
7778      */
7779     public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
7780         return VarHandles.insertCoordinates(target, pos, values);
7781     }
7782 
7783     /**
7784      * Provides a var handle which adapts the coordinate values of the target var handle, by re-arranging them
7785      * so that the new coordinates match the provided ones.
7786      * <p>
7787      * The given array controls the reordering.
7788      * Call {@code #I} the number of incoming coordinates (the value
7789      * {@code newCoordinates.size()}), and call {@code #O} the number
7790      * of outgoing coordinates (the number of coordinates associated with the target var handle).
7791      * Then the length of the reordering array must be {@code #O},
7792      * and each element must be a non-negative number less than {@code #I}.
7793      * For every {@code N} less than {@code #O}, the {@code N}-th
7794      * outgoing coordinate will be taken from the {@code I}-th incoming
7795      * coordinate, where {@code I} is {@code reorder[N]}.
7796      * <p>
7797      * No coordinate value conversions are applied.
7798      * The type of each incoming coordinate, as determined by {@code newCoordinates},
7799      * must be identical to the type of the corresponding outgoing coordinate
7800      * in the target var handle.
7801      * <p>
7802      * The reordering array need not specify an actual permutation.
7803      * An incoming coordinate will be duplicated if its index appears
7804      * more than once in the array, and an incoming coordinate will be dropped
7805      * if its index does not appear in the array.
7806      * <p>
7807      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7808      * atomic access guarantees as those featured by the target var handle.
7809      * @param target the var handle to invoke after the coordinates have been reordered
7810      * @param newCoordinates the new coordinate types
7811      * @param reorder an index array which controls the reordering
7812      * @return an adapter var handle which re-arranges the incoming coordinate values,
7813      * before calling the target var handle
7814      * @throws IllegalArgumentException if the index array length is not equal to
7815      * the number of coordinates of the target var handle, or if any index array element is not a valid index for
7816      * a coordinate of {@code newCoordinates}, or if two corresponding coordinate types in
7817      * the target var handle and in {@code newCoordinates} are not identical.
7818      * @throws NullPointerException if any of the arguments is {@code null} or {@code newCoordinates} contains {@code null}.
7819      * @since 22
7820      */
7821     public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
7822         return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
7823     }
7824 
7825     /**
7826      * Adapts a target var handle by pre-processing
7827      * a sub-sequence of its coordinate values with a filter (a method handle).
7828      * The pre-processed coordinates are replaced by the result (if any) of the
7829      * filter function and the target var handle is then called on the modified (usually shortened)
7830      * coordinate list.
7831      * <p>
7832      * If {@code R} is the return type of the filter, then:
7833      * <ul>
7834      * <li>if {@code R} <em>is not</em> {@code void}, the target var handle must have a coordinate of type {@code R} in
7835      * position {@code pos}. The parameter types of the filter will replace the coordinate type at position {@code pos}
7836      * of the target var handle. When the returned var handle is invoked, it will be as if the filter is invoked first,
7837      * and its result is passed in place of the coordinate at position {@code pos} in a downstream invocation of the
7838      * target var handle.</li>
7839      * <li> if {@code R} <em>is</em> {@code void}, the parameter types (if any) of the filter will be inserted in the
7840      * coordinate type list of the target var handle at position {@code pos}. In this case, when the returned var handle
7841      * is invoked, the filter essentially acts as a side effect, consuming some of the coordinate values, before a
7842      * downstream invocation of the target var handle.</li>
7843      * </ul>
7844      * <p>
7845      * If any of the filters throws a checked exception when invoked, the resulting var handle will
7846      * throw an {@link IllegalStateException}.
7847      * <p>
7848      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7849      * atomic access guarantees as those featured by the target var handle.
7850      *
7851      * @param target the var handle to invoke after the coordinates have been filtered
7852      * @param pos the position in the coordinate list of the target var handle where the filter is to be inserted
7853      * @param filter the filter method handle
7854      * @return an adapter var handle which filters the incoming coordinate values,
7855      * before calling the target var handle
7856      * @throws IllegalArgumentException if the return type of {@code filter}
7857      * is not void, and it is not the same as the {@code pos} coordinate of the target var handle,
7858      * if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive,
7859      * if the resulting var handle's type would have <a href="MethodHandle.html#maxarity">too many coordinates</a>,
7860      * or if it's determined that {@code filter} throws any checked exceptions.
7861      * @throws NullPointerException if any of the arguments is {@code null}.
7862      * @since 22
7863      */
7864     public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
7865         return VarHandles.collectCoordinates(target, pos, filter);
7866     }
7867 
7868     /**
7869      * Returns a var handle which will discard some dummy coordinates before delegating to the
7870      * target var handle. As a consequence, the resulting var handle will feature more
7871      * coordinate types than the target var handle.
7872      * <p>
7873      * The {@code pos} argument may range between zero and <i>N</i>, where <i>N</i> is the arity of the
7874      * target var handle's coordinate types. If {@code pos} is zero, the dummy coordinates will precede
7875      * the target's real arguments; if {@code pos} is <i>N</i> they will come after.
7876      * <p>
7877      * The resulting var handle will feature the same access modes (see {@link VarHandle.AccessMode}) and
7878      * atomic access guarantees as those featured by the target var handle.
7879      *
7880      * @param target the var handle to invoke after the dummy coordinates are dropped
7881      * @param pos position of the first coordinate to drop (zero for the leftmost)
7882      * @param valueTypes the type(s) of the coordinate(s) to drop
7883      * @return an adapter var handle which drops some dummy coordinates,
7884      *         before calling the target var handle
7885      * @throws IllegalArgumentException if {@code pos} is not between 0 and the target var handle coordinate arity, inclusive.
7886      * @throws NullPointerException if any of the arguments is {@code null} or {@code valueTypes} contains {@code null}.
7887      * @since 22
7888      */
7889     public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
7890         return VarHandles.dropCoordinates(target, pos, valueTypes);
7891     }
7892 }