blob: 31756bff3ae5520e187b8fe1ff4de77aa8f32119 [file] [log] [blame]
Aurimas Liutikasdc3f8852024-07-11 10:07:48 -07001/*
2 * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import sun.invoke.util.VerifyAccess;
29import sun.invoke.util.Wrapper;
30import sun.reflect.Reflection;
31
32import java.lang.reflect.*;
33import java.nio.ByteOrder;
34import java.util.List;
35import java.util.Arrays;
36import java.util.ArrayList;
37import java.util.Iterator;
38import java.util.NoSuchElementException;
39import java.util.Objects;
40import java.util.stream.Collectors;
41import java.util.stream.Stream;
42
43import static java.lang.invoke.MethodHandleStatics.*;
44import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
45import static java.lang.invoke.MethodType.methodType;
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 * <p>
56 * @author John Rose, JSR 292 EG
57 * @since 1.7
58 */
59public class MethodHandles {
60
61 private MethodHandles() { } // do not instantiate
62
63 // Android-changed: We do not use MemberName / MethodHandleImpl.
64 //
65 // private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
66 // static { MethodHandleImpl.initStatics(); }
67 // See IMPL_LOOKUP below.
68
69 //// Method handle creation from ordinary methods.
70
71 /**
72 * Returns a {@link Lookup lookup object} with
73 * full capabilities to emulate all supported bytecode behaviors of the caller.
74 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
75 * Factory methods on the lookup object can create
76 * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
77 * for any member that the caller has access to via bytecodes,
78 * including protected and private fields and methods.
79 * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
80 * Do not store it in place where untrusted code can access it.
81 * <p>
82 * This method is caller sensitive, which means that it may return different
83 * values to different callers.
84 * <p>
85 * For any given caller class {@code C}, the lookup object returned by this call
86 * has equivalent capabilities to any lookup object
87 * supplied by the JVM to the bootstrap method of an
88 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
89 * executing in the same caller class {@code C}.
90 * @return a lookup object for the caller of this method, with private access
91 */
92 // Android-changed: Remove caller sensitive.
93 // @CallerSensitive
94 public static Lookup lookup() {
95 return new Lookup(Reflection.getCallerClass());
96 }
97
98 /**
99 * Returns a {@link Lookup lookup object} which is trusted minimally.
100 * It can only be used to create method handles to
101 * publicly accessible fields and methods.
102 * <p>
103 * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
104 * of this lookup object will be {@link java.lang.Object}.
105 *
106 * <p style="font-size:smaller;">
107 * <em>Discussion:</em>
108 * The lookup class can be changed to any other class {@code C} using an expression of the form
109 * {@link Lookup#in publicLookup().in(C.class)}.
110 * Since all classes have equal access to public names,
111 * such a change would confer no new access rights.
112 * A public lookup object is always subject to
113 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
114 * Also, it cannot access
115 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
116 * @return a lookup object which is trusted minimally
117 */
118 public static Lookup publicLookup() {
119 return Lookup.PUBLIC_LOOKUP;
120 }
121
122 // Android-removed: Documentation related to the security manager and module checks
123 /**
124 * Returns a {@link Lookup lookup object} with full capabilities to emulate all
125 * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">
126 * private access</a>, on a target class.
127 * @param targetClass the target class
128 * @param lookup the caller lookup object
129 * @return a lookup object for the target class, with private access
130 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or array class
131 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
132 * @throws IllegalAccessException is not thrown on Android
133 * @since 9
134 */
135 public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
136 // Android-removed: SecurityManager calls
137 // SecurityManager sm = System.getSecurityManager();
138 // if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
139 if (targetClass.isPrimitive())
140 throw new IllegalArgumentException(targetClass + " is a primitive class");
141 if (targetClass.isArray())
142 throw new IllegalArgumentException(targetClass + " is an array class");
143 // BEGIN Android-removed: There is no module information on Android
144 /**
145 * Module targetModule = targetClass.getModule();
146 * Module callerModule = lookup.lookupClass().getModule();
147 * if (!callerModule.canRead(targetModule))
148 * throw new IllegalAccessException(callerModule + " does not read " + targetModule);
149 * if (targetModule.isNamed()) {
150 * String pn = targetClass.getPackageName();
151 * assert pn.length() > 0 : "unnamed package cannot be in named module";
152 * if (!targetModule.isOpen(pn, callerModule))
153 * throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
154 * }
155 * if ((lookup.lookupModes() & Lookup.MODULE) == 0)
156 * throw new IllegalAccessException("lookup does not have MODULE lookup mode");
157 * if (!callerModule.isNamed() && targetModule.isNamed()) {
158 * IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
159 * if (logger != null) {
160 * logger.logIfOpenedForIllegalAccess(lookup, targetClass);
161 * }
162 * }
163 */
164 // END Android-removed: There is no module information on Android
165 return new Lookup(targetClass);
166 }
167
168
169 /**
170 * Performs an unchecked "crack" of a
171 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
172 * The result is as if the user had obtained a lookup object capable enough
173 * to crack the target method handle, called
174 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
175 * on the target to obtain its symbolic reference, and then called
176 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
177 * to resolve the symbolic reference to a member.
178 * <p>
179 * If there is a security manager, its {@code checkPermission} method
180 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
181 * @param <T> the desired type of the result, either {@link Member} or a subtype
182 * @param target a direct method handle to crack into symbolic reference components
183 * @param expected a class object representing the desired result type {@code T}
184 * @return a reference to the method, constructor, or field object
185 * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
186 * @exception NullPointerException if either argument is {@code null}
187 * @exception IllegalArgumentException if the target is not a direct method handle
188 * @exception ClassCastException if the member is not of the expected type
189 * @since 1.8
190 */
191 public static <T extends Member> T
192 reflectAs(Class<T> expected, MethodHandle target) {
193 MethodHandleImpl directTarget = getMethodHandleImpl(target);
194 // Given that this is specified to be an "unchecked" crack, we can directly allocate
195 // a member from the underlying ArtField / Method and bypass all associated access checks.
196 return expected.cast(directTarget.getMemberInternal());
197 }
198
199 /**
200 * A <em>lookup object</em> is a factory for creating method handles,
201 * when the creation requires access checking.
202 * Method handles do not perform
203 * access checks when they are called, but rather when they are created.
204 * Therefore, method handle access
205 * restrictions must be enforced when a method handle is created.
206 * The caller class against which those restrictions are enforced
207 * is known as the {@linkplain #lookupClass lookup class}.
208 * <p>
209 * A lookup class which needs to create method handles will call
210 * {@link #lookup MethodHandles.lookup} to create a factory for itself.
211 * When the {@code Lookup} factory object is created, the identity of the lookup class is
212 * determined, and securely stored in the {@code Lookup} object.
213 * The lookup class (or its delegates) may then use factory methods
214 * on the {@code Lookup} object to create method handles for access-checked members.
215 * This includes all methods, constructors, and fields which are allowed to the lookup class,
216 * even private ones.
217 *
218 * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
219 * The factory methods on a {@code Lookup} object correspond to all major
220 * use cases for methods, constructors, and fields.
221 * Each method handle created by a factory method is the functional
222 * equivalent of a particular <em>bytecode behavior</em>.
223 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
224 * Here is a summary of the correspondence between these factory methods and
225 * the behavior the resulting method handles:
226 * <table border=1 cellpadding=5 summary="lookup method behaviors">
227 * <tr>
228 * <th><a name="equiv"></a>lookup expression</th>
229 * <th>member</th>
230 * <th>bytecode behavior</th>
231 * </tr>
232 * <tr>
233 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
234 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
235 * </tr>
236 * <tr>
237 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
238 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
239 * </tr>
240 * <tr>
241 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
242 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
243 * </tr>
244 * <tr>
245 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
246 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
247 * </tr>
248 * <tr>
249 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
250 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
251 * </tr>
252 * <tr>
253 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
254 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
255 * </tr>
256 * <tr>
257 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
258 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
259 * </tr>
260 * <tr>
261 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
262 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
263 * </tr>
264 * <tr>
265 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
266 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
267 * </tr>
268 * <tr>
269 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
270 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
271 * </tr>
272 * <tr>
273 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
274 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
275 * </tr>
276 * <tr>
277 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
278 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
279 * </tr>
280 * <tr>
281 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
282 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
283 * </tr>
284 * </table>
285 *
286 * Here, the type {@code C} is the class or interface being searched for a member,
287 * documented as a parameter named {@code refc} in the lookup methods.
288 * The method type {@code MT} is composed from the return type {@code T}
289 * and the sequence of argument types {@code A*}.
290 * The constructor also has a sequence of argument types {@code A*} and
291 * is deemed to return the newly-created object of type {@code C}.
292 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
293 * The formal parameter {@code this} stands for the self-reference of type {@code C};
294 * if it is present, it is always the leading argument to the method handle invocation.
295 * (In the case of some {@code protected} members, {@code this} may be
296 * restricted in type to the lookup class; see below.)
297 * The name {@code arg} stands for all the other method handle arguments.
298 * In the code examples for the Core Reflection API, the name {@code thisOrNull}
299 * stands for a null reference if the accessed method or field is static,
300 * and {@code this} otherwise.
301 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
302 * for reflective objects corresponding to the given members.
303 * <p>
304 * In cases where the given member is of variable arity (i.e., a method or constructor)
305 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
306 * In all other cases, the returned method handle will be of fixed arity.
307 * <p style="font-size:smaller;">
308 * <em>Discussion:</em>
309 * The equivalence between looked-up method handles and underlying
310 * class members and bytecode behaviors
311 * can break down in a few ways:
312 * <ul style="font-size:smaller;">
313 * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
314 * the lookup can still succeed, even when there is no equivalent
315 * Java expression or bytecoded constant.
316 * <li>Likewise, if {@code T} or {@code MT}
317 * is not symbolically accessible from the lookup class's loader,
318 * the lookup can still succeed.
319 * For example, lookups for {@code MethodHandle.invokeExact} and
320 * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
321 * <li>If there is a security manager installed, it can forbid the lookup
322 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
323 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
324 * constant is not subject to security manager checks.
325 * <li>If the looked-up method has a
326 * <a href="MethodHandle.html#maxarity">very large arity</a>,
327 * the method handle creation may fail, due to the method handle
328 * type having too many parameters.
329 * </ul>
330 *
331 * <h1><a name="access"></a>Access checking</h1>
332 * Access checks are applied in the factory methods of {@code Lookup},
333 * when a method handle is created.
334 * This is a key difference from the Core Reflection API, since
335 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
336 * performs access checking against every caller, on every call.
337 * <p>
338 * All access checks start from a {@code Lookup} object, which
339 * compares its recorded lookup class against all requests to
340 * create method handles.
341 * A single {@code Lookup} object can be used to create any number
342 * of access-checked method handles, all checked against a single
343 * lookup class.
344 * <p>
345 * A {@code Lookup} object can be shared with other trusted code,
346 * such as a metaobject protocol.
347 * A shared {@code Lookup} object delegates the capability
348 * to create method handles on private members of the lookup class.
349 * Even if privileged code uses the {@code Lookup} object,
350 * the access checking is confined to the privileges of the
351 * original lookup class.
352 * <p>
353 * A lookup can fail, because
354 * the containing class is not accessible to the lookup class, or
355 * because the desired class member is missing, or because the
356 * desired class member is not accessible to the lookup class, or
357 * because the lookup object is not trusted enough to access the member.
358 * In any of these cases, a {@code ReflectiveOperationException} will be
359 * thrown from the attempted lookup. The exact class will be one of
360 * the following:
361 * <ul>
362 * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
363 * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
364 * <li>IllegalAccessException &mdash; if the member exists but an access check fails
365 * </ul>
366 * <p>
367 * In general, the conditions under which a method handle may be
368 * looked up for a method {@code M} are no more restrictive than the conditions
369 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
370 * Where the JVM would raise exceptions like {@code NoSuchMethodError},
371 * a method handle lookup will generally raise a corresponding
372 * checked exception, such as {@code NoSuchMethodException}.
373 * And the effect of invoking the method handle resulting from the lookup
374 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
375 * to executing the compiled, verified, and resolved call to {@code M}.
376 * The same point is true of fields and constructors.
377 * <p style="font-size:smaller;">
378 * <em>Discussion:</em>
379 * Access checks only apply to named and reflected methods,
380 * constructors, and fields.
381 * Other method handle creation methods, such as
382 * {@link MethodHandle#asType MethodHandle.asType},
383 * do not require any access checks, and are used
384 * independently of any {@code Lookup} object.
385 * <p>
386 * If the desired member is {@code protected}, the usual JVM rules apply,
387 * including the requirement that the lookup class must be either be in the
388 * same package as the desired member, or must inherit that member.
389 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
390 * In addition, if the desired member is a non-static field or method
391 * in a different package, the resulting method handle may only be applied
392 * to objects of the lookup class or one of its subclasses.
393 * This requirement is enforced by narrowing the type of the leading
394 * {@code this} parameter from {@code C}
395 * (which will necessarily be a superclass of the lookup class)
396 * to the lookup class itself.
397 * <p>
398 * The JVM imposes a similar requirement on {@code invokespecial} instruction,
399 * that the receiver argument must match both the resolved method <em>and</em>
400 * the current class. Again, this requirement is enforced by narrowing the
401 * type of the leading parameter to the resulting method handle.
402 * (See the Java Virtual Machine Specification, section 4.10.1.9.)
403 * <p>
404 * The JVM represents constructors and static initializer blocks as internal methods
405 * with special names ({@code "<init>"} and {@code "<clinit>"}).
406 * The internal syntax of invocation instructions allows them to refer to such internal
407 * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
408 * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
409 * <p>
410 * In some cases, access between nested classes is obtained by the Java compiler by creating
411 * an wrapper method to access a private method of another class
412 * in the same top-level declaration.
413 * For example, a nested class {@code C.D}
414 * can access private members within other related classes such as
415 * {@code C}, {@code C.D.E}, or {@code C.B},
416 * but the Java compiler may need to generate wrapper methods in
417 * those related classes. In such cases, a {@code Lookup} object on
418 * {@code C.E} would be unable to those private members.
419 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
420 * which can transform a lookup on {@code C.E} into one on any of those other
421 * classes, without special elevation of privilege.
422 * <p>
423 * The accesses permitted to a given lookup object may be limited,
424 * according to its set of {@link #lookupModes lookupModes},
425 * to a subset of members normally accessible to the lookup class.
426 * For example, the {@link #publicLookup publicLookup}
427 * method produces a lookup object which is only allowed to access
428 * public members in public classes.
429 * The caller sensitive method {@link #lookup lookup}
430 * produces a lookup object with full capabilities relative to
431 * its caller class, to emulate all supported bytecode behaviors.
432 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
433 * with fewer access modes than the original lookup object.
434 *
435 * <p style="font-size:smaller;">
436 * <a name="privacc"></a>
437 * <em>Discussion of private access:</em>
438 * We say that a lookup has <em>private access</em>
439 * if its {@linkplain #lookupModes lookup modes}
440 * include the possibility of accessing {@code private} members.
441 * As documented in the relevant methods elsewhere,
442 * only lookups with private access possess the following capabilities:
443 * <ul style="font-size:smaller;">
444 * <li>access private fields, methods, and constructors of the lookup class
445 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
446 * such as {@code Class.forName}
447 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
448 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
449 * for classes accessible to the lookup class
450 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
451 * within the same package member
452 * </ul>
453 * <p style="font-size:smaller;">
454 * Each of these permissions is a consequence of the fact that a lookup object
455 * with private access can be securely traced back to an originating class,
456 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
457 * can be reliably determined and emulated by method handles.
458 *
459 * <h1><a name="secmgr"></a>Security manager interactions</h1>
460 * Although bytecode instructions can only refer to classes in
461 * a related class loader, this API can search for methods in any
462 * class, as long as a reference to its {@code Class} object is
463 * available. Such cross-loader references are also possible with the
464 * Core Reflection API, and are impossible to bytecode instructions
465 * such as {@code invokestatic} or {@code getfield}.
466 * There is a {@linkplain java.lang.SecurityManager security manager API}
467 * to allow applications to check such cross-loader references.
468 * These checks apply to both the {@code MethodHandles.Lookup} API
469 * and the Core Reflection API
470 * (as found on {@link java.lang.Class Class}).
471 * <p>
472 * If a security manager is present, member lookups are subject to
473 * additional checks.
474 * From one to three calls are made to the security manager.
475 * Any of these calls can refuse access by throwing a
476 * {@link java.lang.SecurityException SecurityException}.
477 * Define {@code smgr} as the security manager,
478 * {@code lookc} as the lookup class of the current lookup object,
479 * {@code refc} as the containing class in which the member
480 * is being sought, and {@code defc} as the class in which the
481 * member is actually defined.
482 * The value {@code lookc} is defined as <em>not present</em>
483 * if the current lookup object does not have
484 * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
485 * The calls are made according to the following rules:
486 * <ul>
487 * <li><b>Step 1:</b>
488 * If {@code lookc} is not present, or if its class loader is not
489 * the same as or an ancestor of the class loader of {@code refc},
490 * then {@link SecurityManager#checkPackageAccess
491 * smgr.checkPackageAccess(refcPkg)} is called,
492 * where {@code refcPkg} is the package of {@code refc}.
493 * <li><b>Step 2:</b>
494 * If the retrieved member is not public and
495 * {@code lookc} is not present, then
496 * {@link SecurityManager#checkPermission smgr.checkPermission}
497 * with {@code RuntimePermission("accessDeclaredMembers")} is called.
498 * <li><b>Step 3:</b>
499 * If the retrieved member is not public,
500 * and if {@code lookc} is not present,
501 * and if {@code defc} and {@code refc} are different,
502 * then {@link SecurityManager#checkPackageAccess
503 * smgr.checkPackageAccess(defcPkg)} is called,
504 * where {@code defcPkg} is the package of {@code defc}.
505 * </ul>
506 * Security checks are performed after other access checks have passed.
507 * Therefore, the above rules presuppose a member that is public,
508 * or else that is being accessed from a lookup class that has
509 * rights to access the member.
510 *
511 * <h1><a name="callsens"></a>Caller sensitive methods</h1>
512 * A small number of Java methods have a special property called caller sensitivity.
513 * A <em>caller-sensitive</em> method can behave differently depending on the
514 * identity of its immediate caller.
515 * <p>
516 * If a method handle for a caller-sensitive method is requested,
517 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
518 * but they take account of the lookup class in a special way.
519 * The resulting method handle behaves as if it were called
520 * from an instruction contained in the lookup class,
521 * so that the caller-sensitive method detects the lookup class.
522 * (By contrast, the invoker of the method handle is disregarded.)
523 * Thus, in the case of caller-sensitive methods,
524 * different lookup classes may give rise to
525 * differently behaving method handles.
526 * <p>
527 * In cases where the lookup object is
528 * {@link #publicLookup publicLookup()},
529 * or some other lookup object without
530 * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
531 * the lookup class is disregarded.
532 * In such cases, no caller-sensitive method handle can be created,
533 * access is forbidden, and the lookup fails with an
534 * {@code IllegalAccessException}.
535 * <p style="font-size:smaller;">
536 * <em>Discussion:</em>
537 * For example, the caller-sensitive method
538 * {@link java.lang.Class#forName(String) Class.forName(x)}
539 * can return varying classes or throw varying exceptions,
540 * depending on the class loader of the class that calls it.
541 * A public lookup of {@code Class.forName} will fail, because
542 * there is no reasonable way to determine its bytecode behavior.
543 * <p style="font-size:smaller;">
544 * If an application caches method handles for broad sharing,
545 * it should use {@code publicLookup()} to create them.
546 * If there is a lookup of {@code Class.forName}, it will fail,
547 * and the application must take appropriate action in that case.
548 * It may be that a later lookup, perhaps during the invocation of a
549 * bootstrap method, can incorporate the specific identity
550 * of the caller, making the method accessible.
551 * <p style="font-size:smaller;">
552 * The function {@code MethodHandles.lookup} is caller sensitive
553 * so that there can be a secure foundation for lookups.
554 * Nearly all other methods in the JSR 292 API rely on lookup
555 * objects to check access requests.
556 */
557 // Android-changed: Change link targets from MethodHandles#[public]Lookup to
558 // #[public]Lookup to work around complaints from javadoc.
559 public static final
560 class Lookup {
561 /** The class on behalf of whom the lookup is being performed. */
562 /* @NonNull */ private final Class<?> lookupClass;
563
564 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
565 private final int allowedModes;
566
567 /** A single-bit mask representing {@code public} access,
568 * which may contribute to the result of {@link #lookupModes lookupModes}.
569 * The value, {@code 0x01}, happens to be the same as the value of the
570 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
571 */
572 public static final int PUBLIC = Modifier.PUBLIC;
573
574 /** A single-bit mask representing {@code private} access,
575 * which may contribute to the result of {@link #lookupModes lookupModes}.
576 * The value, {@code 0x02}, happens to be the same as the value of the
577 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
578 */
579 public static final int PRIVATE = Modifier.PRIVATE;
580
581 /** A single-bit mask representing {@code protected} access,
582 * which may contribute to the result of {@link #lookupModes lookupModes}.
583 * The value, {@code 0x04}, happens to be the same as the value of the
584 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
585 */
586 public static final int PROTECTED = Modifier.PROTECTED;
587
588 /** A single-bit mask representing {@code package} access (default access),
589 * which may contribute to the result of {@link #lookupModes lookupModes}.
590 * The value is {@code 0x08}, which does not correspond meaningfully to
591 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
592 */
593 public static final int PACKAGE = Modifier.STATIC;
594
595 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE);
596
597 // Android-note: Android has no notion of a trusted lookup. If required, such lookups
598 // are performed by the runtime. As a result, we always use lookupClass, which will always
599 // be non-null in our implementation.
600 //
601 // private static final int TRUSTED = -1;
602
603 private static int fixmods(int mods) {
604 mods &= (ALL_MODES - PACKAGE);
605 return (mods != 0) ? mods : PACKAGE;
606 }
607
608 /** Tells which class is performing the lookup. It is this class against
609 * which checks are performed for visibility and access permissions.
610 * <p>
611 * The class implies a maximum level of access permission,
612 * but the permissions may be additionally limited by the bitmask
613 * {@link #lookupModes lookupModes}, which controls whether non-public members
614 * can be accessed.
615 * @return the lookup class, on behalf of which this lookup object finds members
616 */
617 public Class<?> lookupClass() {
618 return lookupClass;
619 }
620
621 /** Tells which access-protection classes of members this lookup object can produce.
622 * The result is a bit-mask of the bits
623 * {@linkplain #PUBLIC PUBLIC (0x01)},
624 * {@linkplain #PRIVATE PRIVATE (0x02)},
625 * {@linkplain #PROTECTED PROTECTED (0x04)},
626 * and {@linkplain #PACKAGE PACKAGE (0x08)}.
627 * <p>
628 * A freshly-created lookup object
629 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
630 * has all possible bits set, since the caller class can access all its own members.
631 * A lookup object on a new lookup class
632 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
633 * may have some mode bits set to zero.
634 * The purpose of this is to restrict access via the new lookup object,
635 * so that it can access only names which can be reached by the original
636 * lookup object, and also by the new lookup class.
637 * @return the lookup modes, which limit the kinds of access performed by this lookup object
638 */
639 public int lookupModes() {
640 return allowedModes & ALL_MODES;
641 }
642
643 /** Embody the current class (the lookupClass) as a lookup class
644 * for method handle creation.
645 * Must be called by from a method in this package,
646 * which in turn is called by a method not in this package.
647 */
648 Lookup(Class<?> lookupClass) {
649 this(lookupClass, ALL_MODES);
650 // make sure we haven't accidentally picked up a privileged class:
651 checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
652 }
653
654 private Lookup(Class<?> lookupClass, int allowedModes) {
655 this.lookupClass = lookupClass;
656 this.allowedModes = allowedModes;
657 }
658
659 /**
660 * Creates a lookup on the specified new lookup class.
661 * The resulting object will report the specified
662 * class as its own {@link #lookupClass lookupClass}.
663 * <p>
664 * However, the resulting {@code Lookup} object is guaranteed
665 * to have no more access capabilities than the original.
666 * In particular, access capabilities can be lost as follows:<ul>
667 * <li>If the new lookup class differs from the old one,
668 * protected members will not be accessible by virtue of inheritance.
669 * (Protected members may continue to be accessible because of package sharing.)
670 * <li>If the new lookup class is in a different package
671 * than the old one, protected and default (package) members will not be accessible.
672 * <li>If the new lookup class is not within the same package member
673 * as the old one, private members will not be accessible.
674 * <li>If the new lookup class is not accessible to the old lookup class,
675 * then no members, not even public members, will be accessible.
676 * (In all other cases, public members will continue to be accessible.)
677 * </ul>
678 *
679 * @param requestedLookupClass the desired lookup class for the new lookup object
680 * @return a lookup object which reports the desired lookup class
681 * @throws NullPointerException if the argument is null
682 */
683 public Lookup in(Class<?> requestedLookupClass) {
684 requestedLookupClass.getClass(); // null check
685 // Android-changed: There's no notion of a trusted lookup.
686 // if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all
687 // return new Lookup(requestedLookupClass, ALL_MODES);
688
689 if (requestedLookupClass == this.lookupClass)
690 return this; // keep same capabilities
691 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
692 if ((newModes & PACKAGE) != 0
693 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
694 newModes &= ~(PACKAGE|PRIVATE);
695 }
696 // Allow nestmate lookups to be created without special privilege:
697 if ((newModes & PRIVATE) != 0
698 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
699 newModes &= ~PRIVATE;
700 }
701 if ((newModes & PUBLIC) != 0
702 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
703 // The requested class it not accessible from the lookup class.
704 // No permissions.
705 newModes = 0;
706 }
707 checkUnprivilegedlookupClass(requestedLookupClass, newModes);
708 return new Lookup(requestedLookupClass, newModes);
709 }
710
711 // Make sure outer class is initialized first.
712 //
713 // Android-changed: Removed unnecessary reference to IMPL_NAMES.
714 // static { IMPL_NAMES.getClass(); }
715
716 /** Version of lookup which is trusted minimally.
717 * It can only be used to create method handles to
718 * publicly accessible members.
719 */
720 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC);
721
722 /** Package-private version of lookup which is trusted. */
723 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, ALL_MODES);
724
725 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
726 String name = lookupClass.getName();
727 if (name.startsWith("java.lang.invoke."))
728 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
729
730 // For caller-sensitive MethodHandles.lookup()
731 // disallow lookup more restricted packages
732 //
733 // Android-changed: The bootstrap classloader isn't null.
734 if (allowedModes == ALL_MODES &&
735 lookupClass.getClassLoader() == Object.class.getClassLoader()) {
736 if ((name.startsWith("java.")
737 && !name.startsWith("java.io.ObjectStreamClass")
738 && !name.startsWith("java.util.concurrent.")
739 && !name.equals("java.lang.Daemons$FinalizerWatchdogDaemon")
740 && !name.equals("java.lang.runtime.ObjectMethods")
741 && !name.equals("java.lang.Thread")
742 && !name.equals("java.util.HashMap")) ||
743 (name.startsWith("sun.")
744 && !name.startsWith("sun.invoke.")
745 && !name.equals("sun.reflect.ReflectionFactory"))) {
746 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
747 }
748 }
749 }
750
751 /**
752 * Displays the name of the class from which lookups are to be made.
753 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
754 * If there are restrictions on the access permitted to this lookup,
755 * this is indicated by adding a suffix to the class name, consisting
756 * of a slash and a keyword. The keyword represents the strongest
757 * allowed access, and is chosen as follows:
758 * <ul>
759 * <li>If no access is allowed, the suffix is "/noaccess".
760 * <li>If only public access is allowed, the suffix is "/public".
761 * <li>If only public and package access are allowed, the suffix is "/package".
762 * <li>If only public, package, and private access are allowed, the suffix is "/private".
763 * </ul>
764 * If none of the above cases apply, it is the case that full
765 * access (public, package, private, and protected) is allowed.
766 * In this case, no suffix is added.
767 * This is true only of an object obtained originally from
768 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
769 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
770 * always have restricted access, and will display a suffix.
771 * <p>
772 * (It may seem strange that protected access should be
773 * stronger than private access. Viewed independently from
774 * package access, protected access is the first to be lost,
775 * because it requires a direct subclass relationship between
776 * caller and callee.)
777 * @see #in
778 */
779 @Override
780 public String toString() {
781 String cname = lookupClass.getName();
782 switch (allowedModes) {
783 case 0: // no privileges
784 return cname + "/noaccess";
785 case PUBLIC:
786 return cname + "/public";
787 case PUBLIC|PACKAGE:
788 return cname + "/package";
789 case ALL_MODES & ~PROTECTED:
790 return cname + "/private";
791 case ALL_MODES:
792 return cname;
793 // Android-changed: No support for TRUSTED callers.
794 // case TRUSTED:
795 // return "/trusted"; // internal only; not exported
796 default: // Should not happen, but it's a bitfield...
797 cname = cname + "/" + Integer.toHexString(allowedModes);
798 assert(false) : cname;
799 return cname;
800 }
801 }
802
803 /**
804 * Produces a method handle for a static method.
805 * The type of the method handle will be that of the method.
806 * (Since static methods do not take receivers, there is no
807 * additional receiver argument inserted into the method handle type,
808 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
809 * The method and all its argument types must be accessible to the lookup object.
810 * <p>
811 * The returned method handle will have
812 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
813 * the method's variable arity modifier bit ({@code 0x0080}) is set.
814 * <p>
815 * If the returned method handle is invoked, the method's class will
816 * be initialized, if it has not already been initialized.
817 * <p><b>Example:</b>
818 * <blockquote><pre>{@code
819import static java.lang.invoke.MethodHandles.*;
820import static java.lang.invoke.MethodType.*;
821...
822MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
823 "asList", methodType(List.class, Object[].class));
824assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
825 * }</pre></blockquote>
826 * @param refc the class from which the method is accessed
827 * @param name the name of the method
828 * @param type the type of the method
829 * @return the desired method handle
830 * @throws NoSuchMethodException if the method does not exist
831 * @throws IllegalAccessException if access checking fails,
832 * or if the method is not {@code static},
833 * or if the method's variable arity modifier bit
834 * is set and {@code asVarargsCollector} fails
835 * @exception SecurityException if a security manager is present and it
836 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
837 * @throws NullPointerException if any argument is null
838 */
839 public
840 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
841 Method method = refc.getDeclaredMethod(name, type.ptypes());
842 final int modifiers = method.getModifiers();
843 if (!Modifier.isStatic(modifiers)) {
844 throw new IllegalAccessException("Method" + method + " is not static");
845 }
846 checkReturnType(method, type);
847 checkAccess(refc, method.getDeclaringClass(), modifiers, method.getName());
848 return createMethodHandle(method, MethodHandle.INVOKE_STATIC, type);
849 }
850
851 private MethodHandle findVirtualForMH(String name, MethodType type) {
852 // these names require special lookups because of the implicit MethodType argument
853 if ("invoke".equals(name))
854 return invoker(type);
855 if ("invokeExact".equals(name))
856 return exactInvoker(type);
857 return null;
858 }
859
860 private MethodHandle findVirtualForVH(String name, MethodType type) {
861 VarHandle.AccessMode accessMode;
862 try {
863 accessMode = VarHandle.AccessMode.valueFromMethodName(name);
864 } catch (IllegalArgumentException e) {
865 return null;
866 }
867 return varHandleInvoker(accessMode, type);
868 }
869
870 private static MethodHandle createMethodHandle(Method method, int handleKind,
871 MethodType methodType) {
872 MethodHandle mh = new MethodHandleImpl(method.getArtMethod(), handleKind, methodType);
873 if (method.isVarArgs()) {
874 return new Transformers.VarargsCollector(mh);
875 } else {
876 return mh;
877 }
878 }
879
880 /**
881 * Produces a method handle for a virtual method.
882 * The type of the method handle will be that of the method,
883 * with the receiver type (usually {@code refc}) prepended.
884 * The method and all its argument types must be accessible to the lookup object.
885 * <p>
886 * When called, the handle will treat the first argument as a receiver
887 * and dispatch on the receiver's type to determine which method
888 * implementation to enter.
889 * (The dispatching action is identical with that performed by an
890 * {@code invokevirtual} or {@code invokeinterface} instruction.)
891 * <p>
892 * The first argument will be of type {@code refc} if the lookup
893 * class has full privileges to access the member. Otherwise
894 * the member must be {@code protected} and the first argument
895 * will be restricted in type to the lookup class.
896 * <p>
897 * The returned method handle will have
898 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
899 * the method's variable arity modifier bit ({@code 0x0080}) is set.
900 * <p>
901 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
902 * instructions and method handles produced by {@code findVirtual},
903 * if the class is {@code MethodHandle} and the name string is
904 * {@code invokeExact} or {@code invoke}, the resulting
905 * method handle is equivalent to one produced by
906 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
907 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
908 * with the same {@code type} argument.
909 *
910 * <b>Example:</b>
911 * <blockquote><pre>{@code
912import static java.lang.invoke.MethodHandles.*;
913import static java.lang.invoke.MethodType.*;
914...
915MethodHandle MH_concat = publicLookup().findVirtual(String.class,
916 "concat", methodType(String.class, String.class));
917MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
918 "hashCode", methodType(int.class));
919MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
920 "hashCode", methodType(int.class));
921assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
922assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
923assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
924// interface method:
925MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
926 "subSequence", methodType(CharSequence.class, int.class, int.class));
927assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
928// constructor "internal method" must be accessed differently:
929MethodType MT_newString = methodType(void.class); //()V for new String()
930try { assertEquals("impossible", lookup()
931 .findVirtual(String.class, "<init>", MT_newString));
932 } catch (NoSuchMethodException ex) { } // OK
933MethodHandle MH_newString = publicLookup()
934 .findConstructor(String.class, MT_newString);
935assertEquals("", (String) MH_newString.invokeExact());
936 * }</pre></blockquote>
937 *
938 * @param refc the class or interface from which the method is accessed
939 * @param name the name of the method
940 * @param type the type of the method, with the receiver argument omitted
941 * @return the desired method handle
942 * @throws NoSuchMethodException if the method does not exist
943 * @throws IllegalAccessException if access checking fails,
944 * or if the method is {@code static}
945 * or if the method's variable arity modifier bit
946 * is set and {@code asVarargsCollector} fails
947 * @exception SecurityException if a security manager is present and it
948 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
949 * @throws NullPointerException if any argument is null
950 */
951 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
952 // Special case : when we're looking up a virtual method on the MethodHandles class
953 // itself, we can return one of our specialized invokers.
954 if (refc == MethodHandle.class) {
955 MethodHandle mh = findVirtualForMH(name, type);
956 if (mh != null) {
957 return mh;
958 }
959 } else if (refc == VarHandle.class) {
960 // Returns an non-exact invoker.
961 MethodHandle mh = findVirtualForVH(name, type);
962 if (mh != null) {
963 return mh;
964 }
965 }
966
967 Method method = refc.getInstanceMethod(name, type.ptypes());
968 if (method == null) {
969 // This is pretty ugly and a consequence of the MethodHandles API. We have to throw
970 // an IAE and not an NSME if the method exists but is static (even though the RI's
971 // IAE has a message that says "no such method"). We confine the ugliness and
972 // slowness to the failure case, and allow getInstanceMethod to remain fairly
973 // general.
974 try {
975 Method m = refc.getDeclaredMethod(name, type.ptypes());
976 if (Modifier.isStatic(m.getModifiers())) {
977 throw new IllegalAccessException("Method" + m + " is static");
978 }
979 } catch (NoSuchMethodException ignored) {
980 }
981
982 throw new NoSuchMethodException(name + " " + Arrays.toString(type.ptypes()));
983 }
984 checkReturnType(method, type);
985
986 // We have a valid method, perform access checks.
987 checkAccess(refc, method.getDeclaringClass(), method.getModifiers(), method.getName());
988
989 // Insert the leading reference parameter.
990 MethodType handleType = type.insertParameterTypes(0, refc);
991 return createMethodHandle(method, MethodHandle.INVOKE_VIRTUAL, handleType);
992 }
993
994 /**
995 * Produces a method handle which creates an object and initializes it, using
996 * the constructor of the specified type.
997 * The parameter types of the method handle will be those of the constructor,
998 * while the return type will be a reference to the constructor's class.
999 * The constructor and all its argument types must be accessible to the lookup object.
1000 * <p>
1001 * The requested type must have a return type of {@code void}.
1002 * (This is consistent with the JVM's treatment of constructor type descriptors.)
1003 * <p>
1004 * The returned method handle will have
1005 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1006 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1007 * <p>
1008 * If the returned method handle is invoked, the constructor's class will
1009 * be initialized, if it has not already been initialized.
1010 * <p><b>Example:</b>
1011 * <blockquote><pre>{@code
1012import static java.lang.invoke.MethodHandles.*;
1013import static java.lang.invoke.MethodType.*;
1014...
1015MethodHandle MH_newArrayList = publicLookup().findConstructor(
1016 ArrayList.class, methodType(void.class, Collection.class));
1017Collection orig = Arrays.asList("x", "y");
1018Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
1019assert(orig != copy);
1020assertEquals(orig, copy);
1021// a variable-arity constructor:
1022MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
1023 ProcessBuilder.class, methodType(void.class, String[].class));
1024ProcessBuilder pb = (ProcessBuilder)
1025 MH_newProcessBuilder.invoke("x", "y", "z");
1026assertEquals("[x, y, z]", pb.command().toString());
1027 * }</pre></blockquote>
1028 * @param refc the class or interface from which the method is accessed
1029 * @param type the type of the method, with the receiver argument omitted, and a void return type
1030 * @return the desired method handle
1031 * @throws NoSuchMethodException if the constructor does not exist
1032 * @throws IllegalAccessException if access checking fails
1033 * or if the method's variable arity modifier bit
1034 * is set and {@code asVarargsCollector} fails
1035 * @exception SecurityException if a security manager is present and it
1036 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1037 * @throws NullPointerException if any argument is null
1038 */
1039 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1040 if (refc.isArray()) {
1041 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1042 }
1043 // The queried |type| is (PT1,PT2,..)V
1044 Constructor constructor = refc.getDeclaredConstructor(type.ptypes());
1045 if (constructor == null) {
1046 throw new NoSuchMethodException(
1047 "No constructor for " + constructor.getDeclaringClass() + " matching " + type);
1048 }
1049 checkAccess(refc, constructor.getDeclaringClass(), constructor.getModifiers(),
1050 constructor.getName());
1051
1052 return createMethodHandleForConstructor(constructor);
1053 }
1054
1055 // BEGIN Android-added: Add findClass(String) from OpenJDK 17. http://b/270028670
1056 // TODO: Unhide this method.
1057 /**
1058 * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
1059 * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
1060 * Such a resolution, as specified in JVMS 5.4.3.1 section, attempts to locate and load the class,
1061 * and then determines whether the class is accessible to this lookup object.
1062 * <p>
1063 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
1064 * its class loader, and the {@linkplain #lookupModes() lookup modes}.
1065 *
1066 * @param targetName the fully qualified name of the class to be looked up.
1067 * @return the requested class.
1068 * @throws SecurityException if a security manager is present and it
1069 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1070 * @throws LinkageError if the linkage fails
1071 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1072 * @throws IllegalAccessException if the class is not accessible, using the allowed access
1073 * modes.
1074 * @throws NullPointerException if {@code targetName} is null
1075 * @since 9
1076 * @jvms 5.4.3.1 Class and Interface Resolution
1077 * @hide
1078 */
1079 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1080 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1081 return accessClass(targetClass);
1082 }
1083 // END Android-added: Add findClass(String) from OpenJDK 17. http://b/270028670
1084
1085 private MethodHandle createMethodHandleForConstructor(Constructor constructor) {
1086 Class<?> refc = constructor.getDeclaringClass();
1087 MethodType constructorType =
1088 MethodType.methodType(refc, constructor.getParameterTypes());
1089 MethodHandle mh;
1090 if (refc == String.class) {
1091 // String constructors have optimized StringFactory methods
1092 // that matches returned type. These factory methods combine the
1093 // memory allocation and initialization calls for String objects.
1094 mh = new MethodHandleImpl(constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT,
1095 constructorType);
1096 } else {
1097 // Constructors for all other classes use a Construct transformer to perform
1098 // their memory allocation and call to <init>.
1099 MethodType initType = initMethodType(constructorType);
1100 MethodHandle initHandle = new MethodHandleImpl(
1101 constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT, initType);
1102 mh = new Transformers.Construct(initHandle, constructorType);
1103 }
1104
1105 if (constructor.isVarArgs()) {
1106 mh = new Transformers.VarargsCollector(mh);
1107 }
1108 return mh;
1109 }
1110
1111 private static MethodType initMethodType(MethodType constructorType) {
1112 // Returns a MethodType appropriate for class <init>
1113 // methods. Constructor MethodTypes have the form
1114 // (PT1,PT2,...)C and class <init> MethodTypes have the
1115 // form (C,PT1,PT2,...)V.
1116 assert constructorType.rtype() != void.class;
1117
1118 // Insert constructorType C as the first parameter type in
1119 // the MethodType for <init>.
1120 Class<?> [] initPtypes = new Class<?> [constructorType.ptypes().length + 1];
1121 initPtypes[0] = constructorType.rtype();
1122 System.arraycopy(constructorType.ptypes(), 0, initPtypes, 1,
1123 constructorType.ptypes().length);
1124
1125 // Set the return type for the <init> MethodType to be void.
1126 return MethodType.methodType(void.class, initPtypes);
1127 }
1128
1129 // BEGIN Android-added: Add accessClass(Class) from OpenJDK 17. http://b/270028670
1130 /*
1131 * Returns IllegalAccessException due to access violation to the given targetClass.
1132 *
1133 * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
1134 * which verifies access to a class rather a member.
1135 */
1136 private IllegalAccessException makeAccessException(Class<?> targetClass) {
1137 String message = "access violation: "+ targetClass;
1138 if (this == MethodHandles.publicLookup()) {
1139 message += ", from public Lookup";
1140 } else {
1141 // Android-changed: Remove unsupported module name.
1142 // Module m = lookupClass().getModule();
1143 // message += ", from " + lookupClass() + " (" + m + ")";
1144 message += ", from " + lookupClass();
1145 // Android-removed: Remove prevLookupClass until supported by Lookup in OpenJDK 17.
1146 // if (prevLookupClass != null) {
1147 // message += ", previous lookup " +
1148 // prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
1149 // }
1150 }
1151 return new IllegalAccessException(message);
1152 }
1153
1154 // TODO: Unhide this method.
1155 /**
1156 * Determines if a class can be accessed from the lookup context defined by
1157 * this {@code Lookup} object. The static initializer of the class is not run.
1158 * If {@code targetClass} is an array class, {@code targetClass} is accessible
1159 * if the element type of the array class is accessible. Otherwise,
1160 * {@code targetClass} is determined as accessible as follows.
1161 *
1162 * <p>
1163 * If {@code targetClass} is in the same module as the lookup class,
1164 * the lookup class is {@code LC} in module {@code M1} and
1165 * the previous lookup class is in module {@code M0} or
1166 * {@code null} if not present,
1167 * {@code targetClass} is accessible if and only if one of the following is true:
1168 * <ul>
1169 * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
1170 * {@code LC} or other class in the same nest of {@code LC}.</li>
1171 * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
1172 * in the same runtime package of {@code LC}.</li>
1173 * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
1174 * a public type in {@code M1}.</li>
1175 * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
1176 * a public type in a package exported by {@code M1} to at least {@code M0}
1177 * if the previous lookup class is present; otherwise, {@code targetClass}
1178 * is a public type in a package exported by {@code M1} unconditionally.</li>
1179 * </ul>
1180 *
1181 * <p>
1182 * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
1183 * can access public types in all modules when the type is in a package
1184 * that is exported unconditionally.
1185 * <p>
1186 * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
1187 * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
1188 * is inaccessible.
1189 * <p>
1190 * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
1191 * {@code M1} is the module containing {@code lookupClass} and
1192 * {@code M2} is the module containing {@code targetClass},
1193 * then {@code targetClass} is accessible if and only if
1194 * <ul>
1195 * <li>{@code M1} reads {@code M2}, and
1196 * <li>{@code targetClass} is public and in a package exported by
1197 * {@code M2} at least to {@code M1}.
1198 * </ul>
1199 * <p>
1200 * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
1201 * {@code M1} and {@code M2} are as before, and {@code M0} is the module
1202 * containing the previous lookup class, then {@code targetClass} is accessible
1203 * if and only if one of the following is true:
1204 * <ul>
1205 * <li>{@code targetClass} is in {@code M0} and {@code M1}
1206 * {@linkplain Module#reads reads} {@code M0} and the type is
1207 * in a package that is exported to at least {@code M1}.
1208 * <li>{@code targetClass} is in {@code M1} and {@code M0}
1209 * {@linkplain Module#reads reads} {@code M1} and the type is
1210 * in a package that is exported to at least {@code M0}.
1211 * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
1212 * and {@code M1} reads {@code M2} and the type is in a package
1213 * that is exported to at least both {@code M0} and {@code M2}.
1214 * </ul>
1215 * <p>
1216 * Otherwise, {@code targetClass} is not accessible.
1217 *
1218 * @param targetClass the class to be access-checked
1219 * @return the class that has been access-checked
1220 * @throws IllegalAccessException if the class is not accessible from the lookup class
1221 * and previous lookup class, if present, using the allowed access modes.
1222 * @throws SecurityException if a security manager is present and it
1223 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1224 * @throws NullPointerException if {@code targetClass} is {@code null}
1225 * @since 9
1226 * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1227 * @hide
1228 */
1229 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1230 if (!isClassAccessible(targetClass)) {
1231 throw makeAccessException(targetClass);
1232 }
1233 // Android-removed: SecurityManager is unnecessary on Android.
1234 // checkSecurityManager(targetClass);
1235 return targetClass;
1236 }
1237
1238 boolean isClassAccessible(Class<?> refc) {
1239 Objects.requireNonNull(refc);
1240 Class<?> caller = lookupClassOrNull();
1241 Class<?> type = refc;
1242 while (type.isArray()) {
1243 type = type.getComponentType();
1244 }
1245 // Android-removed: Remove prevLookupClass until supported by Lookup in OpenJDK 17.
1246 // return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
1247 return caller == null || VerifyAccess.isClassAccessible(type, caller, allowedModes);
1248 }
1249
1250 // This is just for calling out to MethodHandleImpl.
1251 private Class<?> lookupClassOrNull() {
1252 // Android-changed: Android always returns lookupClass and has no concept of TRUSTED.
1253 // return (allowedModes == TRUSTED) ? null : lookupClass;
1254 return lookupClass;
1255 }
1256 // END Android-added: Add accessClass(Class) from OpenJDK 17. http://b/270028670
1257
1258 /**
1259 * Produces an early-bound method handle for a virtual method.
1260 * It will bypass checks for overriding methods on the receiver,
1261 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1262 * instruction from within the explicitly specified {@code specialCaller}.
1263 * The type of the method handle will be that of the method,
1264 * with a suitably restricted receiver type prepended.
1265 * (The receiver type will be {@code specialCaller} or a subtype.)
1266 * The method and all its argument types must be accessible
1267 * to the lookup object.
1268 * <p>
1269 * Before method resolution,
1270 * if the explicitly specified caller class is not identical with the
1271 * lookup class, or if this lookup object does not have
1272 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1273 * privileges, the access fails.
1274 * <p>
1275 * The returned method handle will have
1276 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1277 * the method's variable arity modifier bit ({@code 0x0080}) is set.
1278 * <p style="font-size:smaller;">
1279 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API,
1280 * even though the {@code invokespecial} instruction can refer to them
1281 * in special circumstances. Use {@link #findConstructor findConstructor}
1282 * to access instance initialization methods in a safe manner.)</em>
1283 * <p><b>Example:</b>
1284 * <blockquote><pre>{@code
1285import static java.lang.invoke.MethodHandles.*;
1286import static java.lang.invoke.MethodType.*;
1287...
1288static class Listie extends ArrayList {
1289 public String toString() { return "[wee Listie]"; }
1290 static Lookup lookup() { return MethodHandles.lookup(); }
1291}
1292...
1293// no access to constructor via invokeSpecial:
1294MethodHandle MH_newListie = Listie.lookup()
1295 .findConstructor(Listie.class, methodType(void.class));
1296Listie l = (Listie) MH_newListie.invokeExact();
1297try { assertEquals("impossible", Listie.lookup().findSpecial(
1298 Listie.class, "<init>", methodType(void.class), Listie.class));
1299 } catch (NoSuchMethodException ex) { } // OK
1300// access to super and self methods via invokeSpecial:
1301MethodHandle MH_super = Listie.lookup().findSpecial(
1302 ArrayList.class, "toString" , methodType(String.class), Listie.class);
1303MethodHandle MH_this = Listie.lookup().findSpecial(
1304 Listie.class, "toString" , methodType(String.class), Listie.class);
1305MethodHandle MH_duper = Listie.lookup().findSpecial(
1306 Object.class, "toString" , methodType(String.class), Listie.class);
1307assertEquals("[]", (String) MH_super.invokeExact(l));
1308assertEquals(""+l, (String) MH_this.invokeExact(l));
1309assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1310try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1311 String.class, "toString", methodType(String.class), Listie.class));
1312 } catch (IllegalAccessException ex) { } // OK
1313Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1314assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1315 * }</pre></blockquote>
1316 *
1317 * @param refc the class or interface from which the method is accessed
1318 * @param name the name of the method (which must not be "&lt;init&gt;")
1319 * @param type the type of the method, with the receiver argument omitted
1320 * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1321 * @return the desired method handle
1322 * @throws NoSuchMethodException if the method does not exist
1323 * @throws IllegalAccessException if access checking fails
1324 * or if the method's variable arity modifier bit
1325 * is set and {@code asVarargsCollector} fails
1326 * @exception SecurityException if a security manager is present and it
1327 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1328 * @throws NullPointerException if any argument is null
1329 */
1330 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
1331 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
1332 if (specialCaller == null) {
1333 throw new NullPointerException("specialCaller == null");
1334 }
1335
1336 if (type == null) {
1337 throw new NullPointerException("type == null");
1338 }
1339
1340 if (name == null) {
1341 throw new NullPointerException("name == null");
1342 }
1343
1344 if (refc == null) {
1345 throw new NullPointerException("ref == null");
1346 }
1347
1348 // Make sure that the special caller is identical to the lookup class or that we have
1349 // private access.
1350 // Android-changed: Also allow access to any interface methods.
1351 checkSpecialCaller(specialCaller, refc);
1352
1353 // Even though constructors are invoked using a "special" invoke, handles to them can't
1354 // be created using findSpecial. Callers must use findConstructor instead. Similarly,
1355 // there is no path for calling static class initializers.
1356 if (name.startsWith("<")) {
1357 throw new NoSuchMethodException(name + " is not a valid method name.");
1358 }
1359
1360 Method method = refc.getDeclaredMethod(name, type.ptypes());
1361 checkReturnType(method, type);
1362 return findSpecial(method, type, refc, specialCaller);
1363 }
1364
1365 private MethodHandle findSpecial(Method method, MethodType type,
1366 Class<?> refc, Class<?> specialCaller)
1367 throws IllegalAccessException {
1368 if (Modifier.isStatic(method.getModifiers())) {
1369 throw new IllegalAccessException("expected a non-static method:" + method);
1370 }
1371
1372 if (Modifier.isPrivate(method.getModifiers())) {
1373 // Since this is a private method, we'll need to also make sure that the
1374 // lookup class is the same as the refering class. We've already checked that
1375 // the specialCaller is the same as the special lookup class, both of these must
1376 // be the same as the declaring class(*) in order to access the private method.
1377 //
1378 // (*) Well, this isn't true for nested classes but OpenJDK doesn't support those
1379 // either.
1380 if (refc != lookupClass()) {
1381 throw new IllegalAccessException("no private access for invokespecial : "
1382 + refc + ", from" + this);
1383 }
1384
1385 // This is a private method, so there's nothing special to do.
1386 MethodType handleType = type.insertParameterTypes(0, refc);
1387 return createMethodHandle(method, MethodHandle.INVOKE_DIRECT, handleType);
1388 }
1389
1390 // This is a public, protected or package-private method, which means we're expecting
1391 // invoke-super semantics. We'll have to restrict the receiver type appropriately on the
1392 // handle once we check that there really is a "super" relationship between them.
1393 if (!method.getDeclaringClass().isAssignableFrom(specialCaller)) {
1394 throw new IllegalAccessException(refc + "is not assignable from " + specialCaller);
1395 }
1396
1397 // Note that we restrict the receiver to "specialCaller" instances.
1398 MethodType handleType = type.insertParameterTypes(0, specialCaller);
1399 return createMethodHandle(method, MethodHandle.INVOKE_SUPER, handleType);
1400 }
1401
1402 /**
1403 * Produces a method handle giving read access to a non-static field.
1404 * The type of the method handle will have a return type of the field's
1405 * value type.
1406 * The method handle's single argument will be the instance containing
1407 * the field.
1408 * Access checking is performed immediately on behalf of the lookup class.
1409 * @param refc the class or interface from which the method is accessed
1410 * @param name the field's name
1411 * @param type the field's type
1412 * @return a method handle which can load values from the field
1413 * @throws NoSuchFieldException if the field does not exist
1414 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1415 * @exception SecurityException if a security manager is present and it
1416 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1417 * @throws NullPointerException if any argument is null
1418 */
1419 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1420 return findAccessor(refc, name, type, MethodHandle.IGET);
1421 }
1422
1423 private MethodHandle findAccessor(Class<?> refc, String name, Class<?> type, int kind)
1424 throws NoSuchFieldException, IllegalAccessException {
1425 final Field field = findFieldOfType(refc, name, type);
1426 return findAccessor(field, refc, type, kind, true /* performAccessChecks */);
1427 }
1428
1429 private MethodHandle findAccessor(Field field, Class<?> refc, Class<?> type, int kind,
1430 boolean performAccessChecks)
1431 throws IllegalAccessException {
1432 final boolean isSetterKind = kind == MethodHandle.IPUT || kind == MethodHandle.SPUT;
1433 final boolean isStaticKind = kind == MethodHandle.SGET || kind == MethodHandle.SPUT;
1434 commonFieldChecks(field, refc, type, isStaticKind, performAccessChecks);
1435 if (performAccessChecks) {
1436 final int modifiers = field.getModifiers();
1437 if (isSetterKind && Modifier.isFinal(modifiers)) {
1438 throw new IllegalAccessException("Field " + field + " is final");
1439 }
1440 }
1441
1442 final MethodType methodType;
1443 switch (kind) {
1444 case MethodHandle.SGET:
1445 methodType = MethodType.methodType(type);
1446 break;
1447 case MethodHandle.SPUT:
1448 methodType = MethodType.methodType(void.class, type);
1449 break;
1450 case MethodHandle.IGET:
1451 methodType = MethodType.methodType(type, refc);
1452 break;
1453 case MethodHandle.IPUT:
1454 methodType = MethodType.methodType(void.class, refc, type);
1455 break;
1456 default:
1457 throw new IllegalArgumentException("Invalid kind " + kind);
1458 }
1459 return new MethodHandleImpl(field.getArtField(), kind, methodType);
1460 }
1461
1462 /**
1463 * Produces a method handle giving write access to a non-static field.
1464 * The type of the method handle will have a void return type.
1465 * The method handle will take two arguments, the instance containing
1466 * the field, and the value to be stored.
1467 * The second argument will be of the field's value type.
1468 * Access checking is performed immediately on behalf of the lookup class.
1469 * @param refc the class or interface from which the method is accessed
1470 * @param name the field's name
1471 * @param type the field's type
1472 * @return a method handle which can store values into the field
1473 * @throws NoSuchFieldException if the field does not exist
1474 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1475 * @exception SecurityException if a security manager is present and it
1476 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1477 * @throws NullPointerException if any argument is null
1478 */
1479 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1480 return findAccessor(refc, name, type, MethodHandle.IPUT);
1481 }
1482
1483 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1484 /**
1485 * Produces a VarHandle giving access to a non-static field {@code name}
1486 * of type {@code type} declared in a class of type {@code recv}.
1487 * The VarHandle's variable type is {@code type} and it has one
1488 * coordinate type, {@code recv}.
1489 * <p>
1490 * Access checking is performed immediately on behalf of the lookup
1491 * class.
1492 * <p>
1493 * Certain access modes of the returned VarHandle are unsupported under
1494 * the following conditions:
1495 * <ul>
1496 * <li>if the field is declared {@code final}, then the write, atomic
1497 * update, numeric atomic update, and bitwise atomic update access
1498 * modes are unsupported.
1499 * <li>if the field type is anything other than {@code byte},
1500 * {@code short}, {@code char}, {@code int}, {@code long},
1501 * {@code float}, or {@code double} then numeric atomic update
1502 * access modes are unsupported.
1503 * <li>if the field type is anything other than {@code boolean},
1504 * {@code byte}, {@code short}, {@code char}, {@code int} or
1505 * {@code long} then bitwise atomic update access modes are
1506 * unsupported.
1507 * </ul>
1508 * <p>
1509 * If the field is declared {@code volatile} then the returned VarHandle
1510 * will override access to the field (effectively ignore the
1511 * {@code volatile} declaration) in accordance to its specified
1512 * access modes.
1513 * <p>
1514 * If the field type is {@code float} or {@code double} then numeric
1515 * and atomic update access modes compare values using their bitwise
1516 * representation (see {@link Float#floatToRawIntBits} and
1517 * {@link Double#doubleToRawLongBits}, respectively).
1518 * @apiNote
1519 * Bitwise comparison of {@code float} values or {@code double} values,
1520 * as performed by the numeric and atomic update access modes, differ
1521 * from the primitive {@code ==} operator and the {@link Float#equals}
1522 * and {@link Double#equals} methods, specifically with respect to
1523 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1524 * Care should be taken when performing a compare and set or a compare
1525 * and exchange operation with such values since the operation may
1526 * unexpectedly fail.
1527 * There are many possible NaN values that are considered to be
1528 * {@code NaN} in Java, although no IEEE 754 floating-point operation
1529 * provided by Java can distinguish between them. Operation failure can
1530 * occur if the expected or witness value is a NaN value and it is
1531 * transformed (perhaps in a platform specific manner) into another NaN
1532 * value, and thus has a different bitwise representation (see
1533 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1534 * details).
1535 * The values {@code -0.0} and {@code +0.0} have different bitwise
1536 * representations but are considered equal when using the primitive
1537 * {@code ==} operator. Operation failure can occur if, for example, a
1538 * numeric algorithm computes an expected value to be say {@code -0.0}
1539 * and previously computed the witness value to be say {@code +0.0}.
1540 * @param recv the receiver class, of type {@code R}, that declares the
1541 * non-static field
1542 * @param name the field's name
1543 * @param type the field's type, of type {@code T}
1544 * @return a VarHandle giving access to non-static fields.
1545 * @throws NoSuchFieldException if the field does not exist
1546 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1547 * @exception SecurityException if a security manager is present and it
1548 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1549 * @throws NullPointerException if any argument is null
1550 * @since 9
1551 */
1552 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1553 final Field field = findFieldOfType(recv, name, type);
1554 final boolean isStatic = false;
1555 final boolean performAccessChecks = true;
1556 commonFieldChecks(field, recv, type, isStatic, performAccessChecks);
1557 return FieldVarHandle.create(field);
1558 }
1559 // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
1560
1561 // BEGIN Android-added: Common field resolution and access check methods.
1562 private Field findFieldOfType(final Class<?> refc, String name, Class<?> type)
1563 throws NoSuchFieldException {
1564 Field field = null;
1565
1566 // Search refc and super classes for the field.
1567 for (Class<?> cls = refc; cls != null; cls = cls.getSuperclass()) {
1568 try {
1569 field = cls.getDeclaredField(name);
1570 break;
1571 } catch (NoSuchFieldException e) {
1572 }
1573 }
1574
1575 if (field == null) {
1576 // Force failure citing refc.
1577 field = refc.getDeclaredField(name);
1578 }
1579
1580 final Class<?> fieldType = field.getType();
1581 if (fieldType != type) {
1582 throw new NoSuchFieldException(name);
1583 }
1584 return field;
1585 }
1586
1587 private void commonFieldChecks(Field field, Class<?> refc, Class<?> type,
1588 boolean isStatic, boolean performAccessChecks)
1589 throws IllegalAccessException {
1590 final int modifiers = field.getModifiers();
1591 if (performAccessChecks) {
1592 checkAccess(refc, field.getDeclaringClass(), modifiers, field.getName());
1593 }
1594 if (Modifier.isStatic(modifiers) != isStatic) {
1595 String reason = "Field " + field + " is " +
1596 (isStatic ? "not " : "") + "static";
1597 throw new IllegalAccessException(reason);
1598 }
1599 }
1600 // END Android-added: Common field resolution and access check methods.
1601
1602 /**
1603 * Produces a method handle giving read access to a static field.
1604 * The type of the method handle will have a return type of the field's
1605 * value type.
1606 * The method handle will take no arguments.
1607 * Access checking is performed immediately on behalf of the lookup class.
1608 * <p>
1609 * If the returned method handle is invoked, the field's class will
1610 * be initialized, if it has not already been initialized.
1611 * @param refc the class or interface from which the method is accessed
1612 * @param name the field's name
1613 * @param type the field's type
1614 * @return a method handle which can load values from the field
1615 * @throws NoSuchFieldException if the field does not exist
1616 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1617 * @exception SecurityException if a security manager is present and it
1618 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1619 * @throws NullPointerException if any argument is null
1620 */
1621 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1622 return findAccessor(refc, name, type, MethodHandle.SGET);
1623 }
1624
1625 /**
1626 * Produces a method handle giving write access to a static field.
1627 * The type of the method handle will have a void return type.
1628 * The method handle will take a single
1629 * argument, of the field's value type, the value to be stored.
1630 * Access checking is performed immediately on behalf of the lookup class.
1631 * <p>
1632 * If the returned method handle is invoked, the field's class will
1633 * be initialized, if it has not already been initialized.
1634 * @param refc the class or interface from which the method is accessed
1635 * @param name the field's name
1636 * @param type the field's type
1637 * @return a method handle which can store values into the field
1638 * @throws NoSuchFieldException if the field does not exist
1639 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1640 * @exception SecurityException if a security manager is present and it
1641 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1642 * @throws NullPointerException if any argument is null
1643 */
1644 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1645 return findAccessor(refc, name, type, MethodHandle.SPUT);
1646 }
1647
1648 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1649 /**
1650 * Produces a VarHandle giving access to a static field {@code name} of
1651 * type {@code type} declared in a class of type {@code decl}.
1652 * The VarHandle's variable type is {@code type} and it has no
1653 * coordinate types.
1654 * <p>
1655 * Access checking is performed immediately on behalf of the lookup
1656 * class.
1657 * <p>
1658 * If the returned VarHandle is operated on, the declaring class will be
1659 * initialized, if it has not already been initialized.
1660 * <p>
1661 * Certain access modes of the returned VarHandle are unsupported under
1662 * the following conditions:
1663 * <ul>
1664 * <li>if the field is declared {@code final}, then the write, atomic
1665 * update, numeric atomic update, and bitwise atomic update access
1666 * modes are unsupported.
1667 * <li>if the field type is anything other than {@code byte},
1668 * {@code short}, {@code char}, {@code int}, {@code long},
1669 * {@code float}, or {@code double}, then numeric atomic update
1670 * access modes are unsupported.
1671 * <li>if the field type is anything other than {@code boolean},
1672 * {@code byte}, {@code short}, {@code char}, {@code int} or
1673 * {@code long} then bitwise atomic update access modes are
1674 * unsupported.
1675 * </ul>
1676 * <p>
1677 * If the field is declared {@code volatile} then the returned VarHandle
1678 * will override access to the field (effectively ignore the
1679 * {@code volatile} declaration) in accordance to its specified
1680 * access modes.
1681 * <p>
1682 * If the field type is {@code float} or {@code double} then numeric
1683 * and atomic update access modes compare values using their bitwise
1684 * representation (see {@link Float#floatToRawIntBits} and
1685 * {@link Double#doubleToRawLongBits}, respectively).
1686 * @apiNote
1687 * Bitwise comparison of {@code float} values or {@code double} values,
1688 * as performed by the numeric and atomic update access modes, differ
1689 * from the primitive {@code ==} operator and the {@link Float#equals}
1690 * and {@link Double#equals} methods, specifically with respect to
1691 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
1692 * Care should be taken when performing a compare and set or a compare
1693 * and exchange operation with such values since the operation may
1694 * unexpectedly fail.
1695 * There are many possible NaN values that are considered to be
1696 * {@code NaN} in Java, although no IEEE 754 floating-point operation
1697 * provided by Java can distinguish between them. Operation failure can
1698 * occur if the expected or witness value is a NaN value and it is
1699 * transformed (perhaps in a platform specific manner) into another NaN
1700 * value, and thus has a different bitwise representation (see
1701 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
1702 * details).
1703 * The values {@code -0.0} and {@code +0.0} have different bitwise
1704 * representations but are considered equal when using the primitive
1705 * {@code ==} operator. Operation failure can occur if, for example, a
1706 * numeric algorithm computes an expected value to be say {@code -0.0}
1707 * and previously computed the witness value to be say {@code +0.0}.
1708 * @param decl the class that declares the static field
1709 * @param name the field's name
1710 * @param type the field's type, of type {@code T}
1711 * @return a VarHandle giving access to a static field
1712 * @throws NoSuchFieldException if the field does not exist
1713 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1714 * @exception SecurityException if a security manager is present and it
1715 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1716 * @throws NullPointerException if any argument is null
1717 * @since 9
1718 */
1719 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1720 final Field field = findFieldOfType(decl, name, type);
1721 final boolean isStatic = true;
1722 final boolean performAccessChecks = true;
1723 commonFieldChecks(field, decl, type, isStatic, performAccessChecks);
1724 return StaticFieldVarHandle.create(field);
1725 }
1726 // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
1727
1728 /**
1729 * Produces an early-bound method handle for a non-static method.
1730 * The receiver must have a supertype {@code defc} in which a method
1731 * of the given name and type is accessible to the lookup class.
1732 * The method and all its argument types must be accessible to the lookup object.
1733 * The type of the method handle will be that of the method,
1734 * without any insertion of an additional receiver parameter.
1735 * The given receiver will be bound into the method handle,
1736 * so that every call to the method handle will invoke the
1737 * requested method on the given receiver.
1738 * <p>
1739 * The returned method handle will have
1740 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1741 * the method's variable arity modifier bit ({@code 0x0080}) is set
1742 * <em>and</em> the trailing array argument is not the only argument.
1743 * (If the trailing array argument is the only argument,
1744 * the given receiver value will be bound to it.)
1745 * <p>
1746 * This is equivalent to the following code:
1747 * <blockquote><pre>{@code
1748import static java.lang.invoke.MethodHandles.*;
1749import static java.lang.invoke.MethodType.*;
1750...
1751MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1752MethodHandle mh1 = mh0.bindTo(receiver);
1753MethodType mt1 = mh1.type();
1754if (mh0.isVarargsCollector())
1755 mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1));
1756return mh1;
1757 * }</pre></blockquote>
1758 * where {@code defc} is either {@code receiver.getClass()} or a super
1759 * type of that class, in which the requested method is accessible
1760 * to the lookup class.
1761 * (Note that {@code bindTo} does not preserve variable arity.)
1762 * @param receiver the object from which the method is accessed
1763 * @param name the name of the method
1764 * @param type the type of the method, with the receiver argument omitted
1765 * @return the desired method handle
1766 * @throws NoSuchMethodException if the method does not exist
1767 * @throws IllegalAccessException if access checking fails
1768 * or if the method's variable arity modifier bit
1769 * is set and {@code asVarargsCollector} fails
1770 * @exception SecurityException if a security manager is present and it
1771 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1772 * @throws NullPointerException if any argument is null
1773 * @see MethodHandle#bindTo
1774 * @see #findVirtual
1775 */
1776 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
1777 MethodHandle handle = findVirtual(receiver.getClass(), name, type);
1778 MethodHandle adapter = handle.bindTo(receiver);
1779 MethodType adapterType = adapter.type();
1780 if (handle.isVarargsCollector()) {
1781 adapter = adapter.asVarargsCollector(
1782 adapterType.parameterType(adapterType.parameterCount() - 1));
1783 }
1784
1785 return adapter;
1786 }
1787
1788 /**
1789 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1790 * to <i>m</i>, if the lookup class has permission.
1791 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1792 * If <i>m</i> is virtual, overriding is respected on every call.
1793 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1794 * The type of the method handle will be that of the method,
1795 * with the receiver type prepended (but only if it is non-static).
1796 * If the method's {@code accessible} flag is not set,
1797 * access checking is performed immediately on behalf of the lookup class.
1798 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
1799 * <p>
1800 * The returned method handle will have
1801 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1802 * the method's variable arity modifier bit ({@code 0x0080}) is set.
1803 * <p>
1804 * If <i>m</i> is static, and
1805 * if the returned method handle is invoked, the method's class will
1806 * be initialized, if it has not already been initialized.
1807 * @param m the reflected method
1808 * @return a method handle which can invoke the reflected method
1809 * @throws IllegalAccessException if access checking fails
1810 * or if the method's variable arity modifier bit
1811 * is set and {@code asVarargsCollector} fails
1812 * @throws NullPointerException if the argument is null
1813 */
1814 public MethodHandle unreflect(Method m) throws IllegalAccessException {
1815 if (m == null) {
1816 throw new NullPointerException("m == null");
1817 }
1818
1819 MethodType methodType = MethodType.methodType(m.getReturnType(),
1820 m.getParameterTypes());
1821
1822 // We should only perform access checks if setAccessible hasn't been called yet.
1823 if (!m.isAccessible()) {
1824 checkAccess(m.getDeclaringClass(), m.getDeclaringClass(), m.getModifiers(),
1825 m.getName());
1826 }
1827
1828 if (Modifier.isStatic(m.getModifiers())) {
1829 return createMethodHandle(m, MethodHandle.INVOKE_STATIC, methodType);
1830 } else {
1831 methodType = methodType.insertParameterTypes(0, m.getDeclaringClass());
1832 return createMethodHandle(m, MethodHandle.INVOKE_VIRTUAL, methodType);
1833 }
1834 }
1835
1836 /**
1837 * Produces a method handle for a reflected method.
1838 * It will bypass checks for overriding methods on the receiver,
1839 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1840 * instruction from within the explicitly specified {@code specialCaller}.
1841 * The type of the method handle will be that of the method,
1842 * with a suitably restricted receiver type prepended.
1843 * (The receiver type will be {@code specialCaller} or a subtype.)
1844 * If the method's {@code accessible} flag is not set,
1845 * access checking is performed immediately on behalf of the lookup class,
1846 * as if {@code invokespecial} instruction were being linked.
1847 * <p>
1848 * Before method resolution,
1849 * if the explicitly specified caller class is not identical with the
1850 * lookup class, or if this lookup object does not have
1851 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1852 * privileges, the access fails.
1853 * <p>
1854 * The returned method handle will have
1855 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1856 * the method's variable arity modifier bit ({@code 0x0080}) is set.
1857 * @param m the reflected method
1858 * @param specialCaller the class nominally calling the method
1859 * @return a method handle which can invoke the reflected method
1860 * @throws IllegalAccessException if access checking fails
1861 * or if the method's variable arity modifier bit
1862 * is set and {@code asVarargsCollector} fails
1863 * @throws NullPointerException if any argument is null
1864 */
1865 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
1866 if (m == null) {
1867 throw new NullPointerException("m == null");
1868 }
1869
1870 if (specialCaller == null) {
1871 throw new NullPointerException("specialCaller == null");
1872 }
1873
1874 if (!m.isAccessible()) {
1875 // Android-changed: Match Java language 9 behavior where unreflectSpecial continues
1876 // to require exact caller lookupClass match.
1877 checkSpecialCaller(specialCaller, null);
1878 }
1879
1880 final MethodType methodType = MethodType.methodType(m.getReturnType(),
1881 m.getParameterTypes());
1882 return findSpecial(m, methodType, m.getDeclaringClass() /* refc */, specialCaller);
1883 }
1884
1885 /**
1886 * Produces a method handle for a reflected constructor.
1887 * The type of the method handle will be that of the constructor,
1888 * with the return type changed to the declaring class.
1889 * The method handle will perform a {@code newInstance} operation,
1890 * creating a new instance of the constructor's class on the
1891 * arguments passed to the method handle.
1892 * <p>
1893 * If the constructor's {@code accessible} flag is not set,
1894 * access checking is performed immediately on behalf of the lookup class.
1895 * <p>
1896 * The returned method handle will have
1897 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1898 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
1899 * <p>
1900 * If the returned method handle is invoked, the constructor's class will
1901 * be initialized, if it has not already been initialized.
1902 * @param c the reflected constructor
1903 * @return a method handle which can invoke the reflected constructor
1904 * @throws IllegalAccessException if access checking fails
1905 * or if the method's variable arity modifier bit
1906 * is set and {@code asVarargsCollector} fails
1907 * @throws NullPointerException if the argument is null
1908 */
1909 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
1910 if (c == null) {
1911 throw new NullPointerException("c == null");
1912 }
1913
1914 if (!c.isAccessible()) {
1915 checkAccess(c.getDeclaringClass(), c.getDeclaringClass(), c.getModifiers(),
1916 c.getName());
1917 }
1918
1919 return createMethodHandleForConstructor(c);
1920 }
1921
1922 /**
1923 * Produces a method handle giving read access to a reflected field.
1924 * The type of the method handle will have a return type of the field's
1925 * value type.
1926 * If the field is static, the method handle will take no arguments.
1927 * Otherwise, its single argument will be the instance containing
1928 * the field.
1929 * If the field's {@code accessible} flag is not set,
1930 * access checking is performed immediately on behalf of the lookup class.
1931 * <p>
1932 * If the field is static, and
1933 * if the returned method handle is invoked, the field's class will
1934 * be initialized, if it has not already been initialized.
1935 * @param f the reflected field
1936 * @return a method handle which can load values from the reflected field
1937 * @throws IllegalAccessException if access checking fails
1938 * @throws NullPointerException if the argument is null
1939 */
1940 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
1941 return findAccessor(f, f.getDeclaringClass(), f.getType(),
1942 Modifier.isStatic(f.getModifiers()) ? MethodHandle.SGET : MethodHandle.IGET,
1943 !f.isAccessible() /* performAccessChecks */);
1944 }
1945
1946 /**
1947 * Produces a method handle giving write access to a reflected field.
1948 * The type of the method handle will have a void return type.
1949 * If the field is static, the method handle will take a single
1950 * argument, of the field's value type, the value to be stored.
1951 * Otherwise, the two arguments will be the instance containing
1952 * the field, and the value to be stored.
1953 * If the field's {@code accessible} flag is not set,
1954 * access checking is performed immediately on behalf of the lookup class.
1955 * <p>
1956 * If the field is static, and
1957 * if the returned method handle is invoked, the field's class will
1958 * be initialized, if it has not already been initialized.
1959 * @param f the reflected field
1960 * @return a method handle which can store values into the reflected field
1961 * @throws IllegalAccessException if access checking fails
1962 * @throws NullPointerException if the argument is null
1963 */
1964 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
1965 return findAccessor(f, f.getDeclaringClass(), f.getType(),
1966 Modifier.isStatic(f.getModifiers()) ? MethodHandle.SPUT : MethodHandle.IPUT,
1967 !f.isAccessible() /* performAccessChecks */);
1968 }
1969
1970 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method.
1971 /**
1972 * Produces a VarHandle giving access to a reflected field {@code f}
1973 * of type {@code T} declared in a class of type {@code R}.
1974 * The VarHandle's variable type is {@code T}.
1975 * If the field is non-static the VarHandle has one coordinate type,
1976 * {@code R}. Otherwise, the field is static, and the VarHandle has no
1977 * coordinate types.
1978 * <p>
1979 * Access checking is performed immediately on behalf of the lookup
1980 * class, regardless of the value of the field's {@code accessible}
1981 * flag.
1982 * <p>
1983 * If the field is static, and if the returned VarHandle is operated
1984 * on, the field's declaring class will be initialized, if it has not
1985 * already been initialized.
1986 * <p>
1987 * Certain access modes of the returned VarHandle are unsupported under
1988 * the following conditions:
1989 * <ul>
1990 * <li>if the field is declared {@code final}, then the write, atomic
1991 * update, numeric atomic update, and bitwise atomic update access
1992 * modes are unsupported.
1993 * <li>if the field type is anything other than {@code byte},
1994 * {@code short}, {@code char}, {@code int}, {@code long},
1995 * {@code float}, or {@code double} then numeric atomic update
1996 * access modes are unsupported.
1997 * <li>if the field type is anything other than {@code boolean},
1998 * {@code byte}, {@code short}, {@code char}, {@code int} or
1999 * {@code long} then bitwise atomic update access modes are
2000 * unsupported.
2001 * </ul>
2002 * <p>
2003 * If the field is declared {@code volatile} then the returned VarHandle
2004 * will override access to the field (effectively ignore the
2005 * {@code volatile} declaration) in accordance to its specified
2006 * access modes.
2007 * <p>
2008 * If the field type is {@code float} or {@code double} then numeric
2009 * and atomic update access modes compare values using their bitwise
2010 * representation (see {@link Float#floatToRawIntBits} and
2011 * {@link Double#doubleToRawLongBits}, respectively).
2012 * @apiNote
2013 * Bitwise comparison of {@code float} values or {@code double} values,
2014 * as performed by the numeric and atomic update access modes, differ
2015 * from the primitive {@code ==} operator and the {@link Float#equals}
2016 * and {@link Double#equals} methods, specifically with respect to
2017 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2018 * Care should be taken when performing a compare and set or a compare
2019 * and exchange operation with such values since the operation may
2020 * unexpectedly fail.
2021 * There are many possible NaN values that are considered to be
2022 * {@code NaN} in Java, although no IEEE 754 floating-point operation
2023 * provided by Java can distinguish between them. Operation failure can
2024 * occur if the expected or witness value is a NaN value and it is
2025 * transformed (perhaps in a platform specific manner) into another NaN
2026 * value, and thus has a different bitwise representation (see
2027 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2028 * details).
2029 * The values {@code -0.0} and {@code +0.0} have different bitwise
2030 * representations but are considered equal when using the primitive
2031 * {@code ==} operator. Operation failure can occur if, for example, a
2032 * numeric algorithm computes an expected value to be say {@code -0.0}
2033 * and previously computed the witness value to be say {@code +0.0}.
2034 * @param f the reflected field, with a field of type {@code T}, and
2035 * a declaring class of type {@code R}
2036 * @return a VarHandle giving access to non-static fields or a static
2037 * field
2038 * @throws IllegalAccessException if access checking fails
2039 * @throws NullPointerException if the argument is null
2040 * @since 9
2041 */
2042 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
2043 final boolean isStatic = Modifier.isStatic(f.getModifiers());
2044 final boolean performAccessChecks = true;
2045 commonFieldChecks(f, f.getDeclaringClass(), f.getType(), isStatic, performAccessChecks);
2046 return isStatic ? StaticFieldVarHandle.create(f) : FieldVarHandle.create(f);
2047 }
2048 // END Android-changed: OpenJDK 9+181 VarHandle API factory method.
2049
2050 /**
2051 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
2052 * created by this lookup object or a similar one.
2053 * Security and access checks are performed to ensure that this lookup object
2054 * is capable of reproducing the target method handle.
2055 * This means that the cracking may fail if target is a direct method handle
2056 * but was created by an unrelated lookup object.
2057 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
2058 * and was created by a lookup object for a different class.
2059 * @param target a direct method handle to crack into symbolic reference components
2060 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
2061 * @exception SecurityException if a security manager is present and it
2062 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2063 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
2064 * @exception NullPointerException if the target is {@code null}
2065 * @see MethodHandleInfo
2066 * @since 1.8
2067 */
2068 public MethodHandleInfo revealDirect(MethodHandle target) {
2069 MethodHandleImpl directTarget = getMethodHandleImpl(target);
2070 MethodHandleInfo info = directTarget.reveal();
2071
2072 try {
2073 checkAccess(lookupClass(), info.getDeclaringClass(), info.getModifiers(),
2074 info.getName());
2075 } catch (IllegalAccessException exception) {
2076 throw new IllegalArgumentException("Unable to access memeber.", exception);
2077 }
2078
2079 return info;
2080 }
2081
2082 private boolean hasPrivateAccess() {
2083 return (allowedModes & PRIVATE) != 0;
2084 }
2085
2086 /** Check public/protected/private bits on the symbolic reference class and its member. */
2087 void checkAccess(Class<?> refc, Class<?> defc, int mods, String methName)
2088 throws IllegalAccessException {
2089 int allowedModes = this.allowedModes;
2090
2091 if (Modifier.isProtected(mods) &&
2092 defc == Object.class &&
2093 "clone".equals(methName) &&
2094 refc.isArray()) {
2095 // The JVM does this hack also.
2096 // (See ClassVerifier::verify_invoke_instructions
2097 // and LinkResolver::check_method_accessability.)
2098 // Because the JVM does not allow separate methods on array types,
2099 // there is no separate method for int[].clone.
2100 // All arrays simply inherit Object.clone.
2101 // But for access checking logic, we make Object.clone
2102 // (normally protected) appear to be public.
2103 // Later on, when the DirectMethodHandle is created,
2104 // its leading argument will be restricted to the
2105 // requested array type.
2106 // N.B. The return type is not adjusted, because
2107 // that is *not* the bytecode behavior.
2108 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
2109 }
2110
2111 if (Modifier.isProtected(mods) && Modifier.isConstructor(mods)) {
2112 // cannot "new" a protected ctor in a different package
2113 mods ^= Modifier.PROTECTED;
2114 }
2115
2116 if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0)
2117 return; // common case
2118 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
2119 if ((requestedModes & allowedModes) != 0) {
2120 if (VerifyAccess.isMemberAccessible(refc, defc, mods, lookupClass(), allowedModes))
2121 return;
2122 } else {
2123 // Protected members can also be checked as if they were package-private.
2124 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
2125 && VerifyAccess.isSamePackage(defc, lookupClass()))
2126 return;
2127 }
2128
2129 throwMakeAccessException(accessFailedMessage(refc, defc, mods), this);
2130 }
2131
2132 String accessFailedMessage(Class<?> refc, Class<?> defc, int mods) {
2133 // check the class first:
2134 boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
2135 (defc == refc ||
2136 Modifier.isPublic(refc.getModifiers())));
2137 if (!classOK && (allowedModes & PACKAGE) != 0) {
2138 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
2139 (defc == refc ||
2140 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
2141 }
2142 if (!classOK)
2143 return "class is not public";
2144 if (Modifier.isPublic(mods))
2145 return "access to public member failed"; // (how?)
2146 if (Modifier.isPrivate(mods))
2147 return "member is private";
2148 if (Modifier.isProtected(mods))
2149 return "member is protected";
2150 return "member is private to package";
2151 }
2152
2153 // Android-changed: checkSpecialCaller assumes that ALLOW_NESTMATE_ACCESS = false,
2154 // as in upstream OpenJDK.
2155 //
2156 // private static final boolean ALLOW_NESTMATE_ACCESS = false;
2157
2158 // Android-changed: Match java language 9 behavior allowing special access if the reflected
2159 // class (called 'refc', the class from which the method is being accessed) is an interface
2160 // and is implemented by the caller.
2161 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
2162 // Android-changed: No support for TRUSTED lookups. Also construct the
2163 // IllegalAccessException by hand because the upstream code implicitly assumes
2164 // that the lookupClass == specialCaller.
2165 //
2166 // if (allowedModes == TRUSTED) return;
2167 boolean isInterfaceLookup = (refc != null &&
2168 refc.isInterface() &&
2169 refc.isAssignableFrom(specialCaller));
2170 if (!hasPrivateAccess() || (specialCaller != lookupClass() && !isInterfaceLookup)) {
2171 throw new IllegalAccessException("no private access for invokespecial : "
2172 + specialCaller + ", from" + this);
2173 }
2174 }
2175
2176 private void throwMakeAccessException(String message, Object from) throws
2177 IllegalAccessException{
2178 message = message + ": "+ toString();
2179 if (from != null) message += ", from " + from;
2180 throw new IllegalAccessException(message);
2181 }
2182
2183 private void checkReturnType(Method method, MethodType methodType)
2184 throws NoSuchMethodException {
2185 if (method.getReturnType() != methodType.rtype()) {
2186 throw new NoSuchMethodException(method.getName() + methodType);
2187 }
2188 }
2189 }
2190
2191 /**
2192 * "Cracks" {@code target} to reveal the underlying {@code MethodHandleImpl}.
2193 */
2194 private static MethodHandleImpl getMethodHandleImpl(MethodHandle target) {
2195 // Special case : We implement handles to constructors as transformers,
2196 // so we must extract the underlying handle from the transformer.
2197 if (target instanceof Transformers.Construct) {
2198 target = ((Transformers.Construct) target).getConstructorHandle();
2199 }
2200
2201 // Special case: Var-args methods are also implemented as Transformers,
2202 // so we should get the underlying handle in that case as well.
2203 if (target instanceof Transformers.VarargsCollector) {
2204 target = target.asFixedArity();
2205 }
2206
2207 if (target instanceof MethodHandleImpl) {
2208 return (MethodHandleImpl) target;
2209 }
2210
2211 throw new IllegalArgumentException(target + " is not a direct handle");
2212 }
2213
2214 // Android-removed: unsupported @jvms tag in doc-comment.
2215 /**
2216 * Produces a method handle constructing arrays of a desired type,
2217 * as if by the {@code anewarray} bytecode.
2218 * The return type of the method handle will be the array type.
2219 * The type of its sole argument will be {@code int}, which specifies the size of the array.
2220 *
2221 * <p> If the returned method handle is invoked with a negative
2222 * array size, a {@code NegativeArraySizeException} will be thrown.
2223 *
2224 * @param arrayClass an array type
2225 * @return a method handle which can create arrays of the given type
2226 * @throws NullPointerException if the argument is {@code null}
2227 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2228 * @see java.lang.reflect.Array#newInstance(Class, int)
2229 * @since 9
2230 */
2231 public static
2232 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2233 if (!arrayClass.isArray()) {
2234 throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2235 }
2236 // Android-changed: transformer based implementation.
2237 // MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2238 // bindTo(arrayClass.getComponentType());
2239 // return ani.asType(ani.type().changeReturnType(arrayClass))
2240 return new Transformers.ArrayConstructor(arrayClass);
2241 }
2242
2243 // Android-removed: unsupported @jvms tag in doc-comment.
2244 /**
2245 * Produces a method handle returning the length of an array,
2246 * as if by the {@code arraylength} bytecode.
2247 * The type of the method handle will have {@code int} as return type,
2248 * and its sole argument will be the array type.
2249 *
2250 * <p> If the returned method handle is invoked with a {@code null}
2251 * array reference, a {@code NullPointerException} will be thrown.
2252 *
2253 * @param arrayClass an array type
2254 * @return a method handle which can retrieve the length of an array of the given array type
2255 * @throws NullPointerException if the argument is {@code null}
2256 * @throws IllegalArgumentException if arrayClass is not an array type
2257 * @since 9
2258 */
2259 public static
2260 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
2261 // Android-changed: transformer based implementation.
2262 // return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
2263 if (!arrayClass.isArray()) {
2264 throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2265 }
2266 return new Transformers.ArrayLength(arrayClass);
2267 }
2268
2269 // BEGIN Android-added: method to check if a class is an array.
2270 private static void checkClassIsArray(Class<?> c) {
2271 if (!c.isArray()) {
2272 throw new IllegalArgumentException("Not an array type: " + c);
2273 }
2274 }
2275
2276 private static void checkTypeIsViewable(Class<?> componentType) {
2277 if (componentType == short.class ||
2278 componentType == char.class ||
2279 componentType == int.class ||
2280 componentType == long.class ||
2281 componentType == float.class ||
2282 componentType == double.class) {
2283 return;
2284 }
2285 throw new UnsupportedOperationException("Component type not supported: " + componentType);
2286 }
2287 // END Android-added: method to check if a class is an array.
2288
2289 /**
2290 * Produces a method handle giving read access to elements of an array.
2291 * The type of the method handle will have a return type of the array's
2292 * element type. Its first argument will be the array type,
2293 * and the second will be {@code int}.
2294 * @param arrayClass an array type
2295 * @return a method handle which can load values from the given array type
2296 * @throws NullPointerException if the argument is null
2297 * @throws IllegalArgumentException if arrayClass is not an array type
2298 */
2299 public static
2300 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
2301 checkClassIsArray(arrayClass);
2302 final Class<?> componentType = arrayClass.getComponentType();
2303 if (componentType.isPrimitive()) {
2304 try {
2305 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class,
2306 "arrayElementGetter",
2307 MethodType.methodType(componentType, arrayClass, int.class));
2308 } catch (NoSuchMethodException | IllegalAccessException exception) {
2309 throw new AssertionError(exception);
2310 }
2311 }
2312
2313 return new Transformers.ReferenceArrayElementGetter(arrayClass);
2314 }
2315
2316 /** @hide */ public static byte arrayElementGetter(byte[] array, int i) { return array[i]; }
2317 /** @hide */ public static boolean arrayElementGetter(boolean[] array, int i) { return array[i]; }
2318 /** @hide */ public static char arrayElementGetter(char[] array, int i) { return array[i]; }
2319 /** @hide */ public static short arrayElementGetter(short[] array, int i) { return array[i]; }
2320 /** @hide */ public static int arrayElementGetter(int[] array, int i) { return array[i]; }
2321 /** @hide */ public static long arrayElementGetter(long[] array, int i) { return array[i]; }
2322 /** @hide */ public static float arrayElementGetter(float[] array, int i) { return array[i]; }
2323 /** @hide */ public static double arrayElementGetter(double[] array, int i) { return array[i]; }
2324
2325 /**
2326 * Produces a method handle giving write access to elements of an array.
2327 * The type of the method handle will have a void return type.
2328 * Its last argument will be the array's element type.
2329 * The first and second arguments will be the array type and int.
2330 * @param arrayClass the class of an array
2331 * @return a method handle which can store values into the array type
2332 * @throws NullPointerException if the argument is null
2333 * @throws IllegalArgumentException if arrayClass is not an array type
2334 */
2335 public static
2336 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
2337 checkClassIsArray(arrayClass);
2338 final Class<?> componentType = arrayClass.getComponentType();
2339 if (componentType.isPrimitive()) {
2340 try {
2341 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class,
2342 "arrayElementSetter",
2343 MethodType.methodType(void.class, arrayClass, int.class, componentType));
2344 } catch (NoSuchMethodException | IllegalAccessException exception) {
2345 throw new AssertionError(exception);
2346 }
2347 }
2348
2349 return new Transformers.ReferenceArrayElementSetter(arrayClass);
2350 }
2351
2352 /** @hide */
2353 public static void arrayElementSetter(byte[] array, int i, byte val) { array[i] = val; }
2354 /** @hide */
2355 public static void arrayElementSetter(boolean[] array, int i, boolean val) { array[i] = val; }
2356 /** @hide */
2357 public static void arrayElementSetter(char[] array, int i, char val) { array[i] = val; }
2358 /** @hide */
2359 public static void arrayElementSetter(short[] array, int i, short val) { array[i] = val; }
2360 /** @hide */
2361 public static void arrayElementSetter(int[] array, int i, int val) { array[i] = val; }
2362 /** @hide */
2363 public static void arrayElementSetter(long[] array, int i, long val) { array[i] = val; }
2364 /** @hide */
2365 public static void arrayElementSetter(float[] array, int i, float val) { array[i] = val; }
2366 /** @hide */
2367 public static void arrayElementSetter(double[] array, int i, double val) { array[i] = val; }
2368
2369 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory methods.
2370 /**
2371 * Produces a VarHandle giving access to elements of an array of type
2372 * {@code arrayClass}. The VarHandle's variable type is the component type
2373 * of {@code arrayClass} and the list of coordinate types is
2374 * {@code (arrayClass, int)}, where the {@code int} coordinate type
2375 * corresponds to an argument that is an index into an array.
2376 * <p>
2377 * Certain access modes of the returned VarHandle are unsupported under
2378 * the following conditions:
2379 * <ul>
2380 * <li>if the component type is anything other than {@code byte},
2381 * {@code short}, {@code char}, {@code int}, {@code long},
2382 * {@code float}, or {@code double} then numeric atomic update access
2383 * modes are unsupported.
2384 * <li>if the field type is anything other than {@code boolean},
2385 * {@code byte}, {@code short}, {@code char}, {@code int} or
2386 * {@code long} then bitwise atomic update access modes are
2387 * unsupported.
2388 * </ul>
2389 * <p>
2390 * If the component type is {@code float} or {@code double} then numeric
2391 * and atomic update access modes compare values using their bitwise
2392 * representation (see {@link Float#floatToRawIntBits} and
2393 * {@link Double#doubleToRawLongBits}, respectively).
2394 * @apiNote
2395 * Bitwise comparison of {@code float} values or {@code double} values,
2396 * as performed by the numeric and atomic update access modes, differ
2397 * from the primitive {@code ==} operator and the {@link Float#equals}
2398 * and {@link Double#equals} methods, specifically with respect to
2399 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
2400 * Care should be taken when performing a compare and set or a compare
2401 * and exchange operation with such values since the operation may
2402 * unexpectedly fail.
2403 * There are many possible NaN values that are considered to be
2404 * {@code NaN} in Java, although no IEEE 754 floating-point operation
2405 * provided by Java can distinguish between them. Operation failure can
2406 * occur if the expected or witness value is a NaN value and it is
2407 * transformed (perhaps in a platform specific manner) into another NaN
2408 * value, and thus has a different bitwise representation (see
2409 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
2410 * details).
2411 * The values {@code -0.0} and {@code +0.0} have different bitwise
2412 * representations but are considered equal when using the primitive
2413 * {@code ==} operator. Operation failure can occur if, for example, a
2414 * numeric algorithm computes an expected value to be say {@code -0.0}
2415 * and previously computed the witness value to be say {@code +0.0}.
2416 * @param arrayClass the class of an array, of type {@code T[]}
2417 * @return a VarHandle giving access to elements of an array
2418 * @throws NullPointerException if the arrayClass is null
2419 * @throws IllegalArgumentException if arrayClass is not an array type
2420 * @since 9
2421 */
2422 public static
2423 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2424 checkClassIsArray(arrayClass);
2425 return ArrayElementVarHandle.create(arrayClass);
2426 }
2427
2428 /**
2429 * Produces a VarHandle giving access to elements of a {@code byte[]} array
2430 * viewed as if it were a different primitive array type, such as
2431 * {@code int[]} or {@code long[]}.
2432 * The VarHandle's variable type is the component type of
2433 * {@code viewArrayClass} and the list of coordinate types is
2434 * {@code (byte[], int)}, where the {@code int} coordinate type
2435 * corresponds to an argument that is an index into a {@code byte[]} array.
2436 * The returned VarHandle accesses bytes at an index in a {@code byte[]}
2437 * array, composing bytes to or from a value of the component type of
2438 * {@code viewArrayClass} according to the given endianness.
2439 * <p>
2440 * The supported component types (variables types) are {@code short},
2441 * {@code char}, {@code int}, {@code long}, {@code float} and
2442 * {@code double}.
2443 * <p>
2444 * Access of bytes at a given index will result in an
2445 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2446 * or greater than the {@code byte[]} array length minus the size (in bytes)
2447 * of {@code T}.
2448 * <p>
2449 * Access of bytes at an index may be aligned or misaligned for {@code T},
2450 * with respect to the underlying memory address, {@code A} say, associated
2451 * with the array and index.
2452 * If access is misaligned then access for anything other than the
2453 * {@code get} and {@code set} access modes will result in an
2454 * {@code IllegalStateException}. In such cases atomic access is only
2455 * guaranteed with respect to the largest power of two that divides the GCD
2456 * of {@code A} and the size (in bytes) of {@code T}.
2457 * If access is aligned then following access modes are supported and are
2458 * guaranteed to support atomic access:
2459 * <ul>
2460 * <li>read write access modes for all {@code T}, with the exception of
2461 * access modes {@code get} and {@code set} for {@code long} and
2462 * {@code double} on 32-bit platforms.
2463 * <li>atomic update access modes for {@code int}, {@code long},
2464 * {@code float} or {@code double}.
2465 * (Future major platform releases of the JDK may support additional
2466 * types for certain currently unsupported access modes.)
2467 * <li>numeric atomic update access modes for {@code int} and {@code long}.
2468 * (Future major platform releases of the JDK may support additional
2469 * numeric types for certain currently unsupported access modes.)
2470 * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2471 * (Future major platform releases of the JDK may support additional
2472 * numeric types for certain currently unsupported access modes.)
2473 * </ul>
2474 * <p>
2475 * Misaligned access, and therefore atomicity guarantees, may be determined
2476 * for {@code byte[]} arrays without operating on a specific array. Given
2477 * an {@code index}, {@code T} and it's corresponding boxed type,
2478 * {@code T_BOX}, misalignment may be determined as follows:
2479 * <pre>{@code
2480 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
2481 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2482 * alignmentOffset(0, sizeOfT);
2483 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2484 * boolean isMisaligned = misalignedAtIndex != 0;
2485 * }</pre>
2486 * <p>
2487 * If the variable type is {@code float} or {@code double} then atomic
2488 * update access modes compare values using their bitwise representation
2489 * (see {@link Float#floatToRawIntBits} and
2490 * {@link Double#doubleToRawLongBits}, respectively).
2491 * @param viewArrayClass the view array class, with a component type of
2492 * type {@code T}
2493 * @param byteOrder the endianness of the view array elements, as
2494 * stored in the underlying {@code byte} array
2495 * @return a VarHandle giving access to elements of a {@code byte[]} array
2496 * viewed as if elements corresponding to the components type of the view
2497 * array class
2498 * @throws NullPointerException if viewArrayClass or byteOrder is null
2499 * @throws IllegalArgumentException if viewArrayClass is not an array type
2500 * @throws UnsupportedOperationException if the component type of
2501 * viewArrayClass is not supported as a variable type
2502 * @since 9
2503 */
2504 public static
2505 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
2506 ByteOrder byteOrder) throws IllegalArgumentException {
2507 checkClassIsArray(viewArrayClass);
2508 checkTypeIsViewable(viewArrayClass.getComponentType());
2509 return ByteArrayViewVarHandle.create(viewArrayClass, byteOrder);
2510 }
2511
2512 /**
2513 * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2514 * viewed as if it were an array of elements of a different primitive
2515 * component type to that of {@code byte}, such as {@code int[]} or
2516 * {@code long[]}.
2517 * The VarHandle's variable type is the component type of
2518 * {@code viewArrayClass} and the list of coordinate types is
2519 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
2520 * corresponds to an argument that is an index into a {@code byte[]} array.
2521 * The returned VarHandle accesses bytes at an index in a
2522 * {@code ByteBuffer}, composing bytes to or from a value of the component
2523 * type of {@code viewArrayClass} according to the given endianness.
2524 * <p>
2525 * The supported component types (variables types) are {@code short},
2526 * {@code char}, {@code int}, {@code long}, {@code float} and
2527 * {@code double}.
2528 * <p>
2529 * Access will result in a {@code ReadOnlyBufferException} for anything
2530 * other than the read access modes if the {@code ByteBuffer} is read-only.
2531 * <p>
2532 * Access of bytes at a given index will result in an
2533 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2534 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2535 * {@code T}.
2536 * <p>
2537 * Access of bytes at an index may be aligned or misaligned for {@code T},
2538 * with respect to the underlying memory address, {@code A} say, associated
2539 * with the {@code ByteBuffer} and index.
2540 * If access is misaligned then access for anything other than the
2541 * {@code get} and {@code set} access modes will result in an
2542 * {@code IllegalStateException}. In such cases atomic access is only
2543 * guaranteed with respect to the largest power of two that divides the GCD
2544 * of {@code A} and the size (in bytes) of {@code T}.
2545 * If access is aligned then following access modes are supported and are
2546 * guaranteed to support atomic access:
2547 * <ul>
2548 * <li>read write access modes for all {@code T}, with the exception of
2549 * access modes {@code get} and {@code set} for {@code long} and
2550 * {@code double} on 32-bit platforms.
2551 * <li>atomic update access modes for {@code int}, {@code long},
2552 * {@code float} or {@code double}.
2553 * (Future major platform releases of the JDK may support additional
2554 * types for certain currently unsupported access modes.)
2555 * <li>numeric atomic update access modes for {@code int} and {@code long}.
2556 * (Future major platform releases of the JDK may support additional
2557 * numeric types for certain currently unsupported access modes.)
2558 * <li>bitwise atomic update access modes for {@code int} and {@code long}.
2559 * (Future major platform releases of the JDK may support additional
2560 * numeric types for certain currently unsupported access modes.)
2561 * </ul>
2562 * <p>
2563 * Misaligned access, and therefore atomicity guarantees, may be determined
2564 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2565 * {@code index}, {@code T} and it's corresponding boxed type,
2566 * {@code T_BOX}, as follows:
2567 * <pre>{@code
2568 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
2569 * ByteBuffer bb = ...
2570 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2571 * boolean isMisaligned = misalignedAtIndex != 0;
2572 * }</pre>
2573 * <p>
2574 * If the variable type is {@code float} or {@code double} then atomic
2575 * update access modes compare values using their bitwise representation
2576 * (see {@link Float#floatToRawIntBits} and
2577 * {@link Double#doubleToRawLongBits}, respectively).
2578 * @param viewArrayClass the view array class, with a component type of
2579 * type {@code T}
2580 * @param byteOrder the endianness of the view array elements, as
2581 * stored in the underlying {@code ByteBuffer} (Note this overrides the
2582 * endianness of a {@code ByteBuffer})
2583 * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2584 * viewed as if elements corresponding to the components type of the view
2585 * array class
2586 * @throws NullPointerException if viewArrayClass or byteOrder is null
2587 * @throws IllegalArgumentException if viewArrayClass is not an array type
2588 * @throws UnsupportedOperationException if the component type of
2589 * viewArrayClass is not supported as a variable type
2590 * @since 9
2591 */
2592 public static
2593 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
2594 ByteOrder byteOrder) throws IllegalArgumentException {
2595 checkClassIsArray(viewArrayClass);
2596 checkTypeIsViewable(viewArrayClass.getComponentType());
2597 return ByteBufferViewVarHandle.create(viewArrayClass, byteOrder);
2598 }
2599 // END Android-changed: OpenJDK 9+181 VarHandle API factory methods.
2600
2601 /// method handle invocation (reflective style)
2602
2603 /**
2604 * Produces a method handle which will invoke any method handle of the
2605 * given {@code type}, with a given number of trailing arguments replaced by
2606 * a single trailing {@code Object[]} array.
2607 * The resulting invoker will be a method handle with the following
2608 * arguments:
2609 * <ul>
2610 * <li>a single {@code MethodHandle} target
2611 * <li>zero or more leading values (counted by {@code leadingArgCount})
2612 * <li>an {@code Object[]} array containing trailing arguments
2613 * </ul>
2614 * <p>
2615 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
2616 * the indicated {@code type}.
2617 * That is, if the target is exactly of the given {@code type}, it will behave
2618 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
2619 * is used to convert the target to the required {@code type}.
2620 * <p>
2621 * The type of the returned invoker will not be the given {@code type}, but rather
2622 * will have all parameters except the first {@code leadingArgCount}
2623 * replaced by a single array of type {@code Object[]}, which will be
2624 * the final parameter.
2625 * <p>
2626 * Before invoking its target, the invoker will spread the final array, apply
2627 * reference casts as necessary, and unbox and widen primitive arguments.
2628 * If, when the invoker is called, the supplied array argument does
2629 * not have the correct number of elements, the invoker will throw
2630 * an {@link IllegalArgumentException} instead of invoking the target.
2631 * <p>
2632 * This method is equivalent to the following code (though it may be more efficient):
2633 * <blockquote><pre>{@code
2634MethodHandle invoker = MethodHandles.invoker(type);
2635int spreadArgCount = type.parameterCount() - leadingArgCount;
2636invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2637return invoker;
2638 * }</pre></blockquote>
2639 * This method throws no reflective or security exceptions.
2640 * @param type the desired target type
2641 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
2642 * @return a method handle suitable for invoking any method handle of the given type
2643 * @throws NullPointerException if {@code type} is null
2644 * @throws IllegalArgumentException if {@code leadingArgCount} is not in
2645 * the range from 0 to {@code type.parameterCount()} inclusive,
2646 * or if the resulting method handle's type would have
2647 * <a href="MethodHandle.html#maxarity">too many parameters</a>
2648 */
2649 static public
2650 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2651 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
2652 throw newIllegalArgumentException("bad argument count", leadingArgCount);
2653
2654 MethodHandle invoker = MethodHandles.invoker(type);
2655 int spreadArgCount = type.parameterCount() - leadingArgCount;
2656 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2657 return invoker;
2658 }
2659
2660 /**
2661 * Produces a special <em>invoker method handle</em> which can be used to
2662 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
2663 * The resulting invoker will have a type which is
2664 * exactly equal to the desired type, except that it will accept
2665 * an additional leading argument of type {@code MethodHandle}.
2666 * <p>
2667 * This method is equivalent to the following code (though it may be more efficient):
2668 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
2669 *
2670 * <p style="font-size:smaller;">
2671 * <em>Discussion:</em>
2672 * Invoker method handles can be useful when working with variable method handles
2673 * of unknown types.
2674 * For example, to emulate an {@code invokeExact} call to a variable method
2675 * handle {@code M}, extract its type {@code T},
2676 * look up the invoker method {@code X} for {@code T},
2677 * and call the invoker method, as {@code X.invoke(T, A...)}.
2678 * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2679 * is unknown.)
2680 * If spreading, collecting, or other argument transformations are required,
2681 * they can be applied once to the invoker {@code X} and reused on many {@code M}
2682 * method handle values, as long as they are compatible with the type of {@code X}.
2683 * <p style="font-size:smaller;">
2684 * <em>(Note: The invoker method is not available via the Core Reflection API.
2685 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2686 * on the declared {@code invokeExact} or {@code invoke} method will raise an
2687 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2688 * <p>
2689 * This method throws no reflective or security exceptions.
2690 * @param type the desired target type
2691 * @return a method handle suitable for invoking any method handle of the given type
2692 * @throws IllegalArgumentException if the resulting method handle's type would have
2693 * <a href="MethodHandle.html#maxarity">too many parameters</a>
2694 */
2695 static public
2696 MethodHandle exactInvoker(MethodType type) {
2697 return new Transformers.Invoker(type, true /* isExactInvoker */);
2698 }
2699
2700 /**
2701 * Produces a special <em>invoker method handle</em> which can be used to
2702 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
2703 * The resulting invoker will have a type which is
2704 * exactly equal to the desired type, except that it will accept
2705 * an additional leading argument of type {@code MethodHandle}.
2706 * <p>
2707 * Before invoking its target, if the target differs from the expected type,
2708 * the invoker will apply reference casts as
2709 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2710 * Similarly, the return value will be converted as necessary.
2711 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2712 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
2713 * <p>
2714 * This method is equivalent to the following code (though it may be more efficient):
2715 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2716 * <p style="font-size:smaller;">
2717 * <em>Discussion:</em>
2718 * A {@linkplain MethodType#genericMethodType general method type} is one which
2719 * mentions only {@code Object} arguments and return values.
2720 * An invoker for such a type is capable of calling any method handle
2721 * of the same arity as the general type.
2722 * <p style="font-size:smaller;">
2723 * <em>(Note: The invoker method is not available via the Core Reflection API.
2724 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2725 * on the declared {@code invokeExact} or {@code invoke} method will raise an
2726 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2727 * <p>
2728 * This method throws no reflective or security exceptions.
2729 * @param type the desired target type
2730 * @return a method handle suitable for invoking any method handle convertible to the given type
2731 * @throws IllegalArgumentException if the resulting method handle's type would have
2732 * <a href="MethodHandle.html#maxarity">too many parameters</a>
2733 */
2734 static public
2735 MethodHandle invoker(MethodType type) {
2736 return new Transformers.Invoker(type, false /* isExactInvoker */);
2737 }
2738
2739 // BEGIN Android-added: resolver for VarHandle accessor methods.
2740 static private MethodHandle methodHandleForVarHandleAccessor(VarHandle.AccessMode accessMode,
2741 MethodType type,
2742 boolean isExactInvoker) {
2743 Class<?> refc = VarHandle.class;
2744 Method method;
2745 try {
2746 method = refc.getDeclaredMethod(accessMode.methodName(), Object[].class);
2747 } catch (NoSuchMethodException e) {
2748 throw new InternalError("No method for AccessMode " + accessMode, e);
2749 }
2750 MethodType methodType = type.insertParameterTypes(0, VarHandle.class);
2751 int kind = isExactInvoker ? MethodHandle.INVOKE_VAR_HANDLE_EXACT
2752 : MethodHandle.INVOKE_VAR_HANDLE;
2753 return new MethodHandleImpl(method.getArtMethod(), kind, methodType);
2754 }
2755 // END Android-added: resolver for VarHandle accessor methods.
2756
2757 /**
2758 * Produces a special <em>invoker method handle</em> which can be used to
2759 * invoke a signature-polymorphic access mode method on any VarHandle whose
2760 * associated access mode type is compatible with the given type.
2761 * The resulting invoker will have a type which is exactly equal to the
2762 * desired given type, except that it will accept an additional leading
2763 * argument of type {@code VarHandle}.
2764 *
2765 * @param accessMode the VarHandle access mode
2766 * @param type the desired target type
2767 * @return a method handle suitable for invoking an access mode method of
2768 * any VarHandle whose access mode type is of the given type.
2769 * @since 9
2770 */
2771 static public
2772 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2773 return methodHandleForVarHandleAccessor(accessMode, type, true /* isExactInvoker */);
2774 }
2775
2776 /**
2777 * Produces a special <em>invoker method handle</em> which can be used to
2778 * invoke a signature-polymorphic access mode method on any VarHandle whose
2779 * associated access mode type is compatible with the given type.
2780 * The resulting invoker will have a type which is exactly equal to the
2781 * desired given type, except that it will accept an additional leading
2782 * argument of type {@code VarHandle}.
2783 * <p>
2784 * Before invoking its target, if the access mode type differs from the
2785 * desired given type, the invoker will apply reference casts as necessary
2786 * and box, unbox, or widen primitive values, as if by
2787 * {@link MethodHandle#asType asType}. Similarly, the return value will be
2788 * converted as necessary.
2789 * <p>
2790 * This method is equivalent to the following code (though it may be more
2791 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2792 *
2793 * @param accessMode the VarHandle access mode
2794 * @param type the desired target type
2795 * @return a method handle suitable for invoking an access mode method of
2796 * any VarHandle whose access mode type is convertible to the given
2797 * type.
2798 * @since 9
2799 */
2800 static public
2801 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2802 return methodHandleForVarHandleAccessor(accessMode, type, false /* isExactInvoker */);
2803 }
2804
2805 // Android-changed: Basic invokers are not supported.
2806 //
2807 // static /*non-public*/
2808 // MethodHandle basicInvoker(MethodType type) {
2809 // return type.invokers().basicInvoker();
2810 // }
2811
2812 /// method handle modification (creation from other method handles)
2813
2814 /**
2815 * Produces a method handle which adapts the type of the
2816 * given method handle to a new type by pairwise argument and return type conversion.
2817 * The original type and new type must have the same number of arguments.
2818 * The resulting method handle is guaranteed to report a type
2819 * which is equal to the desired new type.
2820 * <p>
2821 * If the original type and new type are equal, returns target.
2822 * <p>
2823 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
2824 * and some additional conversions are also applied if those conversions fail.
2825 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2826 * if possible, before or instead of any conversions done by {@code asType}:
2827 * <ul>
2828 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2829 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
2830 * (This treatment of interfaces follows the usage of the bytecode verifier.)
2831 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2832 * the boolean is converted to a byte value, 1 for true, 0 for false.
2833 * (This treatment follows the usage of the bytecode verifier.)
2834 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2835 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2836 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2837 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2838 * then a Java casting conversion (JLS 5.5) is applied.
2839 * (Specifically, <em>T0</em> will convert to <em>T1</em> by
2840 * widening and/or narrowing.)
2841 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2842 * conversion will be applied at runtime, possibly followed
2843 * by a Java casting conversion (JLS 5.5) on the primitive value,
2844 * possibly followed by a conversion from byte to boolean by testing
2845 * the low-order bit.
2846 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2847 * and if the reference is null at runtime, a zero value is introduced.
2848 * </ul>
2849 * @param target the method handle to invoke after arguments are retyped
2850 * @param newType the expected type of the new method handle
2851 * @return a method handle which delegates to the target after performing
2852 * any necessary argument conversions, and arranges for any
2853 * necessary return value conversions
2854 * @throws NullPointerException if either argument is null
2855 * @throws WrongMethodTypeException if the conversion cannot be made
2856 * @see MethodHandle#asType
2857 */
2858 public static
2859 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
2860 explicitCastArgumentsChecks(target, newType);
2861 // use the asTypeCache when possible:
2862 MethodType oldType = target.type();
2863 if (oldType == newType) return target;
2864 if (oldType.explicitCastEquivalentToAsType(newType)) {
2865 if (Transformers.Transformer.class.isAssignableFrom(target.getClass())) {
2866 // The StackFrameReader and StackFrameWriter used to perform transforms on
2867 // EmulatedStackFrames (in Transformers.java) do not how to perform asType()
2868 // conversions, but we know here that an explicit cast transform is the same as
2869 // having called asType() on the method handle.
2870 return new Transformers.ExplicitCastArguments(target.asFixedArity(), newType);
2871 } else {
2872 // Runtime will perform asType() conversion during invocation.
2873 return target.asFixedArity().asType(newType);
2874 }
2875 }
2876 return new Transformers.ExplicitCastArguments(target, newType);
2877 }
2878
2879 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2880 if (target.type().parameterCount() != newType.parameterCount()) {
2881 throw new WrongMethodTypeException("cannot explicitly cast " + target +
2882 " to " + newType);
2883 }
2884 }
2885
2886 /**
2887 * Produces a method handle which adapts the calling sequence of the
2888 * given method handle to a new type, by reordering the arguments.
2889 * The resulting method handle is guaranteed to report a type
2890 * which is equal to the desired new type.
2891 * <p>
2892 * The given array controls the reordering.
2893 * Call {@code #I} the number of incoming parameters (the value
2894 * {@code newType.parameterCount()}, and call {@code #O} the number
2895 * of outgoing parameters (the value {@code target.type().parameterCount()}).
2896 * Then the length of the reordering array must be {@code #O},
2897 * and each element must be a non-negative number less than {@code #I}.
2898 * For every {@code N} less than {@code #O}, the {@code N}-th
2899 * outgoing argument will be taken from the {@code I}-th incoming
2900 * argument, where {@code I} is {@code reorder[N]}.
2901 * <p>
2902 * No argument or return value conversions are applied.
2903 * The type of each incoming argument, as determined by {@code newType},
2904 * must be identical to the type of the corresponding outgoing parameter
2905 * or parameters in the target method handle.
2906 * The return type of {@code newType} must be identical to the return
2907 * type of the original target.
2908 * <p>
2909 * The reordering array need not specify an actual permutation.
2910 * An incoming argument will be duplicated if its index appears
2911 * more than once in the array, and an incoming argument will be dropped
2912 * if its index does not appear in the array.
2913 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2914 * incoming arguments which are not mentioned in the reordering array
2915 * are may be any type, as determined only by {@code newType}.
2916 * <blockquote><pre>{@code
2917import static java.lang.invoke.MethodHandles.*;
2918import static java.lang.invoke.MethodType.*;
2919...
2920MethodType intfn1 = methodType(int.class, int.class);
2921MethodType intfn2 = methodType(int.class, int.class, int.class);
2922MethodHandle sub = ... (int x, int y) -> (x-y) ...;
2923assert(sub.type().equals(intfn2));
2924MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2925MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
2926assert((int)rsub.invokeExact(1, 100) == 99);
2927MethodHandle add = ... (int x, int y) -> (x+y) ...;
2928assert(add.type().equals(intfn2));
2929MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
2930assert(twice.type().equals(intfn1));
2931assert((int)twice.invokeExact(21) == 42);
2932 * }</pre></blockquote>
2933 * @param target the method handle to invoke after arguments are reordered
2934 * @param newType the expected type of the new method handle
2935 * @param reorder an index array which controls the reordering
2936 * @return a method handle which delegates to the target after it
2937 * drops unused arguments and moves and/or duplicates the other arguments
2938 * @throws NullPointerException if any argument is null
2939 * @throws IllegalArgumentException if the index array length is not equal to
2940 * the arity of the target, or if any index array element
2941 * not a valid index for a parameter of {@code newType},
2942 * or if two corresponding parameter types in
2943 * {@code target.type()} and {@code newType} are not identical,
2944 */
2945 public static
2946 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
2947 reorder = reorder.clone(); // get a private copy
2948 MethodType oldType = target.type();
2949 permuteArgumentChecks(reorder, newType, oldType);
2950
2951 return new Transformers.PermuteArguments(newType, target, reorder);
2952 }
2953
2954 // Android-changed: findFirstDupOrDrop is unused and removed.
2955 // private static int findFirstDupOrDrop(int[] reorder, int newArity);
2956
2957 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
2958 if (newType.returnType() != oldType.returnType())
2959 throw newIllegalArgumentException("return types do not match",
2960 oldType, newType);
2961 if (reorder.length == oldType.parameterCount()) {
2962 int limit = newType.parameterCount();
2963 boolean bad = false;
2964 for (int j = 0; j < reorder.length; j++) {
2965 int i = reorder[j];
2966 if (i < 0 || i >= limit) {
2967 bad = true; break;
2968 }
2969 Class<?> src = newType.parameterType(i);
2970 Class<?> dst = oldType.parameterType(j);
2971 if (src != dst)
2972 throw newIllegalArgumentException("parameter types do not match after reorder",
2973 oldType, newType);
2974 }
2975 if (!bad) return true;
2976 }
2977 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
2978 }
2979
2980 /**
2981 * Produces a method handle of the requested return type which returns the given
2982 * constant value every time it is invoked.
2983 * <p>
2984 * Before the method handle is returned, the passed-in value is converted to the requested type.
2985 * If the requested type is primitive, widening primitive conversions are attempted,
2986 * else reference conversions are attempted.
2987 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
2988 * @param type the return type of the desired method handle
2989 * @param value the value to return
2990 * @return a method handle of the given return type and no arguments, which always returns the given value
2991 * @throws NullPointerException if the {@code type} argument is null
2992 * @throws ClassCastException if the value cannot be converted to the required return type
2993 * @throws IllegalArgumentException if the given type is {@code void.class}
2994 */
2995 public static
2996 MethodHandle constant(Class<?> type, Object value) {
2997 if (type.isPrimitive()) {
2998 if (type == void.class)
2999 throw newIllegalArgumentException("void type");
3000 Wrapper w = Wrapper.forPrimitiveType(type);
3001 value = w.convert(value, type);
3002 if (w.zero().equals(value))
3003 return zero(w, type);
3004 return insertArguments(identity(type), 0, value);
3005 } else {
3006 if (value == null)
3007 return zero(Wrapper.OBJECT, type);
3008 return identity(type).bindTo(value);
3009 }
3010 }
3011
3012 /**
3013 * Produces a method handle which returns its sole argument when invoked.
3014 * @param type the type of the sole parameter and return value of the desired method handle
3015 * @return a unary method handle which accepts and returns the given type
3016 * @throws NullPointerException if the argument is null
3017 * @throws IllegalArgumentException if the given type is {@code void.class}
3018 */
3019 public static
3020 MethodHandle identity(Class<?> type) {
3021 // Android-added: explicit non-null check.
3022 Objects.requireNonNull(type);
3023 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
3024 int pos = btw.ordinal();
3025 MethodHandle ident = IDENTITY_MHS[pos];
3026 if (ident == null) {
3027 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
3028 }
3029 if (ident.type().returnType() == type)
3030 return ident;
3031 // something like identity(Foo.class); do not bother to intern these
3032 assert (btw == Wrapper.OBJECT);
3033 return makeIdentity(type);
3034 }
3035
3036 /**
3037 * Produces a constant method handle of the requested return type which
3038 * returns the default value for that type every time it is invoked.
3039 * The resulting constant method handle will have no side effects.
3040 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
3041 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
3042 * since {@code explicitCastArguments} converts {@code null} to default values.
3043 * @param type the expected return type of the desired method handle
3044 * @return a constant method handle that takes no arguments
3045 * and returns the default value of the given type (or void, if the type is void)
3046 * @throws NullPointerException if the argument is null
3047 * @see MethodHandles#constant
3048 * @see MethodHandles#empty
3049 * @see MethodHandles#explicitCastArguments
3050 * @since 9
3051 */
3052 public static MethodHandle zero(Class<?> type) {
3053 Objects.requireNonNull(type);
3054 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3055 }
3056
3057 private static MethodHandle identityOrVoid(Class<?> type) {
3058 return type == void.class ? zero(type) : identity(type);
3059 }
3060
3061 /**
3062 * Produces a method handle of the requested type which ignores any arguments, does nothing,
3063 * and returns a suitable default depending on the return type.
3064 * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3065 * <p>The returned method handle is equivalent to
3066 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3067 *
3068 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3069 * {@code guardWithTest(pred, target, empty(target.type())}.
3070 * @param type the type of the desired method handle
3071 * @return a constant method handle of the given type, which returns a default value of the given return type
3072 * @throws NullPointerException if the argument is null
3073 * @see MethodHandles#zero
3074 * @see MethodHandles#constant
3075 * @since 9
3076 */
3077 public static MethodHandle empty(MethodType type) {
3078 Objects.requireNonNull(type);
3079 return dropArguments(zero(type.returnType()), 0, type.parameterList());
3080 }
3081
3082 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
3083 private static MethodHandle makeIdentity(Class<?> ptype) {
3084 // Android-changed: Android implementation using identity() functions and transformers.
3085 // MethodType mtype = methodType(ptype, ptype);
3086 // LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3087 // return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3088 if (ptype.isPrimitive()) {
3089 try {
3090 final MethodType mt = methodType(ptype, ptype);
3091 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class, "identity", mt);
3092 } catch (NoSuchMethodException | IllegalAccessException e) {
3093 throw new AssertionError(e);
3094 }
3095 } else {
3096 return new Transformers.ReferenceIdentity(ptype);
3097 }
3098 }
3099
3100 // Android-added: helper methods for identity().
3101 /** @hide */ public static byte identity(byte val) { return val; }
3102 /** @hide */ public static boolean identity(boolean val) { return val; }
3103 /** @hide */ public static char identity(char val) { return val; }
3104 /** @hide */ public static short identity(short val) { return val; }
3105 /** @hide */ public static int identity(int val) { return val; }
3106 /** @hide */ public static long identity(long val) { return val; }
3107 /** @hide */ public static float identity(float val) { return val; }
3108 /** @hide */ public static double identity(double val) { return val; }
3109
3110 private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3111 int pos = btw.ordinal();
3112 MethodHandle zero = ZERO_MHS[pos];
3113 if (zero == null) {
3114 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3115 }
3116 if (zero.type().returnType() == rtype)
3117 return zero;
3118 assert(btw == Wrapper.OBJECT);
3119 return makeZero(rtype);
3120 }
3121 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
3122 private static MethodHandle makeZero(Class<?> rtype) {
3123 // Android-changed: use Android specific implementation.
3124 // MethodType mtype = methodType(rtype);
3125 // LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3126 // return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3127 return new Transformers.ZeroValue(rtype);
3128 }
3129
3130 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
3131 // Simulate a CAS, to avoid racy duplication of results.
3132 MethodHandle prev = cache[pos];
3133 if (prev != null) return prev;
3134 return cache[pos] = value;
3135 }
3136
3137 /**
3138 * Provides a target method handle with one or more <em>bound arguments</em>
3139 * in advance of the method handle's invocation.
3140 * The formal parameters to the target corresponding to the bound
3141 * arguments are called <em>bound parameters</em>.
3142 * Returns a new method handle which saves away the bound arguments.
3143 * When it is invoked, it receives arguments for any non-bound parameters,
3144 * binds the saved arguments to their corresponding parameters,
3145 * and calls the original target.
3146 * <p>
3147 * The type of the new method handle will drop the types for the bound
3148 * parameters from the original target type, since the new method handle
3149 * will no longer require those arguments to be supplied by its callers.
3150 * <p>
3151 * Each given argument object must match the corresponding bound parameter type.
3152 * If a bound parameter type is a primitive, the argument object
3153 * must be a wrapper, and will be unboxed to produce the primitive value.
3154 * <p>
3155 * The {@code pos} argument selects which parameters are to be bound.
3156 * It may range between zero and <i>N-L</i> (inclusively),
3157 * where <i>N</i> is the arity of the target method handle
3158 * and <i>L</i> is the length of the values array.
3159 * @param target the method handle to invoke after the argument is inserted
3160 * @param pos where to insert the argument (zero for the first)
3161 * @param values the series of arguments to insert
3162 * @return a method handle which inserts an additional argument,
3163 * before calling the original method handle
3164 * @throws NullPointerException if the target or the {@code values} array is null
3165 * @see MethodHandle#bindTo
3166 */
3167 public static
3168 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3169 int insCount = values.length;
3170 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3171 if (insCount == 0) {
3172 return target;
3173 }
3174
3175 // Throw ClassCastExceptions early if we can't cast any of the provided values
3176 // to the required type.
3177 for (int i = 0; i < insCount; i++) {
3178 final Class<?> ptype = ptypes[pos + i];
3179 if (!ptype.isPrimitive()) {
3180 ptypes[pos + i].cast(values[i]);
3181 } else {
3182 // Will throw a ClassCastException if something terrible happens.
3183 values[i] = Wrapper.forPrimitiveType(ptype).convert(values[i], ptype);
3184 }
3185 }
3186
3187 return new Transformers.InsertArguments(target, pos, values);
3188 }
3189
3190 // Android-changed: insertArgumentPrimitive is unused.
3191 //
3192 // private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3193 // Class<?> ptype, Object value) {
3194 // Wrapper w = Wrapper.forPrimitiveType(ptype);
3195 // // perform unboxing and/or primitive conversion
3196 // value = w.convert(value, ptype);
3197 // switch (w) {
3198 // case INT: return result.bindArgumentI(pos, (int)value);
3199 // case LONG: return result.bindArgumentJ(pos, (long)value);
3200 // case FLOAT: return result.bindArgumentF(pos, (float)value);
3201 // case DOUBLE: return result.bindArgumentD(pos, (double)value);
3202 // default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3203 // }
3204 // }
3205
3206 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
3207 MethodType oldType = target.type();
3208 int outargs = oldType.parameterCount();
3209 int inargs = outargs - insCount;
3210 if (inargs < 0)
3211 throw newIllegalArgumentException("too many values to insert");
3212 if (pos < 0 || pos > inargs)
3213 throw newIllegalArgumentException("no argument type to append");
3214 return oldType.ptypes();
3215 }
3216
3217 // Android-changed: inclusive language preference for 'placeholder'.
3218 /**
3219 * Produces a method handle which will discard some placeholder arguments
3220 * before calling some other specified <i>target</i> method handle.
3221 * The type of the new method handle will be the same as the target's type,
3222 * except it will also include the placeholder argument types,
3223 * at some given position.
3224 * <p>
3225 * The {@code pos} argument may range between zero and <i>N</i>,
3226 * where <i>N</i> is the arity of the target.
3227 * If {@code pos} is zero, the placeholder arguments will precede
3228 * the target's real arguments; if {@code pos} is <i>N</i>
3229 * they will come after.
3230 * <p>
3231 * <b>Example:</b>
3232 * <blockquote><pre>{@code
3233import static java.lang.invoke.MethodHandles.*;
3234import static java.lang.invoke.MethodType.*;
3235...
3236MethodHandle cat = lookup().findVirtual(String.class,
3237 "concat", methodType(String.class, String.class));
3238assertEquals("xy", (String) cat.invokeExact("x", "y"));
3239MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3240MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3241assertEquals(bigType, d0.type());
3242assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
3243 * }</pre></blockquote>
3244 * <p>
3245 * This method is also equivalent to the following code:
3246 * <blockquote><pre>
3247 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
3248 * </pre></blockquote>
3249 * @param target the method handle to invoke after the arguments are dropped
3250 * @param valueTypes the type(s) of the argument(s) to drop
3251 * @param pos position of first argument to drop (zero for the leftmost)
3252 * @return a method handle which drops arguments of the given types,
3253 * before calling the original method handle
3254 * @throws NullPointerException if the target is null,
3255 * or if the {@code valueTypes} list or any of its elements is null
3256 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3257 * or if {@code pos} is negative or greater than the arity of the target,
3258 * or if the new method handle's type would have too many parameters
3259 */
3260 public static
3261 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3262 return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
3263 }
3264
3265 private static List<Class<?>> copyTypes(Object[] array) {
3266 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
3267 }
3268
3269 private static
3270 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
3271 MethodType oldType = target.type(); // get NPE
3272 int dropped = dropArgumentChecks(oldType, pos, valueTypes);
3273 MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
3274 if (dropped == 0) return target;
3275 // Android-changed: transformer implementation.
3276 // BoundMethodHandle result = target.rebind();
3277 // LambdaForm lform = result.form;
3278 // int insertFormArg = 1 + pos;
3279 // for (Class<?> ptype : valueTypes) {
3280 // lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
3281 // }
3282 // result = result.copyWith(newType, lform);
3283 // return result;
3284 return new Transformers.DropArguments(newType, target, pos, dropped);
3285 }
3286
3287 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
3288 int dropped = valueTypes.size();
3289 MethodType.checkSlotCount(dropped);
3290 int outargs = oldType.parameterCount();
3291 int inargs = outargs + dropped;
3292 if (pos < 0 || pos > outargs)
3293 throw newIllegalArgumentException("no argument type to remove"
3294 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3295 );
3296 return dropped;
3297 }
3298
3299 // Android-changed: inclusive language preference for 'placeholder'.
3300 /**
3301 * Produces a method handle which will discard some placeholder arguments
3302 * before calling some other specified <i>target</i> method handle.
3303 * The type of the new method handle will be the same as the target's type,
3304 * except it will also include the placeholder argument types,
3305 * at some given position.
3306 * <p>
3307 * The {@code pos} argument may range between zero and <i>N</i>,
3308 * where <i>N</i> is the arity of the target.
3309 * If {@code pos} is zero, the placeholder arguments will precede
3310 * the target's real arguments; if {@code pos} is <i>N</i>
3311 * they will come after.
3312 * @apiNote
3313 * <blockquote><pre>{@code
3314import static java.lang.invoke.MethodHandles.*;
3315import static java.lang.invoke.MethodType.*;
3316...
3317MethodHandle cat = lookup().findVirtual(String.class,
3318 "concat", methodType(String.class, String.class));
3319assertEquals("xy", (String) cat.invokeExact("x", "y"));
3320MethodHandle d0 = dropArguments(cat, 0, String.class);
3321assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
3322MethodHandle d1 = dropArguments(cat, 1, String.class);
3323assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
3324MethodHandle d2 = dropArguments(cat, 2, String.class);
3325assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
3326MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
3327assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
3328 * }</pre></blockquote>
3329 * <p>
3330 * This method is also equivalent to the following code:
3331 * <blockquote><pre>
3332 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
3333 * </pre></blockquote>
3334 * @param target the method handle to invoke after the arguments are dropped
3335 * @param valueTypes the type(s) of the argument(s) to drop
3336 * @param pos position of first argument to drop (zero for the leftmost)
3337 * @return a method handle which drops arguments of the given types,
3338 * before calling the original method handle
3339 * @throws NullPointerException if the target is null,
3340 * or if the {@code valueTypes} array or any of its elements is null
3341 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3342 * or if {@code pos} is negative or greater than the arity of the target,
3343 * or if the new method handle's type would have
3344 * <a href="MethodHandle.html#maxarity">too many parameters</a>
3345 */
3346 public static
3347 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
3348 return dropArguments0(target, pos, copyTypes(valueTypes));
3349 }
3350
3351 // private version which allows caller some freedom with error handling
3352 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
3353 boolean nullOnFailure) {
3354 newTypes = copyTypes(newTypes.toArray());
3355 List<Class<?>> oldTypes = target.type().parameterList();
3356 int match = oldTypes.size();
3357 if (skip != 0) {
3358 if (skip < 0 || skip > match) {
3359 throw newIllegalArgumentException("illegal skip", skip, target);
3360 }
3361 oldTypes = oldTypes.subList(skip, match);
3362 match -= skip;
3363 }
3364 List<Class<?>> addTypes = newTypes;
3365 int add = addTypes.size();
3366 if (pos != 0) {
3367 if (pos < 0 || pos > add) {
3368 throw newIllegalArgumentException("illegal pos", pos, newTypes);
3369 }
3370 addTypes = addTypes.subList(pos, add);
3371 add -= pos;
3372 assert(addTypes.size() == add);
3373 }
3374 // Do not add types which already match the existing arguments.
3375 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
3376 if (nullOnFailure) {
3377 return null;
3378 }
3379 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
3380 }
3381 addTypes = addTypes.subList(match, add);
3382 add -= match;
3383 assert(addTypes.size() == add);
3384 // newTypes: ( P*[pos], M*[match], A*[add] )
3385 // target: ( S*[skip], M*[match] )
3386 MethodHandle adapter = target;
3387 if (add > 0) {
3388 adapter = dropArguments0(adapter, skip+ match, addTypes);
3389 }
3390 // adapter: (S*[skip], M*[match], A*[add] )
3391 if (pos > 0) {
3392 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
3393 }
3394 // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
3395 return adapter;
3396 }
3397
3398 // Android-changed: inclusive language preference for 'placeholder'.
3399 /**
3400 * Adapts a target method handle to match the given parameter type list. If necessary, adds placeholder arguments. Some
3401 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
3402 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
3403 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
3404 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
3405 * {@link #dropArguments(MethodHandle, int, Class[])}.
3406 * <p>
3407 * The resulting handle will have the same return type as the target handle.
3408 * <p>
3409 * In more formal terms, assume these two type lists:<ul>
3410 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
3411 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
3412 * {@code newTypes}.
3413 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
3414 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
3415 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
3416 * sub-list.
3417 * </ul>
3418 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
3419 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
3420 * {@link #dropArguments(MethodHandle, int, Class[])}.
3421 *
3422 * @apiNote
3423 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
3424 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
3425 * <blockquote><pre>{@code
3426import static java.lang.invoke.MethodHandles.*;
3427import static java.lang.invoke.MethodType.*;
3428...
3429...
3430MethodHandle h0 = constant(boolean.class, true);
3431MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
3432MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
3433MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
3434if (h1.type().parameterCount() < h2.type().parameterCount())
3435 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1
3436else
3437 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2
3438MethodHandle h3 = guardWithTest(h0, h1, h2);
3439assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
3440 * }</pre></blockquote>
3441 * @param target the method handle to adapt
3442 * @param skip number of targets parameters to disregard (they will be unchanged)
3443 * @param newTypes the list of types to match {@code target}'s parameter type list to
3444 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
3445 * @return a possibly adapted method handle
3446 * @throws NullPointerException if either argument is null
3447 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
3448 * or if {@code skip} is negative or greater than the arity of the target,
3449 * or if {@code pos} is negative or greater than the newTypes list size,
3450 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
3451 * {@code pos}.
3452 * @since 9
3453 */
3454 public static
3455 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
3456 Objects.requireNonNull(target);
3457 Objects.requireNonNull(newTypes);
3458 return dropArgumentsToMatch(target, skip, newTypes, pos, false);
3459 }
3460
3461 /**
3462 * Drop the return value of the target handle (if any).
3463 * The returned method handle will have a {@code void} return type.
3464 *
3465 * @param target the method handle to adapt
3466 * @return a possibly adapted method handle
3467 * @throws NullPointerException if {@code target} is null
3468 * @since 16
3469 */
3470 public static MethodHandle dropReturn(MethodHandle target) {
3471 Objects.requireNonNull(target);
3472 MethodType oldType = target.type();
3473 Class<?> oldReturnType = oldType.returnType();
3474 if (oldReturnType == void.class)
3475 return target;
3476
3477 MethodType newType = oldType.changeReturnType(void.class);
3478 // Android-changed: no support for BoundMethodHandle or LambdaForm.
3479 // BoundMethodHandle result = target.rebind();
3480 // LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
3481 // result = result.copyWith(newType, lform);
3482 // return result;
3483 return target.asType(newType);
3484 }
3485
3486 /**
3487 * Adapts a target method handle by pre-processing
3488 * one or more of its arguments, each with its own unary filter function,
3489 * and then calling the target with each pre-processed argument
3490 * replaced by the result of its corresponding filter function.
3491 * <p>
3492 * The pre-processing is performed by one or more method handles,
3493 * specified in the elements of the {@code filters} array.
3494 * The first element of the filter array corresponds to the {@code pos}
3495 * argument of the target, and so on in sequence.
3496 * The filter functions are invoked in left to right order.
3497 * <p>
3498 * Null arguments in the array are treated as identity functions,
3499 * and the corresponding arguments left unchanged.
3500 * (If there are no non-null elements in the array, the original target is returned.)
3501 * Each filter is applied to the corresponding argument of the adapter.
3502 * <p>
3503 * If a filter {@code F} applies to the {@code N}th argument of
3504 * the target, then {@code F} must be a method handle which
3505 * takes exactly one argument. The type of {@code F}'s sole argument
3506 * replaces the corresponding argument type of the target
3507 * in the resulting adapted method handle.
3508 * The return type of {@code F} must be identical to the corresponding
3509 * parameter type of the target.
3510 * <p>
3511 * It is an error if there are elements of {@code filters}
3512 * (null or not)
3513 * which do not correspond to argument positions in the target.
3514 * <p><b>Example:</b>
3515 * <blockquote><pre>{@code
3516import static java.lang.invoke.MethodHandles.*;
3517import static java.lang.invoke.MethodType.*;
3518...
3519MethodHandle cat = lookup().findVirtual(String.class,
3520 "concat", methodType(String.class, String.class));
3521MethodHandle upcase = lookup().findVirtual(String.class,
3522 "toUpperCase", methodType(String.class));
3523assertEquals("xy", (String) cat.invokeExact("x", "y"));
3524MethodHandle f0 = filterArguments(cat, 0, upcase);
3525assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
3526MethodHandle f1 = filterArguments(cat, 1, upcase);
3527assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
3528MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
3529assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
3530 * }</pre></blockquote>
3531 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3532 * denotes the return type of both the {@code target} and resulting adapter.
3533 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
3534 * of the parameters and arguments that precede and follow the filter position
3535 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
3536 * values of the filtered parameters and arguments; they also represent the
3537 * return types of the {@code filter[i]} handles. The latter accept arguments
3538 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
3539 * the resulting adapter.
3540 * <blockquote><pre>{@code
3541 * T target(P... p, A[i]... a[i], B... b);
3542 * A[i] filter[i](V[i]);
3543 * T adapter(P... p, V[i]... v[i], B... b) {
3544 * return target(p..., filter[i](v[i])..., b...);
3545 * }
3546 * }</pre></blockquote>
3547 * <p>
3548 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3549 * variable-arity method handle}, even if the original target method handle was.
3550 *
3551 * @param target the method handle to invoke after arguments are filtered
3552 * @param pos the position of the first argument to filter
3553 * @param filters method handles to call initially on filtered arguments
3554 * @return method handle which incorporates the specified argument filtering logic
3555 * @throws NullPointerException if the target is null
3556 * or if the {@code filters} array is null
3557 * @throws IllegalArgumentException if a non-null element of {@code filters}
3558 * does not match a corresponding argument type of target as described above,
3559 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3560 * or if the resulting method handle's type would have
3561 * <a href="MethodHandle.html#maxarity">too many parameters</a>
3562 */
3563 public static
3564 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
3565 filterArgumentsCheckArity(target, pos, filters);
3566 MethodHandle adapter = target;
3567 // Android-changed: transformer implementation.
3568 // process filters in reverse order so that the invocation of
3569 // the resulting adapter will invoke the filters in left-to-right order
3570 // for (int i = filters.length - 1; i >= 0; --i) {
3571 // MethodHandle filter = filters[i];
3572 // if (filter == null) continue; // ignore null elements of filters
3573 // adapter = filterArgument(adapter, pos + i, filter);
3574 // }
3575 // return adapter;
3576 boolean hasNonNullFilter = false;
3577 for (int i = 0; i < filters.length; ++i) {
3578 MethodHandle filter = filters[i];
3579 if (filter != null) {
3580 hasNonNullFilter = true;
3581 filterArgumentChecks(target, i + pos, filter);
3582 }
3583 }
3584 if (!hasNonNullFilter) {
3585 return target;
3586 }
3587 return new Transformers.FilterArguments(target, pos, filters);
3588 }
3589
3590 /*non-public*/ static
3591 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
3592 filterArgumentChecks(target, pos, filter);
3593 // Android-changed: use Transformer implementation.
3594 // MethodType targetType = target.type();
3595 // MethodType filterType = filter.type();
3596 // BoundMethodHandle result = target.rebind();
3597 // Class<?> newParamType = filterType.parameterType(0);
3598 // LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
3599 // MethodType newType = targetType.changeParameterType(pos, newParamType);
3600 // result = result.copyWithExtendL(newType, lform, filter);
3601 // return result;
3602 return new Transformers.FilterArguments(target, pos, filter);
3603 }
3604
3605 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3606 MethodType targetType = target.type();
3607 int maxPos = targetType.parameterCount();
3608 if (pos + filters.length > maxPos)
3609 throw newIllegalArgumentException("too many filters");
3610 }
3611
3612 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3613 MethodType targetType = target.type();
3614 MethodType filterType = filter.type();
3615 if (filterType.parameterCount() != 1
3616 || filterType.returnType() != targetType.parameterType(pos))
3617 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3618 }
3619
3620 /**
3621 * Adapts a target method handle by pre-processing
3622 * a sub-sequence of its arguments with a filter (another method handle).
3623 * The pre-processed arguments are replaced by the result (if any) of the
3624 * filter function.
3625 * The target is then called on the modified (usually shortened) argument list.
3626 * <p>
3627 * If the filter returns a value, the target must accept that value as
3628 * its argument in position {@code pos}, preceded and/or followed by
3629 * any arguments not passed to the filter.
3630 * If the filter returns void, the target must accept all arguments
3631 * not passed to the filter.
3632 * No arguments are reordered, and a result returned from the filter
3633 * replaces (in order) the whole subsequence of arguments originally
3634 * passed to the adapter.
3635 * <p>
3636 * The argument types (if any) of the filter
3637 * replace zero or one argument types of the target, at position {@code pos},
3638 * in the resulting adapted method handle.
3639 * The return type of the filter (if any) must be identical to the
3640 * argument type of the target at position {@code pos}, and that target argument
3641 * is supplied by the return value of the filter.
3642 * <p>
3643 * In all cases, {@code pos} must be greater than or equal to zero, and
3644 * {@code pos} must also be less than or equal to the target's arity.
3645 * <p><b>Example:</b>
3646 * <blockquote><pre>{@code
3647import static java.lang.invoke.MethodHandles.*;
3648import static java.lang.invoke.MethodType.*;
3649...
3650MethodHandle deepToString = publicLookup()
3651 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3652
3653MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3654assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3655
3656MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3657assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3658
3659MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3660MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3661assertEquals("[top, [up, down], strange]",
3662 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3663
3664MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3665assertEquals("[top, [up, down], [strange]]",
3666 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3667
3668MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3669assertEquals("[top, [[up, down, strange], charm], bottom]",
3670 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
3671 * }</pre></blockquote>
3672 * <p> Here is pseudocode for the resulting adapter:
3673 * <blockquote><pre>{@code
3674 * T target(A...,V,C...);
3675 * V filter(B...);
3676 * T adapter(A... a,B... b,C... c) {
3677 * V v = filter(b...);
3678 * return target(a...,v,c...);
3679 * }
3680 * // and if the filter has no arguments:
3681 * T target2(A...,V,C...);
3682 * V filter2();
3683 * T adapter2(A... a,C... c) {
3684 * V v = filter2();
3685 * return target2(a...,v,c...);
3686 * }
3687 * // and if the filter has a void return:
3688 * T target3(A...,C...);
3689 * void filter3(B...);
3690 * void adapter3(A... a,B... b,C... c) {
3691 * filter3(b...);
3692 * return target3(a...,c...);
3693 * }
3694 * }</pre></blockquote>
3695 * <p>
3696 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3697 * one which first "folds" the affected arguments, and then drops them, in separate
3698 * steps as follows:
3699 * <blockquote><pre>{@code
3700 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3701 * mh = MethodHandles.foldArguments(mh, coll); //step 1
3702 * }</pre></blockquote>
3703 * If the target method handle consumes no arguments besides than the result
3704 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3705 * is equivalent to {@code filterReturnValue(coll, mh)}.
3706 * If the filter method handle {@code coll} consumes one argument and produces
3707 * a non-void result, then {@code collectArguments(mh, N, coll)}
3708 * is equivalent to {@code filterArguments(mh, N, coll)}.
3709 * Other equivalences are possible but would require argument permutation.
3710 *
3711 * @param target the method handle to invoke after filtering the subsequence of arguments
3712 * @param pos the position of the first adapter argument to pass to the filter,
3713 * and/or the target argument which receives the result of the filter
3714 * @param filter method handle to call on the subsequence of arguments
3715 * @return method handle which incorporates the specified argument subsequence filtering logic
3716 * @throws NullPointerException if either argument is null
3717 * @throws IllegalArgumentException if the return type of {@code filter}
3718 * is non-void and is not the same as the {@code pos} argument of the target,
3719 * or if {@code pos} is not between 0 and the target's arity, inclusive,
3720 * or if the resulting method handle's type would have
3721 * <a href="MethodHandle.html#maxarity">too many parameters</a>
3722 * @see MethodHandles#foldArguments
3723 * @see MethodHandles#filterArguments
3724 * @see MethodHandles#filterReturnValue
3725 */
3726 public static
3727 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
3728 MethodType newType = collectArgumentsChecks(target, pos, filter);
3729 return new Transformers.CollectArguments(target, filter, pos, newType);
3730 }
3731
3732 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
3733 MethodType targetType = target.type();
3734 MethodType filterType = filter.type();
3735 Class<?> rtype = filterType.returnType();
3736 List<Class<?>> filterArgs = filterType.parameterList();
3737 if (rtype == void.class) {
3738 return targetType.insertParameterTypes(pos, filterArgs);
3739 }
3740 if (rtype != targetType.parameterType(pos)) {
3741 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3742 }
3743 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
3744 }
3745
3746 /**
3747 * Adapts a target method handle by post-processing
3748 * its return value (if any) with a filter (another method handle).
3749 * The result of the filter is returned from the adapter.
3750 * <p>
3751 * If the target returns a value, the filter must accept that value as
3752 * its only argument.
3753 * If the target returns void, the filter must accept no arguments.
3754 * <p>
3755 * The return type of the filter
3756 * replaces the return type of the target
3757 * in the resulting adapted method handle.
3758 * The argument type of the filter (if any) must be identical to the
3759 * return type of the target.
3760 * <p><b>Example:</b>
3761 * <blockquote><pre>{@code
3762import static java.lang.invoke.MethodHandles.*;
3763import static java.lang.invoke.MethodType.*;
3764...
3765MethodHandle cat = lookup().findVirtual(String.class,
3766 "concat", methodType(String.class, String.class));
3767MethodHandle length = lookup().findVirtual(String.class,
3768 "length", methodType(int.class));
3769System.out.println((String) cat.invokeExact("x", "y")); // xy
3770MethodHandle f0 = filterReturnValue(cat, length);
3771System.out.println((int) f0.invokeExact("x", "y")); // 2
3772 * }</pre></blockquote>
3773 * <p>Here is pseudocode for the resulting adapter. In the code,
3774 * {@code T}/{@code t} represent the result type and value of the
3775 * {@code target}; {@code V}, the result type of the {@code filter}; and
3776 * {@code A}/{@code a}, the types and values of the parameters and arguments
3777 * of the {@code target} as well as the resulting adapter.
3778 * <blockquote><pre>{@code
3779 * T target(A...);
3780 * V filter(T);
3781 * V adapter(A... a) {
3782 * T t = target(a...);
3783 * return filter(t);
3784 * }
3785 * // and if the target has a void return:
3786 * void target2(A...);
3787 * V filter2();
3788 * V adapter2(A... a) {
3789 * target2(a...);
3790 * return filter2();
3791 * }
3792 * // and if the filter has a void return:
3793 * T target3(A...);
3794 * void filter3(V);
3795 * void adapter3(A... a) {
3796 * T t = target3(a...);
3797 * filter3(t);
3798 * }
3799 * }</pre></blockquote>
3800 * <p>
3801 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3802 * variable-arity method handle}, even if the original target method handle was.
3803 * @param target the method handle to invoke before filtering the return value
3804 * @param filter method handle to call on the return value
3805 * @return method handle which incorporates the specified return value filtering logic
3806 * @throws NullPointerException if either argument is null
3807 * @throws IllegalArgumentException if the argument list of {@code filter}
3808 * does not match the return type of target as described above
3809 */
3810 public static
3811 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3812 MethodType targetType = target.type();
3813 MethodType filterType = filter.type();
3814 filterReturnValueChecks(targetType, filterType);
3815 // Android-changed: use a transformer.
3816 // BoundMethodHandle result = target.rebind();
3817 // BasicType rtype = BasicType.basicType(filterType.returnType());
3818 // LambdaForm lform = result.editor().filterReturnForm(rtype, false);
3819 // MethodType newType = targetType.changeReturnType(filterType.returnType());
3820 // result = result.copyWithExtendL(newType, lform, filter);
3821 // return result;
3822 return new Transformers.FilterReturnValue(target, filter);
3823 }
3824
3825 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
3826 Class<?> rtype = targetType.returnType();
3827 int filterValues = filterType.parameterCount();
3828 if (filterValues == 0
3829 ? (rtype != void.class)
3830 : (rtype != filterType.parameterType(0) || filterValues != 1))
3831 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
3832 }
3833
3834 /**
3835 * Adapts a target method handle by pre-processing
3836 * some of its arguments, and then calling the target with
3837 * the result of the pre-processing, inserted into the original
3838 * sequence of arguments.
3839 * <p>
3840 * The pre-processing is performed by {@code combiner}, a second method handle.
3841 * Of the arguments passed to the adapter, the first {@code N} arguments
3842 * are copied to the combiner, which is then called.
3843 * (Here, {@code N} is defined as the parameter count of the combiner.)
3844 * After this, control passes to the target, with any result
3845 * from the combiner inserted before the original {@code N} incoming
3846 * arguments.
3847 * <p>
3848 * If the combiner returns a value, the first parameter type of the target
3849 * must be identical with the return type of the combiner, and the next
3850 * {@code N} parameter types of the target must exactly match the parameters
3851 * of the combiner.
3852 * <p>
3853 * If the combiner has a void return, no result will be inserted,
3854 * and the first {@code N} parameter types of the target
3855 * must exactly match the parameters of the combiner.
3856 * <p>
3857 * The resulting adapter is the same type as the target, except that the
3858 * first parameter type is dropped,
3859 * if it corresponds to the result of the combiner.
3860 * <p>
3861 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
3862 * that either the combiner or the target does not wish to receive.
3863 * If some of the incoming arguments are destined only for the combiner,
3864 * consider using {@link MethodHandle#asCollector asCollector} instead, since those
3865 * arguments will not need to be live on the stack on entry to the
3866 * target.)
3867 * <p><b>Example:</b>
3868 * <blockquote><pre>{@code
3869import static java.lang.invoke.MethodHandles.*;
3870import static java.lang.invoke.MethodType.*;
3871...
3872MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3873 "println", methodType(void.class, String.class))
3874 .bindTo(System.out);
3875MethodHandle cat = lookup().findVirtual(String.class,
3876 "concat", methodType(String.class, String.class));
3877assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3878MethodHandle catTrace = foldArguments(cat, trace);
3879// also prints "boo":
3880assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3881 * }</pre></blockquote>
3882 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3883 * represents the result type of the {@code target} and resulting adapter.
3884 * {@code V}/{@code v} represent the type and value of the parameter and argument
3885 * of {@code target} that precedes the folding position; {@code V} also is
3886 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3887 * types and values of the {@code N} parameters and arguments at the folding
3888 * position. {@code B}/{@code b} represent the types and values of the
3889 * {@code target} parameters and arguments that follow the folded parameters
3890 * and arguments.
3891 * <blockquote><pre>{@code
3892 * // there are N arguments in A...
3893 * T target(V, A[N]..., B...);
3894 * V combiner(A...);
3895 * T adapter(A... a, B... b) {
3896 * V v = combiner(a...);
3897 * return target(v, a..., b...);
3898 * }
3899 * // and if the combiner has a void return:
3900 * T target2(A[N]..., B...);
3901 * void combiner2(A...);
3902 * T adapter2(A... a, B... b) {
3903 * combiner2(a...);
3904 * return target2(a..., b...);
3905 * }
3906 * }</pre></blockquote>
3907 * <p>
3908 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3909 * variable-arity method handle}, even if the original target method handle was.
3910 * @param target the method handle to invoke after arguments are combined
3911 * @param combiner method handle to call initially on the incoming arguments
3912 * @return method handle which incorporates the specified argument folding logic
3913 * @throws NullPointerException if either argument is null
3914 * @throws IllegalArgumentException if {@code combiner}'s return type
3915 * is non-void and not the same as the first argument type of
3916 * the target, or if the initial {@code N} argument types
3917 * of the target
3918 * (skipping one matching the {@code combiner}'s return type)
3919 * are not identical with the argument types of {@code combiner}
3920 */
3921 public static
3922 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
3923 return foldArguments(target, 0, combiner);
3924 }
3925
3926 /**
3927 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
3928 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
3929 * before the folded arguments.
3930 * <p>
3931 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
3932 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
3933 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
3934 * 0.
3935 *
3936 * @apiNote Example:
3937 * <blockquote><pre>{@code
3938 import static java.lang.invoke.MethodHandles.*;
3939 import static java.lang.invoke.MethodType.*;
3940 ...
3941 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3942 "println", methodType(void.class, String.class))
3943 .bindTo(System.out);
3944 MethodHandle cat = lookup().findVirtual(String.class,
3945 "concat", methodType(String.class, String.class));
3946 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3947 MethodHandle catTrace = foldArguments(cat, 1, trace);
3948 // also prints "jum":
3949 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
3950 * }</pre></blockquote>
3951 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3952 * represents the result type of the {@code target} and resulting adapter.
3953 * {@code V}/{@code v} represent the type and value of the parameter and argument
3954 * of {@code target} that precedes the folding position; {@code V} also is
3955 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3956 * types and values of the {@code N} parameters and arguments at the folding
3957 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
3958 * and values of the {@code target} parameters and arguments that precede and
3959 * follow the folded parameters and arguments starting at {@code pos},
3960 * respectively.
3961 * <blockquote><pre>{@code
3962 * // there are N arguments in A...
3963 * T target(Z..., V, A[N]..., B...);
3964 * V combiner(A...);
3965 * T adapter(Z... z, A... a, B... b) {
3966 * V v = combiner(a...);
3967 * return target(z..., v, a..., b...);
3968 * }
3969 * // and if the combiner has a void return:
3970 * T target2(Z..., A[N]..., B...);
3971 * void combiner2(A...);
3972 * T adapter2(Z... z, A... a, B... b) {
3973 * combiner2(a...);
3974 * return target2(z..., a..., b...);
3975 * }
3976 * }</pre></blockquote>
3977 * <p>
3978 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3979 * variable-arity method handle}, even if the original target method handle was.
3980 *
3981 * @param target the method handle to invoke after arguments are combined
3982 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
3983 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
3984 * @param combiner method handle to call initially on the incoming arguments
3985 * @return method handle which incorporates the specified argument folding logic
3986 * @throws NullPointerException if either argument is null
3987 * @throws IllegalArgumentException if either of the following two conditions holds:
3988 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
3989 * {@code pos} of the target signature;
3990 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
3991 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
3992 *
3993 * @see #foldArguments(MethodHandle, MethodHandle)
3994 * @since 9
3995 */
3996 public static
3997 MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
3998 MethodType targetType = target.type();
3999 MethodType combinerType = combiner.type();
4000 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4001 // Android-changed: // Android-changed: transformer implementation.
4002 // BoundMethodHandle result = target.rebind();
4003 // boolean dropResult = rtype == void.class;
4004 // LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4005 // MethodType newType = targetType;
4006 // if (!dropResult) {
4007 // newType = newType.dropParameterTypes(pos, pos + 1);
4008 // }
4009 // result = result.copyWithExtendL(newType, lform, combiner);
4010 // return result;
4011
4012 return new Transformers.FoldArguments(target, pos, combiner);
4013 }
4014
4015 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
4016 int foldArgs = combinerType.parameterCount();
4017 Class<?> rtype = combinerType.returnType();
4018 int foldVals = rtype == void.class ? 0 : 1;
4019 int afterInsertPos = foldPos + foldVals;
4020 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
4021 if (ok) {
4022 for (int i = 0; i < foldArgs; i++) {
4023 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
4024 ok = false;
4025 break;
4026 }
4027 }
4028 }
4029 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
4030 ok = false;
4031 if (!ok)
4032 throw misMatchedTypes("target and combiner types", targetType, combinerType);
4033 return rtype;
4034 }
4035
4036 /**
4037 * Makes a method handle which adapts a target method handle,
4038 * by guarding it with a test, a boolean-valued method handle.
4039 * If the guard fails, a fallback handle is called instead.
4040 * All three method handles must have the same corresponding
4041 * argument and return types, except that the return type
4042 * of the test must be boolean, and the test is allowed
4043 * to have fewer arguments than the other two method handles.
4044 * <p> Here is pseudocode for the resulting adapter:
4045 * <blockquote><pre>{@code
4046 * boolean test(A...);
4047 * T target(A...,B...);
4048 * T fallback(A...,B...);
4049 * T adapter(A... a,B... b) {
4050 * if (test(a...))
4051 * return target(a..., b...);
4052 * else
4053 * return fallback(a..., b...);
4054 * }
4055 * }</pre></blockquote>
4056 * Note that the test arguments ({@code a...} in the pseudocode) cannot
4057 * be modified by execution of the test, and so are passed unchanged
4058 * from the caller to the target or fallback as appropriate.
4059 * @param test method handle used for test, must return boolean
4060 * @param target method handle to call if test passes
4061 * @param fallback method handle to call if test fails
4062 * @return method handle which incorporates the specified if/then/else logic
4063 * @throws NullPointerException if any argument is null
4064 * @throws IllegalArgumentException if {@code test} does not return boolean,
4065 * or if all three method types do not match (with the return
4066 * type of {@code test} changed to match that of the target).
4067 */
4068 public static
4069 MethodHandle guardWithTest(MethodHandle test,
4070 MethodHandle target,
4071 MethodHandle fallback) {
4072 MethodType gtype = test.type();
4073 MethodType ttype = target.type();
4074 MethodType ftype = fallback.type();
4075 if (!ttype.equals(ftype))
4076 throw misMatchedTypes("target and fallback types", ttype, ftype);
4077 if (gtype.returnType() != boolean.class)
4078 throw newIllegalArgumentException("guard type is not a predicate "+gtype);
4079 List<Class<?>> targs = ttype.parameterList();
4080 List<Class<?>> gargs = gtype.parameterList();
4081 if (!targs.equals(gargs)) {
4082 int gpc = gargs.size(), tpc = targs.size();
4083 if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs))
4084 throw misMatchedTypes("target and test types", ttype, gtype);
4085 test = dropArguments(test, gpc, targs.subList(gpc, tpc));
4086 gtype = test.type();
4087 }
4088
4089 return new Transformers.GuardWithTest(test, target, fallback);
4090 }
4091
4092 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
4093 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
4094 }
4095
4096 /**
4097 * Makes a method handle which adapts a target method handle,
4098 * by running it inside an exception handler.
4099 * If the target returns normally, the adapter returns that value.
4100 * If an exception matching the specified type is thrown, the fallback
4101 * handle is called instead on the exception, plus the original arguments.
4102 * <p>
4103 * The target and handler must have the same corresponding
4104 * argument and return types, except that handler may omit trailing arguments
4105 * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
4106 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
4107 * <p>
4108 * Here is pseudocode for the resulting adapter. In the code, {@code T}
4109 * represents the return type of the {@code target} and {@code handler},
4110 * and correspondingly that of the resulting adapter; {@code A}/{@code a},
4111 * the types and values of arguments to the resulting handle consumed by
4112 * {@code handler}; and {@code B}/{@code b}, those of arguments to the
4113 * resulting handle discarded by {@code handler}.
4114 * <blockquote><pre>{@code
4115 * T target(A..., B...);
4116 * T handler(ExType, A...);
4117 * T adapter(A... a, B... b) {
4118 * try {
4119 * return target(a..., b...);
4120 * } catch (ExType ex) {
4121 * return handler(ex, a...);
4122 * }
4123 * }
4124 * }</pre></blockquote>
4125 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4126 * be modified by execution of the target, and so are passed unchanged
4127 * from the caller to the handler, if the handler is invoked.
4128 * <p>
4129 * The target and handler must return the same type, even if the handler
4130 * always throws. (This might happen, for instance, because the handler
4131 * is simulating a {@code finally} clause).
4132 * To create such a throwing handler, compose the handler creation logic
4133 * with {@link #throwException throwException},
4134 * in order to create a method handle of the correct return type.
4135 * @param target method handle to call
4136 * @param exType the type of exception which the handler will catch
4137 * @param handler method handle to call if a matching exception is thrown
4138 * @return method handle which incorporates the specified try/catch logic
4139 * @throws NullPointerException if any argument is null
4140 * @throws IllegalArgumentException if {@code handler} does not accept
4141 * the given exception type, or if the method handle types do
4142 * not match in their return types and their
4143 * corresponding parameters
4144 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
4145 */
4146 public static
4147 MethodHandle catchException(MethodHandle target,
4148 Class<? extends Throwable> exType,
4149 MethodHandle handler) {
4150 MethodType ttype = target.type();
4151 MethodType htype = handler.type();
4152 if (!Throwable.class.isAssignableFrom(exType))
4153 throw new ClassCastException(exType.getName());
4154 if (htype.parameterCount() < 1 ||
4155 !htype.parameterType(0).isAssignableFrom(exType))
4156 throw newIllegalArgumentException("handler does not accept exception type "+exType);
4157 if (htype.returnType() != ttype.returnType())
4158 throw misMatchedTypes("target and handler return types", ttype, htype);
4159 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
4160 if (handler == null) {
4161 throw misMatchedTypes("target and handler types", ttype, htype);
4162 }
4163 // Android-changed: use Transformer implementation.
4164 // return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
4165 return new Transformers.CatchException(target, handler, exType);
4166 }
4167
4168 /**
4169 * Produces a method handle which will throw exceptions of the given {@code exType}.
4170 * The method handle will accept a single argument of {@code exType},
4171 * and immediately throw it as an exception.
4172 * The method type will nominally specify a return of {@code returnType}.
4173 * The return type may be anything convenient: It doesn't matter to the
4174 * method handle's behavior, since it will never return normally.
4175 * @param returnType the return type of the desired method handle
4176 * @param exType the parameter type of the desired method handle
4177 * @return method handle which can throw the given exceptions
4178 * @throws NullPointerException if either argument is null
4179 */
4180 public static
4181 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
4182 if (!Throwable.class.isAssignableFrom(exType))
4183 throw new ClassCastException(exType.getName());
4184 // Android-changed: use Transformer implementation.
4185 // return MethodHandleImpl.throwException(methodType(returnType, exType));
4186 return new Transformers.AlwaysThrow(returnType, exType);
4187 }
4188
4189 /**
4190 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
4191 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
4192 * delivers the loop's result, which is the return value of the resulting handle.
4193 * <p>
4194 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
4195 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
4196 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
4197 * terms of method handles, each clause will specify up to four independent actions:<ul>
4198 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
4199 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
4200 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
4201 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
4202 * </ul>
4203 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
4204 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually
4205 * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
4206 * <p>
4207 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
4208 * this case. See below for a detailed description.
4209 * <p>
4210 * <em>Parameters optional everywhere:</em>
4211 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
4212 * As an exception, the init functions cannot take any {@code v} parameters,
4213 * because those values are not yet computed when the init functions are executed.
4214 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
4215 * In fact, any clause function may take no arguments at all.
4216 * <p>
4217 * <em>Loop parameters:</em>
4218 * A clause function may take all the iteration variable values it is entitled to, in which case
4219 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
4220 * with their types and values notated as {@code (A...)} and {@code (a...)}.
4221 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
4222 * (Since init functions do not accept iteration variables {@code v}, any parameter to an
4223 * init function is automatically a loop parameter {@code a}.)
4224 * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
4225 * These loop parameters act as loop-invariant values visible across the whole loop.
4226 * <p>
4227 * <em>Parameters visible everywhere:</em>
4228 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
4229 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
4230 * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
4231 * Most clause functions will not need all of this information, but they will be formally connected to it
4232 * as if by {@link #dropArguments}.
4233 * <a id="astar"></a>
4234 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
4235 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
4236 * In that notation, the general form of an init function parameter list
4237 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
4238 * <p>
4239 * <em>Checking clause structure:</em>
4240 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
4241 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
4242 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
4243 * met by the inputs to the loop combinator.
4244 * <p>
4245 * <em>Effectively identical sequences:</em>
4246 * <a id="effid"></a>
4247 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
4248 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
4249 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
4250 * as a whole if the set contains a longest list, and all members of the set are effectively identical to
4251 * that longest list.
4252 * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
4253 * and the same is true if more sequences of the form {@code (V... A*)} are added.
4254 * <p>
4255 * <em>Step 0: Determine clause structure.</em><ol type="a">
4256 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
4257 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
4258 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
4259 * four. Padding takes place by appending elements to the array.
4260 * <li>Clauses with all {@code null}s are disregarded.
4261 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
4262 * </ol>
4263 * <p>
4264 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
4265 * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
4266 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
4267 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
4268 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
4269 * iteration variable type.
4270 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
4271 * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
4272 * </ol>
4273 * <p>
4274 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
4275 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
4276 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
4277 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
4278 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
4279 * (These types will be checked in step 2, along with all the clause function types.)
4280 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.)
4281 * <li>All of the collected parameter lists must be effectively identical.
4282 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
4283 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
4284 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
4285 * the "internal parameter list".
4286 * </ul>
4287 * <p>
4288 * <em>Step 1C: Determine loop return type.</em><ol type="a">
4289 * <li>Examine fini function return types, disregarding omitted fini functions.
4290 * <li>If there are no fini functions, the loop return type is {@code void}.
4291 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
4292 * type.
4293 * </ol>
4294 * <p>
4295 * <em>Step 1D: Check other types.</em><ol type="a">
4296 * <li>There must be at least one non-omitted pred function.
4297 * <li>Every non-omitted pred function must have a {@code boolean} return type.
4298 * </ol>
4299 * <p>
4300 * <em>Step 2: Determine parameter lists.</em><ol type="a">
4301 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
4302 * <li>The parameter list for init functions will be adjusted to the external parameter list.
4303 * (Note that their parameter lists are already effectively identical to this list.)
4304 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
4305 * effectively identical to the internal parameter list {@code (V... A...)}.
4306 * </ol>
4307 * <p>
4308 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4309 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
4310 * type.
4311 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4312 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4313 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4314 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4315 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.)
4316 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
4317 * loop return type.
4318 * </ol>
4319 * <p>
4320 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4321 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
4322 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
4323 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
4324 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
4325 * pad out the end of the list.
4326 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
4327 * </ol>
4328 * <p>
4329 * <em>Final observations.</em><ol type="a">
4330 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4331 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
4332 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
4333 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
4334 * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
4335 * <li>Each pair of init and step functions agrees in their return type {@code V}.
4336 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
4337 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
4338 * </ol>
4339 * <p>
4340 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
4341 * <ul>
4342 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
4343 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
4344 * (Only one {@code Pn} has to be non-{@code null}.)
4345 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
4346 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
4347 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
4348 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
4349 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
4350 * the resulting loop handle's parameter types {@code (A...)}.
4351 * </ul>
4352 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
4353 * which is natural if most of the loop computation happens in the steps. For some loops,
4354 * the burden of computation might be heaviest in the pred functions, and so the pred functions
4355 * might need to accept the loop parameter values. For loops with complex exit logic, the fini
4356 * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
4357 * where the init functions will need the extra parameters. For such reasons, the rules for
4358 * determining these parameters are as symmetric as possible, across all clause parts.
4359 * In general, the loop parameters function as common invariant values across the whole
4360 * loop, while the iteration variables function as common variant values, or (if there is
4361 * no step function) as internal loop invariant temporaries.
4362 * <p>
4363 * <em>Loop execution.</em><ol type="a">
4364 * <li>When the loop is called, the loop input values are saved in locals, to be passed to
4365 * every clause function. These locals are loop invariant.
4366 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
4367 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
4368 * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
4369 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
4370 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
4371 * (in argument order).
4372 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
4373 * returns {@code false}.
4374 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
4375 * sequence {@code (v...)} of loop variables.
4376 * The updated value is immediately visible to all subsequent function calls.
4377 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
4378 * (of type {@code R}) is returned from the loop as a whole.
4379 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
4380 * except by throwing an exception.
4381 * </ol>
4382 * <p>
4383 * <em>Usage tips.</em>
4384 * <ul>
4385 * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
4386 * sometimes a step function only needs to observe the current value of its own variable.
4387 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
4388 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
4389 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create
4390 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be
4391 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
4392 * <li>If some of the clause functions are virtual methods on an instance, the instance
4393 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
4394 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference
4395 * will be the first iteration variable value, and it will be easy to use virtual
4396 * methods as clause parts, since all of them will take a leading instance reference matching that value.
4397 * </ul>
4398 * <p>
4399 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
4400 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
4401 * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
4402 * <blockquote><pre>{@code
4403 * V... init...(A...);
4404 * boolean pred...(V..., A...);
4405 * V... step...(V..., A...);
4406 * R fini...(V..., A...);
4407 * R loop(A... a) {
4408 * V... v... = init...(a...);
4409 * for (;;) {
4410 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4411 * v = s(v..., a...);
4412 * if (!p(v..., a...)) {
4413 * return f(v..., a...);
4414 * }
4415 * }
4416 * }
4417 * }
4418 * }</pre></blockquote>
4419 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
4420 * to their full length, even though individual clause functions may neglect to take them all.
4421 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
4422 *
4423 * @apiNote Example:
4424 * <blockquote><pre>{@code
4425 * // iterative implementation of the factorial function as a loop handle
4426 * static int one(int k) { return 1; }
4427 * static int inc(int i, int acc, int k) { return i + 1; }
4428 * static int mult(int i, int acc, int k) { return i * acc; }
4429 * static boolean pred(int i, int acc, int k) { return i < k; }
4430 * static int fin(int i, int acc, int k) { return acc; }
4431 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4432 * // null initializer for counter, should initialize to 0
4433 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4434 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4435 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4436 * assertEquals(120, loop.invoke(5));
4437 * }</pre></blockquote>
4438 * The same example, dropping arguments and using combinators:
4439 * <blockquote><pre>{@code
4440 * // simplified implementation of the factorial function as a loop handle
4441 * static int inc(int i) { return i + 1; } // drop acc, k
4442 * static int mult(int i, int acc) { return i * acc; } //drop k
4443 * static boolean cmp(int i, int k) { return i < k; }
4444 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
4445 * // null initializer for counter, should initialize to 0
4446 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
4447 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
4448 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
4449 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4450 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4451 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4452 * assertEquals(720, loop.invoke(6));
4453 * }</pre></blockquote>
4454 * A similar example, using a helper object to hold a loop parameter:
4455 * <blockquote><pre>{@code
4456 * // instance-based implementation of the factorial function as a loop handle
4457 * static class FacLoop {
4458 * final int k;
4459 * FacLoop(int k) { this.k = k; }
4460 * int inc(int i) { return i + 1; }
4461 * int mult(int i, int acc) { return i * acc; }
4462 * boolean pred(int i) { return i < k; }
4463 * int fin(int i, int acc) { return acc; }
4464 * }
4465 * // assume MH_FacLoop is a handle to the constructor
4466 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4467 * // null initializer for counter, should initialize to 0
4468 * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
4469 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
4470 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4471 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4472 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
4473 * assertEquals(5040, loop.invoke(7));
4474 * }</pre></blockquote>
4475 *
4476 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
4477 *
4478 * @return a method handle embodying the looping behavior as defined by the arguments.
4479 *
4480 * @throws IllegalArgumentException in case any of the constraints described above is violated.
4481 *
4482 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
4483 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4484 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
4485 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
4486 * @since 9
4487 */
4488 public static MethodHandle loop(MethodHandle[]... clauses) {
4489 // Step 0: determine clause structure.
4490 loopChecks0(clauses);
4491
4492 List<MethodHandle> init = new ArrayList<>();
4493 List<MethodHandle> step = new ArrayList<>();
4494 List<MethodHandle> pred = new ArrayList<>();
4495 List<MethodHandle> fini = new ArrayList<>();
4496
4497 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
4498 init.add(clause[0]); // all clauses have at least length 1
4499 step.add(clause.length <= 1 ? null : clause[1]);
4500 pred.add(clause.length <= 2 ? null : clause[2]);
4501 fini.add(clause.length <= 3 ? null : clause[3]);
4502 });
4503
4504 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
4505 final int nclauses = init.size();
4506
4507 // Step 1A: determine iteration variables (V...).
4508 final List<Class<?>> iterationVariableTypes = new ArrayList<>();
4509 for (int i = 0; i < nclauses; ++i) {
4510 MethodHandle in = init.get(i);
4511 MethodHandle st = step.get(i);
4512 if (in == null && st == null) {
4513 iterationVariableTypes.add(void.class);
4514 } else if (in != null && st != null) {
4515 loopChecks1a(i, in, st);
4516 iterationVariableTypes.add(in.type().returnType());
4517 } else {
4518 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
4519 }
4520 }
4521 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
4522 collect(Collectors.toList());
4523
4524 // Step 1B: determine loop parameters (A...).
4525 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
4526 loopChecks1b(init, commonSuffix);
4527
4528 // Step 1C: determine loop return type.
4529 // Step 1D: check other types.
4530 // local variable required here; see JDK-8223553
4531 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
4532 .map(MethodType::returnType);
4533 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
4534 loopChecks1cd(pred, fini, loopReturnType);
4535
4536 // Step 2: determine parameter lists.
4537 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
4538 commonParameterSequence.addAll(commonSuffix);
4539 loopChecks2(step, pred, fini, commonParameterSequence);
4540
4541 // Step 3: fill in omitted functions.
4542 for (int i = 0; i < nclauses; ++i) {
4543 Class<?> t = iterationVariableTypes.get(i);
4544 if (init.get(i) == null) {
4545 init.set(i, empty(methodType(t, commonSuffix)));
4546 }
4547 if (step.get(i) == null) {
4548 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
4549 }
4550 if (pred.get(i) == null) {
4551 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
4552 }
4553 if (fini.get(i) == null) {
4554 fini.set(i, empty(methodType(t, commonParameterSequence)));
4555 }
4556 }
4557
4558 // Step 4: fill in missing parameter types.
4559 // Also convert all handles to fixed-arity handles.
4560 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
4561 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
4562 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
4563 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
4564
4565 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
4566 allMatch(pl -> pl.equals(commonSuffix));
4567 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
4568 allMatch(pl -> pl.equals(commonParameterSequence));
4569
4570 // Android-changed: transformer implementation.
4571 // return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
4572 return new Transformers.Loop(loopReturnType,
4573 commonSuffix,
4574 finit.toArray(MethodHandle[]::new),
4575 fstep.toArray(MethodHandle[]::new),
4576 fpred.toArray(MethodHandle[]::new),
4577 ffini.toArray(MethodHandle[]::new));
4578 }
4579
4580 private static void loopChecks0(MethodHandle[][] clauses) {
4581 if (clauses == null || clauses.length == 0) {
4582 throw newIllegalArgumentException("null or no clauses passed");
4583 }
4584 if (Stream.of(clauses).anyMatch(Objects::isNull)) {
4585 throw newIllegalArgumentException("null clauses are not allowed");
4586 }
4587 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4588 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4589 }
4590 }
4591
4592 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
4593 if (in.type().returnType() != st.type().returnType()) {
4594 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4595 st.type().returnType());
4596 }
4597 }
4598
4599 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
4600 final List<Class<?>> empty = List.of();
4601 final List<Class<?>> longest = mhs.filter(Objects::nonNull).
4602 // take only those that can contribute to a common suffix because they are longer than the prefix
4603 map(MethodHandle::type).
4604 filter(t -> t.parameterCount() > skipSize).
4605 map(MethodType::parameterList).
4606 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4607 return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size());
4608 }
4609
4610 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
4611 final List<Class<?>> empty = List.of();
4612 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4613 }
4614
4615 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
4616 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
4617 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
4618 return longestParameterList(Arrays.asList(longest1, longest2));
4619 }
4620
4621 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4622 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
4623 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
4624 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4625 " (common suffix: " + commonSuffix + ")");
4626 }
4627 }
4628
4629 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4630 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4631 anyMatch(t -> t != loopReturnType)) {
4632 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4633 loopReturnType + ")");
4634 }
4635
4636 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4637 throw newIllegalArgumentException("no predicate found", pred);
4638 }
4639 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4640 anyMatch(t -> t != boolean.class)) {
4641 throw newIllegalArgumentException("predicates must have boolean return type", pred);
4642 }
4643 }
4644
4645 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
4646 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
4647 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
4648 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4649 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4650 }
4651 }
4652
4653 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
4654 return hs.stream().map(h -> {
4655 int pc = h.type().parameterCount();
4656 int tpsize = targetParams.size();
4657 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
4658 }).collect(Collectors.toList());
4659 }
4660
4661 private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
4662 return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList());
4663 }
4664
4665 /**
4666 * Constructs a {@code while} loop from an initializer, a body, and a predicate.
4667 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4668 * <p>
4669 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
4670 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
4671 * evaluates to {@code true}).
4672 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
4673 * <p>
4674 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
4675 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
4676 * and updated with the value returned from its invocation. The result of loop execution will be
4677 * the final value of the additional loop-local variable (if present).
4678 * <p>
4679 * The following rules hold for these argument handles:<ul>
4680 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
4681 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
4682 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
4683 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
4684 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
4685 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
4686 * It will constrain the parameter lists of the other loop parts.
4687 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
4688 * list {@code (A...)} is called the <em>external parameter list</em>.
4689 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
4690 * additional state variable of the loop.
4691 * The body must both accept and return a value of this type {@code V}.
4692 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
4693 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
4694 * <a href="MethodHandles.html#effid">effectively identical</a>
4695 * to the external parameter list {@code (A...)}.
4696 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
4697 * {@linkplain #empty default value}.
4698 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
4699 * Its parameter list (either empty or of the form {@code (V A*)}) must be
4700 * effectively identical to the internal parameter list.
4701 * </ul>
4702 * <p>
4703 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
4704 * <li>The loop handle's result type is the result type {@code V} of the body.
4705 * <li>The loop handle's parameter types are the types {@code (A...)},
4706 * from the external parameter list.
4707 * </ul>
4708 * <p>
4709 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4710 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4711 * passed to the loop.
4712 * <blockquote><pre>{@code
4713 * V init(A...);
4714 * boolean pred(V, A...);
4715 * V body(V, A...);
4716 * V whileLoop(A... a...) {
4717 * V v = init(a...);
4718 * while (pred(v, a...)) {
4719 * v = body(v, a...);
4720 * }
4721 * return v;
4722 * }
4723 * }</pre></blockquote>
4724 *
4725 * @apiNote Example:
4726 * <blockquote><pre>{@code
4727 * // implement the zip function for lists as a loop handle
4728 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
4729 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
4730 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
4731 * zip.add(a.next());
4732 * zip.add(b.next());
4733 * return zip;
4734 * }
4735 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
4736 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
4737 * List<String> a = Arrays.asList("a", "b", "c", "d");
4738 * List<String> b = Arrays.asList("e", "f", "g", "h");
4739 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
4740 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
4741 * }</pre></blockquote>
4742 *
4743 *
4744 * @apiNote The implementation of this method can be expressed as follows:
4745 * <blockquote><pre>{@code
4746 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4747 * MethodHandle fini = (body.type().returnType() == void.class
4748 * ? null : identity(body.type().returnType()));
4749 * MethodHandle[]
4750 * checkExit = { null, null, pred, fini },
4751 * varBody = { init, body };
4752 * return loop(checkExit, varBody);
4753 * }
4754 * }</pre></blockquote>
4755 *
4756 * @param init optional initializer, providing the initial value of the loop variable.
4757 * May be {@code null}, implying a default initial value. See above for other constraints.
4758 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
4759 * above for other constraints.
4760 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
4761 * See above for other constraints.
4762 *
4763 * @return a method handle implementing the {@code while} loop as described by the arguments.
4764 * @throws IllegalArgumentException if the rules for the arguments are violated.
4765 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
4766 *
4767 * @see #loop(MethodHandle[][])
4768 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4769 * @since 9
4770 */
4771 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4772 whileLoopChecks(init, pred, body);
4773 MethodHandle fini = identityOrVoid(body.type().returnType());
4774 MethodHandle[] checkExit = { null, null, pred, fini };
4775 MethodHandle[] varBody = { init, body };
4776 return loop(checkExit, varBody);
4777 }
4778
4779 /**
4780 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
4781 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4782 * <p>
4783 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
4784 * method will, in each iteration, first execute its body and then evaluate the predicate.
4785 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
4786 * <p>
4787 * The {@code init} handle describes the initial value of an additional optional loop-local variable.
4788 * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
4789 * and updated with the value returned from its invocation. The result of loop execution will be
4790 * the final value of the additional loop-local variable (if present).
4791 * <p>
4792 * The following rules hold for these argument handles:<ul>
4793 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
4794 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
4795 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
4796 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
4797 * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
4798 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
4799 * It will constrain the parameter lists of the other loop parts.
4800 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
4801 * list {@code (A...)} is called the <em>external parameter list</em>.
4802 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
4803 * additional state variable of the loop.
4804 * The body must both accept and return a value of this type {@code V}.
4805 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
4806 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
4807 * <a href="MethodHandles.html#effid">effectively identical</a>
4808 * to the external parameter list {@code (A...)}.
4809 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
4810 * {@linkplain #empty default value}.
4811 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type.
4812 * Its parameter list (either empty or of the form {@code (V A*)}) must be
4813 * effectively identical to the internal parameter list.
4814 * </ul>
4815 * <p>
4816 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
4817 * <li>The loop handle's result type is the result type {@code V} of the body.
4818 * <li>The loop handle's parameter types are the types {@code (A...)},
4819 * from the external parameter list.
4820 * </ul>
4821 * <p>
4822 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4823 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4824 * passed to the loop.
4825 * <blockquote><pre>{@code
4826 * V init(A...);
4827 * boolean pred(V, A...);
4828 * V body(V, A...);
4829 * V doWhileLoop(A... a...) {
4830 * V v = init(a...);
4831 * do {
4832 * v = body(v, a...);
4833 * } while (pred(v, a...));
4834 * return v;
4835 * }
4836 * }</pre></blockquote>
4837 *
4838 * @apiNote Example:
4839 * <blockquote><pre>{@code
4840 * // int i = 0; while (i < limit) { ++i; } return i; => limit
4841 * static int zero(int limit) { return 0; }
4842 * static int step(int i, int limit) { return i + 1; }
4843 * static boolean pred(int i, int limit) { return i < limit; }
4844 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
4845 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
4846 * assertEquals(23, loop.invoke(23));
4847 * }</pre></blockquote>
4848 *
4849 *
4850 * @apiNote The implementation of this method can be expressed as follows:
4851 * <blockquote><pre>{@code
4852 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4853 * MethodHandle fini = (body.type().returnType() == void.class
4854 * ? null : identity(body.type().returnType()));
4855 * MethodHandle[] clause = { init, body, pred, fini };
4856 * return loop(clause);
4857 * }
4858 * }</pre></blockquote>
4859 *
4860 * @param init optional initializer, providing the initial value of the loop variable.
4861 * May be {@code null}, implying a default initial value. See above for other constraints.
4862 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
4863 * See above for other constraints.
4864 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
4865 * above for other constraints.
4866 *
4867 * @return a method handle implementing the {@code while} loop as described by the arguments.
4868 * @throws IllegalArgumentException if the rules for the arguments are violated.
4869 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
4870 *
4871 * @see #loop(MethodHandle[][])
4872 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
4873 * @since 9
4874 */
4875 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4876 whileLoopChecks(init, pred, body);
4877 MethodHandle fini = identityOrVoid(body.type().returnType());
4878 MethodHandle[] clause = {init, body, pred, fini };
4879 return loop(clause);
4880 }
4881
4882 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
4883 Objects.requireNonNull(pred);
4884 Objects.requireNonNull(body);
4885 MethodType bodyType = body.type();
4886 Class<?> returnType = bodyType.returnType();
4887 List<Class<?>> innerList = bodyType.parameterList();
4888 List<Class<?>> outerList = innerList;
4889 if (returnType == void.class) {
4890 // OK
4891 } else if (innerList.size() == 0 || innerList.get(0) != returnType) {
4892 // leading V argument missing => error
4893 MethodType expected = bodyType.insertParameterTypes(0, returnType);
4894 throw misMatchedTypes("body function", bodyType, expected);
4895 } else {
4896 outerList = innerList.subList(1, innerList.size());
4897 }
4898 MethodType predType = pred.type();
4899 if (predType.returnType() != boolean.class ||
4900 !predType.effectivelyIdenticalParameters(0, innerList)) {
4901 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
4902 }
4903 if (init != null) {
4904 MethodType initType = init.type();
4905 if (initType.returnType() != returnType ||
4906 !initType.effectivelyIdenticalParameters(0, outerList)) {
4907 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
4908 }
4909 }
4910 }
4911
4912 /**
4913 * Constructs a loop that runs a given number of iterations.
4914 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4915 * <p>
4916 * The number of iterations is determined by the {@code iterations} handle evaluation result.
4917 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
4918 * It will be initialized to 0 and incremented by 1 in each iteration.
4919 * <p>
4920 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
4921 * of that type is also present. This variable is initialized using the optional {@code init} handle,
4922 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
4923 * <p>
4924 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
4925 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
4926 * iteration variable.
4927 * The result of the loop handle execution will be the final {@code V} value of that variable
4928 * (or {@code void} if there is no {@code V} variable).
4929 * <p>
4930 * The following rules hold for the argument handles:<ul>
4931 * <li>The {@code iterations} handle must not be {@code null}, and must return
4932 * the type {@code int}, referred to here as {@code I} in parameter type lists.
4933 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
4934 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
4935 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
4936 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
4937 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
4938 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
4939 * of types called the <em>internal parameter list</em>.
4940 * It will constrain the parameter lists of the other loop parts.
4941 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
4942 * with no additional {@code A} types, then the internal parameter list is extended by
4943 * the argument types {@code A...} of the {@code iterations} handle.
4944 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
4945 * list {@code (A...)} is called the <em>external parameter list</em>.
4946 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
4947 * additional state variable of the loop.
4948 * The body must both accept a leading parameter and return a value of this type {@code V}.
4949 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
4950 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
4951 * <a href="MethodHandles.html#effid">effectively identical</a>
4952 * to the external parameter list {@code (A...)}.
4953 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
4954 * {@linkplain #empty default value}.
4955 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
4956 * effectively identical to the external parameter list {@code (A...)}.
4957 * </ul>
4958 * <p>
4959 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
4960 * <li>The loop handle's result type is the result type {@code V} of the body.
4961 * <li>The loop handle's parameter types are the types {@code (A...)},
4962 * from the external parameter list.
4963 * </ul>
4964 * <p>
4965 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4966 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
4967 * arguments passed to the loop.
4968 * <blockquote><pre>{@code
4969 * int iterations(A...);
4970 * V init(A...);
4971 * V body(V, int, A...);
4972 * V countedLoop(A... a...) {
4973 * int end = iterations(a...);
4974 * V v = init(a...);
4975 * for (int i = 0; i < end; ++i) {
4976 * v = body(v, i, a...);
4977 * }
4978 * return v;
4979 * }
4980 * }</pre></blockquote>
4981 *
4982 * @apiNote Example with a fully conformant body method:
4983 * <blockquote><pre>{@code
4984 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
4985 * // => a variation on a well known theme
4986 * static String step(String v, int counter, String init) { return "na " + v; }
4987 * // assume MH_step is a handle to the method above
4988 * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
4989 * MethodHandle start = MethodHandles.identity(String.class);
4990 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
4991 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
4992 * }</pre></blockquote>
4993 *
4994 * @apiNote Example with the simplest possible body method type,
4995 * and passing the number of iterations to the loop invocation:
4996 * <blockquote><pre>{@code
4997 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
4998 * // => a variation on a well known theme
4999 * static String step(String v, int counter ) { return "na " + v; }
5000 * // assume MH_step is a handle to the method above
5001 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
5002 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
5003 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v
5004 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
5005 * }</pre></blockquote>
5006 *
5007 * @apiNote Example that treats the number of iterations, string to append to, and string to append
5008 * as loop parameters:
5009 * <blockquote><pre>{@code
5010 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5011 * // => a variation on a well known theme
5012 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
5013 * // assume MH_step is a handle to the method above
5014 * MethodHandle count = MethodHandles.identity(int.class);
5015 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
5016 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v
5017 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
5018 * }</pre></blockquote>
5019 *
5020 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
5021 * to enforce a loop type:
5022 * <blockquote><pre>{@code
5023 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
5024 * // => a variation on a well known theme
5025 * static String step(String v, int counter, String pre) { return pre + " " + v; }
5026 * // assume MH_step is a handle to the method above
5027 * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
5028 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1);
5029 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
5030 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0);
5031 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v
5032 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
5033 * }</pre></blockquote>
5034 *
5035 * @apiNote The implementation of this method can be expressed as follows:
5036 * <blockquote><pre>{@code
5037 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5038 * return countedLoop(empty(iterations.type()), iterations, init, body);
5039 * }
5040 * }</pre></blockquote>
5041 *
5042 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
5043 * result type must be {@code int}. See above for other constraints.
5044 * @param init optional initializer, providing the initial value of the loop variable.
5045 * May be {@code null}, implying a default initial value. See above for other constraints.
5046 * @param body body of the loop, which may not be {@code null}.
5047 * It controls the loop parameters and result type in the standard case (see above for details).
5048 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5049 * and may accept any number of additional types.
5050 * See above for other constraints.
5051 *
5052 * @return a method handle representing the loop.
5053 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
5054 * @throws IllegalArgumentException if any argument violates the rules formulated above.
5055 *
5056 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
5057 * @since 9
5058 */
5059 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
5060 return countedLoop(empty(iterations.type()), iterations, init, body);
5061 }
5062
5063 /**
5064 * Constructs a loop that counts over a range of numbers.
5065 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5066 * <p>
5067 * The loop counter {@code i} is a loop iteration variable of type {@code int}.
5068 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
5069 * values of the loop counter.
5070 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
5071 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
5072 * <p>
5073 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5074 * of that type is also present. This variable is initialized using the optional {@code init} handle,
5075 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5076 * <p>
5077 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5078 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5079 * iteration variable.
5080 * The result of the loop handle execution will be the final {@code V} value of that variable
5081 * (or {@code void} if there is no {@code V} variable).
5082 * <p>
5083 * The following rules hold for the argument handles:<ul>
5084 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
5085 * the common type {@code int}, referred to here as {@code I} in parameter type lists.
5086 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5087 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
5088 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5089 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
5090 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
5091 * <li>The parameter list {@code (V I A...)} of the body contributes to a list
5092 * of types called the <em>internal parameter list</em>.
5093 * It will constrain the parameter lists of the other loop parts.
5094 * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
5095 * with no additional {@code A} types, then the internal parameter list is extended by
5096 * the argument types {@code A...} of the {@code end} handle.
5097 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
5098 * list {@code (A...)} is called the <em>external parameter list</em>.
5099 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5100 * additional state variable of the loop.
5101 * The body must both accept a leading parameter and return a value of this type {@code V}.
5102 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5103 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5104 * <a href="MethodHandles.html#effid">effectively identical</a>
5105 * to the external parameter list {@code (A...)}.
5106 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5107 * {@linkplain #empty default value}.
5108 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
5109 * effectively identical to the external parameter list {@code (A...)}.
5110 * <li>Likewise, the parameter list of {@code end} must be effectively identical
5111 * to the external parameter list.
5112 * </ul>
5113 * <p>
5114 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5115 * <li>The loop handle's result type is the result type {@code V} of the body.
5116 * <li>The loop handle's parameter types are the types {@code (A...)},
5117 * from the external parameter list.
5118 * </ul>
5119 * <p>
5120 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5121 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
5122 * arguments passed to the loop.
5123 * <blockquote><pre>{@code
5124 * int start(A...);
5125 * int end(A...);
5126 * V init(A...);
5127 * V body(V, int, A...);
5128 * V countedLoop(A... a...) {
5129 * int e = end(a...);
5130 * int s = start(a...);
5131 * V v = init(a...);
5132 * for (int i = s; i < e; ++i) {
5133 * v = body(v, i, a...);
5134 * }
5135 * return v;
5136 * }
5137 * }</pre></blockquote>
5138 *
5139 * @apiNote The implementation of this method can be expressed as follows:
5140 * <blockquote><pre>{@code
5141 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5142 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
5143 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with
5144 * // the following semantics:
5145 * // MH_increment: (int limit, int counter) -> counter + 1
5146 * // MH_predicate: (int limit, int counter) -> counter < limit
5147 * Class<?> counterType = start.type().returnType(); // int
5148 * Class<?> returnType = body.type().returnType();
5149 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
5150 * if (returnType != void.class) { // ignore the V variable
5151 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
5152 * pred = dropArguments(pred, 1, returnType); // ditto
5153 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
5154 * }
5155 * body = dropArguments(body, 0, counterType); // ignore the limit variable
5156 * MethodHandle[]
5157 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
5158 * bodyClause = { init, body }, // v = init(); v = body(v, i)
5159 * indexVar = { start, incr }; // i = start(); i = i + 1
5160 * return loop(loopLimit, bodyClause, indexVar);
5161 * }
5162 * }</pre></blockquote>
5163 *
5164 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
5165 * See above for other constraints.
5166 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
5167 * {@code end-1}). The result type must be {@code int}. See above for other constraints.
5168 * @param init optional initializer, providing the initial value of the loop variable.
5169 * May be {@code null}, implying a default initial value. See above for other constraints.
5170 * @param body body of the loop, which may not be {@code null}.
5171 * It controls the loop parameters and result type in the standard case (see above for details).
5172 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
5173 * and may accept any number of additional types.
5174 * See above for other constraints.
5175 *
5176 * @return a method handle representing the loop.
5177 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
5178 * @throws IllegalArgumentException if any argument violates the rules formulated above.
5179 *
5180 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
5181 * @since 9
5182 */
5183 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5184 countedLoopChecks(start, end, init, body);
5185 Class<?> counterType = start.type().returnType(); // int, but who's counting?
5186 Class<?> limitType = end.type().returnType(); // yes, int again
5187 Class<?> returnType = body.type().returnType();
5188 // Android-changed: getConstantHandle is in MethodHandles.
5189 // MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
5190 // MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
5191 MethodHandle incr = getConstantHandle(MH_countedLoopStep);
5192 MethodHandle pred = getConstantHandle(MH_countedLoopPred);
5193 MethodHandle retv = null;
5194 if (returnType != void.class) {
5195 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i)
5196 pred = dropArguments(pred, 1, returnType); // ditto
5197 retv = dropArguments(identity(returnType), 0, counterType);
5198 }
5199 body = dropArguments(body, 0, counterType); // ignore the limit variable
5200 MethodHandle[]
5201 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v
5202 bodyClause = { init, body }, // v = init(); v = body(v, i)
5203 indexVar = { start, incr }; // i = start(); i = i + 1
5204 return loop(loopLimit, bodyClause, indexVar);
5205 }
5206
5207 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
5208 Objects.requireNonNull(start);
5209 Objects.requireNonNull(end);
5210 Objects.requireNonNull(body);
5211 Class<?> counterType = start.type().returnType();
5212 if (counterType != int.class) {
5213 MethodType expected = start.type().changeReturnType(int.class);
5214 throw misMatchedTypes("start function", start.type(), expected);
5215 } else if (end.type().returnType() != counterType) {
5216 MethodType expected = end.type().changeReturnType(counterType);
5217 throw misMatchedTypes("end function", end.type(), expected);
5218 }
5219 MethodType bodyType = body.type();
5220 Class<?> returnType = bodyType.returnType();
5221 List<Class<?>> innerList = bodyType.parameterList();
5222 // strip leading V value if present
5223 int vsize = (returnType == void.class ? 0 : 1);
5224 if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) {
5225 // argument list has no "V" => error
5226 MethodType expected = bodyType.insertParameterTypes(0, returnType);
5227 throw misMatchedTypes("body function", bodyType, expected);
5228 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
5229 // missing I type => error
5230 MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
5231 throw misMatchedTypes("body function", bodyType, expected);
5232 }
5233 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
5234 if (outerList.isEmpty()) {
5235 // special case; take lists from end handle
5236 outerList = end.type().parameterList();
5237 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
5238 }
5239 MethodType expected = methodType(counterType, outerList);
5240 if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
5241 throw misMatchedTypes("start parameter types", start.type(), expected);
5242 }
5243 if (end.type() != start.type() &&
5244 !end.type().effectivelyIdenticalParameters(0, outerList)) {
5245 throw misMatchedTypes("end parameter types", end.type(), expected);
5246 }
5247 if (init != null) {
5248 MethodType initType = init.type();
5249 if (initType.returnType() != returnType ||
5250 !initType.effectivelyIdenticalParameters(0, outerList)) {
5251 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
5252 }
5253 }
5254 }
5255
5256 /**
5257 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
5258 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
5259 * <p>
5260 * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
5261 * Each value it produces will be stored in a loop iteration variable of type {@code T}.
5262 * <p>
5263 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
5264 * of that type is also present. This variable is initialized using the optional {@code init} handle,
5265 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
5266 * <p>
5267 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
5268 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
5269 * iteration variable.
5270 * The result of the loop handle execution will be the final {@code V} value of that variable
5271 * (or {@code void} if there is no {@code V} variable).
5272 * <p>
5273 * The following rules hold for the argument handles:<ul>
5274 * <li>The {@code body} handle must not be {@code null}; its type must be of the form
5275 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
5276 * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
5277 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
5278 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
5279 * <li>The parameter list {@code (V T A...)} of the body contributes to a list
5280 * of types called the <em>internal parameter list</em>.
5281 * It will constrain the parameter lists of the other loop parts.
5282 * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
5283 * with no additional {@code A} types, then the internal parameter list is extended by
5284 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
5285 * single type {@code Iterable} is added and constitutes the {@code A...} list.
5286 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
5287 * list {@code (A...)} is called the <em>external parameter list</em>.
5288 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
5289 * additional state variable of the loop.
5290 * The body must both accept a leading parameter and return a value of this type {@code V}.
5291 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
5292 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
5293 * <a href="MethodHandles.html#effid">effectively identical</a>
5294 * to the external parameter list {@code (A...)}.
5295 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
5296 * {@linkplain #empty default value}.
5297 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
5298 * type {@code java.util.Iterator} or a subtype thereof.
5299 * The iterator it produces when the loop is executed will be assumed
5300 * to yield values which can be converted to type {@code T}.
5301 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
5302 * effectively identical to the external parameter list {@code (A...)}.
5303 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
5304 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list
5305 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
5306 * handle parameter is adjusted to accept the leading {@code A} type, as if by
5307 * the {@link MethodHandle#asType asType} conversion method.
5308 * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
5309 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
5310 * </ul>
5311 * <p>
5312 * The type {@code T} may be either a primitive or reference.
5313 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
5314 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
5315 * as if by the {@link MethodHandle#asType asType} conversion method.
5316 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
5317 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
5318 * <p>
5319 * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
5320 * <li>The loop handle's result type is the result type {@code V} of the body.
5321 * <li>The loop handle's parameter types are the types {@code (A...)},
5322 * from the external parameter list.
5323 * </ul>
5324 * <p>
5325 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
5326 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
5327 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
5328 * <blockquote><pre>{@code
5329 * Iterator<T> iterator(A...); // defaults to Iterable::iterator
5330 * V init(A...);
5331 * V body(V,T,A...);
5332 * V iteratedLoop(A... a...) {
5333 * Iterator<T> it = iterator(a...);
5334 * V v = init(a...);
5335 * while (it.hasNext()) {
5336 * T t = it.next();
5337 * v = body(v, t, a...);
5338 * }
5339 * return v;
5340 * }
5341 * }</pre></blockquote>
5342 *
5343 * @apiNote Example:
5344 * <blockquote><pre>{@code
5345 * // get an iterator from a list
5346 * static List<String> reverseStep(List<String> r, String e) {
5347 * r.add(0, e);
5348 * return r;
5349 * }
5350 * static List<String> newArrayList() { return new ArrayList<>(); }
5351 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
5352 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
5353 * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
5354 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
5355 * assertEquals(reversedList, (List<String>) loop.invoke(list));
5356 * }</pre></blockquote>
5357 *
5358 * @apiNote The implementation of this method can be expressed approximately as follows:
5359 * <blockquote><pre>{@code
5360 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5361 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
5362 * Class<?> returnType = body.type().returnType();
5363 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
5364 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
5365 * MethodHandle retv = null, step = body, startIter = iterator;
5366 * if (returnType != void.class) {
5367 * // the simple thing first: in (I V A...), drop the I to get V
5368 * retv = dropArguments(identity(returnType), 0, Iterator.class);
5369 * // body type signature (V T A...), internal loop types (I V A...)
5370 * step = swapArguments(body, 0, 1); // swap V <-> T
5371 * }
5372 * if (startIter == null) startIter = MH_getIter;
5373 * MethodHandle[]
5374 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
5375 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a)
5376 * return loop(iterVar, bodyClause);
5377 * }
5378 * }</pre></blockquote>
5379 *
5380 * @param iterator an optional handle to return the iterator to start the loop.
5381 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
5382 * See above for other constraints.
5383 * @param init optional initializer, providing the initial value of the loop variable.
5384 * May be {@code null}, implying a default initial value. See above for other constraints.
5385 * @param body body of the loop, which may not be {@code null}.
5386 * It controls the loop parameters and result type in the standard case (see above for details).
5387 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
5388 * and may accept any number of additional types.
5389 * See above for other constraints.
5390 *
5391 * @return a method handle embodying the iteration loop functionality.
5392 * @throws NullPointerException if the {@code body} handle is {@code null}.
5393 * @throws IllegalArgumentException if any argument violates the above requirements.
5394 *
5395 * @since 9
5396 */
5397 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5398 Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
5399 Class<?> returnType = body.type().returnType();
5400 // Android-changed: getConstantHandle is in MethodHandles.
5401 // MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
5402 // MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
5403 MethodHandle hasNext = getConstantHandle(MH_iteratePred);
5404 MethodHandle nextRaw = getConstantHandle(MH_iterateNext);
5405 MethodHandle startIter;
5406 MethodHandle nextVal;
5407 {
5408 MethodType iteratorType;
5409 if (iterator == null) {
5410 // derive argument type from body, if available, else use Iterable
5411 // Android-changed: getConstantHandle is in MethodHandles.
5412 // startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
5413 startIter = getConstantHandle(MH_initIterator);
5414 iteratorType = startIter.type().changeParameterType(0, iterableType);
5415 } else {
5416 // force return type to the internal iterator class
5417 iteratorType = iterator.type().changeReturnType(Iterator.class);
5418 startIter = iterator;
5419 }
5420 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
5421 MethodType nextValType = nextRaw.type().changeReturnType(ttype);
5422
5423 // perform the asType transforms under an exception transformer, as per spec.:
5424 try {
5425 startIter = startIter.asType(iteratorType);
5426 nextVal = nextRaw.asType(nextValType);
5427 } catch (WrongMethodTypeException ex) {
5428 throw new IllegalArgumentException(ex);
5429 }
5430 }
5431
5432 MethodHandle retv = null, step = body;
5433 if (returnType != void.class) {
5434 // the simple thing first: in (I V A...), drop the I to get V
5435 retv = dropArguments(identity(returnType), 0, Iterator.class);
5436 // body type signature (V T A...), internal loop types (I V A...)
5437 step = swapArguments(body, 0, 1); // swap V <-> T
5438 }
5439
5440 MethodHandle[]
5441 iterVar = { startIter, null, hasNext, retv },
5442 bodyClause = { init, filterArgument(step, 0, nextVal) };
5443 return loop(iterVar, bodyClause);
5444 }
5445
5446 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
5447 Objects.requireNonNull(body);
5448 MethodType bodyType = body.type();
5449 Class<?> returnType = bodyType.returnType();
5450 List<Class<?>> internalParamList = bodyType.parameterList();
5451 // strip leading V value if present
5452 int vsize = (returnType == void.class ? 0 : 1);
5453 if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) {
5454 // argument list has no "V" => error
5455 MethodType expected = bodyType.insertParameterTypes(0, returnType);
5456 throw misMatchedTypes("body function", bodyType, expected);
5457 } else if (internalParamList.size() <= vsize) {
5458 // missing T type => error
5459 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
5460 throw misMatchedTypes("body function", bodyType, expected);
5461 }
5462 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
5463 Class<?> iterableType = null;
5464 if (iterator != null) {
5465 // special case; if the body handle only declares V and T then
5466 // the external parameter list is obtained from iterator handle
5467 if (externalParamList.isEmpty()) {
5468 externalParamList = iterator.type().parameterList();
5469 }
5470 MethodType itype = iterator.type();
5471 if (!Iterator.class.isAssignableFrom(itype.returnType())) {
5472 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
5473 }
5474 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
5475 MethodType expected = methodType(itype.returnType(), externalParamList);
5476 throw misMatchedTypes("iterator parameters", itype, expected);
5477 }
5478 } else {
5479 if (externalParamList.isEmpty()) {
5480 // special case; if the iterator handle is null and the body handle
5481 // only declares V and T then the external parameter list consists
5482 // of Iterable
5483 externalParamList = Arrays.asList(Iterable.class);
5484 iterableType = Iterable.class;
5485 } else {
5486 // special case; if the iterator handle is null and the external
5487 // parameter list is not empty then the first parameter must be
5488 // assignable to Iterable
5489 iterableType = externalParamList.get(0);
5490 if (!Iterable.class.isAssignableFrom(iterableType)) {
5491 throw newIllegalArgumentException(
5492 "inferred first loop argument must inherit from Iterable: " + iterableType);
5493 }
5494 }
5495 }
5496 if (init != null) {
5497 MethodType initType = init.type();
5498 if (initType.returnType() != returnType ||
5499 !initType.effectivelyIdenticalParameters(0, externalParamList)) {
5500 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
5501 }
5502 }
5503 return iterableType; // help the caller a bit
5504 }
5505
5506 /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
5507 // there should be a better way to uncross my wires
5508 int arity = mh.type().parameterCount();
5509 int[] order = new int[arity];
5510 for (int k = 0; k < arity; k++) order[k] = k;
5511 order[i] = j; order[j] = i;
5512 Class<?>[] types = mh.type().parameterArray();
5513 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
5514 MethodType swapType = methodType(mh.type().returnType(), types);
5515 return permuteArguments(mh, swapType, order);
5516 }
5517
5518 /**
5519 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
5520 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
5521 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
5522 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The
5523 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
5524 * {@code try-finally} handle.
5525 * <p>
5526 * The {@code cleanup} handle will be passed one or two additional leading arguments.
5527 * The first is the exception thrown during the
5528 * execution of the {@code target} handle, or {@code null} if no exception was thrown.
5529 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
5530 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
5531 * The second argument is not present if the {@code target} handle has a {@code void} return type.
5532 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
5533 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
5534 * <p>
5535 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
5536 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
5537 * two extra leading parameters:<ul>
5538 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
5539 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
5540 * the result from the execution of the {@code target} handle.
5541 * This parameter is not present if the {@code target} returns {@code void}.
5542 * </ul>
5543 * <p>
5544 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
5545 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
5546 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
5547 * the cleanup.
5548 * <blockquote><pre>{@code
5549 * V target(A..., B...);
5550 * V cleanup(Throwable, V, A...);
5551 * V adapter(A... a, B... b) {
5552 * V result = (zero value for V);
5553 * Throwable throwable = null;
5554 * try {
5555 * result = target(a..., b...);
5556 * } catch (Throwable t) {
5557 * throwable = t;
5558 * throw t;
5559 * } finally {
5560 * result = cleanup(throwable, result, a...);
5561 * }
5562 * return result;
5563 * }
5564 * }</pre></blockquote>
5565 * <p>
5566 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
5567 * be modified by execution of the target, and so are passed unchanged
5568 * from the caller to the cleanup, if it is invoked.
5569 * <p>
5570 * The target and cleanup must return the same type, even if the cleanup
5571 * always throws.
5572 * To create such a throwing cleanup, compose the cleanup logic
5573 * with {@link #throwException throwException},
5574 * in order to create a method handle of the correct return type.
5575 * <p>
5576 * Note that {@code tryFinally} never converts exceptions into normal returns.
5577 * In rare cases where exceptions must be converted in that way, first wrap
5578 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
5579 * to capture an outgoing exception, and then wrap with {@code tryFinally}.
5580 * <p>
5581 * It is recommended that the first parameter type of {@code cleanup} be
5582 * declared {@code Throwable} rather than a narrower subtype. This ensures
5583 * {@code cleanup} will always be invoked with whatever exception that
5584 * {@code target} throws. Declaring a narrower type may result in a
5585 * {@code ClassCastException} being thrown by the {@code try-finally}
5586 * handle if the type of the exception thrown by {@code target} is not
5587 * assignable to the first parameter type of {@code cleanup}. Note that
5588 * various exception types of {@code VirtualMachineError},
5589 * {@code LinkageError}, and {@code RuntimeException} can in principle be
5590 * thrown by almost any kind of Java code, and a finally clause that
5591 * catches (say) only {@code IOException} would mask any of the others
5592 * behind a {@code ClassCastException}.
5593 *
5594 * @param target the handle whose execution is to be wrapped in a {@code try} block.
5595 * @param cleanup the handle that is invoked in the finally block.
5596 *
5597 * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
5598 * @throws NullPointerException if any argument is null
5599 * @throws IllegalArgumentException if {@code cleanup} does not accept
5600 * the required leading arguments, or if the method handle types do
5601 * not match in their return types and their
5602 * corresponding trailing parameters
5603 *
5604 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
5605 * @since 9
5606 */
5607 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
5608 List<Class<?>> targetParamTypes = target.type().parameterList();
5609 Class<?> rtype = target.type().returnType();
5610
5611 tryFinallyChecks(target, cleanup);
5612
5613 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
5614 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
5615 // target parameter list.
5616 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
5617
5618 // Ensure that the intrinsic type checks the instance thrown by the
5619 // target against the first parameter of cleanup
5620 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
5621
5622 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
5623 // Android-changed: use Transformer implementation.
5624 // return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
5625 return new Transformers.TryFinally(target.asFixedArity(), cleanup.asFixedArity());
5626 }
5627
5628 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
5629 Class<?> rtype = target.type().returnType();
5630 if (rtype != cleanup.type().returnType()) {
5631 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
5632 }
5633 MethodType cleanupType = cleanup.type();
5634 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
5635 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
5636 }
5637 if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
5638 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
5639 }
5640 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
5641 // target parameter list.
5642 int cleanupArgIndex = rtype == void.class ? 1 : 2;
5643 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
5644 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
5645 cleanup.type(), target.type());
5646 }
5647 }
5648
5649 /**
5650 * Creates a table switch method handle, which can be used to switch over a set of target
5651 * method handles, based on a given target index, called selector.
5652 * <p>
5653 * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
5654 * and where {@code N} is the number of target method handles, the table switch method
5655 * handle will invoke the n-th target method handle from the list of target method handles.
5656 * <p>
5657 * For a selector value that does not fall in the range {@code [0, N)}, the table switch
5658 * method handle will invoke the given fallback method handle.
5659 * <p>
5660 * All method handles passed to this method must have the same type, with the additional
5661 * requirement that the leading parameter be of type {@code int}. The leading parameter
5662 * represents the selector.
5663 * <p>
5664 * Any trailing parameters present in the type will appear on the returned table switch
5665 * method handle as well. Any arguments assigned to these parameters will be forwarded,
5666 * together with the selector value, to the selected method handle when invoking it.
5667 *
5668 * @apiNote Example:
5669 * The cases each drop the {@code selector} value they are given, and take an additional
5670 * {@code String} argument, which is concatenated (using {@link String#concat(String)})
5671 * to a specific constant label string for each case:
5672 * <blockquote><pre>{@code
5673 * MethodHandles.Lookup lookup = MethodHandles.lookup();
5674 * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
5675 * MethodType.methodType(String.class, String.class));
5676 * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
5677 *
5678 * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
5679 * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
5680 * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
5681 *
5682 * MethodHandle mhSwitch = MethodHandles.tableSwitch(
5683 * caseDefault,
5684 * case0,
5685 * case1
5686 * );
5687 *
5688 * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
5689 * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
5690 * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
5691 * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
5692 * }</pre></blockquote>
5693 *
5694 * @param fallback the fallback method handle that is called when the selector is not
5695 * within the range {@code [0, N)}.
5696 * @param targets array of target method handles.
5697 * @return the table switch method handle.
5698 * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
5699 * any of the elements of the {@code targets} array are
5700 * {@code null}.
5701 * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
5702 * parameter of the fallback handle or any of the target
5703 * handles is not {@code int}, or if the types of
5704 * the fallback handle and all of target handles are
5705 * not the same.
5706 */
5707 public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
5708 Objects.requireNonNull(fallback);
5709 Objects.requireNonNull(targets);
5710 targets = targets.clone();
5711 MethodType type = tableSwitchChecks(fallback, targets);
5712 // Android-changed: use a Transformer for the implementation.
5713 // return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
5714 return new Transformers.TableSwitch(type, fallback, targets);
5715 }
5716
5717 private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
5718 if (caseActions.length == 0)
5719 throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
5720
5721 MethodType expectedType = defaultCase.type();
5722
5723 if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
5724 throw new IllegalArgumentException(
5725 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
5726
5727 for (MethodHandle mh : caseActions) {
5728 Objects.requireNonNull(mh);
5729 // Android-changed: MethodType's not interned.
5730 // if (mh.type() != expectedType)
5731 if (!mh.type().equals(expectedType))
5732 throw new IllegalArgumentException(
5733 "Case actions must have the same type: " + Arrays.toString(caseActions));
5734 }
5735
5736 return expectedType;
5737 }
5738
5739 // BEGIN Android-added: Code from OpenJDK's MethodHandleImpl.
5740
5741 /**
5742 * This method is bound as the predicate in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
5743 * MethodHandle) counting loops}.
5744 *
5745 * @param limit the upper bound of the parameter, statically bound at loop creation time.
5746 * @param counter the counter parameter, passed in during loop execution.
5747 *
5748 * @return whether the counter has reached the limit.
5749 * @hide
5750 */
5751 public static boolean countedLoopPredicate(int limit, int counter) {
5752 return counter < limit;
5753 }
5754
5755 /**
5756 * This method is bound as the step function in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
5757 * MethodHandle) counting loops} to increment the counter.
5758 *
5759 * @param limit the upper bound of the loop counter (ignored).
5760 * @param counter the loop counter.
5761 *
5762 * @return the loop counter incremented by 1.
5763 * @hide
5764 */
5765 public static int countedLoopStep(int limit, int counter) {
5766 return counter + 1;
5767 }
5768
5769 /**
5770 * This is bound to initialize the loop-local iterator in {@linkplain MethodHandles#iteratedLoop iterating loops}.
5771 *
5772 * @param it the {@link Iterable} over which the loop iterates.
5773 *
5774 * @return an {@link Iterator} over the argument's elements.
5775 * @hide
5776 */
5777 public static Iterator<?> initIterator(Iterable<?> it) {
5778 return it.iterator();
5779 }
5780
5781 /**
5782 * This method is bound as the predicate in {@linkplain MethodHandles#iteratedLoop iterating loops}.
5783 *
5784 * @param it the iterator to be checked.
5785 *
5786 * @return {@code true} iff there are more elements to iterate over.
5787 * @hide
5788 */
5789 public static boolean iteratePredicate(Iterator<?> it) {
5790 return it.hasNext();
5791 }
5792
5793 /**
5794 * This method is bound as the step for retrieving the current value from the iterator in {@linkplain
5795 * MethodHandles#iteratedLoop iterating loops}.
5796 *
5797 * @param it the iterator.
5798 *
5799 * @return the next element from the iterator.
5800 * @hide
5801 */
5802 public static Object iterateNext(Iterator<?> it) {
5803 return it.next();
5804 }
5805
5806 // Indexes into constant method handles:
5807 static final int
5808 MH_cast = 0,
5809 MH_selectAlternative = 1,
5810 MH_copyAsPrimitiveArray = 2,
5811 MH_fillNewTypedArray = 3,
5812 MH_fillNewArray = 4,
5813 MH_arrayIdentity = 5,
5814 MH_countedLoopPred = 6,
5815 MH_countedLoopStep = 7,
5816 MH_initIterator = 8,
5817 MH_iteratePred = 9,
5818 MH_iterateNext = 10,
5819 MH_Array_newInstance = 11,
5820 MH_LIMIT = 12;
5821
5822 static MethodHandle getConstantHandle(int idx) {
5823 MethodHandle handle = HANDLES[idx];
5824 if (handle != null) {
5825 return handle;
5826 }
5827 return setCachedHandle(idx, makeConstantHandle(idx));
5828 }
5829
5830 private static synchronized MethodHandle setCachedHandle(int idx, final MethodHandle method) {
5831 // Simulate a CAS, to avoid racy duplication of results.
5832 MethodHandle prev = HANDLES[idx];
5833 if (prev != null) {
5834 return prev;
5835 }
5836 HANDLES[idx] = method;
5837 return method;
5838 }
5839
5840 // Local constant method handles:
5841 private static final @Stable MethodHandle[] HANDLES = new MethodHandle[MH_LIMIT];
5842
5843 private static MethodHandle makeConstantHandle(int idx) {
5844 try {
5845 // Android-added: local IMPL_LOOKUP.
5846 final Lookup IMPL_LOOKUP = MethodHandles.Lookup.IMPL_LOOKUP;
5847 switch (idx) {
5848 // Android-removed: not-used.
5849 /*
5850 case MH_cast:
5851 return IMPL_LOOKUP.findVirtual(Class.class, "cast",
5852 MethodType.methodType(Object.class, Object.class));
5853 case MH_copyAsPrimitiveArray:
5854 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "copyAsPrimitiveArray",
5855 MethodType.methodType(Object.class, Wrapper.class, Object[].class));
5856 case MH_arrayIdentity:
5857 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "identity",
5858 MethodType.methodType(Object[].class, Object[].class));
5859 case MH_fillNewArray:
5860 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "fillNewArray",
5861 MethodType.methodType(Object[].class, Integer.class, Object[].class));
5862 case MH_fillNewTypedArray:
5863 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "fillNewTypedArray",
5864 MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
5865 case MH_selectAlternative:
5866 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative",
5867 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class));
5868 */
5869 case MH_countedLoopPred:
5870 // Android-changed: methods moved to this file.
5871 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopPredicate",
5872 // MethodType.methodType(boolean.class, int.class, int.class));
5873 return IMPL_LOOKUP.findStatic(MethodHandles.class, "countedLoopPredicate",
5874 MethodType.methodType(boolean.class, int.class, int.class));
5875 case MH_countedLoopStep:
5876 // Android-changed: methods moved to this file.
5877 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopStep",
5878 // MethodType.methodType(int.class, int.class, int.class));
5879 return IMPL_LOOKUP.findStatic(MethodHandles.class, "countedLoopStep",
5880 MethodType.methodType(int.class, int.class, int.class));
5881 case MH_initIterator:
5882 // Android-changed: methods moved to this file.
5883 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "initIterator",
5884 // MethodType.methodType(Iterator.class, Iterable.class));
5885 return IMPL_LOOKUP.findStatic(MethodHandles.class, "initIterator",
5886 MethodType.methodType(Iterator.class, Iterable.class));
5887 case MH_iteratePred:
5888 // Android-changed: methods moved to this file.
5889 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iteratePredicate",
5890 // MethodType.methodType(boolean.class, Iterator.class));
5891 return IMPL_LOOKUP.findStatic(MethodHandles.class, "iteratePredicate",
5892 MethodType.methodType(boolean.class, Iterator.class));
5893 case MH_iterateNext:
5894 // Android-changed: methods moved to this file.
5895 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iterateNext",
5896 // MethodType.methodType(Object.class, Iterator.class));
5897 return IMPL_LOOKUP.findStatic(MethodHandles.class, "iterateNext",
5898 MethodType.methodType(Object.class, Iterator.class));
5899 // Android-removed: not-used.
5900 /*
5901 case MH_Array_newInstance:
5902 return IMPL_LOOKUP.findStatic(Array.class, "newInstance",
5903 MethodType.methodType(Object.class, Class.class, int.class));
5904 */
5905 }
5906 } catch (ReflectiveOperationException ex) {
5907 throw newInternalError(ex);
5908 }
5909
5910 throw newInternalError("Unknown function index: " + idx);
5911 }
5912 // END Android-added: Code from OpenJDK's MethodHandleImpl.
5913}