< prev index next >

src/java.base/share/classes/java/lang/invoke/MethodHandles.java

Print this page
rev 13059 : 8130227: Extend MethodHandle APIs


   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 java.lang.reflect.*;
  29 import java.util.BitSet;
  30 import java.util.List;
  31 import java.util.Arrays;
  32 import java.util.Objects;
  33 
  34 import sun.invoke.util.ValueConversions;
  35 import sun.invoke.util.VerifyAccess;
  36 import sun.invoke.util.Wrapper;
  37 import sun.reflect.CallerSensitive;
  38 import sun.reflect.Reflection;
  39 import sun.reflect.misc.ReflectUtil;
  40 import sun.security.util.SecurityConstants;
  41 import java.lang.invoke.LambdaForm.BasicType;
  42 import static java.lang.invoke.LambdaForm.BasicType.*;
  43 import static java.lang.invoke.MethodHandleStatics.*;
  44 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  45 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  46 import java.util.concurrent.ConcurrentHashMap;


  47 
  48 /**
  49  * This class consists exclusively of static methods that operate on or return
  50  * method handles. They fall into several categories:
  51  * <ul>
  52  * <li>Lookup methods which help create method handles for methods and fields.
  53  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  54  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  55  * </ul>
  56  *
  57  * @author John Rose, JSR 292 EG
  58  * @since 1.7
  59  */
  60 public class MethodHandles {
  61 
  62     private MethodHandles() { }  // do not instantiate
  63 
  64     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  65     static { MethodHandleImpl.initStatics(); }
  66     // See IMPL_LOOKUP below.


 159      * restrictions must be enforced when a method handle is created.
 160      * The caller class against which those restrictions are enforced
 161      * is known as the {@linkplain #lookupClass lookup class}.
 162      * <p>
 163      * A lookup class which needs to create method handles will call
 164      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 165      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 166      * determined, and securely stored in the {@code Lookup} object.
 167      * The lookup class (or its delegates) may then use factory methods
 168      * on the {@code Lookup} object to create method handles for access-checked members.
 169      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 170      * even private ones.
 171      *
 172      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 173      * The factory methods on a {@code Lookup} object correspond to all major
 174      * use cases for methods, constructors, and fields.
 175      * Each method handle created by a factory method is the functional
 176      * equivalent of a particular <em>bytecode behavior</em>.
 177      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 178      * Here is a summary of the correspondence between these factory methods and
 179      * the behavior the resulting method handles:
 180      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 181      * <tr>
 182      *     <th><a name="equiv"></a>lookup expression</th>
 183      *     <th>member</th>
 184      *     <th>bytecode behavior</th>
 185      * </tr>
 186      * <tr>
 187      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 188      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 189      * </tr>
 190      * <tr>
 191      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 192      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 193      * </tr>
 194      * <tr>
 195      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 196      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 197      * </tr>
 198      * <tr>
 199      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>


 218      * <tr>
 219      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 220      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 221      * </tr>
 222      * <tr>
 223      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 224      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 225      * </tr>
 226      * <tr>
 227      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 228      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 229      * </tr>
 230      * <tr>
 231      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 232      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 233      * </tr>
 234      * <tr>
 235      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 236      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 237      * </tr>




 238      * </table>
 239      *
 240      * Here, the type {@code C} is the class or interface being searched for a member,
 241      * documented as a parameter named {@code refc} in the lookup methods.
 242      * The method type {@code MT} is composed from the return type {@code T}
 243      * and the sequence of argument types {@code A*}.
 244      * The constructor also has a sequence of argument types {@code A*} and
 245      * is deemed to return the newly-created object of type {@code C}.
 246      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 247      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 248      * if it is present, it is always the leading argument to the method handle invocation.
 249      * (In the case of some {@code protected} members, {@code this} may be
 250      * restricted in type to the lookup class; see below.)
 251      * The name {@code arg} stands for all the other method handle arguments.
 252      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 253      * stands for a null reference if the accessed method or field is static,
 254      * and {@code this} otherwise.
 255      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 256      * for reflective objects corresponding to the given members.
 257      * <p>




 258      * In cases where the given member is of variable arity (i.e., a method or constructor)
 259      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 260      * In all other cases, the returned method handle will be of fixed arity.
 261      * <p style="font-size:smaller;">
 262      * <em>Discussion:</em>
 263      * The equivalence between looked-up method handles and underlying
 264      * class members and bytecode behaviors
 265      * can break down in a few ways:
 266      * <ul style="font-size:smaller;">
 267      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 268      * the lookup can still succeed, even when there is no equivalent
 269      * Java expression or bytecoded constant.
 270      * <li>Likewise, if {@code T} or {@code MT}
 271      * is not symbolically accessible from the lookup class's loader,
 272      * the lookup can still succeed.
 273      * For example, lookups for {@code MethodHandle.invokeExact} and
 274      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 275      * <li>If there is a security manager installed, it can forbid the lookup
 276      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 277      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}


 406      * </ul>
 407      * <p style="font-size:smaller;">
 408      * Each of these permissions is a consequence of the fact that a lookup object
 409      * with private access can be securely traced back to an originating class,
 410      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 411      * can be reliably determined and emulated by method handles.
 412      *
 413      * <h1><a name="secmgr"></a>Security manager interactions</h1>
 414      * Although bytecode instructions can only refer to classes in
 415      * a related class loader, this API can search for methods in any
 416      * class, as long as a reference to its {@code Class} object is
 417      * available.  Such cross-loader references are also possible with the
 418      * Core Reflection API, and are impossible to bytecode instructions
 419      * such as {@code invokestatic} or {@code getfield}.
 420      * There is a {@linkplain java.lang.SecurityManager security manager API}
 421      * to allow applications to check such cross-loader references.
 422      * These checks apply to both the {@code MethodHandles.Lookup} API
 423      * and the Core Reflection API
 424      * (as found on {@link java.lang.Class Class}).
 425      * <p>
 426      * If a security manager is present, member lookups are subject to
 427      * additional checks.
 428      * From one to three calls are made to the security manager.
 429      * Any of these calls can refuse access by throwing a
 430      * {@link java.lang.SecurityException SecurityException}.
 431      * Define {@code smgr} as the security manager,
 432      * {@code lookc} as the lookup class of the current lookup object,
 433      * {@code refc} as the containing class in which the member
 434      * is being sought, and {@code defc} as the class in which the
 435      * member is actually defined.


 436      * The value {@code lookc} is defined as <em>not present</em>
 437      * if the current lookup object does not have
 438      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 439      * The calls are made according to the following rules:
 440      * <ul>
 441      * <li><b>Step 1:</b>
 442      *     If {@code lookc} is not present, or if its class loader is not
 443      *     the same as or an ancestor of the class loader of {@code refc},
 444      *     then {@link SecurityManager#checkPackageAccess
 445      *     smgr.checkPackageAccess(refcPkg)} is called,
 446      *     where {@code refcPkg} is the package of {@code refc}.
 447      * <li><b>Step 2:</b>
 448      *     If the retrieved member is not public and
 449      *     {@code lookc} is not present, then
 450      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 451      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.





 452      * <li><b>Step 3:</b>
 453      *     If the retrieved member is not public,
 454      *     and if {@code lookc} is not present,
 455      *     and if {@code defc} and {@code refc} are different,
 456      *     then {@link SecurityManager#checkPackageAccess
 457      *     smgr.checkPackageAccess(defcPkg)} is called,
 458      *     where {@code defcPkg} is the package of {@code defc}.
 459      * </ul>
 460      * Security checks are performed after other access checks have passed.
 461      * Therefore, the above rules presuppose a member that is public,
 462      * or else that is being accessed from a lookup class that has
 463      * rights to access the member.
 464      *
 465      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
 466      * A small number of Java methods have a special property called caller sensitivity.
 467      * A <em>caller-sensitive</em> method can behave differently depending on the
 468      * identity of its immediate caller.
 469      * <p>
 470      * If a method handle for a caller-sensitive method is requested,
 471      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 472      * but they take account of the lookup class in a special way.
 473      * The resulting method handle behaves as if it were called
 474      * from an instruction contained in the lookup class,
 475      * so that the caller-sensitive method detects the lookup class.
 476      * (By contrast, the invoker of the method handle is disregarded.)
 477      * Thus, in the case of caller-sensitive methods,
 478      * different lookup classes may give rise to
 479      * differently behaving method handles.
 480      * <p>
 481      * In cases where the lookup object is
 482      * {@link MethodHandles#publicLookup() publicLookup()},
 483      * or some other lookup object without


 905 assertEquals("[x, y, z]", pb.command().toString());
 906          * }</pre></blockquote>
 907          * @param refc the class or interface from which the method is accessed
 908          * @param type the type of the method, with the receiver argument omitted, and a void return type
 909          * @return the desired method handle
 910          * @throws NoSuchMethodException if the constructor does not exist
 911          * @throws IllegalAccessException if access checking fails
 912          *                                or if the method's variable arity modifier bit
 913          *                                is set and {@code asVarargsCollector} fails
 914          * @exception SecurityException if a security manager is present and it
 915          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 916          * @throws NullPointerException if any argument is null
 917          */
 918         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 919             String name = "<init>";
 920             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
 921             return getDirectConstructor(refc, ctor);
 922         }
 923 
 924         /**









































 925          * Produces an early-bound method handle for a virtual method.
 926          * It will bypass checks for overriding methods on the receiver,
 927          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
 928          * instruction from within the explicitly specified {@code specialCaller}.
 929          * The type of the method handle will be that of the method,
 930          * with a suitably restricted receiver type prepended.
 931          * (The receiver type will be {@code specialCaller} or a subtype.)
 932          * The method and all its argument types must be accessible
 933          * to the lookup object.
 934          * <p>
 935          * Before method resolution,
 936          * if the explicitly specified caller class is not identical with the
 937          * lookup class, or if this lookup object does not have
 938          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
 939          * privileges, the access fails.
 940          * <p>
 941          * The returned method handle will have
 942          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 943          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 944          * <p style="font-size:smaller;">


 978  } catch (IllegalAccessException ex) { } // OK
 979 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
 980 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
 981          * }</pre></blockquote>
 982          *
 983          * @param refc the class or interface from which the method is accessed
 984          * @param name the name of the method (which must not be "&lt;init&gt;")
 985          * @param type the type of the method, with the receiver argument omitted
 986          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
 987          * @return the desired method handle
 988          * @throws NoSuchMethodException if the method does not exist
 989          * @throws IllegalAccessException if access checking fails
 990          *                                or if the method's variable arity modifier bit
 991          *                                is set and {@code asVarargsCollector} fails
 992          * @exception SecurityException if a security manager is present and it
 993          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 994          * @throws NullPointerException if any argument is null
 995          */
 996         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
 997                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
 998             checkSpecialCaller(specialCaller);
 999             Lookup specialLookup = this.in(specialCaller);
1000             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1001             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1002         }
1003 
1004         /**
1005          * Produces a method handle giving read access to a non-static field.
1006          * The type of the method handle will have a return type of the field's
1007          * value type.
1008          * The method handle's single argument will be the instance containing
1009          * the field.
1010          * Access checking is performed immediately on behalf of the lookup class.
1011          * @param refc the class or interface from which the method is accessed
1012          * @param name the field's name
1013          * @param type the field's type
1014          * @return a method handle which can load values from the field
1015          * @throws NoSuchFieldException if the field does not exist
1016          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1017          * @exception SecurityException if a security manager is present and it
1018          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>


1207          * as if {@code invokespecial} instruction were being linked.
1208          * <p>
1209          * Before method resolution,
1210          * if the explicitly specified caller class is not identical with the
1211          * lookup class, or if this lookup object does not have
1212          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1213          * privileges, the access fails.
1214          * <p>
1215          * The returned method handle will have
1216          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1217          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1218          * @param m the reflected method
1219          * @param specialCaller the class nominally calling the method
1220          * @return a method handle which can invoke the reflected method
1221          * @throws IllegalAccessException if access checking fails
1222          *                                or if the method's variable arity modifier bit
1223          *                                is set and {@code asVarargsCollector} fails
1224          * @throws NullPointerException if any argument is null
1225          */
1226         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1227             checkSpecialCaller(specialCaller);
1228             Lookup specialLookup = this.in(specialCaller);
1229             MemberName method = new MemberName(m, true);
1230             assert(method.isMethod());
1231             // ignore m.isAccessible:  this is a new kind of access
1232             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1233         }
1234 
1235         /**
1236          * Produces a method handle for a reflected constructor.
1237          * The type of the method handle will be that of the constructor,
1238          * with the return type changed to the declaring class.
1239          * The method handle will perform a {@code newInstance} operation,
1240          * creating a new instance of the constructor's class on the
1241          * arguments passed to the method handle.
1242          * <p>
1243          * If the constructor's {@code accessible} flag is not set,
1244          * access checking is performed immediately on behalf of the lookup class.
1245          * <p>
1246          * The returned method handle will have
1247          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if


1427             return (allowedModes & PRIVATE) != 0;
1428         }
1429 
1430         /**
1431          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1432          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1433          * If this lookup object has private access, then the caller class is the lookupClass.
1434          */
1435         void checkSecurityManager(Class<?> refc, MemberName m) {
1436             SecurityManager smgr = System.getSecurityManager();
1437             if (smgr == null)  return;
1438             if (allowedModes == TRUSTED)  return;
1439 
1440             // Step 1:
1441             boolean fullPowerLookup = hasPrivateAccess();
1442             if (!fullPowerLookup ||
1443                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1444                 ReflectUtil.checkPackageAccess(refc);
1445             }
1446 
1447             // Step 2:








1448             if (m.isPublic()) return;
1449             if (!fullPowerLookup) {
1450                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1451             }
1452 
1453             // Step 3:
1454             Class<?> defc = m.getDeclaringClass();
1455             if (!fullPowerLookup && defc != refc) {
1456                 ReflectUtil.checkPackageAccess(defc);
1457             }
1458         }
1459 
1460         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1461             boolean wantStatic = (refKind == REF_invokeStatic);
1462             String message;
1463             if (m.isConstructor())
1464                 message = "expected a method, not a constructor";
1465             else if (!m.isMethod())
1466                 message = "expected a method";
1467             else if (wantStatic != m.isStatic())


1540                                (defc == refc ||
1541                                 Modifier.isPublic(refc.getModifiers())));
1542             if (!classOK && (allowedModes & PACKAGE) != 0) {
1543                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1544                            (defc == refc ||
1545                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1546             }
1547             if (!classOK)
1548                 return "class is not public";
1549             if (Modifier.isPublic(mods))
1550                 return "access to public member failed";  // (how?)
1551             if (Modifier.isPrivate(mods))
1552                 return "member is private";
1553             if (Modifier.isProtected(mods))
1554                 return "member is protected";
1555             return "member is private to package";
1556         }
1557 
1558         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1559 
1560         private void checkSpecialCaller(Class<?> specialCaller) throws IllegalAccessException {
1561             int allowedModes = this.allowedModes;
1562             if (allowedModes == TRUSTED)  return;
1563             if (!hasPrivateAccess()
1564                 || (specialCaller != lookupClass()


1565                     && !(ALLOW_NESTMATE_ACCESS &&
1566                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1567                 throw new MemberName(specialCaller).
1568                     makeAccessException("no private access for invokespecial", this);
1569         }
1570 
1571         private boolean restrictProtectedReceiver(MemberName method) {
1572             // The accessing class only has the right to use a protected member
1573             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1574             if (!method.isProtected() || method.isStatic()
1575                 || allowedModes == TRUSTED
1576                 || method.getDeclaringClass() == lookupClass()
1577                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1578                 || (ALLOW_NESTMATE_ACCESS &&
1579                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1580                 return false;
1581             return true;
1582         }
1583         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
1584             assert(!method.isStatic());


1871      * <blockquote><pre>{@code
1872 MethodHandle invoker = MethodHandles.invoker(type);
1873 int spreadArgCount = type.parameterCount() - leadingArgCount;
1874 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1875 return invoker;
1876      * }</pre></blockquote>
1877      * This method throws no reflective or security exceptions.
1878      * @param type the desired target type
1879      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1880      * @return a method handle suitable for invoking any method handle of the given type
1881      * @throws NullPointerException if {@code type} is null
1882      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1883      *                  the range from 0 to {@code type.parameterCount()} inclusive,
1884      *                  or if the resulting method handle's type would have
1885      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1886      */
1887     public static
1888     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1889         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1890             throw newIllegalArgumentException("bad argument count", leadingArgCount);
1891         type = type.asSpreaderType(Object[].class, type.parameterCount() - leadingArgCount);
1892         return type.invokers().spreadInvoker(leadingArgCount);
1893     }
1894 
1895     /**
1896      * Produces a special <em>invoker method handle</em> which can be used to
1897      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1898      * The resulting invoker will have a type which is
1899      * exactly equal to the desired type, except that it will accept
1900      * an additional leading argument of type {@code MethodHandle}.
1901      * <p>
1902      * This method is equivalent to the following code (though it may be more efficient):
1903      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
1904      *
1905      * <p style="font-size:smaller;">
1906      * <em>Discussion:</em>
1907      * Invoker method handles can be useful when working with variable method handles
1908      * of unknown types.
1909      * For example, to emulate an {@code invokeExact} call to a variable method
1910      * handle {@code M}, extract its type {@code T},
1911      * look up the invoker method {@code X} for {@code T},


2907      * T target2(A[N]..., B...);
2908      * void combiner2(A...);
2909      * T adapter2(A... a, B... b) {
2910      *   combiner2(a...);
2911      *   return target2(a..., b...);
2912      * }
2913      * }</pre></blockquote>
2914      * @param target the method handle to invoke after arguments are combined
2915      * @param combiner method handle to call initially on the incoming arguments
2916      * @return method handle which incorporates the specified argument folding logic
2917      * @throws NullPointerException if either argument is null
2918      * @throws IllegalArgumentException if {@code combiner}'s return type
2919      *          is non-void and not the same as the first argument type of
2920      *          the target, or if the initial {@code N} argument types
2921      *          of the target
2922      *          (skipping one matching the {@code combiner}'s return type)
2923      *          are not identical with the argument types of {@code combiner}
2924      */
2925     public static
2926     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
2927         int foldPos = 0;
2928         MethodType targetType = target.type();
2929         MethodType combinerType = combiner.type();
2930         Class<?> rtype = foldArgumentChecks(foldPos, targetType, combinerType);
2931         BoundMethodHandle result = target.rebind();
2932         boolean dropResult = (rtype == void.class);
2933         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
2934         LambdaForm lform = result.editor().foldArgumentsForm(1 + foldPos, dropResult, combinerType.basicType());
2935         MethodType newType = targetType;
2936         if (!dropResult)
2937             newType = newType.dropParameterTypes(foldPos, foldPos + 1);
2938         result = result.copyWithExtendL(newType, lform, combiner);
2939         return result;
2940     }
2941 
2942     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
2943         int foldArgs   = combinerType.parameterCount();
2944         Class<?> rtype = combinerType.returnType();
2945         int foldVals = rtype == void.class ? 0 : 1;
2946         int afterInsertPos = foldPos + foldVals;
2947         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
2948         if (ok && !(combinerType.parameterList()
2949                     .equals(targetType.parameterList().subList(afterInsertPos,
2950                                                                afterInsertPos + foldArgs))))
2951             ok = false;
2952         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(0))
2953             ok = false;
2954         if (!ok)
2955             throw misMatchedTypes("target and combiner types", targetType, combinerType);
2956         return rtype;
2957     }
2958 
2959     /**
2960      * Makes a method handle which adapts a target method handle,
2961      * by guarding it with a test, a boolean-valued method handle.
2962      * If the guard fails, a fallback handle is called instead.
2963      * All three method handles must have the same corresponding
2964      * argument and return types, except that the return type
2965      * of the test must be boolean, and the test is allowed
2966      * to have fewer arguments than the other two method handles.
2967      * <p> Here is pseudocode for the resulting adapter:
2968      * <blockquote><pre>{@code
2969      * boolean test(A...);
2970      * T target(A...,B...);
2971      * T fallback(A...,B...);
2972      * T adapter(A... a,B... b) {


3040      * }</pre></blockquote>
3041      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3042      * be modified by execution of the target, and so are passed unchanged
3043      * from the caller to the handler, if the handler is invoked.
3044      * <p>
3045      * The target and handler must return the same type, even if the handler
3046      * always throws.  (This might happen, for instance, because the handler
3047      * is simulating a {@code finally} clause).
3048      * To create such a throwing handler, compose the handler creation logic
3049      * with {@link #throwException throwException},
3050      * in order to create a method handle of the correct return type.
3051      * @param target method handle to call
3052      * @param exType the type of exception which the handler will catch
3053      * @param handler method handle to call if a matching exception is thrown
3054      * @return method handle which incorporates the specified try/catch logic
3055      * @throws NullPointerException if any argument is null
3056      * @throws IllegalArgumentException if {@code handler} does not accept
3057      *          the given exception type, or if the method handle types do
3058      *          not match in their return types and their
3059      *          corresponding parameters

3060      */
3061     public static
3062     MethodHandle catchException(MethodHandle target,
3063                                 Class<? extends Throwable> exType,
3064                                 MethodHandle handler) {
3065         MethodType ttype = target.type();
3066         MethodType htype = handler.type();
3067         if (htype.parameterCount() < 1 ||
3068             !htype.parameterType(0).isAssignableFrom(exType))
3069             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3070         if (htype.returnType() != ttype.returnType())
3071             throw misMatchedTypes("target and handler return types", ttype, htype);
3072         List<Class<?>> targs = ttype.parameterList();
3073         List<Class<?>> hargs = htype.parameterList();
3074         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
3075         if (!targs.equals(hargs)) {
3076             int hpc = hargs.size(), tpc = targs.size();
3077             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
3078                 throw misMatchedTypes("target and handler types", ttype, htype);
3079             handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));


3083     }
3084 
3085     /**
3086      * Produces a method handle which will throw exceptions of the given {@code exType}.
3087      * The method handle will accept a single argument of {@code exType},
3088      * and immediately throw it as an exception.
3089      * The method type will nominally specify a return of {@code returnType}.
3090      * The return type may be anything convenient:  It doesn't matter to the
3091      * method handle's behavior, since it will never return normally.
3092      * @param returnType the return type of the desired method handle
3093      * @param exType the parameter type of the desired method handle
3094      * @return method handle which can throw the given exceptions
3095      * @throws NullPointerException if either argument is null
3096      */
3097     public static
3098     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3099         if (!Throwable.class.isAssignableFrom(exType))
3100             throw new ClassCastException(exType.getName());
3101         return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
3102     }



























































































































































































































































































































































































































































































































































































































































































































































































































































































3103 }


   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 java.lang.reflect.*;
  29 import java.util.*;



  30 
  31 import sun.invoke.util.ValueConversions;
  32 import sun.invoke.util.VerifyAccess;
  33 import sun.invoke.util.Wrapper;
  34 import sun.reflect.CallerSensitive;
  35 import sun.reflect.Reflection;
  36 import sun.reflect.misc.ReflectUtil;
  37 import sun.security.util.SecurityConstants;
  38 import java.lang.invoke.LambdaForm.BasicType;
  39 
  40 import static java.lang.invoke.MethodHandleStatics.*;
  41 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  42 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  43 import java.util.concurrent.ConcurrentHashMap;
  44 import java.util.stream.Collectors;
  45 import java.util.stream.Stream;
  46 
  47 /**
  48  * This class consists exclusively of static methods that operate on or return
  49  * method handles. They fall into several categories:
  50  * <ul>
  51  * <li>Lookup methods which help create method handles for methods and fields.
  52  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  53  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  54  * </ul>
  55  *
  56  * @author John Rose, JSR 292 EG
  57  * @since 1.7
  58  */
  59 public class MethodHandles {
  60 
  61     private MethodHandles() { }  // do not instantiate
  62 
  63     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  64     static { MethodHandleImpl.initStatics(); }
  65     // See IMPL_LOOKUP below.


 158      * restrictions must be enforced when a method handle is created.
 159      * The caller class against which those restrictions are enforced
 160      * is known as the {@linkplain #lookupClass lookup class}.
 161      * <p>
 162      * A lookup class which needs to create method handles will call
 163      * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
 164      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 165      * determined, and securely stored in the {@code Lookup} object.
 166      * The lookup class (or its delegates) may then use factory methods
 167      * on the {@code Lookup} object to create method handles for access-checked members.
 168      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 169      * even private ones.
 170      *
 171      * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
 172      * The factory methods on a {@code Lookup} object correspond to all major
 173      * use cases for methods, constructors, and fields.
 174      * Each method handle created by a factory method is the functional
 175      * equivalent of a particular <em>bytecode behavior</em>.
 176      * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
 177      * Here is a summary of the correspondence between these factory methods and
 178      * the behavior of the resulting method handles:
 179      * <table border=1 cellpadding=5 summary="lookup method behaviors">
 180      * <tr>
 181      *     <th><a name="equiv"></a>lookup expression</th>
 182      *     <th>member</th>
 183      *     <th>bytecode behavior</th>
 184      * </tr>
 185      * <tr>
 186      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
 187      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 188      * </tr>
 189      * <tr>
 190      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
 191      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 192      * </tr>
 193      * <tr>
 194      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
 195      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 196      * </tr>
 197      * <tr>
 198      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>


 217      * <tr>
 218      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
 219      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 220      * </tr>
 221      * <tr>
 222      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
 223      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 224      * </tr>
 225      * <tr>
 226      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 227      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 228      * </tr>
 229      * <tr>
 230      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
 231      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 232      * </tr>
 233      * <tr>
 234      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
 235      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 236      * </tr>
 237      * <tr>
 238      *     <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
 239      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 240      * </tr>
 241      * </table>
 242      *
 243      * Here, the type {@code C} is the class or interface being searched for a member,
 244      * documented as a parameter named {@code refc} in the lookup methods.
 245      * The method type {@code MT} is composed from the return type {@code T}
 246      * and the sequence of argument types {@code A*}.
 247      * The constructor also has a sequence of argument types {@code A*} and
 248      * is deemed to return the newly-created object of type {@code C}.
 249      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 250      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 251      * if it is present, it is always the leading argument to the method handle invocation.
 252      * (In the case of some {@code protected} members, {@code this} may be
 253      * restricted in type to the lookup class; see below.)
 254      * The name {@code arg} stands for all the other method handle arguments.
 255      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 256      * stands for a null reference if the accessed method or field is static,
 257      * and {@code this} otherwise.
 258      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 259      * for reflective objects corresponding to the given members.
 260      * <p>
 261      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 262      * as if by {@code ldc CONSTANT_Class}.
 263      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 264      * <p>
 265      * In cases where the given member is of variable arity (i.e., a method or constructor)
 266      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 267      * In all other cases, the returned method handle will be of fixed arity.
 268      * <p style="font-size:smaller;">
 269      * <em>Discussion:</em>
 270      * The equivalence between looked-up method handles and underlying
 271      * class members and bytecode behaviors
 272      * can break down in a few ways:
 273      * <ul style="font-size:smaller;">
 274      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 275      * the lookup can still succeed, even when there is no equivalent
 276      * Java expression or bytecoded constant.
 277      * <li>Likewise, if {@code T} or {@code MT}
 278      * is not symbolically accessible from the lookup class's loader,
 279      * the lookup can still succeed.
 280      * For example, lookups for {@code MethodHandle.invokeExact} and
 281      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 282      * <li>If there is a security manager installed, it can forbid the lookup
 283      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 284      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}


 413      * </ul>
 414      * <p style="font-size:smaller;">
 415      * Each of these permissions is a consequence of the fact that a lookup object
 416      * with private access can be securely traced back to an originating class,
 417      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 418      * can be reliably determined and emulated by method handles.
 419      *
 420      * <h1><a name="secmgr"></a>Security manager interactions</h1>
 421      * Although bytecode instructions can only refer to classes in
 422      * a related class loader, this API can search for methods in any
 423      * class, as long as a reference to its {@code Class} object is
 424      * available.  Such cross-loader references are also possible with the
 425      * Core Reflection API, and are impossible to bytecode instructions
 426      * such as {@code invokestatic} or {@code getfield}.
 427      * There is a {@linkplain java.lang.SecurityManager security manager API}
 428      * to allow applications to check such cross-loader references.
 429      * These checks apply to both the {@code MethodHandles.Lookup} API
 430      * and the Core Reflection API
 431      * (as found on {@link java.lang.Class Class}).
 432      * <p>
 433      * If a security manager is present, member and class lookups are subject to
 434      * additional checks.
 435      * From one to three calls are made to the security manager.
 436      * Any of these calls can refuse access by throwing a
 437      * {@link java.lang.SecurityException SecurityException}.
 438      * Define {@code smgr} as the security manager,
 439      * {@code lookc} as the lookup class of the current lookup object,
 440      * {@code refc} as the containing class in which the member
 441      * is being sought, and {@code defc} as the class in which the
 442      * member is actually defined.
 443      * (If a class or other type is being accessed,
 444      * the {@code refc} and {@code defc} values are the class itself.)
 445      * The value {@code lookc} is defined as <em>not present</em>
 446      * if the current lookup object does not have
 447      * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 448      * The calls are made according to the following rules:
 449      * <ul>
 450      * <li><b>Step 1:</b>
 451      *     If {@code lookc} is not present, or if its class loader is not
 452      *     the same as or an ancestor of the class loader of {@code refc},
 453      *     then {@link SecurityManager#checkPackageAccess
 454      *     smgr.checkPackageAccess(refcPkg)} is called,
 455      *     where {@code refcPkg} is the package of {@code refc}.
 456      * <li><b>Step 2a:</b>
 457      *     If the retrieved member is not public and
 458      *     {@code lookc} is not present, then
 459      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 460      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
 461      * <li><b>Step 2b:</b>
 462      *     If the retrieved class has a {@code null} class loader,
 463      *     and {@code lookc} is not present, then
 464      *     {@link SecurityManager#checkPermission smgr.checkPermission}
 465      *     with {@code RuntimePermission("getClassLoader")} is called.
 466      * <li><b>Step 3:</b>
 467      *     If the retrieved member is not public,
 468      *     and if {@code lookc} is not present,
 469      *     and if {@code defc} and {@code refc} are different,
 470      *     then {@link SecurityManager#checkPackageAccess
 471      *     smgr.checkPackageAccess(defcPkg)} is called,
 472      *     where {@code defcPkg} is the package of {@code defc}.
 473      * </ul>
 474      * Security checks are performed after other access checks have passed.
 475      * Therefore, the above rules presuppose a member or class that is public,
 476      * or else that is being accessed from a lookup class that has
 477      * rights to access the member or class.
 478      *
 479      * <h1><a name="callsens"></a>Caller sensitive methods</h1>
 480      * A small number of Java methods have a special property called caller sensitivity.
 481      * A <em>caller-sensitive</em> method can behave differently depending on the
 482      * identity of its immediate caller.
 483      * <p>
 484      * If a method handle for a caller-sensitive method is requested,
 485      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
 486      * but they take account of the lookup class in a special way.
 487      * The resulting method handle behaves as if it were called
 488      * from an instruction contained in the lookup class,
 489      * so that the caller-sensitive method detects the lookup class.
 490      * (By contrast, the invoker of the method handle is disregarded.)
 491      * Thus, in the case of caller-sensitive methods,
 492      * different lookup classes may give rise to
 493      * differently behaving method handles.
 494      * <p>
 495      * In cases where the lookup object is
 496      * {@link MethodHandles#publicLookup() publicLookup()},
 497      * or some other lookup object without


 919 assertEquals("[x, y, z]", pb.command().toString());
 920          * }</pre></blockquote>
 921          * @param refc the class or interface from which the method is accessed
 922          * @param type the type of the method, with the receiver argument omitted, and a void return type
 923          * @return the desired method handle
 924          * @throws NoSuchMethodException if the constructor does not exist
 925          * @throws IllegalAccessException if access checking fails
 926          *                                or if the method's variable arity modifier bit
 927          *                                is set and {@code asVarargsCollector} fails
 928          * @exception SecurityException if a security manager is present and it
 929          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 930          * @throws NullPointerException if any argument is null
 931          */
 932         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
 933             String name = "<init>";
 934             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
 935             return getDirectConstructor(refc, ctor);
 936         }
 937 
 938         /**
 939          * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
 940          * initializer of the class is not run.
 941          *
 942          * @param targetName the fully qualified name of the class to be looked up.
 943          * @return the requested class.
 944          * @exception SecurityException if a security manager is present and it
 945          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 946          * @throws LinkageError if the linkage fails
 947          * @throws ClassNotFoundException if the class does not exist.
 948          * @throws IllegalAccessException if the class is not accessible, using the allowed access
 949          * modes.
 950          * @exception SecurityException if a security manager is present and it
 951          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 952          */
 953         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
 954             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
 955             return accessClass(targetClass);
 956         }
 957 
 958         /**
 959          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
 960          * static initializer of the class is not run.
 961          *
 962          * @param targetClass the class to be accessed
 963          *
 964          * @return the class that has been accessed
 965          *
 966          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
 967          * modes.
 968          * @exception SecurityException if a security manager is present and it
 969          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
 970          */
 971         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
 972             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
 973                 throw new MemberName(targetClass).makeAccessException("access violation", this);
 974             }
 975             checkSecurityManager(targetClass, null);
 976             return targetClass;
 977         }
 978 
 979         /**
 980          * Produces an early-bound method handle for a virtual method.
 981          * It will bypass checks for overriding methods on the receiver,
 982          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
 983          * instruction from within the explicitly specified {@code specialCaller}.
 984          * The type of the method handle will be that of the method,
 985          * with a suitably restricted receiver type prepended.
 986          * (The receiver type will be {@code specialCaller} or a subtype.)
 987          * The method and all its argument types must be accessible
 988          * to the lookup object.
 989          * <p>
 990          * Before method resolution,
 991          * if the explicitly specified caller class is not identical with the
 992          * lookup class, or if this lookup object does not have
 993          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
 994          * privileges, the access fails.
 995          * <p>
 996          * The returned method handle will have
 997          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
 998          * the method's variable arity modifier bit ({@code 0x0080}) is set.
 999          * <p style="font-size:smaller;">


1033  } catch (IllegalAccessException ex) { } // OK
1034 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1035 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1036          * }</pre></blockquote>
1037          *
1038          * @param refc the class or interface from which the method is accessed
1039          * @param name the name of the method (which must not be "&lt;init&gt;")
1040          * @param type the type of the method, with the receiver argument omitted
1041          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1042          * @return the desired method handle
1043          * @throws NoSuchMethodException if the method does not exist
1044          * @throws IllegalAccessException if access checking fails
1045          *                                or if the method's variable arity modifier bit
1046          *                                is set and {@code asVarargsCollector} fails
1047          * @exception SecurityException if a security manager is present and it
1048          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1049          * @throws NullPointerException if any argument is null
1050          */
1051         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1052                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1053             checkSpecialCaller(specialCaller, refc);
1054             Lookup specialLookup = this.in(specialCaller);
1055             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
1056             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
1057         }
1058 
1059         /**
1060          * Produces a method handle giving read access to a non-static field.
1061          * The type of the method handle will have a return type of the field's
1062          * value type.
1063          * The method handle's single argument will be the instance containing
1064          * the field.
1065          * Access checking is performed immediately on behalf of the lookup class.
1066          * @param refc the class or interface from which the method is accessed
1067          * @param name the field's name
1068          * @param type the field's type
1069          * @return a method handle which can load values from the field
1070          * @throws NoSuchFieldException if the field does not exist
1071          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1072          * @exception SecurityException if a security manager is present and it
1073          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>


1262          * as if {@code invokespecial} instruction were being linked.
1263          * <p>
1264          * Before method resolution,
1265          * if the explicitly specified caller class is not identical with the
1266          * lookup class, or if this lookup object does not have
1267          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1268          * privileges, the access fails.
1269          * <p>
1270          * The returned method handle will have
1271          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1272          * the method's variable arity modifier bit ({@code 0x0080}) is set.
1273          * @param m the reflected method
1274          * @param specialCaller the class nominally calling the method
1275          * @return a method handle which can invoke the reflected method
1276          * @throws IllegalAccessException if access checking fails
1277          *                                or if the method's variable arity modifier bit
1278          *                                is set and {@code asVarargsCollector} fails
1279          * @throws NullPointerException if any argument is null
1280          */
1281         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1282             checkSpecialCaller(specialCaller, null);
1283             Lookup specialLookup = this.in(specialCaller);
1284             MemberName method = new MemberName(m, true);
1285             assert(method.isMethod());
1286             // ignore m.isAccessible:  this is a new kind of access
1287             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
1288         }
1289 
1290         /**
1291          * Produces a method handle for a reflected constructor.
1292          * The type of the method handle will be that of the constructor,
1293          * with the return type changed to the declaring class.
1294          * The method handle will perform a {@code newInstance} operation,
1295          * creating a new instance of the constructor's class on the
1296          * arguments passed to the method handle.
1297          * <p>
1298          * If the constructor's {@code accessible} flag is not set,
1299          * access checking is performed immediately on behalf of the lookup class.
1300          * <p>
1301          * The returned method handle will have
1302          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if


1482             return (allowedModes & PRIVATE) != 0;
1483         }
1484 
1485         /**
1486          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
1487          * Determines a trustable caller class to compare with refc, the symbolic reference class.
1488          * If this lookup object has private access, then the caller class is the lookupClass.
1489          */
1490         void checkSecurityManager(Class<?> refc, MemberName m) {
1491             SecurityManager smgr = System.getSecurityManager();
1492             if (smgr == null)  return;
1493             if (allowedModes == TRUSTED)  return;
1494 
1495             // Step 1:
1496             boolean fullPowerLookup = hasPrivateAccess();
1497             if (!fullPowerLookup ||
1498                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1499                 ReflectUtil.checkPackageAccess(refc);
1500             }
1501 
1502             if (m == null) {  // findClass or accessClass
1503                 // Step 2b:
1504                 if (!fullPowerLookup) {
1505                     smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1506                 }
1507                 return;
1508             }
1509 
1510             // Step 2a:
1511             if (m.isPublic()) return;
1512             if (!fullPowerLookup) {
1513                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
1514             }
1515 
1516             // Step 3:
1517             Class<?> defc = m.getDeclaringClass();
1518             if (!fullPowerLookup && defc != refc) {
1519                 ReflectUtil.checkPackageAccess(defc);
1520             }
1521         }
1522 
1523         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1524             boolean wantStatic = (refKind == REF_invokeStatic);
1525             String message;
1526             if (m.isConstructor())
1527                 message = "expected a method, not a constructor";
1528             else if (!m.isMethod())
1529                 message = "expected a method";
1530             else if (wantStatic != m.isStatic())


1603                                (defc == refc ||
1604                                 Modifier.isPublic(refc.getModifiers())));
1605             if (!classOK && (allowedModes & PACKAGE) != 0) {
1606                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
1607                            (defc == refc ||
1608                             VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
1609             }
1610             if (!classOK)
1611                 return "class is not public";
1612             if (Modifier.isPublic(mods))
1613                 return "access to public member failed";  // (how?)
1614             if (Modifier.isPrivate(mods))
1615                 return "member is private";
1616             if (Modifier.isProtected(mods))
1617                 return "member is protected";
1618             return "member is private to package";
1619         }
1620 
1621         private static final boolean ALLOW_NESTMATE_ACCESS = false;
1622 
1623         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
1624             int allowedModes = this.allowedModes;
1625             if (allowedModes == TRUSTED)  return;
1626             if (!hasPrivateAccess()
1627                 || (specialCaller != lookupClass()
1628                        // ensure non-abstract methods in superinterfaces can be special-invoked
1629                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
1630                     && !(ALLOW_NESTMATE_ACCESS &&
1631                          VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
1632                 throw new MemberName(specialCaller).
1633                     makeAccessException("no private access for invokespecial", this);
1634         }
1635 
1636         private boolean restrictProtectedReceiver(MemberName method) {
1637             // The accessing class only has the right to use a protected member
1638             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
1639             if (!method.isProtected() || method.isStatic()
1640                 || allowedModes == TRUSTED
1641                 || method.getDeclaringClass() == lookupClass()
1642                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
1643                 || (ALLOW_NESTMATE_ACCESS &&
1644                     VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
1645                 return false;
1646             return true;
1647         }
1648         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
1649             assert(!method.isStatic());


1936      * <blockquote><pre>{@code
1937 MethodHandle invoker = MethodHandles.invoker(type);
1938 int spreadArgCount = type.parameterCount() - leadingArgCount;
1939 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
1940 return invoker;
1941      * }</pre></blockquote>
1942      * This method throws no reflective or security exceptions.
1943      * @param type the desired target type
1944      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
1945      * @return a method handle suitable for invoking any method handle of the given type
1946      * @throws NullPointerException if {@code type} is null
1947      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
1948      *                  the range from 0 to {@code type.parameterCount()} inclusive,
1949      *                  or if the resulting method handle's type would have
1950      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
1951      */
1952     public static
1953     MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
1954         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
1955             throw newIllegalArgumentException("bad argument count", leadingArgCount);
1956         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
1957         return type.invokers().spreadInvoker(leadingArgCount);
1958     }
1959 
1960     /**
1961      * Produces a special <em>invoker method handle</em> which can be used to
1962      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
1963      * The resulting invoker will have a type which is
1964      * exactly equal to the desired type, except that it will accept
1965      * an additional leading argument of type {@code MethodHandle}.
1966      * <p>
1967      * This method is equivalent to the following code (though it may be more efficient):
1968      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
1969      *
1970      * <p style="font-size:smaller;">
1971      * <em>Discussion:</em>
1972      * Invoker method handles can be useful when working with variable method handles
1973      * of unknown types.
1974      * For example, to emulate an {@code invokeExact} call to a variable method
1975      * handle {@code M}, extract its type {@code T},
1976      * look up the invoker method {@code X} for {@code T},


2972      * T target2(A[N]..., B...);
2973      * void combiner2(A...);
2974      * T adapter2(A... a, B... b) {
2975      *   combiner2(a...);
2976      *   return target2(a..., b...);
2977      * }
2978      * }</pre></blockquote>
2979      * @param target the method handle to invoke after arguments are combined
2980      * @param combiner method handle to call initially on the incoming arguments
2981      * @return method handle which incorporates the specified argument folding logic
2982      * @throws NullPointerException if either argument is null
2983      * @throws IllegalArgumentException if {@code combiner}'s return type
2984      *          is non-void and not the same as the first argument type of
2985      *          the target, or if the initial {@code N} argument types
2986      *          of the target
2987      *          (skipping one matching the {@code combiner}'s return type)
2988      *          are not identical with the argument types of {@code combiner}
2989      */
2990     public static
2991     MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
2992         return foldArguments(target, 0, combiner);












2993     }
2994 
2995     static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
2996         int foldArgs   = combinerType.parameterCount();
2997         Class<?> rtype = combinerType.returnType();
2998         int foldVals = rtype == void.class ? 0 : 1;
2999         int afterInsertPos = foldPos + foldVals;
3000         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3001         if (ok && !(combinerType.parameterList()
3002                     .equals(targetType.parameterList().subList(afterInsertPos,
3003                                                                afterInsertPos + foldArgs))))
3004             ok = false;
3005         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
3006             ok = false;
3007         if (!ok)
3008             throw misMatchedTypes("target and combiner types", targetType, combinerType);
3009         return rtype;
3010     }
3011 
3012     /**
3013      * Makes a method handle which adapts a target method handle,
3014      * by guarding it with a test, a boolean-valued method handle.
3015      * If the guard fails, a fallback handle is called instead.
3016      * All three method handles must have the same corresponding
3017      * argument and return types, except that the return type
3018      * of the test must be boolean, and the test is allowed
3019      * to have fewer arguments than the other two method handles.
3020      * <p> Here is pseudocode for the resulting adapter:
3021      * <blockquote><pre>{@code
3022      * boolean test(A...);
3023      * T target(A...,B...);
3024      * T fallback(A...,B...);
3025      * T adapter(A... a,B... b) {


3093      * }</pre></blockquote>
3094      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3095      * be modified by execution of the target, and so are passed unchanged
3096      * from the caller to the handler, if the handler is invoked.
3097      * <p>
3098      * The target and handler must return the same type, even if the handler
3099      * always throws.  (This might happen, for instance, because the handler
3100      * is simulating a {@code finally} clause).
3101      * To create such a throwing handler, compose the handler creation logic
3102      * with {@link #throwException throwException},
3103      * in order to create a method handle of the correct return type.
3104      * @param target method handle to call
3105      * @param exType the type of exception which the handler will catch
3106      * @param handler method handle to call if a matching exception is thrown
3107      * @return method handle which incorporates the specified try/catch logic
3108      * @throws NullPointerException if any argument is null
3109      * @throws IllegalArgumentException if {@code handler} does not accept
3110      *          the given exception type, or if the method handle types do
3111      *          not match in their return types and their
3112      *          corresponding parameters
3113      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
3114      */
3115     public static
3116     MethodHandle catchException(MethodHandle target,
3117                                 Class<? extends Throwable> exType,
3118                                 MethodHandle handler) {
3119         MethodType ttype = target.type();
3120         MethodType htype = handler.type();
3121         if (htype.parameterCount() < 1 ||
3122             !htype.parameterType(0).isAssignableFrom(exType))
3123             throw newIllegalArgumentException("handler does not accept exception type "+exType);
3124         if (htype.returnType() != ttype.returnType())
3125             throw misMatchedTypes("target and handler return types", ttype, htype);
3126         List<Class<?>> targs = ttype.parameterList();
3127         List<Class<?>> hargs = htype.parameterList();
3128         hargs = hargs.subList(1, hargs.size());  // omit leading parameter from handler
3129         if (!targs.equals(hargs)) {
3130             int hpc = hargs.size(), tpc = targs.size();
3131             if (hpc >= tpc || !targs.subList(0, hpc).equals(hargs))
3132                 throw misMatchedTypes("target and handler types", ttype, htype);
3133             handler = dropArguments(handler, 1+hpc, targs.subList(hpc, tpc));


3137     }
3138 
3139     /**
3140      * Produces a method handle which will throw exceptions of the given {@code exType}.
3141      * The method handle will accept a single argument of {@code exType},
3142      * and immediately throw it as an exception.
3143      * The method type will nominally specify a return of {@code returnType}.
3144      * The return type may be anything convenient:  It doesn't matter to the
3145      * method handle's behavior, since it will never return normally.
3146      * @param returnType the return type of the desired method handle
3147      * @param exType the parameter type of the desired method handle
3148      * @return method handle which can throw the given exceptions
3149      * @throws NullPointerException if either argument is null
3150      */
3151     public static
3152     MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
3153         if (!Throwable.class.isAssignableFrom(exType))
3154             throw new ClassCastException(exType.getName());
3155         return MethodHandleImpl.throwException(MethodType.methodType(returnType, exType));
3156     }
3157 
3158     /**
3159      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
3160      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
3161      * delivers the loop's result, which is the return value of the resulting handle.
3162      * <p>
3163      * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
3164      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
3165      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
3166      * terms of method handles, each clause will determine four actions:<ul>
3167      * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
3168      * <li>When a clause executes, an update step for the iteration variable.
3169      * <li>When a clause executes, a predicate execution to test for loop exit.
3170      * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
3171      * </ul>
3172      * <p>
3173      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
3174      * this case. See below for a detailed description.
3175      * <p>
3176      * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
3177      * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
3178      * parameters. Most clause functions will not need all of this information, but they will be formally connected as
3179      * if by {@link #dropArguments}.
3180      * <p>
3181      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
3182      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
3183      * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
3184      * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
3185      * that they must be identical, or else one list must be a proper prefix of the other.
3186      * <p>
3187      * <em>Step 0: Determine clause structure.</em><ol type="a">
3188      * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
3189      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
3190      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
3191      * four. Padding takes place by appending elements to the array.
3192      * <li>Clauses with all {@code null}s are disregarded.
3193      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
3194      * </ol>
3195      * <p>
3196      * <em>Step 1A: Determine iteration variables.</em><ol type="a">
3197      * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
3198      * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
3199      * use the common return type (they must be identical).
3200      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
3201      * <li>This list of types is called the "common prefix".
3202      * </ol>
3203      * <p>
3204      * <em>Step 1B: Determine loop parameters.</em><ol type="a">
3205      * <li>Examine init function parameter lists.
3206      * <li>Omitted init functions are deemed to have {@code null} parameter lists.
3207      * <li>All init function parameter lists must be effectively identical.
3208      * <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
3209      * </ol>
3210      * <p>
3211      * <em>Step 1C: Determine loop return type.</em><ol type="a">
3212      * <li>Examine fini function return types, disregarding omitted fini functions.
3213      * <li>If there are no fini functions, use {@code void} as the loop return type.
3214      * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
3215      * </ol>
3216      * <p>
3217      * <em>Step 1D: Check other types.</em><ol type="a">
3218      * <li>There must be at least one non-omitted pred function.
3219      * <li>Every non-omitted pred function must have a {@code boolean} return type.
3220      * </ol>
3221      * <p>
3222      * (Implementation Note: Steps 1A, 1B, 1C, 1D are logically independent of each other, and may be performed in any
3223      * order.)
3224      * <p>
3225      * <em>Step 2: Determine parameter lists.</em><ol type="a">
3226      * <li>The parameter list for the resulting loop handle will be the "common suffix".
3227      * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
3228      * lists are already effectively identical to the common suffix.)
3229      * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
3230      * followed by the common suffix, called the "common parameter sequence".
3231      * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
3232      * sequence.
3233      * </ol>
3234      * <p>
3235      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
3236      * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
3237      * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
3238      * function which does nothing and returns {@code void}; it can be obtained from another constant function by
3239      * {@linkplain MethodHandle#asType type conversion}.)
3240      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
3241      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
3242      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
3243      * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
3244      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
3245      * as this clause is concerned.)
3246      * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
3247      * loop return type.
3248      * </ol>
3249      * <p>
3250      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
3251      * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
3252      * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
3253      * {@linkplain #dropArguments dropping arguments}.
3254      * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
3255      * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
3256      * of the list by {@linkplain #dropArguments dropping arguments}.
3257      * </ol>
3258      * <p>
3259      * <em>Final observations.</em><ol type="a">
3260      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
3261      * <li>All init functions have a common parameter type list, which the final loop handle will also have.
3262      * <li>All fini functions have a common return type, which the final loop handle will also have.
3263      * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
3264      * (non-{@code void}) iteration variables followed by loop parameters.
3265      * <li>Each pair of init and step functions agrees in their return types.
3266      * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
3267      * common prefix.
3268      * </ol>
3269      * <p>
3270      * <em>Loop execution.</em><ol type="a">
3271      * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
3272      * every clause function. These locals are loop invariant.
3273      * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
3274      * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
3275      * functions, as noted above).
3276      * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
3277      * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
3278      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
3279      * returns {@code false}.
3280      * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
3281      * updated value is immediately visible to all subsequent function calls.
3282      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
3283      * is returned from the loop as a whole.
3284      * </ol>
3285      * <p>
3286      * Here is pseudocode for the resulting loop handle:
3287      * <blockquote><pre>{@code
3288      * V... init...(A...);
3289      * boolean pred...(V..., A...);
3290      * V... step...(V..., A...);
3291      * R fini...(V..., A...);
3292      * R loop(A... a) {
3293      *   V... v... = init...(a...);
3294      *   for (;;) {
3295      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
3296      *       v = s(v..., a...);
3297      *       if (!p(v..., a...)) {
3298      *         return f(v..., a...);
3299      *       }
3300      *     }
3301      *   }
3302      * }
3303      * }</pre></blockquote>
3304      * <p>
3305      * Example:
3306      * <blockquote><pre>{@code
3307      * // iterative implementation of the factorial function as a loop handle
3308      * static int one(int k) { return 1; }
3309      * int inc(int i, int acc, int k) { return i + 1; }
3310      * int mult(int i, int acc, int k) { return i * acc; }
3311      * boolean pred(int i, int acc, int k) { return i < k; }
3312      * int fin(int i, int acc, int k) { return acc; }
3313      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
3314      * // null initializer for counter, should initialize to 0
3315      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
3316      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
3317      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
3318      * assertEquals(120, loop.invoke(5));
3319      * }</pre></blockquote>
3320      *
3321      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
3322      *
3323      * @return a method handle embodying the looping behavior as defined by the arguments.
3324      *
3325      * @throws IllegalArgumentException in case any of the constraints described above is violated.
3326      *
3327      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
3328      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
3329      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
3330      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
3331      */
3332     public static MethodHandle loop(MethodHandle[]... clauses) {
3333         // Step 0: determine clause structure.
3334         if (clauses == null || clauses.length == 0) {
3335             err("null or no clauses passed");
3336         }
3337         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
3338             err("null clauses are not allowed");
3339         }
3340         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
3341             err("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
3342         }
3343 
3344         List<MethodHandle> init = new ArrayList<>();
3345         List<MethodHandle> step = new ArrayList<>();
3346         List<MethodHandle> pred = new ArrayList<>();
3347         List<MethodHandle> fini = new ArrayList<>();
3348 
3349         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
3350             init.add(clause[0]); // all clauses have at least length 1
3351             step.add(clause.length <= 1 ? null : clause[1]);
3352             pred.add(clause.length <= 2 ? null : clause[2]);
3353             fini.add(clause.length <= 3 ? null : clause[3]);
3354         });
3355 
3356         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
3357         final int nclauses = init.size();
3358 
3359         // Step 1A: determine iteration variables.
3360         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
3361         for (int i = 0; i < nclauses; ++i) {
3362             MethodHandle in = init.get(i);
3363             MethodHandle st = step.get(i);
3364             if (in == null && st == null) {
3365                 iterationVariableTypes.add(void.class);
3366             } else if (in != null && st != null) {
3367                 if (in.type().returnType() != st.type().returnType()) {
3368                     err("error in clause " + i +": init and step return types mismatch (" + in.type().returnType() +
3369                             ", " + st.type().returnType() + ")");
3370                 }
3371                 iterationVariableTypes.add(in.type().returnType());
3372             } else {
3373                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
3374             }
3375         }
3376         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
3377                 collect(Collectors.toList());
3378 
3379         // Step 1B: determine loop parameters.
3380         final List<Class<?>> empty = new ArrayList<>();
3381         final List<Class<?>> commonSuffix = init.stream().filter(Objects::nonNull).map(MethodHandle::type).
3382                 map(MethodType::parameterList).reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
3383         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
3384                 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
3385             err("found non-effectively identical init parameter type lists: " + init + " (common suffix: " +
3386                     commonSuffix + ")");
3387         }
3388 
3389         // Step 1C: determine loop return type.
3390         final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
3391                 map(MethodType::returnType).findFirst().orElse(void.class);
3392         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
3393                 anyMatch(t -> t != loopReturnType)) {
3394             err("found non-identical finalizer return types: " + fini + " (return type: " + loopReturnType + ")");
3395         }
3396 
3397         // Step 1D: check other types.
3398         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
3399             err("no predicate found: " + pred);
3400         }
3401         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
3402                 anyMatch(t -> t != boolean.class)) {
3403             err("predicates must have boolean return type: " + pred);
3404         }
3405 
3406         // Step 2: determine parameter lists.
3407         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
3408         commonParameterSequence.addAll(commonSuffix);
3409         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
3410                 map(MethodType::parameterList).anyMatch(pl -> !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
3411             err("found non-effectively identical parameter type lists:\nstep: " + step + "\npred: " + pred + "\nfini: " +
3412                     fini + " (common parameter sequence: " + commonParameterSequence + ")");
3413         }
3414 
3415         // Step 3: fill in omitted functions.
3416         for (int i = 0; i < nclauses; ++i) {
3417             Class<?> t = iterationVariableTypes.get(i);
3418             if (init.get(i) == null) {
3419                 init.set(i, zeroHandle(t));
3420             }
3421             if (step.get(i) == null) {
3422                 step.set(i, dropArguments(t == void.class ? zeroHandle(t) : identity(t), 0, commonPrefix.subList(0, i)));
3423             }
3424             if (pred.get(i) == null) {
3425                 pred.set(i, constant(boolean.class, true));
3426             }
3427             if (fini.get(i) == null) {
3428                 fini.set(i, zeroHandle(t));
3429             }
3430         }
3431 
3432         // Step 4: fill in missing parameter types.
3433         List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
3434         List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
3435         List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
3436         List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
3437 
3438         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
3439                 allMatch(pl -> pl.equals(commonSuffix));
3440         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
3441                 allMatch(pl -> pl.equals(commonParameterSequence));
3442 
3443         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
3444     }
3445 
3446     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
3447         return hs.stream().map(h -> {
3448             int pc = h.type().parameterCount();
3449             int tpsize = targetParams.size();
3450             return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
3451         }).collect(Collectors.toList());
3452     }
3453 
3454     /**
3455      * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
3456      * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
3457      * <p>
3458      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
3459      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
3460      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
3461      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
3462      * generic loop combinator}.
3463      * <p>
3464      * Here is pseudocode for the resulting loop handle:
3465      * <blockquote><pre>{@code
3466      * V init(A);
3467      * boolean pred(V, A);
3468      * V body(V, A);
3469      * V whileLoop(A a) {
3470      *   V v = init(a);
3471      *   while (pred(v, a)) {
3472      *     v = body(v, a);
3473      *   }
3474      *   return v;
3475      * }
3476      * }</pre></blockquote>
3477      * <p>
3478      * Example:
3479      * <blockquote><pre>{@code
3480      * // implement the zip function for lists as a loop handle
3481      * List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
3482      * boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
3483      * List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
3484      *   zip.add(a.next());
3485      *   zip.add(b.next());
3486      *   return zip;
3487      * }
3488      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
3489      * MethodHandle loop = MethodHandles.doWhileLoop(MH_initZip, MH_zipPred, MH_zipStep);
3490      * List<String> a = Arrays.asList(new String[]{"a", "b", "c", "d"});
3491      * List<String> b = Arrays.asList(new String[]{"e", "f", "g", "h"});
3492      * List<String> zipped = Arrays.asList(new String[]{"a", "e", "b", "f", "c", "g", "d", "h"});
3493      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
3494      * }</pre></blockquote>
3495      *
3496      * <p>
3497      * The implementation of this method is equivalent to:
3498      * <blockquote><pre>{@code
3499      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
3500      *     MethodHandle[]
3501      *         checkExit = {null, null, pred, identity(init.type().returnType())},
3502      *         varBody = {init, body};
3503      *     return loop(checkExit, varBody);
3504      * }
3505      * }</pre></blockquote>
3506      *
3507      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
3508      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
3509      *             {@code void}.
3510      * @param pred condition for the loop, which may not be {@code null}.
3511      * @param body body of the loop, which may not be {@code null}.
3512      *
3513      * @return the value of the loop variable as the loop terminates.
3514      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3515      *
3516      * @see MethodHandles#loop(MethodHandle[][])
3517      */
3518     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
3519         MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
3520         MethodHandle[] checkExit = {null, null, pred, fin};
3521         MethodHandle[] varBody = {init, body};
3522         return loop(checkExit, varBody);
3523     }
3524 
3525     /**
3526      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
3527      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3528      * <p>
3529      * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
3530      * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
3531      * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
3532      * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
3533      * generic loop combinator}.
3534      * <p>
3535      * Here is pseudocode for the resulting loop handle:
3536      * <blockquote><pre>{@code
3537      * V init(A);
3538      * boolean pred(V, A);
3539      * V body(V, A);
3540      * V doWhileLoop(A a) {
3541      *   V v = init(a);
3542      *   do {
3543      *     v = body(v, a);
3544      *   } while (pred(v, a));
3545      *   return v;
3546      * }
3547      * }</pre></blockquote>
3548      * <p>
3549      * Example:
3550      * <blockquote><pre>{@code
3551      * // int i = 0; while (i < limit) { ++i; } return i; => limit
3552      * int zero(int limit) { return 0; }
3553      * int step(int i, int limit) { return i + 1; }
3554      * boolean pred(int i, int limit) { return i < limit; }
3555      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
3556      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
3557      * assertEquals(23, loop.invoke(23));
3558      * }</pre></blockquote>
3559      *
3560      * * <p>
3561      * The implementation of this method is equivalent to:
3562      * <blockquote><pre>{@code
3563      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
3564      *     MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
3565      *     return loop(clause);
3566      * }
3567      * }</pre></blockquote>
3568      *
3569      *
3570      * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
3571      *             result type. Passing {@code null} or a {@code void} init function will make the loop's result type
3572      *             {@code void}.
3573      * @param pred condition for the loop, which may not be {@code null}.
3574      * @param body body of the loop, which may not be {@code null}.
3575      *
3576      * @return the value of the loop variable as the loop terminates.
3577      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3578      *
3579      * @see MethodHandles#loop(MethodHandle[][])
3580      */
3581     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
3582         MethodHandle fin = init == null ? zeroHandle(void.class) : identity(init.type().returnType());
3583         MethodHandle[] clause = {init, body, pred, fin};
3584         return loop(clause);
3585     }
3586 
3587     /**
3588      * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
3589      * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
3590      * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
3591      * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3592      * <p>
3593      * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
3594      * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
3595      * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
3596      * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
3597      * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3598      * <p>
3599      * Here is pseudocode for the resulting loop handle:
3600      * <blockquote><pre>{@code
3601      * int iterations(A);
3602      * V init(A);
3603      * V body(int, V, A);
3604      * V countedLoop(A a) {
3605      *   int end = iterations(a);
3606      *   V v = init(a);
3607      *   for (int i = 0; i < end; ++i) {
3608      *     v = body(i, v, a);
3609      *   }
3610      *   return v;
3611      * }
3612      * }</pre></blockquote>
3613      * <p>
3614      * Example:
3615      * <blockquote><pre>{@code
3616      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
3617      * // => a variation on a well known theme
3618      * String start(String arg) { return arg; }
3619      * String step(int counter, String v, String arg) { return "na " + v; }
3620      * // assume MH_start and MH_step are handles to the two methods above
3621      * MethodHandle loop = MethodHandles.countedLoop(13, MH_start, MH_step);
3622      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
3623      * }</pre></blockquote>
3624      *
3625      * <p>
3626      * The implementation of this method is equivalent to:
3627      * <blockquote><pre>{@code
3628      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
3629      *     return countedLoop(null, iterations, init, body);  // null => constant zero
3630      * }
3631      * }</pre></blockquote>
3632      *
3633      * @param iterations a handle to return the number of iterations this loop should run.
3634      * @param init initializer for additional loop state. This determines the loop's result type.
3635      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3636      *             {@code void}.
3637      * @param body the body of the loop, which must not be {@code null}.
3638      *             It must accept an initial {@code int} parameter (for the counter), and then any
3639      *             additional loop-local variable plus loop parameters.
3640      *
3641      * @return a method handle representing the loop.
3642      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3643      */
3644     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
3645         return countedLoop(null, iterations, init, body);
3646     }
3647 
3648     /**
3649      * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
3650      * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
3651      * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
3652      * body} function in each iteration; it has to accept an initial {@code int} parameter
3653      * for that. The result of the loop execution is the final value of the additional local state
3654      * obtained by running {@code init}.
3655      * This is a
3656      * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
3657      * <p>
3658      * The constraints for the {@code init} and {@code body} handles are the same as for {@link
3659      * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
3660      * must return an {@code int} and accept the same parameters as {@code init}.
3661      * <p>
3662      * Here is pseudocode for the resulting loop handle:
3663      * <blockquote><pre>{@code
3664      * int start(A);
3665      * int end(A);
3666      * V init(A);
3667      * V body(int, V, A);
3668      * V countedLoop(A a) {
3669      *   int s = start(a);
3670      *   int e = end(a);
3671      *   V v = init(a);
3672      *   for (int i = s; i < e; ++i) {
3673      *     v = body(i, v, a);
3674      *   }
3675      *   return v;
3676      * }
3677      * }</pre></blockquote>
3678      *
3679      * <p>
3680      * The implementation of this method is equivalent to:
3681      * <blockquote><pre>{@code
3682      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
3683      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
3684      *     // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int
3685      *     MethodHandle[]
3686      *         indexVar = {start, MH_increment}, // i = start; i = i+1
3687      *         loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
3688      *         bodyClause = {init, dropArguments(body, 1, int.class)};  // v = body(i, v);
3689      *     return loop(indexVar, loopLimit, bodyClause);
3690      * }
3691      * }</pre></blockquote>
3692      *
3693      * @param start a handle to return the start value of the loop counter.
3694      *              If it is {@code null}, a constant zero is assumed.
3695      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
3696      * @param init initializer for additional loop state. This determines the loop's result type.
3697      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3698      *             {@code void}.
3699      * @param body the body of the loop, which must not be {@code null}.
3700      *             It must accept an initial {@code int} parameter (for the counter), and then any
3701      *             additional loop-local variable plus loop parameters.
3702      *
3703      * @return a method handle representing the loop.
3704      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3705      */
3706     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
3707         MethodHandle returnVar = dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()),
3708                 0, int.class, int.class);
3709         MethodHandle[] indexVar = {start, MethodHandleImpl.Lazy.MH_countedLoopStep};
3710         MethodHandle[] loopLimit = {end, null, MethodHandleImpl.Lazy.MH_countedLoopPred, returnVar};
3711         MethodHandle[] bodyClause = {init, dropArguments(body, 1, int.class)};
3712         return loop(indexVar, loopLimit, bodyClause);
3713     }
3714 
3715     /**
3716      * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
3717      * The iterator will be produced by the evaluation of the {@code iterator} handle.
3718      * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
3719      * and will be applied to a leading argument of the loop handle.
3720      * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
3721      * The result of the loop execution is the final value of the additional local state
3722      * obtained by running {@code init}.
3723      * <p>
3724      * This is a convenience wrapper for the
3725      * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
3726      * handle follow directly from those described for the latter.
3727      * <p>
3728      * Here is pseudocode for the resulting loop handle:
3729      * <blockquote><pre>{@code
3730      * Iterator<T> iterator(A);  // defaults to Iterable::iterator
3731      * V init(A);
3732      * V body(T,V,A);
3733      * V iteratedLoop(A a) {
3734      *   Iterator<T> it = iterator(a);
3735      *   V v = init(a);
3736      *   for (T t : it) {
3737      *     v = body(t, v, a);
3738      *   }
3739      *   return v;
3740      * }
3741      * }</pre></blockquote>
3742      * <p>
3743      * The type {@code T} may be either a primitive or reference.
3744      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
3745      * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
3746      * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
3747      * Therefore, if an iterator of the wrong type appears as the loop is executed,
3748      * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
3749      * <p>
3750      * Example:
3751      * <blockquote><pre>{@code
3752      * // reverse a list
3753      * List<String> reverseStep(String e, List<String> r) {
3754      *   r.add(0, e);
3755      *   return r;
3756      * }
3757      * List<String> newArrayList() { return new ArrayList<>(); }
3758      * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
3759      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
3760      * List<String> list = Arrays.asList(new String[]{"a", "b", "c", "d", "e"});
3761      * List<String> reversedList = Arrays.asList(new String[]{"e", "d", "c", "b", "a"});
3762      * assertEquals(reversedList, (List<String>) loop.invoke(list));
3763      * }</pre></blockquote>
3764      * <p>
3765      * The implementation of this method is equivalent to:
3766      * <blockquote><pre>{@code
3767      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
3768      *     // assume MH_next and MH_hasNext are handles to methods of Iterator
3769      *     Class<?> itype = iterator.type().returnType();
3770      *     Class<?> ttype = body.type().parameterType(0);
3771      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
3772      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
3773      *     MethodHandle[]
3774      *         iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
3775      *         bodyClause = {init, filterArgument(body, 0, nextVal)};  // v = body(t, v, a);
3776      *     return loop(iterVar, bodyClause);
3777      * }
3778      * }</pre></blockquote>
3779      *
3780      * @param iterator a handle to return the iterator to start the loop.
3781      *             Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
3782      *             incoming value.
3783      * @param init initializer for additional loop state. This determines the loop's result type.
3784      *             Passing {@code null} or a {@code void} init function will make the loop's result type
3785      *             {@code void}.
3786      * @param body the body of the loop, which must not be {@code null}.
3787      *             It must accept an initial {@code T} parameter (for the iterated values), and then any
3788      *             additional loop-local variable plus loop parameters.
3789      *
3790      * @return a method handle embodying the iteration loop functionality.
3791      * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
3792      */
3793     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
3794         if (null == body) {
3795             err("iterated loop body must not be null");
3796         }
3797 
3798         MethodHandle initIterator = iterator == null ?
3799                 MethodHandleImpl.Lazy.MH_initIterator.asType(MethodHandleImpl.Lazy.MH_initIterator.type().
3800                         changeParameterType(0, body.type().parameterType(init == null ? 1 : 2))) :
3801                 iterator;
3802         Class<?> itype = initIterator.type().returnType();
3803         Class<?> ttype = body.type().parameterType(0);
3804 
3805         MethodHandle returnVar =
3806                 dropArguments(init == null ? zeroHandle(void.class) : identity(init.type().returnType()), 0, itype);
3807         MethodHandle nextVal = MethodHandleImpl.Lazy.MH_iterateNext.
3808                 asType(MethodHandleImpl.Lazy.MH_iterateNext.type().changeReturnType(ttype));
3809 
3810         MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.Lazy.MH_iteratePred, returnVar};
3811         MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
3812 
3813         return loop(iterVar, bodyClause);
3814     }
3815 
3816     /**
3817      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
3818      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
3819      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
3820      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
3821      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
3822      * {@code try-finally} handle.
3823      * <p>
3824      * The {@code cleanup} handle will be passed one or two additional leading arguments.
3825      * The first is the exception thrown during the
3826      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
3827      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
3828      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
3829      * The second argument is not present if the {@code target} handle has a {@code void} return type.
3830      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
3831      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
3832      * <p>
3833      * The {@code target} and {@code cleanup} handles' return types must be the same. Their parameter type lists also
3834      * must be the same, but the {@code cleanup} handle must accept one or two more leading parameters:<ul>
3835      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
3836      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
3837      * the result from the execution of the {@code target} handle.
3838      * This parameter is not present if the {@code target} returns {@code void}.
3839      * </ul>
3840      * <p>
3841      * The pseudocode for the resulting adapter looks like this:
3842      * <blockquote><pre>{@code
3843      * T target(A..., B...);
3844      * T cleanup(Throwable, T, A...);
3845      * T adapter(A... a, B... b) {
3846      *   T result = (zero value for T);
3847      *   Throwable throwable = null;
3848      *   try {
3849      *     result = target(a..., b...);
3850      *   } catch (Throwable t) {
3851      *     throwable = t;
3852      *     throw t;
3853      *   } finally {
3854      *     result = cleanup(throwable, result, a...);
3855      *   }
3856      *   return result;
3857      * }
3858      * }</pre></blockquote>
3859      * <p>
3860      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3861      * be modified by execution of the target, and so are passed unchanged
3862      * from the caller to the cleanup, if it is invoked.
3863      * <p>
3864      * The target and cleanup must return the same type, even if the cleanup
3865      * always throws.
3866      * To create such a throwing cleanup, compose the cleanup logic
3867      * with {@link #throwException throwException},
3868      * in order to create a method handle of the correct return type.
3869      * <p>
3870      * Note that {@code tryFinally} never converts exceptions into normal returns.
3871      * In rare cases where exceptions must be converted in that way, first wrap
3872      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
3873      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
3874      *
3875      * @param target the handle whose execution is to be wrapped in a {@code try} block.
3876      * @param cleanup the handle that is invoked in the finally block.
3877      *
3878      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
3879      * @throws NullPointerException if any argument is null
3880      * @throws IllegalArgumentException if {@code cleanup} does not accept
3881      *          the required leading arguments, or if the method handle types do
3882      *          not match in their return types and their
3883      *          corresponding trailing parameters
3884      *
3885      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
3886      */
3887     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
3888         List<Class<?>> targetParamTypes = target.type().parameterList();
3889         List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
3890         Class<?> rtype = target.type().returnType();
3891 
3892         checkTryFinally(cleanup, targetParamTypes, cleanupParamTypes, rtype);
3893 
3894         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
3895         int tpSize = targetParamTypes.size();
3896         int cpPrefixLength = MethodHandleImpl.isVoid(rtype) ? 1 : 2;
3897         int cpSize = cleanupParamTypes.size();
3898         MethodHandle aCleanup = cpSize - cpPrefixLength < tpSize ?
3899                 dropArguments(cleanup, cpSize, targetParamTypes.subList(tpSize - (cpSize - cpPrefixLength), tpSize)) :
3900                 cleanup;
3901 
3902         MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
3903         aCleanup = aCleanup.asSpreader(Object[].class, tpSize);
3904 
3905         return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
3906     }
3907 
3908     /**
3909      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
3910      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
3911      * before the folded arguments.
3912      * <p>
3913      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
3914      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
3915      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
3916      * 0.
3917      * <p>
3918      * <b>Example:</b>
3919      * <blockquote><pre>{@code
3920     import static java.lang.invoke.MethodHandles.*;
3921     import static java.lang.invoke.MethodType.*;
3922     ...
3923     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3924     "println", methodType(void.class, String.class))
3925     .bindTo(System.out);
3926     MethodHandle cat = lookup().findVirtual(String.class,
3927     "concat", methodType(String.class, String.class));
3928     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3929     MethodHandle catTrace = foldArguments(cat, 1, trace);
3930     // also prints "jum":
3931     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3932      * }</pre></blockquote>
3933      * <p> Here is pseudocode for the resulting adapter:
3934      * <blockquote><pre>{@code
3935      * // there are N arguments in A...
3936      * T target(Z..., V, A[N]..., B...);
3937      * V combiner(A...);
3938      * T adapter(Z... z, A... a, B... b) {
3939      *   V v = combiner(a...);
3940      *   return target(z..., v, a..., b...);
3941      * }
3942      * // and if the combiner has a void return:
3943      * T target2(Z..., A[N]..., B...);
3944      * void combiner2(A...);
3945      * T adapter2(Z... z, A... a, B... b) {
3946      *   combiner2(a...);
3947      *   return target2(z..., a..., b...);
3948      * }
3949      * }</pre></blockquote>
3950      *
3951      * @param target the method handle to invoke after arguments are combined
3952      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
3953      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
3954      * @param combiner method handle to call initially on the incoming arguments
3955      * @return method handle which incorporates the specified argument folding logic
3956      * @throws NullPointerException if either argument is null
3957      * @throws IllegalArgumentException if {@code combiner}'s return type
3958      *          is non-void and not the same as the argument type at position {@code pos} of
3959      *          the target signature, or if the {@code N} argument types at position {@code pos}
3960      *          of the target signature
3961      *          (skipping one matching the {@code combiner}'s return type)
3962      *          are not identical with the argument types of {@code combiner}
3963      *
3964      * @see #foldArguments(MethodHandle, MethodHandle)
3965      */
3966     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
3967         MethodType targetType = target.type();
3968         MethodType combinerType = combiner.type();
3969         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
3970         BoundMethodHandle result = target.rebind();
3971         boolean dropResult = rtype == void.class;
3972         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
3973         MethodType newType = targetType;
3974         if (!dropResult) {
3975             newType = newType.dropParameterTypes(pos, pos + 1);
3976         }
3977         result = result.copyWithExtendL(newType, lform, combiner);
3978         return result;
3979     }
3980 
3981     /**
3982      * Wrap creation of a proper zero handle for a given type.
3983      *
3984      * @param type the type.
3985      *
3986      * @return a zero value for the given type.
3987      */
3988     static MethodHandle zeroHandle(Class<?> type) {
3989         return type.isPrimitive() ?  zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3990     }
3991 
3992     private static void checkTryFinally(MethodHandle cleanup, List<Class<?>> targetParamTypes, List<Class<?>> cleanupParamTypes, Class<?> rtype) {
3993         if (rtype != cleanup.type().returnType()) {
3994             err("target and cleanup return types must match");
3995         }
3996         if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
3997             err("cleanup must accept Throwable subclass as first argument");
3998         }
3999         if (!MethodHandleImpl.isVoid(rtype) && cleanupParamTypes.get(1) != rtype) {
4000             err("cleanup must accept target return type argument as second argument");
4001         }
4002         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4003         // target parameter list.
4004         int cleanupArgIndex = MethodHandleImpl.isVoid(rtype) ? 1 : 2;
4005         if (!cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()).
4006                 equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
4007             err("cleanup parameter list " + cleanupParamTypes +
4008                     " after Throwable and result must be a prefix of target parameter list " + targetParamTypes);
4009         }
4010     }
4011 
4012     static void err(String msg) {
4013         throw new IllegalArgumentException(msg);
4014     }
4015 
4016 }
< prev index next >