blob: c3a97a178a30d426f3b43f363bf1365736386221 [file] [log] [blame]
John R Rosefb6164c2009-05-05 22:40:09 -07001/*
Michael Hauptd64d6d82016-01-14 13:53:13 +01002 * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
John R Rosefb6164c2009-05-05 22:40:09 -07003 * 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
Kelly O'Hairfe008ae2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
John R Rosefb6164c2009-05-05 22:40:09 -07008 * particular file as subject to the "Classpath" exception as provided
Kelly O'Hairfe008ae2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
John R Rosefb6164c2009-05-05 22:40:09 -070010 *
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 *
Kelly O'Hairfe008ae2010-05-25 15:58:33 -070021 * 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.
John R Rosefb6164c2009-05-05 22:40:09 -070024 */
25
John R Rose37188242011-03-23 23:02:31 -070026package java.lang.invoke;
John R Rosefb6164c2009-05-05 22:40:09 -070027
Paul Sandoz1af28062016-04-26 18:30:00 -070028import jdk.internal.org.objectweb.asm.ClassWriter;
29import jdk.internal.org.objectweb.asm.Opcodes;
30import jdk.internal.reflect.CallerSensitive;
31import jdk.internal.reflect.Reflection;
Mandy Chung176ed8d2013-04-16 21:39:52 -070032import sun.invoke.util.ValueConversions;
33import sun.invoke.util.VerifyAccess;
34import sun.invoke.util.Wrapper;
Christian Thalinger94bc7322013-05-08 12:09:35 -070035import sun.reflect.misc.ReflectUtil;
Mandy Chung176ed8d2013-04-16 21:39:52 -070036import sun.security.util.SecurityConstants;
Michael Haupt5b2c88e2015-11-20 15:34:12 +010037
Paul Sandoz1af28062016-04-26 18:30:00 -070038import java.lang.invoke.LambdaForm.BasicType;
39import java.lang.reflect.Constructor;
40import java.lang.reflect.Field;
41import java.lang.reflect.Member;
42import java.lang.reflect.Method;
43import java.lang.reflect.Modifier;
44import java.lang.reflect.ReflectPermission;
45import java.nio.ByteOrder;
46import java.security.AccessController;
47import java.security.PrivilegedAction;
48import java.util.ArrayList;
49import java.util.Arrays;
50import java.util.BitSet;
51import java.util.Iterator;
52import java.util.List;
53import java.util.Objects;
John R Rose62ee2112013-10-05 05:30:38 -070054import java.util.concurrent.ConcurrentHashMap;
Michael Haupt5b2c88e2015-11-20 15:34:12 +010055import java.util.stream.Collectors;
56import java.util.stream.Stream;
John R Rosefb6164c2009-05-05 22:40:09 -070057
Paul Sandoz1af28062016-04-26 18:30:00 -070058import static java.lang.invoke.MethodHandleImpl.Intrinsic;
59import static java.lang.invoke.MethodHandleNatives.Constants.*;
Paul Sandoz9fb30a32016-03-24 11:21:21 +010060import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
Michael Haupt402c4482016-04-19 14:39:35 +020061import static java.lang.invoke.MethodType.methodType;
Paul Sandoz9fb30a32016-03-24 11:21:21 +010062
John R Rosefb6164c2009-05-05 22:40:09 -070063/**
John R Rose0d30a782010-04-30 23:48:23 -070064 * This class consists exclusively of static methods that operate on or return
65 * method handles. They fall into several categories:
John R Rose020e5502010-01-07 16:16:45 -080066 * <ul>
John R Rose54e473f2011-02-11 01:26:28 -080067 * <li>Lookup methods which help create method handles for methods and fields.
68 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
69 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
John R Rose020e5502010-01-07 16:16:45 -080070 * </ul>
Alexander Stepanov0547ad22014-05-12 14:12:33 +040071 *
John R Rosefb6164c2009-05-05 22:40:09 -070072 * @author John Rose, JSR 292 EG
John Rose59440ee2013-09-03 21:42:56 -070073 * @since 1.7
John R Rosefb6164c2009-05-05 22:40:09 -070074 */
75public class MethodHandles {
76
77 private MethodHandles() { } // do not instantiate
78
John R Rosee7ebd472011-03-18 00:03:24 -070079 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
Claes Redestad4e062cd2015-12-19 02:24:27 +010080
John R Rosefb6164c2009-05-05 22:40:09 -070081 // See IMPL_LOOKUP below.
82
83 //// Method handle creation from ordinary methods.
84
John R Rose0d30a782010-04-30 23:48:23 -070085 /**
John R Rosebe5df962013-10-05 05:30:40 -070086 * Returns a {@link Lookup lookup object} with
87 * full capabilities to emulate all supported bytecode behaviors of the caller.
88 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller.
89 * Factory methods on the lookup object can create
90 * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
91 * for any member that the caller has access to via bytecodes,
92 * including protected and private fields and methods.
John R Rose0d30a782010-04-30 23:48:23 -070093 * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
94 * Do not store it in place where untrusted code can access it.
John R Rosebe5df962013-10-05 05:30:40 -070095 * <p>
96 * This method is caller sensitive, which means that it may return different
97 * values to different callers.
98 * <p>
99 * For any given caller class {@code C}, the lookup object returned by this call
100 * has equivalent capabilities to any lookup object
101 * supplied by the JVM to the bootstrap method of an
102 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a>
103 * executing in the same caller class {@code C}.
104 * @return a lookup object for the caller of this method, with private access
John R Rose020e5502010-01-07 16:16:45 -0800105 */
Mandy Chung176ed8d2013-04-16 21:39:52 -0700106 @CallerSensitive
John R Rosefb6164c2009-05-05 22:40:09 -0700107 public static Lookup lookup() {
Mandy Chung176ed8d2013-04-16 21:39:52 -0700108 return new Lookup(Reflection.getCallerClass());
John R Rosefb6164c2009-05-05 22:40:09 -0700109 }
110
John R Rose0d30a782010-04-30 23:48:23 -0700111 /**
John R Rose37188242011-03-23 23:02:31 -0700112 * Returns a {@link Lookup lookup object} which is trusted minimally.
Alan Batemandb4d3832016-03-17 19:04:16 +0000113 * It can only be used to create method handles to public members in
114 * public classes in packages that are exported unconditionally.
John R Rose6fbfeff2010-09-08 18:40:23 -0700115 * <p>
Alan Batemandb4d3832016-03-17 19:04:16 +0000116 * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup
117 * object is in an unnamed module.
Michael Hauptbfb7e8c2016-03-13 20:26:29 +0100118 * Consequently, the lookup context of this lookup object will be the bootstrap
119 * class loader, which means it cannot find user classes.
John R Rosebe5df962013-10-05 05:30:40 -0700120 *
121 * <p style="font-size:smaller;">
122 * <em>Discussion:</em>
John R Rose6fbfeff2010-09-08 18:40:23 -0700123 * The lookup class can be changed to any other class {@code C} using an expression of the form
John R Rosebe5df962013-10-05 05:30:40 -0700124 * {@link Lookup#in publicLookup().in(C.class)}.
Michael Hauptbfb7e8c2016-03-13 20:26:29 +0100125 * but may change the lookup context by virtue of changing the class loader.
John R Rosec5b5f0d2013-10-05 05:30:39 -0700126 * A public lookup object is always subject to
127 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
128 * Also, it cannot access
129 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
Joe Darcy0e32f672013-06-27 19:02:02 -0700130 * @return a lookup object which is trusted minimally
John R Rose020e5502010-01-07 16:16:45 -0800131 */
132 public static Lookup publicLookup() {
Alan Batemandb4d3832016-03-17 19:04:16 +0000133 // During VM startup then only classes in the java.base module can be
134 // loaded and linked. This is because java.base exports aren't setup until
135 // the module system is initialized, hence types in the unnamed module
136 // (or any named module) can't link to java/lang/Object.
137 if (!jdk.internal.misc.VM.isModuleSystemInited()) {
138 return new Lookup(Object.class, Lookup.PUBLIC);
139 } else {
140 return LookupHelper.PUBLIC_LOOKUP;
141 }
John R Rose020e5502010-01-07 16:16:45 -0800142 }
143
John R Rosefb6164c2009-05-05 22:40:09 -0700144 /**
John R Rosebe5df962013-10-05 05:30:40 -0700145 * Performs an unchecked "crack" of a
146 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
John Rose59440ee2013-09-03 21:42:56 -0700147 * The result is as if the user had obtained a lookup object capable enough
148 * to crack the target method handle, called
149 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
150 * on the target to obtain its symbolic reference, and then called
151 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
152 * to resolve the symbolic reference to a member.
153 * <p>
154 * If there is a security manager, its {@code checkPermission} method
155 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
156 * @param <T> the desired type of the result, either {@link Member} or a subtype
157 * @param target a direct method handle to crack into symbolic reference components
158 * @param expected a class object representing the desired result type {@code T}
159 * @return a reference to the method, constructor, or field object
160 * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
161 * @exception NullPointerException if either argument is {@code null}
162 * @exception IllegalArgumentException if the target is not a direct method handle
163 * @exception ClassCastException if the member is not of the expected type
164 * @since 1.8
165 */
166 public static <T extends Member> T
167 reflectAs(Class<T> expected, MethodHandle target) {
168 SecurityManager smgr = System.getSecurityManager();
169 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION);
170 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup
171 return lookup.revealDirect(target).reflectAs(expected, lookup);
172 }
173 // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
Martin Buchholza2f0fe32015-09-15 21:56:04 -0700174 private static final java.security.Permission ACCESS_PERMISSION =
John Rose59440ee2013-09-03 21:42:56 -0700175 new ReflectPermission("suppressAccessChecks");
176
177 /**
John R Rose0d30a782010-04-30 23:48:23 -0700178 * A <em>lookup object</em> is a factory for creating method handles,
179 * when the creation requires access checking.
180 * Method handles do not perform
John R Rose6fbfeff2010-09-08 18:40:23 -0700181 * access checks when they are called, but rather when they are created.
John R Rose0d30a782010-04-30 23:48:23 -0700182 * Therefore, method handle access
183 * restrictions must be enforced when a method handle is created.
John R Rosefb6164c2009-05-05 22:40:09 -0700184 * The caller class against which those restrictions are enforced
John R Rose0d30a782010-04-30 23:48:23 -0700185 * is known as the {@linkplain #lookupClass lookup class}.
John R Rose54e473f2011-02-11 01:26:28 -0800186 * <p>
187 * A lookup class which needs to create method handles will call
188 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
189 * When the {@code Lookup} factory object is created, the identity of the lookup class is
190 * determined, and securely stored in the {@code Lookup} object.
191 * The lookup class (or its delegates) may then use factory methods
192 * on the {@code Lookup} object to create method handles for access-checked members.
193 * This includes all methods, constructors, and fields which are allowed to the lookup class,
194 * even private ones.
Joe Darcy0e32f672013-06-27 19:02:02 -0700195 *
196 * <h1><a name="lookups"></a>Lookup Factory Methods</h1>
John R Rose54e473f2011-02-11 01:26:28 -0800197 * The factory methods on a {@code Lookup} object correspond to all major
198 * use cases for methods, constructors, and fields.
John R Rosebe5df962013-10-05 05:30:40 -0700199 * Each method handle created by a factory method is the functional
200 * equivalent of a particular <em>bytecode behavior</em>.
201 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
John R Rose54e473f2011-02-11 01:26:28 -0800202 * Here is a summary of the correspondence between these factory methods and
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100203 * the behavior of the resulting method handles:
John R Rose54e473f2011-02-11 01:26:28 -0800204 * <table border=1 cellpadding=5 summary="lookup method behaviors">
John R Rosebe5df962013-10-05 05:30:40 -0700205 * <tr>
206 * <th><a name="equiv"></a>lookup expression</th>
207 * <th>member</th>
208 * <th>bytecode behavior</th>
209 * </tr>
John R Rose54e473f2011-02-11 01:26:28 -0800210 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700211 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td>
212 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800213 * </tr>
214 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700215 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td>
216 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800217 * </tr>
218 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700219 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td>
220 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800221 * </tr>
222 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700223 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td>
224 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800225 * </tr>
226 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700227 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td>
228 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800229 * </tr>
230 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700231 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td>
232 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800233 * </tr>
234 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700235 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td>
236 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800237 * </tr>
238 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700239 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td>
240 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800241 * </tr>
242 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700243 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td>
244 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800245 * </tr>
246 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700247 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td>
248 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800249 * </tr>
250 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700251 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
252 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800253 * </tr>
254 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700255 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td>
256 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800257 * </tr>
258 * <tr>
Joe Darcy0e32f672013-06-27 19:02:02 -0700259 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td>
260 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
John R Rose54e473f2011-02-11 01:26:28 -0800261 * </tr>
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100262 * <tr>
263 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td>
264 * <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
265 * </tr>
John R Rose54e473f2011-02-11 01:26:28 -0800266 * </table>
Joe Darcy0e32f672013-06-27 19:02:02 -0700267 *
John R Rose54e473f2011-02-11 01:26:28 -0800268 * Here, the type {@code C} is the class or interface being searched for a member,
269 * documented as a parameter named {@code refc} in the lookup methods.
Joe Darcy0e32f672013-06-27 19:02:02 -0700270 * The method type {@code MT} is composed from the return type {@code T}
John R Rose54e473f2011-02-11 01:26:28 -0800271 * and the sequence of argument types {@code A*}.
Joe Darcy0e32f672013-06-27 19:02:02 -0700272 * The constructor also has a sequence of argument types {@code A*} and
273 * is deemed to return the newly-created object of type {@code C}.
John R Rose54e473f2011-02-11 01:26:28 -0800274 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
275 * The formal parameter {@code this} stands for the self-reference of type {@code C};
276 * if it is present, it is always the leading argument to the method handle invocation.
Christian Thalinger360d5122012-07-24 10:47:44 -0700277 * (In the case of some {@code protected} members, {@code this} may be
278 * restricted in type to the lookup class; see below.)
John R Rose54e473f2011-02-11 01:26:28 -0800279 * The name {@code arg} stands for all the other method handle arguments.
280 * In the code examples for the Core Reflection API, the name {@code thisOrNull}
281 * stands for a null reference if the accessed method or field is static,
282 * and {@code this} otherwise.
283 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
284 * for reflective objects corresponding to the given members.
285 * <p>
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100286 * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
287 * as if by {@code ldc CONSTANT_Class}.
288 * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
289 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -0700290 * In cases where the given member is of variable arity (i.e., a method or constructor)
291 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
292 * In all other cases, the returned method handle will be of fixed arity.
John R Rosebe5df962013-10-05 05:30:40 -0700293 * <p style="font-size:smaller;">
294 * <em>Discussion:</em>
John R Rose54e473f2011-02-11 01:26:28 -0800295 * The equivalence between looked-up method handles and underlying
John R Rosebe5df962013-10-05 05:30:40 -0700296 * class members and bytecode behaviors
297 * can break down in a few ways:
298 * <ul style="font-size:smaller;">
John R Rose54e473f2011-02-11 01:26:28 -0800299 * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
300 * the lookup can still succeed, even when there is no equivalent
301 * Java expression or bytecoded constant.
302 * <li>Likewise, if {@code T} or {@code MT}
303 * is not symbolically accessible from the lookup class's loader,
304 * the lookup can still succeed.
305 * For example, lookups for {@code MethodHandle.invokeExact} and
John R Roseeb963252011-05-12 19:27:33 -0700306 * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
John R Roseba8c9922011-02-15 00:16:53 -0800307 * <li>If there is a security manager installed, it can forbid the lookup
John R Rosec5b5f0d2013-10-05 05:30:39 -0700308 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
309 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
310 * constant is not subject to security manager checks.
John R Rose77dc59f2013-10-05 05:30:39 -0700311 * <li>If the looked-up method has a
312 * <a href="MethodHandle.html#maxarity">very large arity</a>,
313 * the method handle creation may fail, due to the method handle
314 * type having too many parameters.
John R Rose54e473f2011-02-11 01:26:28 -0800315 * </ul>
316 *
Joe Darcy0e32f672013-06-27 19:02:02 -0700317 * <h1><a name="access"></a>Access checking</h1>
John R Rose54e473f2011-02-11 01:26:28 -0800318 * Access checks are applied in the factory methods of {@code Lookup},
319 * when a method handle is created.
320 * This is a key difference from the Core Reflection API, since
John R Rose025d0ae2011-05-26 17:37:36 -0700321 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
John R Rose54e473f2011-02-11 01:26:28 -0800322 * performs access checking against every caller, on every call.
323 * <p>
324 * All access checks start from a {@code Lookup} object, which
325 * compares its recorded lookup class against all requests to
326 * create method handles.
327 * A single {@code Lookup} object can be used to create any number
John R Rosefb6164c2009-05-05 22:40:09 -0700328 * of access-checked method handles, all checked against a single
329 * lookup class.
330 * <p>
John R Rose54e473f2011-02-11 01:26:28 -0800331 * A {@code Lookup} object can be shared with other trusted code,
332 * such as a metaobject protocol.
333 * A shared {@code Lookup} object delegates the capability
334 * to create method handles on private members of the lookup class.
335 * Even if privileged code uses the {@code Lookup} object,
336 * the access checking is confined to the privileges of the
337 * original lookup class.
John R Rosefb6164c2009-05-05 22:40:09 -0700338 * <p>
John R Rose0d30a782010-04-30 23:48:23 -0700339 * A lookup can fail, because
John R Rosefb6164c2009-05-05 22:40:09 -0700340 * the containing class is not accessible to the lookup class, or
341 * because the desired class member is missing, or because the
John R Rosebe5df962013-10-05 05:30:40 -0700342 * desired class member is not accessible to the lookup class, or
343 * because the lookup object is not trusted enough to access the member.
John R Rosef485ab52011-02-11 01:26:32 -0800344 * In any of these cases, a {@code ReflectiveOperationException} will be
345 * thrown from the attempted lookup. The exact class will be one of
346 * the following:
347 * <ul>
348 * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
349 * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
350 * <li>IllegalAccessException &mdash; if the member exists but an access check fails
351 * </ul>
John R Rose6fbfeff2010-09-08 18:40:23 -0700352 * <p>
John R Rosefb6164c2009-05-05 22:40:09 -0700353 * In general, the conditions under which a method handle may be
John R Rosebe5df962013-10-05 05:30:40 -0700354 * looked up for a method {@code M} are no more restrictive than the conditions
355 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
John R Rose154969a2013-10-05 05:30:39 -0700356 * Where the JVM would raise exceptions like {@code NoSuchMethodError},
357 * a method handle lookup will generally raise a corresponding
358 * checked exception, such as {@code NoSuchMethodException}.
John R Rose54e473f2011-02-11 01:26:28 -0800359 * And the effect of invoking the method handle resulting from the lookup
John R Rosebe5df962013-10-05 05:30:40 -0700360 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
361 * to executing the compiled, verified, and resolved call to {@code M}.
John R Roseeedbeda2011-02-11 01:26:24 -0800362 * The same point is true of fields and constructors.
John R Rosebe5df962013-10-05 05:30:40 -0700363 * <p style="font-size:smaller;">
364 * <em>Discussion:</em>
365 * Access checks only apply to named and reflected methods,
366 * constructors, and fields.
367 * Other method handle creation methods, such as
368 * {@link MethodHandle#asType MethodHandle.asType},
369 * do not require any access checks, and are used
370 * independently of any {@code Lookup} object.
John R Rose4f508ab2010-10-30 21:08:23 -0700371 * <p>
Christian Thalinger360d5122012-07-24 10:47:44 -0700372 * If the desired member is {@code protected}, the usual JVM rules apply,
373 * including the requirement that the lookup class must be either be in the
374 * same package as the desired member, or must inherit that member.
375 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.)
376 * In addition, if the desired member is a non-static field or method
377 * in a different package, the resulting method handle may only be applied
378 * to objects of the lookup class or one of its subclasses.
379 * This requirement is enforced by narrowing the type of the leading
380 * {@code this} parameter from {@code C}
381 * (which will necessarily be a superclass of the lookup class)
382 * to the lookup class itself.
383 * <p>
John R Rosebe5df962013-10-05 05:30:40 -0700384 * The JVM imposes a similar requirement on {@code invokespecial} instruction,
385 * that the receiver argument must match both the resolved method <em>and</em>
386 * the current class. Again, this requirement is enforced by narrowing the
387 * type of the leading parameter to the resulting method handle.
388 * (See the Java Virtual Machine Specification, section 4.10.1.9.)
389 * <p>
John R Rose154969a2013-10-05 05:30:39 -0700390 * The JVM represents constructors and static initializer blocks as internal methods
391 * with special names ({@code "<init>"} and {@code "<clinit>"}).
392 * The internal syntax of invocation instructions allows them to refer to such internal
393 * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
394 * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
395 * <p>
John R Rose54e473f2011-02-11 01:26:28 -0800396 * In some cases, access between nested classes is obtained by the Java compiler by creating
John R Rose6fbfeff2010-09-08 18:40:23 -0700397 * an wrapper method to access a private method of another class
398 * in the same top-level declaration.
John R Rose4f508ab2010-10-30 21:08:23 -0700399 * For example, a nested class {@code C.D}
John R Rose6fbfeff2010-09-08 18:40:23 -0700400 * can access private members within other related classes such as
John R Rose4f508ab2010-10-30 21:08:23 -0700401 * {@code C}, {@code C.D.E}, or {@code C.B},
402 * but the Java compiler may need to generate wrapper methods in
403 * those related classes. In such cases, a {@code Lookup} object on
404 * {@code C.E} would be unable to those private members.
405 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
406 * which can transform a lookup on {@code C.E} into one on any of those other
407 * classes, without special elevation of privilege.
John R Rose54e473f2011-02-11 01:26:28 -0800408 * <p>
John R Rosebe5df962013-10-05 05:30:40 -0700409 * The accesses permitted to a given lookup object may be limited,
410 * according to its set of {@link #lookupModes lookupModes},
411 * to a subset of members normally accessible to the lookup class.
412 * For example, the {@link MethodHandles#publicLookup publicLookup}
413 * method produces a lookup object which is only allowed to access
Alan Batemandb4d3832016-03-17 19:04:16 +0000414 * public members in public classes of exported packages.
John R Rosebe5df962013-10-05 05:30:40 -0700415 * The caller sensitive method {@link MethodHandles#lookup lookup}
416 * produces a lookup object with full capabilities relative to
417 * its caller class, to emulate all supported bytecode behaviors.
418 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
419 * with fewer access modes than the original lookup object.
420 *
421 * <p style="font-size:smaller;">
422 * <a name="privacc"></a>
423 * <em>Discussion of private access:</em>
424 * We say that a lookup has <em>private access</em>
425 * if its {@linkplain #lookupModes lookup modes}
426 * include the possibility of accessing {@code private} members.
427 * As documented in the relevant methods elsewhere,
428 * only lookups with private access possess the following capabilities:
429 * <ul style="font-size:smaller;">
430 * <li>access private fields, methods, and constructors of the lookup class
431 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
432 * such as {@code Class.forName}
433 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
434 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
435 * for classes accessible to the lookup class
436 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
437 * within the same package member
438 * </ul>
439 * <p style="font-size:smaller;">
440 * Each of these permissions is a consequence of the fact that a lookup object
441 * with private access can be securely traced back to an originating class,
442 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
443 * can be reliably determined and emulated by method handles.
444 *
445 * <h1><a name="secmgr"></a>Security manager interactions</h1>
John R Roseba8c9922011-02-15 00:16:53 -0800446 * Although bytecode instructions can only refer to classes in
447 * a related class loader, this API can search for methods in any
448 * class, as long as a reference to its {@code Class} object is
449 * available. Such cross-loader references are also possible with the
450 * Core Reflection API, and are impossible to bytecode instructions
451 * such as {@code invokestatic} or {@code getfield}.
452 * There is a {@linkplain java.lang.SecurityManager security manager API}
453 * to allow applications to check such cross-loader references.
454 * These checks apply to both the {@code MethodHandles.Lookup} API
455 * and the Core Reflection API
456 * (as found on {@link java.lang.Class Class}).
457 * <p>
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100458 * If a security manager is present, member and class lookups are subject to
John R Roseba8c9922011-02-15 00:16:53 -0800459 * additional checks.
Mandy Chung5a360a72013-07-02 15:58:09 -0700460 * From one to three calls are made to the security manager.
John R Roseba8c9922011-02-15 00:16:53 -0800461 * Any of these calls can refuse access by throwing a
462 * {@link java.lang.SecurityException SecurityException}.
463 * Define {@code smgr} as the security manager,
Mandy Chung5a360a72013-07-02 15:58:09 -0700464 * {@code lookc} as the lookup class of the current lookup object,
John R Roseba8c9922011-02-15 00:16:53 -0800465 * {@code refc} as the containing class in which the member
466 * is being sought, and {@code defc} as the class in which the
467 * member is actually defined.
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100468 * (If a class or other type is being accessed,
469 * the {@code refc} and {@code defc} values are the class itself.)
Mandy Chung5a360a72013-07-02 15:58:09 -0700470 * The value {@code lookc} is defined as <em>not present</em>
471 * if the current lookup object does not have
John R Rosebe5df962013-10-05 05:30:40 -0700472 * <a href="MethodHandles.Lookup.html#privacc">private access</a>.
John R Roseba8c9922011-02-15 00:16:53 -0800473 * The calls are made according to the following rules:
474 * <ul>
John R Rosebe5df962013-10-05 05:30:40 -0700475 * <li><b>Step 1:</b>
476 * If {@code lookc} is not present, or if its class loader is not
John R Roseba8c9922011-02-15 00:16:53 -0800477 * the same as or an ancestor of the class loader of {@code refc},
478 * then {@link SecurityManager#checkPackageAccess
479 * smgr.checkPackageAccess(refcPkg)} is called,
480 * where {@code refcPkg} is the package of {@code refc}.
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100481 * <li><b>Step 2a:</b>
John R Rosebe5df962013-10-05 05:30:40 -0700482 * If the retrieved member is not public and
Mandy Chung5a360a72013-07-02 15:58:09 -0700483 * {@code lookc} is not present, then
484 * {@link SecurityManager#checkPermission smgr.checkPermission}
485 * with {@code RuntimePermission("accessDeclaredMembers")} is called.
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100486 * <li><b>Step 2b:</b>
487 * If the retrieved class has a {@code null} class loader,
488 * and {@code lookc} is not present, then
489 * {@link SecurityManager#checkPermission smgr.checkPermission}
490 * with {@code RuntimePermission("getClassLoader")} is called.
John R Rosebe5df962013-10-05 05:30:40 -0700491 * <li><b>Step 3:</b>
492 * If the retrieved member is not public,
John R Rosec5b5f0d2013-10-05 05:30:39 -0700493 * and if {@code lookc} is not present,
Mandy Chung5a360a72013-07-02 15:58:09 -0700494 * and if {@code defc} and {@code refc} are different,
John R Roseba8c9922011-02-15 00:16:53 -0800495 * then {@link SecurityManager#checkPackageAccess
496 * smgr.checkPackageAccess(defcPkg)} is called,
497 * where {@code defcPkg} is the package of {@code defc}.
498 * </ul>
John R Rosec5b5f0d2013-10-05 05:30:39 -0700499 * Security checks are performed after other access checks have passed.
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100500 * Therefore, the above rules presuppose a member or class that is public,
John R Rosec5b5f0d2013-10-05 05:30:39 -0700501 * or else that is being accessed from a lookup class that has
Michael Haupt5b2c88e2015-11-20 15:34:12 +0100502 * rights to access the member or class.
John R Rosec5b5f0d2013-10-05 05:30:39 -0700503 *
504 * <h1><a name="callsens"></a>Caller sensitive methods</h1>
505 * A small number of Java methods have a special property called caller sensitivity.
506 * A <em>caller-sensitive</em> method can behave differently depending on the
507 * identity of its immediate caller.
508 * <p>
509 * If a method handle for a caller-sensitive method is requested,
510 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
511 * but they take account of the lookup class in a special way.
512 * The resulting method handle behaves as if it were called
513 * from an instruction contained in the lookup class,
514 * so that the caller-sensitive method detects the lookup class.
515 * (By contrast, the invoker of the method handle is disregarded.)
516 * Thus, in the case of caller-sensitive methods,
517 * different lookup classes may give rise to
518 * differently behaving method handles.
519 * <p>
520 * In cases where the lookup object is
521 * {@link MethodHandles#publicLookup() publicLookup()},
522 * or some other lookup object without
John R Rosebe5df962013-10-05 05:30:40 -0700523 * <a href="MethodHandles.Lookup.html#privacc">private access</a>,
John R Rosec5b5f0d2013-10-05 05:30:39 -0700524 * the lookup class is disregarded.
525 * In such cases, no caller-sensitive method handle can be created,
526 * access is forbidden, and the lookup fails with an
527 * {@code IllegalAccessException}.
John R Rosebe5df962013-10-05 05:30:40 -0700528 * <p style="font-size:smaller;">
529 * <em>Discussion:</em>
530 * For example, the caller-sensitive method
531 * {@link java.lang.Class#forName(String) Class.forName(x)}
532 * can return varying classes or throw varying exceptions,
533 * depending on the class loader of the class that calls it.
534 * A public lookup of {@code Class.forName} will fail, because
535 * there is no reasonable way to determine its bytecode behavior.
536 * <p style="font-size:smaller;">
537 * If an application caches method handles for broad sharing,
538 * it should use {@code publicLookup()} to create them.
539 * If there is a lookup of {@code Class.forName}, it will fail,
540 * and the application must take appropriate action in that case.
541 * It may be that a later lookup, perhaps during the invocation of a
542 * bootstrap method, can incorporate the specific identity
543 * of the caller, making the method accessible.
544 * <p style="font-size:smaller;">
545 * The function {@code MethodHandles.lookup} is caller sensitive
546 * so that there can be a secure foundation for lookups.
547 * Nearly all other methods in the JSR 292 API rely on lookup
548 * objects to check access requests.
John R Rosefb6164c2009-05-05 22:40:09 -0700549 */
550 public static final
551 class Lookup {
John R Rose0d30a782010-04-30 23:48:23 -0700552 /** The class on behalf of whom the lookup is being performed. */
John R Rosefb6164c2009-05-05 22:40:09 -0700553 private final Class<?> lookupClass;
554
John R Rose34cd7bc2010-12-16 15:59:27 -0800555 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
John R Rose0d30a782010-04-30 23:48:23 -0700556 private final int allowedModes;
557
John R Rose34cd7bc2010-12-16 15:59:27 -0800558 /** A single-bit mask representing {@code public} access,
559 * which may contribute to the result of {@link #lookupModes lookupModes}.
560 * The value, {@code 0x01}, happens to be the same as the value of the
561 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
562 */
563 public static final int PUBLIC = Modifier.PUBLIC;
564
565 /** A single-bit mask representing {@code private} access,
566 * which may contribute to the result of {@link #lookupModes lookupModes}.
567 * The value, {@code 0x02}, happens to be the same as the value of the
568 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
569 */
570 public static final int PRIVATE = Modifier.PRIVATE;
571
572 /** A single-bit mask representing {@code protected} access,
573 * which may contribute to the result of {@link #lookupModes lookupModes}.
574 * The value, {@code 0x04}, happens to be the same as the value of the
575 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
576 */
577 public static final int PROTECTED = Modifier.PROTECTED;
578
579 /** A single-bit mask representing {@code package} access (default access),
580 * which may contribute to the result of {@link #lookupModes lookupModes}.
581 * The value is {@code 0x08}, which does not correspond meaningfully to
582 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
583 */
584 public static final int PACKAGE = Modifier.STATIC;
585
Alan Batemandb4d3832016-03-17 19:04:16 +0000586 /** A single-bit mask representing {@code module} access (default access),
587 * which may contribute to the result of {@link #lookupModes lookupModes}.
588 * The value is {@code 0x10}, which does not correspond meaningfully to
589 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
590 * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
591 * with this lookup mode can access all public types in the module of the
592 * lookup class and public types in packages exported by other modules
593 * to the module of the lookup class.
594 * @since 9
595 */
596 public static final int MODULE = PACKAGE << 1;
597
598 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE);
John R Rose34cd7bc2010-12-16 15:59:27 -0800599 private static final int TRUSTED = -1;
John R Rose0d30a782010-04-30 23:48:23 -0700600
601 private static int fixmods(int mods) {
Alan Batemandb4d3832016-03-17 19:04:16 +0000602 mods &= (ALL_MODES - PACKAGE - MODULE);
603 return (mods != 0) ? mods : (PACKAGE | MODULE);
John R Rose0d30a782010-04-30 23:48:23 -0700604 }
605
John R Rose54e473f2011-02-11 01:26:28 -0800606 /** Tells which class is performing the lookup. It is this class against
John R Rosefb6164c2009-05-05 22:40:09 -0700607 * which checks are performed for visibility and access permissions.
608 * <p>
John R Rose6fbfeff2010-09-08 18:40:23 -0700609 * The class implies a maximum level of access permission,
610 * but the permissions may be additionally limited by the bitmask
John R Rose54e473f2011-02-11 01:26:28 -0800611 * {@link #lookupModes lookupModes}, which controls whether non-public members
John R Rose6fbfeff2010-09-08 18:40:23 -0700612 * can be accessed.
Joe Darcy0e32f672013-06-27 19:02:02 -0700613 * @return the lookup class, on behalf of which this lookup object finds members
John R Rosefb6164c2009-05-05 22:40:09 -0700614 */
615 public Class<?> lookupClass() {
616 return lookupClass;
617 }
618
John R Rose0d30a782010-04-30 23:48:23 -0700619 // This is just for calling out to MethodHandleImpl.
620 private Class<?> lookupClassOrNull() {
621 return (allowedModes == TRUSTED) ? null : lookupClass;
622 }
623
John R Rose54e473f2011-02-11 01:26:28 -0800624 /** Tells which access-protection classes of members this lookup object can produce.
John R Rose34cd7bc2010-12-16 15:59:27 -0800625 * The result is a bit-mask of the bits
626 * {@linkplain #PUBLIC PUBLIC (0x01)},
627 * {@linkplain #PRIVATE PRIVATE (0x02)},
628 * {@linkplain #PROTECTED PROTECTED (0x04)},
Alan Batemandb4d3832016-03-17 19:04:16 +0000629 * {@linkplain #PACKAGE PACKAGE (0x08)},
630 * and {@linkplain #MODULE MODULE (0x10)}.
John R Rose4f508ab2010-10-30 21:08:23 -0700631 * <p>
632 * A freshly-created lookup object
John R Rose37188242011-03-23 23:02:31 -0700633 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
Alan Batemandb4d3832016-03-17 19:04:16 +0000634 * has all possible bits set, since the caller class can access all its own members,
635 * all public types in the caller's module, and all public types in packages exported
636 * by other modules to the caller's module.
John R Rose4f508ab2010-10-30 21:08:23 -0700637 * A lookup object on a new lookup class
John R Rose37188242011-03-23 23:02:31 -0700638 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
John R Rose4f508ab2010-10-30 21:08:23 -0700639 * may have some mode bits set to zero.
640 * The purpose of this is to restrict access via the new lookup object,
641 * so that it can access only names which can be reached by the original
642 * lookup object, and also by the new lookup class.
Joe Darcy0e32f672013-06-27 19:02:02 -0700643 * @return the lookup modes, which limit the kinds of access performed by this lookup object
John R Rose0d30a782010-04-30 23:48:23 -0700644 */
John R Rose6fbfeff2010-09-08 18:40:23 -0700645 public int lookupModes() {
John R Rose0d30a782010-04-30 23:48:23 -0700646 return allowedModes & ALL_MODES;
647 }
648
John R Rosefb6164c2009-05-05 22:40:09 -0700649 /** Embody the current class (the lookupClass) as a lookup class
650 * for method handle creation.
651 * Must be called by from a method in this package,
652 * which in turn is called by a method not in this package.
John R Rosefb6164c2009-05-05 22:40:09 -0700653 */
John R Rosee7ebd472011-03-18 00:03:24 -0700654 Lookup(Class<?> lookupClass) {
John R Rose0d30a782010-04-30 23:48:23 -0700655 this(lookupClass, ALL_MODES);
Mandy Chung176ed8d2013-04-16 21:39:52 -0700656 // make sure we haven't accidentally picked up a privileged class:
Mandy Chungbd41c422013-07-22 19:41:07 -0700657 checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
John R Rose0d30a782010-04-30 23:48:23 -0700658 }
659
660 private Lookup(Class<?> lookupClass, int allowedModes) {
John R Rose020e5502010-01-07 16:16:45 -0800661 this.lookupClass = lookupClass;
John R Rose0d30a782010-04-30 23:48:23 -0700662 this.allowedModes = allowedModes;
John R Rose020e5502010-01-07 16:16:45 -0800663 }
664
665 /**
John R Rose54e473f2011-02-11 01:26:28 -0800666 * Creates a lookup on the specified new lookup class.
John R Rose0d30a782010-04-30 23:48:23 -0700667 * The resulting object will report the specified
John R Rose34cd7bc2010-12-16 15:59:27 -0800668 * class as its own {@link #lookupClass lookupClass}.
John R Rose0d30a782010-04-30 23:48:23 -0700669 * <p>
670 * However, the resulting {@code Lookup} object is guaranteed
671 * to have no more access capabilities than the original.
John R Rose4f508ab2010-10-30 21:08:23 -0700672 * In particular, access capabilities can be lost as follows:<ul>
Alan Batemandb4d3832016-03-17 19:04:16 +0000673 * <li>If the lookup class for this {@code Lookup} is not in a named module,
674 * and the new lookup class is in a named module {@code M}, then no members in
675 * {@code M}'s non-exported packages will be accessible.
676 * <li>If the lookup for this {@code Lookup} is in a named module, and the
677 * new lookup class is in a different module {@code M}, then no members, not even
678 * public members in {@code M}'s exported packages, will be accessible.
John R Rose0d30a782010-04-30 23:48:23 -0700679 * <li>If the new lookup class differs from the old one,
680 * protected members will not be accessible by virtue of inheritance.
John R Rose4f508ab2010-10-30 21:08:23 -0700681 * (Protected members may continue to be accessible because of package sharing.)
John R Rose0d30a782010-04-30 23:48:23 -0700682 * <li>If the new lookup class is in a different package
683 * than the old one, protected and default (package) members will not be accessible.
684 * <li>If the new lookup class is not within the same package member
685 * as the old one, private members will not be accessible.
John R Rose4f508ab2010-10-30 21:08:23 -0700686 * <li>If the new lookup class is not accessible to the old lookup class,
687 * then no members, not even public members, will be accessible.
688 * (In all other cases, public members will continue to be accessible.)
John R Rose0d30a782010-04-30 23:48:23 -0700689 * </ul>
Michael Hauptbfb7e8c2016-03-13 20:26:29 +0100690 * <p>
691 * The resulting lookup's capabilities for loading classes
692 * (used during {@link #findClass} invocations)
693 * are determined by the lookup class' loader,
694 * which may change due to this operation.
John R Rose54e473f2011-02-11 01:26:28 -0800695 *
696 * @param requestedLookupClass the desired lookup class for the new lookup object
697 * @return a lookup object which reports the desired lookup class
698 * @throws NullPointerException if the argument is null
John R Rose020e5502010-01-07 16:16:45 -0800699 */
John R Rose0d30a782010-04-30 23:48:23 -0700700 public Lookup in(Class<?> requestedLookupClass) {
Aleksey Shipileve0e6ce32015-02-20 18:32:10 +0300701 Objects.requireNonNull(requestedLookupClass);
John R Rose0d30a782010-04-30 23:48:23 -0700702 if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all
703 return new Lookup(requestedLookupClass, ALL_MODES);
704 if (requestedLookupClass == this.lookupClass)
705 return this; // keep same capabilities
Alan Batemandb4d3832016-03-17 19:04:16 +0000706
John R Rose0d30a782010-04-30 23:48:23 -0700707 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
Alan Batemandb4d3832016-03-17 19:04:16 +0000708 if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
709 // Allowed to teleport from an unnamed to a named module but resulting
710 // Lookup has no access to module private members
711 if (this.lookupClass.getModule().isNamed()) {
712 newModes = 0;
713 } else {
714 newModes &= ~MODULE;
715 }
716 }
John R Rose0d30a782010-04-30 23:48:23 -0700717 if ((newModes & PACKAGE) != 0
718 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
719 newModes &= ~(PACKAGE|PRIVATE);
John R Rose020e5502010-01-07 16:16:45 -0800720 }
John R Rose4f508ab2010-10-30 21:08:23 -0700721 // Allow nestmate lookups to be created without special privilege:
John R Rose0d30a782010-04-30 23:48:23 -0700722 if ((newModes & PRIVATE) != 0
723 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
724 newModes &= ~PRIVATE;
725 }
John R Rose6b14cf62012-05-18 20:31:28 -0700726 if ((newModes & PUBLIC) != 0
727 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
John R Rose4f508ab2010-10-30 21:08:23 -0700728 // The requested class it not accessible from the lookup class.
729 // No permissions.
730 newModes = 0;
731 }
Alan Batemandb4d3832016-03-17 19:04:16 +0000732
Mandy Chungbd41c422013-07-22 19:41:07 -0700733 checkUnprivilegedlookupClass(requestedLookupClass, newModes);
John R Rose0d30a782010-04-30 23:48:23 -0700734 return new Lookup(requestedLookupClass, newModes);
John R Rosefb6164c2009-05-05 22:40:09 -0700735 }
736
John R Rose020e5502010-01-07 16:16:45 -0800737 // Make sure outer class is initialized first.
John R Rosee7ebd472011-03-18 00:03:24 -0700738 static { IMPL_NAMES.getClass(); }
John R Rose020e5502010-01-07 16:16:45 -0800739
John R Rosefb6164c2009-05-05 22:40:09 -0700740 /** Package-private version of lookup which is trusted. */
John R Rose0d30a782010-04-30 23:48:23 -0700741 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
John R Rosefb6164c2009-05-05 22:40:09 -0700742
Mandy Chungbd41c422013-07-22 19:41:07 -0700743 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
John R Rose708863f2009-05-12 13:54:22 -0700744 String name = lookupClass.getName();
John R Rose37188242011-03-23 23:02:31 -0700745 if (name.startsWith("java.lang.invoke."))
John R Rosefb6164c2009-05-05 22:40:09 -0700746 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
Mandy Chungbd41c422013-07-22 19:41:07 -0700747
Paul Sandoz27f82be2016-04-26 18:42:51 -0700748 // For caller-sensitive MethodHandles.lookup() disallow lookup from
749 // restricted packages. This a fragile and blunt approach.
750 // TODO replace with a more formal and less fragile mechanism
751 // that does not bluntly restrict classes under packages within
752 // java.base from looking up MethodHandles or VarHandles.
Mandy Chungbd41c422013-07-22 19:41:07 -0700753 if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
Paul Sandoz27f82be2016-04-26 18:42:51 -0700754 if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) ||
Mandy Chungbd41c422013-07-22 19:41:07 -0700755 (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
756 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
757 }
758 }
John R Rosefb6164c2009-05-05 22:40:09 -0700759 }
760
John R Rose34cd7bc2010-12-16 15:59:27 -0800761 /**
John R Rose54e473f2011-02-11 01:26:28 -0800762 * Displays the name of the class from which lookups are to be made.
John R Rose34cd7bc2010-12-16 15:59:27 -0800763 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
764 * If there are restrictions on the access permitted to this lookup,
765 * this is indicated by adding a suffix to the class name, consisting
John R Rose54e473f2011-02-11 01:26:28 -0800766 * of a slash and a keyword. The keyword represents the strongest
767 * allowed access, and is chosen as follows:
John R Rose34cd7bc2010-12-16 15:59:27 -0800768 * <ul>
769 * <li>If no access is allowed, the suffix is "/noaccess".
Alan Batemandb4d3832016-03-17 19:04:16 +0000770 * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
771 * <li>If only public and module access are allowed, the suffix is "/module".
772 * <li>If only public, module and package access are allowed, the suffix is "/package".
773 * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
John R Rose34cd7bc2010-12-16 15:59:27 -0800774 * </ul>
775 * If none of the above cases apply, it is the case that full
Alan Batemandb4d3832016-03-17 19:04:16 +0000776 * access (public, module, package, private, and protected) is allowed.
John R Rose34cd7bc2010-12-16 15:59:27 -0800777 * In this case, no suffix is added.
778 * This is true only of an object obtained originally from
John R Rose37188242011-03-23 23:02:31 -0700779 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
780 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
John R Rose34cd7bc2010-12-16 15:59:27 -0800781 * always have restricted access, and will display a suffix.
John R Rose54e473f2011-02-11 01:26:28 -0800782 * <p>
783 * (It may seem strange that protected access should be
784 * stronger than private access. Viewed independently from
785 * package access, protected access is the first to be lost,
786 * because it requires a direct subclass relationship between
787 * caller and callee.)
788 * @see #in
John R Rose0d30a782010-04-30 23:48:23 -0700789 */
John R Rosefb6164c2009-05-05 22:40:09 -0700790 @Override
791 public String toString() {
John R Rose0d30a782010-04-30 23:48:23 -0700792 String cname = lookupClass.getName();
793 switch (allowedModes) {
John R Rose54e473f2011-02-11 01:26:28 -0800794 case 0: // no privileges
795 return cname + "/noaccess";
John R Rose0d30a782010-04-30 23:48:23 -0700796 case PUBLIC:
John R Rose34cd7bc2010-12-16 15:59:27 -0800797 return cname + "/public";
Alan Batemandb4d3832016-03-17 19:04:16 +0000798 case PUBLIC|MODULE:
799 return cname + "/module";
800 case PUBLIC|MODULE|PACKAGE:
John R Rose0d30a782010-04-30 23:48:23 -0700801 return cname + "/package";
John R Rose54e473f2011-02-11 01:26:28 -0800802 case ALL_MODES & ~PROTECTED:
803 return cname + "/private";
John R Rose0d30a782010-04-30 23:48:23 -0700804 case ALL_MODES:
805 return cname;
John R Rose54e473f2011-02-11 01:26:28 -0800806 case TRUSTED:
807 return "/trusted"; // internal only; not exported
808 default: // Should not happen, but it's a bitfield...
809 cname = cname + "/" + Integer.toHexString(allowedModes);
810 assert(false) : cname;
811 return cname;
John R Rose0d30a782010-04-30 23:48:23 -0700812 }
John R Rosefb6164c2009-05-05 22:40:09 -0700813 }
814
John R Rosefb6164c2009-05-05 22:40:09 -0700815 /**
John R Rose54e473f2011-02-11 01:26:28 -0800816 * Produces a method handle for a static method.
John R Rosefb6164c2009-05-05 22:40:09 -0700817 * The type of the method handle will be that of the method.
John R Rose020e5502010-01-07 16:16:45 -0800818 * (Since static methods do not take receivers, there is no
819 * additional receiver argument inserted into the method handle type,
John R Rose54e473f2011-02-11 01:26:28 -0800820 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
John R Rosebe5df962013-10-05 05:30:40 -0700821 * The method and all its argument types must be accessible to the lookup object.
John R Roseeedbeda2011-02-11 01:26:24 -0800822 * <p>
823 * The returned method handle will have
824 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
825 * the method's variable arity modifier bit ({@code 0x0080}) is set.
John R Rose4ea5f812013-10-05 05:30:39 -0700826 * <p>
827 * If the returned method handle is invoked, the method's class will
828 * be initialized, if it has not already been initialized.
829 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -0400830 * <blockquote><pre>{@code
John R Rose154969a2013-10-05 05:30:39 -0700831import static java.lang.invoke.MethodHandles.*;
832import static java.lang.invoke.MethodType.*;
833...
834MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
835 "asList", methodType(List.class, Object[].class));
836assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
837 * }</pre></blockquote>
John R Rose0d30a782010-04-30 23:48:23 -0700838 * @param refc the class from which the method is accessed
John R Rosefb6164c2009-05-05 22:40:09 -0700839 * @param name the name of the method
840 * @param type the type of the method
841 * @return the desired method handle
John R Rosef485ab52011-02-11 01:26:32 -0800842 * @throws NoSuchMethodException if the method does not exist
John R Rose025d0ae2011-05-26 17:37:36 -0700843 * @throws IllegalAccessException if access checking fails,
844 * or if the method is not {@code static},
845 * or if the method's variable arity modifier bit
846 * is set and {@code asVarargsCollector} fails
John R Roseba8c9922011-02-15 00:16:53 -0800847 * @exception SecurityException if a security manager is present and it
848 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -0800849 * @throws NullPointerException if any argument is null
John R Rosefb6164c2009-05-05 22:40:09 -0700850 */
851 public
John R Rosef485ab52011-02-11 01:26:32 -0800852 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -0700853 MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
Christian Thalinger94bc7322013-05-08 12:09:35 -0700854 return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
John R Rosef3279532011-06-01 23:56:47 -0700855 }
John R Rosefb6164c2009-05-05 22:40:09 -0700856
857 /**
John R Rose54e473f2011-02-11 01:26:28 -0800858 * Produces a method handle for a virtual method.
John R Rosefb6164c2009-05-05 22:40:09 -0700859 * The type of the method handle will be that of the method,
John R Rose0d30a782010-04-30 23:48:23 -0700860 * with the receiver type (usually {@code refc}) prepended.
John R Rosebe5df962013-10-05 05:30:40 -0700861 * The method and all its argument types must be accessible to the lookup object.
John R Rosefb6164c2009-05-05 22:40:09 -0700862 * <p>
863 * When called, the handle will treat the first argument as a receiver
864 * and dispatch on the receiver's type to determine which method
865 * implementation to enter.
866 * (The dispatching action is identical with that performed by an
867 * {@code invokevirtual} or {@code invokeinterface} instruction.)
John R Roseeedbeda2011-02-11 01:26:24 -0800868 * <p>
Christian Thalinger360d5122012-07-24 10:47:44 -0700869 * The first argument will be of type {@code refc} if the lookup
870 * class has full privileges to access the member. Otherwise
871 * the member must be {@code protected} and the first argument
872 * will be restricted in type to the lookup class.
873 * <p>
John R Roseeedbeda2011-02-11 01:26:24 -0800874 * The returned method handle will have
875 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
876 * the method's variable arity modifier bit ({@code 0x0080}) is set.
John R Rose54e473f2011-02-11 01:26:28 -0800877 * <p>
John R Rosebe5df962013-10-05 05:30:40 -0700878 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
John R Rose54e473f2011-02-11 01:26:28 -0800879 * instructions and method handles produced by {@code findVirtual},
880 * if the class is {@code MethodHandle} and the name string is
John R Roseeb963252011-05-12 19:27:33 -0700881 * {@code invokeExact} or {@code invoke}, the resulting
John R Rose54e473f2011-02-11 01:26:28 -0800882 * method handle is equivalent to one produced by
John R Rose37188242011-03-23 23:02:31 -0700883 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
John R Roseeb963252011-05-12 19:27:33 -0700884 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
John R Rose54e473f2011-02-11 01:26:28 -0800885 * with the same {@code type} argument.
Paul Sandoz9fb30a32016-03-24 11:21:21 +0100886 * <p>
887 * If the class is {@code VarHandle} and the name string corresponds to
888 * the name of a signature-polymorphic access mode method, the resulting
889 * method handle is equivalent to one produced by
890 * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
891 * the access mode corresponding to the name string and with the same
892 * {@code type} arguments.
893 * <p>
John R Rose154969a2013-10-05 05:30:39 -0700894 * <b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -0400895 * <blockquote><pre>{@code
John R Rose154969a2013-10-05 05:30:39 -0700896import static java.lang.invoke.MethodHandles.*;
897import static java.lang.invoke.MethodType.*;
898...
899MethodHandle MH_concat = publicLookup().findVirtual(String.class,
900 "concat", methodType(String.class, String.class));
901MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
902 "hashCode", methodType(int.class));
903MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
904 "hashCode", methodType(int.class));
905assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
906assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
907assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
908// interface method:
909MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
910 "subSequence", methodType(CharSequence.class, int.class, int.class));
911assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
912// constructor "internal method" must be accessed differently:
913MethodType MT_newString = methodType(void.class); //()V for new String()
914try { assertEquals("impossible", lookup()
915 .findVirtual(String.class, "<init>", MT_newString));
916 } catch (NoSuchMethodException ex) { } // OK
917MethodHandle MH_newString = publicLookup()
918 .findConstructor(String.class, MT_newString);
919assertEquals("", (String) MH_newString.invokeExact());
920 * }</pre></blockquote>
921 *
John R Rose0d30a782010-04-30 23:48:23 -0700922 * @param refc the class or interface from which the method is accessed
John R Rosefb6164c2009-05-05 22:40:09 -0700923 * @param name the name of the method
924 * @param type the type of the method, with the receiver argument omitted
925 * @return the desired method handle
John R Rosef485ab52011-02-11 01:26:32 -0800926 * @throws NoSuchMethodException if the method does not exist
John R Rose025d0ae2011-05-26 17:37:36 -0700927 * @throws IllegalAccessException if access checking fails,
Shilpi Rastogi3e459662016-02-10 10:44:58 +0100928 * or if the method is {@code static},
929 * or if the method is {@code private} method of interface,
John R Rose025d0ae2011-05-26 17:37:36 -0700930 * or if the method's variable arity modifier bit
931 * is set and {@code asVarargsCollector} fails
John R Roseba8c9922011-02-15 00:16:53 -0800932 * @exception SecurityException if a security manager is present and it
933 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -0800934 * @throws NullPointerException if any argument is null
John R Rosefb6164c2009-05-05 22:40:09 -0700935 */
John R Rosef485ab52011-02-11 01:26:32 -0800936 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -0700937 if (refc == MethodHandle.class) {
938 MethodHandle mh = findVirtualForMH(name, type);
939 if (mh != null) return mh;
Paul Sandoz9fb30a32016-03-24 11:21:21 +0100940 } else if (refc == VarHandle.class) {
941 MethodHandle mh = findVirtualForVH(name, type);
942 if (mh != null) return mh;
Christian Thalinger360d5122012-07-24 10:47:44 -0700943 }
944 byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
945 MemberName method = resolveOrFail(refKind, refc, name, type);
Christian Thalinger94bc7322013-05-08 12:09:35 -0700946 return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
John R Rosef3279532011-06-01 23:56:47 -0700947 }
Christian Thalinger360d5122012-07-24 10:47:44 -0700948 private MethodHandle findVirtualForMH(String name, MethodType type) {
949 // these names require special lookups because of the implicit MethodType argument
950 if ("invoke".equals(name))
951 return invoker(type);
952 if ("invokeExact".equals(name))
953 return exactInvoker(type);
John Roseda56d3f2014-09-10 19:19:47 +0400954 if ("invokeBasic".equals(name))
955 return basicInvoker(type);
John Rose59440ee2013-09-03 21:42:56 -0700956 assert(!MemberName.isMethodHandleInvokeName(name));
Christian Thalinger360d5122012-07-24 10:47:44 -0700957 return null;
John R Rose0d30a782010-04-30 23:48:23 -0700958 }
Paul Sandoz9fb30a32016-03-24 11:21:21 +0100959 private MethodHandle findVirtualForVH(String name, MethodType type) {
960 try {
Paul Sandoza7aff442016-04-13 15:05:48 +0200961 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
Paul Sandoz9fb30a32016-03-24 11:21:21 +0100962 } catch (IllegalArgumentException e) {
963 return null;
964 }
965 }
John R Rose0d30a782010-04-30 23:48:23 -0700966
967 /**
John R Rose54e473f2011-02-11 01:26:28 -0800968 * Produces a method handle which creates an object and initializes it, using
John R Rose0d30a782010-04-30 23:48:23 -0700969 * the constructor of the specified type.
970 * The parameter types of the method handle will be those of the constructor,
971 * while the return type will be a reference to the constructor's class.
John R Rosebe5df962013-10-05 05:30:40 -0700972 * The constructor and all its argument types must be accessible to the lookup object.
John R Rose0d30a782010-04-30 23:48:23 -0700973 * <p>
John R Rosebe5df962013-10-05 05:30:40 -0700974 * The requested type must have a return type of {@code void}.
975 * (This is consistent with the JVM's treatment of constructor type descriptors.)
John R Roseeedbeda2011-02-11 01:26:24 -0800976 * <p>
977 * The returned method handle will have
978 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
979 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
John R Rose4ea5f812013-10-05 05:30:39 -0700980 * <p>
981 * If the returned method handle is invoked, the constructor's class will
982 * be initialized, if it has not already been initialized.
John R Rose154969a2013-10-05 05:30:39 -0700983 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -0400984 * <blockquote><pre>{@code
John R Rose154969a2013-10-05 05:30:39 -0700985import static java.lang.invoke.MethodHandles.*;
986import static java.lang.invoke.MethodType.*;
987...
988MethodHandle MH_newArrayList = publicLookup().findConstructor(
989 ArrayList.class, methodType(void.class, Collection.class));
990Collection orig = Arrays.asList("x", "y");
991Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
992assert(orig != copy);
993assertEquals(orig, copy);
994// a variable-arity constructor:
995MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
996 ProcessBuilder.class, methodType(void.class, String[].class));
997ProcessBuilder pb = (ProcessBuilder)
998 MH_newProcessBuilder.invoke("x", "y", "z");
999assertEquals("[x, y, z]", pb.command().toString());
1000 * }</pre></blockquote>
John R Rose0d30a782010-04-30 23:48:23 -07001001 * @param refc the class or interface from which the method is accessed
1002 * @param type the type of the method, with the receiver argument omitted, and a void return type
1003 * @return the desired method handle
John R Rosef485ab52011-02-11 01:26:32 -08001004 * @throws NoSuchMethodException if the constructor does not exist
1005 * @throws IllegalAccessException if access checking fails
John R Rose025d0ae2011-05-26 17:37:36 -07001006 * or if the method's variable arity modifier bit
1007 * is set and {@code asVarargsCollector} fails
John R Roseba8c9922011-02-15 00:16:53 -08001008 * @exception SecurityException if a security manager is present and it
1009 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001010 * @throws NullPointerException if any argument is null
John R Rose0d30a782010-04-30 23:48:23 -07001011 */
John R Rosef485ab52011-02-11 01:26:32 -08001012 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
Michael Haupt0b777552016-04-27 20:18:49 +02001013 if (refc.isArray()) {
1014 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
1015 }
John R Rose0d30a782010-04-30 23:48:23 -07001016 String name = "<init>";
Christian Thalinger360d5122012-07-24 10:47:44 -07001017 MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001018 return getDirectConstructor(refc, ctor);
John R Rosefb6164c2009-05-05 22:40:09 -07001019 }
1020
1021 /**
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001022 * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static
1023 * initializer of the class is not run.
Michael Hauptbfb7e8c2016-03-13 20:26:29 +01001024 * <p>
1025 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class
1026 * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to
1027 * load the requested class, and then determines whether the class is accessible to this lookup object.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001028 *
1029 * @param targetName the fully qualified name of the class to be looked up.
1030 * @return the requested class.
1031 * @exception SecurityException if a security manager is present and it
1032 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1033 * @throws LinkageError if the linkage fails
Michael Hauptbfb7e8c2016-03-13 20:26:29 +01001034 * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001035 * @throws IllegalAccessException if the class is not accessible, using the allowed access
1036 * modes.
1037 * @exception SecurityException if a security manager is present and it
1038 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1039 * @since 9
1040 */
1041 public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1042 Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1043 return accessClass(targetClass);
1044 }
1045
1046 /**
1047 * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1048 * static initializer of the class is not run.
Michael Hauptbfb7e8c2016-03-13 20:26:29 +01001049 * <p>
1050 * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1051 * {@linkplain #lookupModes() lookup modes}.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001052 *
1053 * @param targetClass the class to be access-checked
1054 *
1055 * @return the class that has been access-checked
1056 *
1057 * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1058 * modes.
1059 * @exception SecurityException if a security manager is present and it
1060 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1061 * @since 9
1062 */
1063 public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1064 if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
1065 throw new MemberName(targetClass).makeAccessException("access violation", this);
1066 }
1067 checkSecurityManager(targetClass, null);
1068 return targetClass;
1069 }
1070
1071 /**
John R Rosebe5df962013-10-05 05:30:40 -07001072 * Produces an early-bound method handle for a virtual method.
1073 * It will bypass checks for overriding methods on the receiver,
1074 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1075 * instruction from within the explicitly specified {@code specialCaller}.
John R Rose9d698bd2009-05-11 21:09:58 -07001076 * The type of the method handle will be that of the method,
John R Rosebe5df962013-10-05 05:30:40 -07001077 * with a suitably restricted receiver type prepended.
1078 * (The receiver type will be {@code specialCaller} or a subtype.)
John R Rose9d698bd2009-05-11 21:09:58 -07001079 * The method and all its argument types must be accessible
John R Rosebe5df962013-10-05 05:30:40 -07001080 * to the lookup object.
John R Rosefb6164c2009-05-05 22:40:09 -07001081 * <p>
John R Rosebe5df962013-10-05 05:30:40 -07001082 * Before method resolution,
1083 * if the explicitly specified caller class is not identical with the
1084 * lookup class, or if this lookup object does not have
1085 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
John R Rose4f508ab2010-10-30 21:08:23 -07001086 * privileges, the access fails.
John R Roseeedbeda2011-02-11 01:26:24 -08001087 * <p>
1088 * The returned method handle will have
1089 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1090 * the method's variable arity modifier bit ({@code 0x0080}) is set.
John R Rosebe5df962013-10-05 05:30:40 -07001091 * <p style="font-size:smaller;">
John R Rose154969a2013-10-05 05:30:39 -07001092 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API,
1093 * even though the {@code invokespecial} instruction can refer to them
1094 * in special circumstances. Use {@link #findConstructor findConstructor}
1095 * to access instance initialization methods in a safe manner.)</em>
1096 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04001097 * <blockquote><pre>{@code
John R Rose154969a2013-10-05 05:30:39 -07001098import static java.lang.invoke.MethodHandles.*;
1099import static java.lang.invoke.MethodType.*;
1100...
1101static class Listie extends ArrayList {
1102 public String toString() { return "[wee Listie]"; }
1103 static Lookup lookup() { return MethodHandles.lookup(); }
1104}
1105...
1106// no access to constructor via invokeSpecial:
1107MethodHandle MH_newListie = Listie.lookup()
1108 .findConstructor(Listie.class, methodType(void.class));
1109Listie l = (Listie) MH_newListie.invokeExact();
1110try { assertEquals("impossible", Listie.lookup().findSpecial(
1111 Listie.class, "<init>", methodType(void.class), Listie.class));
1112 } catch (NoSuchMethodException ex) { } // OK
1113// access to super and self methods via invokeSpecial:
1114MethodHandle MH_super = Listie.lookup().findSpecial(
1115 ArrayList.class, "toString" , methodType(String.class), Listie.class);
1116MethodHandle MH_this = Listie.lookup().findSpecial(
1117 Listie.class, "toString" , methodType(String.class), Listie.class);
1118MethodHandle MH_duper = Listie.lookup().findSpecial(
1119 Object.class, "toString" , methodType(String.class), Listie.class);
1120assertEquals("[]", (String) MH_super.invokeExact(l));
1121assertEquals(""+l, (String) MH_this.invokeExact(l));
1122assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
1123try { assertEquals("inaccessible", Listie.lookup().findSpecial(
1124 String.class, "toString", methodType(String.class), Listie.class));
1125 } catch (IllegalAccessException ex) { } // OK
1126Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
1127assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
1128 * }</pre></blockquote>
1129 *
John R Rose0d30a782010-04-30 23:48:23 -07001130 * @param refc the class or interface from which the method is accessed
1131 * @param name the name of the method (which must not be "&lt;init&gt;")
John R Rosefb6164c2009-05-05 22:40:09 -07001132 * @param type the type of the method, with the receiver argument omitted
1133 * @param specialCaller the proposed calling class to perform the {@code invokespecial}
1134 * @return the desired method handle
John R Rosef485ab52011-02-11 01:26:32 -08001135 * @throws NoSuchMethodException if the method does not exist
Shilpi Rastogie49c2412016-02-08 17:37:46 +01001136 * @throws IllegalAccessException if access checking fails,
1137 * or if the method is {@code static},
John R Rose025d0ae2011-05-26 17:37:36 -07001138 * or if the method's variable arity modifier bit
1139 * is set and {@code asVarargsCollector} fails
John R Roseba8c9922011-02-15 00:16:53 -08001140 * @exception SecurityException if a security manager is present and it
1141 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001142 * @throws NullPointerException if any argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001143 */
John R Rose0d30a782010-04-30 23:48:23 -07001144 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
John R Rosef485ab52011-02-11 01:26:32 -08001145 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001146 checkSpecialCaller(specialCaller, refc);
Christian Thalinger360d5122012-07-24 10:47:44 -07001147 Lookup specialLookup = this.in(specialCaller);
1148 MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
Christian Thalinger94bc7322013-05-08 12:09:35 -07001149 return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
John R Rosef3279532011-06-01 23:56:47 -07001150 }
John R Rose0d30a782010-04-30 23:48:23 -07001151
1152 /**
John R Rose54e473f2011-02-11 01:26:28 -08001153 * Produces a method handle giving read access to a non-static field.
John R Rose0d30a782010-04-30 23:48:23 -07001154 * The type of the method handle will have a return type of the field's
1155 * value type.
John R Rose4df63ba2010-06-08 23:08:56 -07001156 * The method handle's single argument will be the instance containing
John R Rose0d30a782010-04-30 23:48:23 -07001157 * the field.
1158 * Access checking is performed immediately on behalf of the lookup class.
John R Rose54e473f2011-02-11 01:26:28 -08001159 * @param refc the class or interface from which the method is accessed
John R Rose0d30a782010-04-30 23:48:23 -07001160 * @param name the field's name
1161 * @param type the field's type
John R Rose0d30a782010-04-30 23:48:23 -07001162 * @return a method handle which can load values from the field
John R Rosef485ab52011-02-11 01:26:32 -08001163 * @throws NoSuchFieldException if the field does not exist
1164 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
John R Roseba8c9922011-02-15 00:16:53 -08001165 * @exception SecurityException if a security manager is present and it
1166 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001167 * @throws NullPointerException if any argument is null
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001168 * @see #findVarHandle(Class, String, Class)
John R Rose0d30a782010-04-30 23:48:23 -07001169 */
John R Rosef485ab52011-02-11 01:26:32 -08001170 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001171 MemberName field = resolveOrFail(REF_getField, refc, name, type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001172 return getDirectField(REF_getField, refc, field);
John R Rosef3279532011-06-01 23:56:47 -07001173 }
John R Rose0d30a782010-04-30 23:48:23 -07001174
1175 /**
John R Rose54e473f2011-02-11 01:26:28 -08001176 * Produces a method handle giving write access to a non-static field.
John R Rose0d30a782010-04-30 23:48:23 -07001177 * The type of the method handle will have a void return type.
John R Rose4df63ba2010-06-08 23:08:56 -07001178 * The method handle will take two arguments, the instance containing
John R Rose0d30a782010-04-30 23:48:23 -07001179 * the field, and the value to be stored.
John R Rose4df63ba2010-06-08 23:08:56 -07001180 * The second argument will be of the field's value type.
John R Rose0d30a782010-04-30 23:48:23 -07001181 * Access checking is performed immediately on behalf of the lookup class.
John R Rose54e473f2011-02-11 01:26:28 -08001182 * @param refc the class or interface from which the method is accessed
John R Rose0d30a782010-04-30 23:48:23 -07001183 * @param name the field's name
1184 * @param type the field's type
John R Rose4df63ba2010-06-08 23:08:56 -07001185 * @return a method handle which can store values into the field
John R Rosef485ab52011-02-11 01:26:32 -08001186 * @throws NoSuchFieldException if the field does not exist
1187 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
John R Roseba8c9922011-02-15 00:16:53 -08001188 * @exception SecurityException if a security manager is present and it
1189 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001190 * @throws NullPointerException if any argument is null
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001191 * @see #findVarHandle(Class, String, Class)
John R Rose0d30a782010-04-30 23:48:23 -07001192 */
John R Rosef485ab52011-02-11 01:26:32 -08001193 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001194 MemberName field = resolveOrFail(REF_putField, refc, name, type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001195 return getDirectField(REF_putField, refc, field);
John R Rosef3279532011-06-01 23:56:47 -07001196 }
John R Rose4df63ba2010-06-08 23:08:56 -07001197
1198 /**
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001199 * Produces a VarHandle giving access to non-static fields of type
1200 * {@code T} declared by a receiver class of type {@code R}, supporting
1201 * shape {@code (R : T)}.
1202 * <p>
1203 * Access checking is performed immediately on behalf of the lookup
1204 * class.
1205 * <p>
1206 * Certain access modes of the returned VarHandle are unsupported under
1207 * the following conditions:
1208 * <ul>
1209 * <li>if the field is declared {@code final}, then the write, atomic
1210 * update, and numeric atomic update access modes are unsupported.
1211 * <li>if the field type is anything other than {@code int},
1212 * {@code long} or a reference type, then atomic update access modes
1213 * are unsupported. (Future major platform releases of the JDK may
1214 * support additional types for certain currently unsupported access
1215 * modes.)
1216 * <li>if the field type is anything other than {@code int} or
1217 * {@code long}, then numeric atomic update access modes are
1218 * unsupported. (Future major platform releases of the JDK may
1219 * support additional numeric types for certain currently
1220 * unsupported access modes.)
1221 * </ul>
1222 * <p>
1223 * If the field is declared {@code volatile} then the returned VarHandle
1224 * will override access to the field (effectively ignore the
1225 * {@code volatile} declaration) in accordance to it's specified
1226 * access modes.
1227 * @param recv the receiver class, of type {@code R}, that declares the
1228 * non-static field
1229 * @param name the field's name
1230 * @param type the field's type, of type {@code T}
1231 * @return a VarHandle giving access to non-static fields.
1232 * @throws NoSuchFieldException if the field does not exist
1233 * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
1234 * @exception SecurityException if a security manager is present and it
1235 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1236 * @throws NullPointerException if any argument is null
1237 * @since 9
1238 */
1239 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1240 MemberName getField = resolveOrFail(REF_getField, recv, name, type);
1241 MemberName putField = resolveOrFail(REF_putField, recv, name, type);
1242 return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
1243 }
1244
1245 /**
John R Rose54e473f2011-02-11 01:26:28 -08001246 * Produces a method handle giving read access to a static field.
John R Rose4df63ba2010-06-08 23:08:56 -07001247 * The type of the method handle will have a return type of the field's
1248 * value type.
1249 * The method handle will take no arguments.
1250 * Access checking is performed immediately on behalf of the lookup class.
John R Rose4ea5f812013-10-05 05:30:39 -07001251 * <p>
1252 * If the returned method handle is invoked, the field's class will
1253 * be initialized, if it has not already been initialized.
John R Rose54e473f2011-02-11 01:26:28 -08001254 * @param refc the class or interface from which the method is accessed
John R Rose4df63ba2010-06-08 23:08:56 -07001255 * @param name the field's name
1256 * @param type the field's type
1257 * @return a method handle which can load values from the field
John R Rosef485ab52011-02-11 01:26:32 -08001258 * @throws NoSuchFieldException if the field does not exist
1259 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
John R Roseba8c9922011-02-15 00:16:53 -08001260 * @exception SecurityException if a security manager is present and it
1261 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001262 * @throws NullPointerException if any argument is null
John R Rose4df63ba2010-06-08 23:08:56 -07001263 */
John R Rosef485ab52011-02-11 01:26:32 -08001264 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001265 MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001266 return getDirectField(REF_getStatic, refc, field);
John R Rosef3279532011-06-01 23:56:47 -07001267 }
John R Rose4df63ba2010-06-08 23:08:56 -07001268
1269 /**
John R Rose54e473f2011-02-11 01:26:28 -08001270 * Produces a method handle giving write access to a static field.
John R Rose4df63ba2010-06-08 23:08:56 -07001271 * The type of the method handle will have a void return type.
1272 * The method handle will take a single
1273 * argument, of the field's value type, the value to be stored.
1274 * Access checking is performed immediately on behalf of the lookup class.
John R Rose4ea5f812013-10-05 05:30:39 -07001275 * <p>
1276 * If the returned method handle is invoked, the field's class will
1277 * be initialized, if it has not already been initialized.
John R Rose54e473f2011-02-11 01:26:28 -08001278 * @param refc the class or interface from which the method is accessed
John R Rose4df63ba2010-06-08 23:08:56 -07001279 * @param name the field's name
1280 * @param type the field's type
1281 * @return a method handle which can store values into the field
John R Rosef485ab52011-02-11 01:26:32 -08001282 * @throws NoSuchFieldException if the field does not exist
1283 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
John R Roseba8c9922011-02-15 00:16:53 -08001284 * @exception SecurityException if a security manager is present and it
1285 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001286 * @throws NullPointerException if any argument is null
John R Rose4df63ba2010-06-08 23:08:56 -07001287 */
John R Rosef485ab52011-02-11 01:26:32 -08001288 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001289 MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001290 return getDirectField(REF_putStatic, refc, field);
John R Rosef3279532011-06-01 23:56:47 -07001291 }
John R Rosefb6164c2009-05-05 22:40:09 -07001292
1293 /**
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001294 * Produces a VarHandle giving access to a static field of type
1295 * {@code T} declared by a given declaring class, supporting shape
1296 * {@code ((empty) : T)}.
1297 * <p>
1298 * Access checking is performed immediately on behalf of the lookup
1299 * class.
1300 * <p>
1301 * If the returned VarHandle is operated on, the declaring class will be
1302 * initialized, if it has not already been initialized.
1303 * <p>
1304 * Certain access modes of the returned VarHandle are unsupported under
1305 * the following conditions:
1306 * <ul>
1307 * <li>if the field is declared {@code final}, then the write, atomic
1308 * update, and numeric atomic update access modes are unsupported.
1309 * <li>if the field type is anything other than {@code int},
1310 * {@code long} or a reference type, then atomic update access modes
1311 * are unsupported. (Future major platform releases of the JDK may
1312 * support additional types for certain currently unsupported access
1313 * modes.)
1314 * <li>if the field type is anything other than {@code int} or
1315 * {@code long}, then numeric atomic update access modes are
1316 * unsupported. (Future major platform releases of the JDK may
1317 * support additional numeric types for certain currently
1318 * unsupported access modes.)
1319 * </ul>
1320 * <p>
1321 * If the field is declared {@code volatile} then the returned VarHandle
1322 * will override access to the field (effectively ignore the
1323 * {@code volatile} declaration) in accordance to it's specified
1324 * access modes.
1325 * @param decl the class that declares the static field
1326 * @param name the field's name
1327 * @param type the field's type, of type {@code T}
1328 * @return a VarHandle giving access to a static field
1329 * @throws NoSuchFieldException if the field does not exist
1330 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
1331 * @exception SecurityException if a security manager is present and it
1332 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1333 * @throws NullPointerException if any argument is null
1334 * @since 9
1335 */
1336 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
1337 MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
1338 MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
1339 return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
1340 }
1341
1342 /**
John R Rose54e473f2011-02-11 01:26:28 -08001343 * Produces an early-bound method handle for a non-static method.
John R Rosefb6164c2009-05-05 22:40:09 -07001344 * The receiver must have a supertype {@code defc} in which a method
1345 * of the given name and type is accessible to the lookup class.
John R Rosebe5df962013-10-05 05:30:40 -07001346 * The method and all its argument types must be accessible to the lookup object.
John R Rose020e5502010-01-07 16:16:45 -08001347 * The type of the method handle will be that of the method,
1348 * without any insertion of an additional receiver parameter.
1349 * The given receiver will be bound into the method handle,
1350 * so that every call to the method handle will invoke the
1351 * requested method on the given receiver.
John R Rosefb6164c2009-05-05 22:40:09 -07001352 * <p>
John R Roseeedbeda2011-02-11 01:26:24 -08001353 * The returned method handle will have
1354 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1355 * the method's variable arity modifier bit ({@code 0x0080}) is set
1356 * <em>and</em> the trailing array argument is not the only argument.
1357 * (If the trailing array argument is the only argument,
1358 * the given receiver value will be bound to it.)
1359 * <p>
1360 * This is equivalent to the following code:
John R Rosebe5df962013-10-05 05:30:40 -07001361 * <blockquote><pre>{@code
John R Rose025d0ae2011-05-26 17:37:36 -07001362import static java.lang.invoke.MethodHandles.*;
1363import static java.lang.invoke.MethodType.*;
1364...
John R Rosebe5df962013-10-05 05:30:40 -07001365MethodHandle mh0 = lookup().findVirtual(defc, name, type);
1366MethodHandle mh1 = mh0.bindTo(receiver);
Shilpi Rastogi284ec152016-04-13 15:48:14 +02001367mh1 = mh1.withVarargs(mh0.isVarargsCollector());
John R Roseeedbeda2011-02-11 01:26:24 -08001368return mh1;
John R Rosebe5df962013-10-05 05:30:40 -07001369 * }</pre></blockquote>
John R Rose020e5502010-01-07 16:16:45 -08001370 * where {@code defc} is either {@code receiver.getClass()} or a super
1371 * type of that class, in which the requested method is accessible
1372 * to the lookup class.
John R Roseeedbeda2011-02-11 01:26:24 -08001373 * (Note that {@code bindTo} does not preserve variable arity.)
John R Rosefb6164c2009-05-05 22:40:09 -07001374 * @param receiver the object from which the method is accessed
1375 * @param name the name of the method
1376 * @param type the type of the method, with the receiver argument omitted
1377 * @return the desired method handle
John R Rosef485ab52011-02-11 01:26:32 -08001378 * @throws NoSuchMethodException if the method does not exist
1379 * @throws IllegalAccessException if access checking fails
John R Rose025d0ae2011-05-26 17:37:36 -07001380 * or if the method's variable arity modifier bit
1381 * is set and {@code asVarargsCollector} fails
John R Roseba8c9922011-02-15 00:16:53 -08001382 * @exception SecurityException if a security manager is present and it
1383 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
John R Rosef485ab52011-02-11 01:26:32 -08001384 * @throws NullPointerException if any argument is null
John R Rosebe5df962013-10-05 05:30:40 -07001385 * @see MethodHandle#bindTo
1386 * @see #findVirtual
John R Rosefb6164c2009-05-05 22:40:09 -07001387 */
John R Rosef485ab52011-02-11 01:26:32 -08001388 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
John R Rose0d30a782010-04-30 23:48:23 -07001389 Class<? extends Object> refc = receiver.getClass(); // may get NPE
Christian Thalinger360d5122012-07-24 10:47:44 -07001390 MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
Christian Thalinger94bc7322013-05-08 12:09:35 -07001391 MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
John Rose2f4b5e82014-09-10 19:19:48 +04001392 return mh.bindArgumentL(0, receiver).setVarargs(method);
John R Rosefb6164c2009-05-05 22:40:09 -07001393 }
1394
1395 /**
John R Rosebe5df962013-10-05 05:30:40 -07001396 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1397 * to <i>m</i>, if the lookup class has permission.
John R Rosefb6164c2009-05-05 22:40:09 -07001398 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
1399 * If <i>m</i> is virtual, overriding is respected on every call.
1400 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
1401 * The type of the method handle will be that of the method,
1402 * with the receiver type prepended (but only if it is non-static).
1403 * If the method's {@code accessible} flag is not set,
1404 * access checking is performed immediately on behalf of the lookup class.
1405 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
John R Roseeedbeda2011-02-11 01:26:24 -08001406 * <p>
1407 * The returned method handle will have
1408 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1409 * the method's variable arity modifier bit ({@code 0x0080}) is set.
John R Rose4ea5f812013-10-05 05:30:39 -07001410 * <p>
1411 * If <i>m</i> is static, and
1412 * if the returned method handle is invoked, the method's class will
1413 * be initialized, if it has not already been initialized.
John R Rosefb6164c2009-05-05 22:40:09 -07001414 * @param m the reflected method
1415 * @return a method handle which can invoke the reflected method
John R Rosef485ab52011-02-11 01:26:32 -08001416 * @throws IllegalAccessException if access checking fails
John R Rose025d0ae2011-05-26 17:37:36 -07001417 * or if the method's variable arity modifier bit
1418 * is set and {@code asVarargsCollector} fails
John R Rosef485ab52011-02-11 01:26:32 -08001419 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001420 */
John R Rosef485ab52011-02-11 01:26:32 -08001421 public MethodHandle unreflect(Method m) throws IllegalAccessException {
John Rose59440ee2013-09-03 21:42:56 -07001422 if (m.getDeclaringClass() == MethodHandle.class) {
1423 MethodHandle mh = unreflectForMH(m);
1424 if (mh != null) return mh;
1425 }
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001426 if (m.getDeclaringClass() == VarHandle.class) {
1427 MethodHandle mh = unreflectForVH(m);
1428 if (mh != null) return mh;
1429 }
John R Rose0d30a782010-04-30 23:48:23 -07001430 MemberName method = new MemberName(m);
Christian Thalinger360d5122012-07-24 10:47:44 -07001431 byte refKind = method.getReferenceKind();
1432 if (refKind == REF_invokeSpecial)
1433 refKind = REF_invokeVirtual;
John R Rose0d30a782010-04-30 23:48:23 -07001434 assert(method.isMethod());
Christian Thalinger360d5122012-07-24 10:47:44 -07001435 Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001436 return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
John R Rosefb6164c2009-05-05 22:40:09 -07001437 }
John Rose59440ee2013-09-03 21:42:56 -07001438 private MethodHandle unreflectForMH(Method m) {
1439 // these names require special lookups because they throw UnsupportedOperationException
1440 if (MemberName.isMethodHandleInvokeName(m.getName()))
1441 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
1442 return null;
1443 }
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001444 private MethodHandle unreflectForVH(Method m) {
1445 // these names require special lookups because they throw UnsupportedOperationException
1446 if (MemberName.isVarHandleMethodInvokeName(m.getName()))
1447 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
1448 return null;
1449 }
John R Rosefb6164c2009-05-05 22:40:09 -07001450
1451 /**
John R Rose54e473f2011-02-11 01:26:28 -08001452 * Produces a method handle for a reflected method.
John R Rosefb6164c2009-05-05 22:40:09 -07001453 * It will bypass checks for overriding methods on the receiver,
John R Rosebe5df962013-10-05 05:30:40 -07001454 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1455 * instruction from within the explicitly specified {@code specialCaller}.
John R Rosefb6164c2009-05-05 22:40:09 -07001456 * The type of the method handle will be that of the method,
John R Rosebe5df962013-10-05 05:30:40 -07001457 * with a suitably restricted receiver type prepended.
1458 * (The receiver type will be {@code specialCaller} or a subtype.)
John R Rosefb6164c2009-05-05 22:40:09 -07001459 * If the method's {@code accessible} flag is not set,
1460 * access checking is performed immediately on behalf of the lookup class,
1461 * as if {@code invokespecial} instruction were being linked.
John R Roseeedbeda2011-02-11 01:26:24 -08001462 * <p>
John R Rosebe5df962013-10-05 05:30:40 -07001463 * Before method resolution,
1464 * if the explicitly specified caller class is not identical with the
1465 * lookup class, or if this lookup object does not have
1466 * <a href="MethodHandles.Lookup.html#privacc">private access</a>
1467 * privileges, the access fails.
1468 * <p>
John R Roseeedbeda2011-02-11 01:26:24 -08001469 * The returned method handle will have
1470 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1471 * the method's variable arity modifier bit ({@code 0x0080}) is set.
John R Rosefb6164c2009-05-05 22:40:09 -07001472 * @param m the reflected method
John R Rose0d30a782010-04-30 23:48:23 -07001473 * @param specialCaller the class nominally calling the method
John R Rosefb6164c2009-05-05 22:40:09 -07001474 * @return a method handle which can invoke the reflected method
Shilpi Rastogie49c2412016-02-08 17:37:46 +01001475 * @throws IllegalAccessException if access checking fails,
1476 * or if the method is {@code static},
John R Rose025d0ae2011-05-26 17:37:36 -07001477 * or if the method's variable arity modifier bit
1478 * is set and {@code asVarargsCollector} fails
John R Rosef485ab52011-02-11 01:26:32 -08001479 * @throws NullPointerException if any argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001480 */
John R Rosef485ab52011-02-11 01:26:32 -08001481 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001482 checkSpecialCaller(specialCaller, null);
Christian Thalinger360d5122012-07-24 10:47:44 -07001483 Lookup specialLookup = this.in(specialCaller);
1484 MemberName method = new MemberName(m, true);
John R Rose0d30a782010-04-30 23:48:23 -07001485 assert(method.isMethod());
1486 // ignore m.isAccessible: this is a new kind of access
John R Rosec5b5f0d2013-10-05 05:30:39 -07001487 return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
John R Rosefb6164c2009-05-05 22:40:09 -07001488 }
1489
1490 /**
John R Rose54e473f2011-02-11 01:26:28 -08001491 * Produces a method handle for a reflected constructor.
John R Rose020e5502010-01-07 16:16:45 -08001492 * The type of the method handle will be that of the constructor,
1493 * with the return type changed to the declaring class.
John R Rosefb6164c2009-05-05 22:40:09 -07001494 * The method handle will perform a {@code newInstance} operation,
1495 * creating a new instance of the constructor's class on the
1496 * arguments passed to the method handle.
1497 * <p>
1498 * If the constructor's {@code accessible} flag is not set,
John R Rose020e5502010-01-07 16:16:45 -08001499 * access checking is performed immediately on behalf of the lookup class.
John R Roseeedbeda2011-02-11 01:26:24 -08001500 * <p>
1501 * The returned method handle will have
1502 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
1503 * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
John R Rose4ea5f812013-10-05 05:30:39 -07001504 * <p>
1505 * If the returned method handle is invoked, the constructor's class will
1506 * be initialized, if it has not already been initialized.
John R Rose0d30a782010-04-30 23:48:23 -07001507 * @param c the reflected constructor
John R Rosefb6164c2009-05-05 22:40:09 -07001508 * @return a method handle which can invoke the reflected constructor
John R Rosef485ab52011-02-11 01:26:32 -08001509 * @throws IllegalAccessException if access checking fails
John R Rose025d0ae2011-05-26 17:37:36 -07001510 * or if the method's variable arity modifier bit
1511 * is set and {@code asVarargsCollector} fails
John R Rosef485ab52011-02-11 01:26:32 -08001512 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001513 */
John R Rosebe5df962013-10-05 05:30:40 -07001514 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
John R Rose0d30a782010-04-30 23:48:23 -07001515 MemberName ctor = new MemberName(c);
1516 assert(ctor.isConstructor());
Christian Thalinger360d5122012-07-24 10:47:44 -07001517 Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001518 return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
John R Rosefb6164c2009-05-05 22:40:09 -07001519 }
1520
1521 /**
John R Rose54e473f2011-02-11 01:26:28 -08001522 * Produces a method handle giving read access to a reflected field.
John R Rosefb6164c2009-05-05 22:40:09 -07001523 * The type of the method handle will have a return type of the field's
John R Rose020e5502010-01-07 16:16:45 -08001524 * value type.
1525 * If the field is static, the method handle will take no arguments.
1526 * Otherwise, its single argument will be the instance containing
1527 * the field.
John R Rose37188242011-03-23 23:02:31 -07001528 * If the field's {@code accessible} flag is not set,
John R Rosefb6164c2009-05-05 22:40:09 -07001529 * access checking is performed immediately on behalf of the lookup class.
John R Rose4ea5f812013-10-05 05:30:39 -07001530 * <p>
1531 * If the field is static, and
1532 * if the returned method handle is invoked, the field's class will
1533 * be initialized, if it has not already been initialized.
John R Rosefb6164c2009-05-05 22:40:09 -07001534 * @param f the reflected field
1535 * @return a method handle which can load values from the reflected field
John R Rosef485ab52011-02-11 01:26:32 -08001536 * @throws IllegalAccessException if access checking fails
1537 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001538 */
John R Rosef485ab52011-02-11 01:26:32 -08001539 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001540 return unreflectField(f, false);
1541 }
1542 private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
1543 MemberName field = new MemberName(f, isSetter);
1544 assert(isSetter
1545 ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
1546 : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
1547 Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001548 return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
John R Rosefb6164c2009-05-05 22:40:09 -07001549 }
1550
1551 /**
John R Rose54e473f2011-02-11 01:26:28 -08001552 * Produces a method handle giving write access to a reflected field.
John R Rosefb6164c2009-05-05 22:40:09 -07001553 * The type of the method handle will have a void return type.
John R Rose020e5502010-01-07 16:16:45 -08001554 * If the field is static, the method handle will take a single
1555 * argument, of the field's value type, the value to be stored.
1556 * Otherwise, the two arguments will be the instance containing
1557 * the field, and the value to be stored.
John R Rose37188242011-03-23 23:02:31 -07001558 * If the field's {@code accessible} flag is not set,
John R Rosefb6164c2009-05-05 22:40:09 -07001559 * access checking is performed immediately on behalf of the lookup class.
John R Rose4ea5f812013-10-05 05:30:39 -07001560 * <p>
1561 * If the field is static, and
1562 * if the returned method handle is invoked, the field's class will
1563 * be initialized, if it has not already been initialized.
John R Rosefb6164c2009-05-05 22:40:09 -07001564 * @param f the reflected field
1565 * @return a method handle which can store values into the reflected field
John R Rosef485ab52011-02-11 01:26:32 -08001566 * @throws IllegalAccessException if access checking fails
1567 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07001568 */
John R Rosef485ab52011-02-11 01:26:32 -08001569 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001570 return unreflectField(f, true);
John R Rosefb6164c2009-05-05 22:40:09 -07001571 }
1572
John Rose59440ee2013-09-03 21:42:56 -07001573 /**
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001574 * Produces a VarHandle that accesses fields of type {@code T} declared
1575 * by a class of type {@code R}, as described by the given reflected
1576 * field.
1577 * If the field is non-static the VarHandle supports a shape of
1578 * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}.
1579 * <p>
1580 * Access checking is performed immediately on behalf of the lookup
1581 * class, regardless of the value of the field's {@code accessible}
1582 * flag.
1583 * <p>
1584 * If the field is static, and if the returned VarHandle is operated
1585 * on, the field's declaring class will be initialized, if it has not
1586 * already been initialized.
1587 * <p>
1588 * Certain access modes of the returned VarHandle are unsupported under
1589 * the following conditions:
1590 * <ul>
1591 * <li>if the field is declared {@code final}, then the write, atomic
1592 * update, and numeric atomic update access modes are unsupported.
1593 * <li>if the field type is anything other than {@code int},
1594 * {@code long} or a reference type, then atomic update access modes
1595 * are unsupported. (Future major platform releases of the JDK may
1596 * support additional types for certain currently unsupported access
1597 * modes.)
1598 * <li>if the field type is anything other than {@code int} or
1599 * {@code long}, then numeric atomic update access modes are
1600 * unsupported. (Future major platform releases of the JDK may
1601 * support additional numeric types for certain currently
1602 * unsupported access modes.)
1603 * </ul>
1604 * <p>
1605 * If the field is declared {@code volatile} then the returned VarHandle
1606 * will override access to the field (effectively ignore the
1607 * {@code volatile} declaration) in accordance to it's specified
1608 * access modes.
1609 * @param f the reflected field, with a field of type {@code T}, and
1610 * a declaring class of type {@code R}
1611 * @return a VarHandle giving access to non-static fields or a static
1612 * field
1613 * @throws IllegalAccessException if access checking fails
1614 * @throws NullPointerException if the argument is null
1615 * @since 9
1616 */
1617 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
1618 MemberName getField = new MemberName(f, false);
1619 MemberName putField = new MemberName(f, true);
1620 return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
1621 f.getDeclaringClass(), getField, putField);
1622 }
1623
1624 /**
John R Rosebe5df962013-10-05 05:30:40 -07001625 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
1626 * created by this lookup object or a similar one.
John Rose59440ee2013-09-03 21:42:56 -07001627 * Security and access checks are performed to ensure that this lookup object
1628 * is capable of reproducing the target method handle.
1629 * This means that the cracking may fail if target is a direct method handle
1630 * but was created by an unrelated lookup object.
John R Rosec5b5f0d2013-10-05 05:30:39 -07001631 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
1632 * and was created by a lookup object for a different class.
John Rose59440ee2013-09-03 21:42:56 -07001633 * @param target a direct method handle to crack into symbolic reference components
1634 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
1635 * @exception SecurityException if a security manager is present and it
1636 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1637 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
1638 * @exception NullPointerException if the target is {@code null}
John R Rosebe5df962013-10-05 05:30:40 -07001639 * @see MethodHandleInfo
John Rose59440ee2013-09-03 21:42:56 -07001640 * @since 1.8
1641 */
1642 public MethodHandleInfo revealDirect(MethodHandle target) {
1643 MemberName member = target.internalMemberName();
Paul Sandoz9fb30a32016-03-24 11:21:21 +01001644 if (member == null || (!member.isResolved() &&
1645 !member.isMethodHandleInvoke() &&
1646 !member.isVarHandleMethodInvoke()))
John Rose59440ee2013-09-03 21:42:56 -07001647 throw newIllegalArgumentException("not a direct method handle");
1648 Class<?> defc = member.getDeclaringClass();
1649 byte refKind = member.getReferenceKind();
1650 assert(MethodHandleNatives.refKindIsValid(refKind));
1651 if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
1652 // Devirtualized method invocation is usually formally virtual.
1653 // To avoid creating extra MemberName objects for this common case,
1654 // we encode this extra degree of freedom using MH.isInvokeSpecial.
1655 refKind = REF_invokeVirtual;
1656 if (refKind == REF_invokeVirtual && defc.isInterface())
1657 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
1658 refKind = REF_invokeInterface;
1659 // Check SM permissions and member access before cracking.
1660 try {
John Rose59440ee2013-09-03 21:42:56 -07001661 checkAccess(refKind, defc, member);
John R Rosec5b5f0d2013-10-05 05:30:39 -07001662 checkSecurityManager(defc, member);
John Rose59440ee2013-09-03 21:42:56 -07001663 } catch (IllegalAccessException ex) {
1664 throw new IllegalArgumentException(ex);
1665 }
John R Rosec5b5f0d2013-10-05 05:30:39 -07001666 if (allowedModes != TRUSTED && member.isCallerSensitive()) {
1667 Class<?> callerClass = target.internalCallerClass();
1668 if (!hasPrivateAccess() || callerClass != lookupClass())
1669 throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
1670 }
John Rose59440ee2013-09-03 21:42:56 -07001671 // Produce the handle to the results.
1672 return new InfoFromMemberName(this, member, refKind);
1673 }
1674
John R Rose0d30a782010-04-30 23:48:23 -07001675 /// Helper methods, all package-private.
John R Rosefb6164c2009-05-05 22:40:09 -07001676
Christian Thalinger360d5122012-07-24 10:47:44 -07001677 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
John R Rose0d30a782010-04-30 23:48:23 -07001678 checkSymbolicClass(refc); // do this before attempting to resolve
Aleksey Shipileve0e6ce32015-02-20 18:32:10 +03001679 Objects.requireNonNull(name);
1680 Objects.requireNonNull(type);
Christian Thalinger360d5122012-07-24 10:47:44 -07001681 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
John R Rosef485ab52011-02-11 01:26:32 -08001682 NoSuchFieldException.class);
John R Rosefb6164c2009-05-05 22:40:09 -07001683 }
John R Rosefb6164c2009-05-05 22:40:09 -07001684
Christian Thalinger360d5122012-07-24 10:47:44 -07001685 MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
John R Rose0d30a782010-04-30 23:48:23 -07001686 checkSymbolicClass(refc); // do this before attempting to resolve
Aleksey Shipileve0e6ce32015-02-20 18:32:10 +03001687 Objects.requireNonNull(name);
1688 Objects.requireNonNull(type);
John R Rose154969a2013-10-05 05:30:39 -07001689 checkMethodName(refKind, name); // NPE check on name
Christian Thalinger360d5122012-07-24 10:47:44 -07001690 return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(),
John R Rosef485ab52011-02-11 01:26:32 -08001691 NoSuchMethodException.class);
John R Rose0d30a782010-04-30 23:48:23 -07001692 }
1693
John R Rose62ee2112013-10-05 05:30:38 -07001694 MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
1695 checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve
Aleksey Shipileve0e6ce32015-02-20 18:32:10 +03001696 Objects.requireNonNull(member.getName());
1697 Objects.requireNonNull(member.getType());
John R Rose62ee2112013-10-05 05:30:38 -07001698 return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(),
1699 ReflectiveOperationException.class);
1700 }
1701
John R Rosef485ab52011-02-11 01:26:32 -08001702 void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
Aleksey Shipileve0e6ce32015-02-20 18:32:10 +03001703 Objects.requireNonNull(refc);
John R Rose0d30a782010-04-30 23:48:23 -07001704 Class<?> caller = lookupClassOrNull();
John R Rose6b14cf62012-05-18 20:31:28 -07001705 if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes))
Alan Batemandb4d3832016-03-17 19:04:16 +00001706 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
John R Rose0d30a782010-04-30 23:48:23 -07001707 }
1708
John R Rosebe5df962013-10-05 05:30:40 -07001709 /** Check name for an illegal leading "&lt;" character. */
John R Rose154969a2013-10-05 05:30:39 -07001710 void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
1711 if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
1712 throw new NoSuchMethodException("illegal method name: "+name);
1713 }
1714
1715
John R Rose025d0ae2011-05-26 17:37:36 -07001716 /**
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001717 * Find my trustable caller class if m is a caller sensitive method.
1718 * If this lookup object has private access, then the caller class is the lookupClass.
Christian Thalinger94bc7322013-05-08 12:09:35 -07001719 * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001720 */
Christian Thalinger94bc7322013-05-08 12:09:35 -07001721 Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001722 Class<?> callerClass = null;
1723 if (MethodHandleNatives.isCallerSensitive(m)) {
John R Rosec5b5f0d2013-10-05 05:30:39 -07001724 // Only lookups with private access are allowed to resolve caller-sensitive methods
1725 if (hasPrivateAccess()) {
Christian Thalinger94bc7322013-05-08 12:09:35 -07001726 callerClass = lookupClass;
1727 } else {
1728 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
1729 }
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001730 }
1731 return callerClass;
1732 }
Mandy Chung176ed8d2013-04-16 21:39:52 -07001733
John R Rosec5b5f0d2013-10-05 05:30:39 -07001734 private boolean hasPrivateAccess() {
Christian Thalinger94bc7322013-05-08 12:09:35 -07001735 return (allowedModes & PRIVATE) != 0;
1736 }
1737
Mandy Chung176ed8d2013-04-16 21:39:52 -07001738 /**
John R Rose025d0ae2011-05-26 17:37:36 -07001739 * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001740 * Determines a trustable caller class to compare with refc, the symbolic reference class.
1741 * If this lookup object has private access, then the caller class is the lookupClass.
John R Rose025d0ae2011-05-26 17:37:36 -07001742 */
Christian Thalinger94bc7322013-05-08 12:09:35 -07001743 void checkSecurityManager(Class<?> refc, MemberName m) {
John R Rose025d0ae2011-05-26 17:37:36 -07001744 SecurityManager smgr = System.getSecurityManager();
1745 if (smgr == null) return;
1746 if (allowedModes == TRUSTED) return;
Mandy Chung176ed8d2013-04-16 21:39:52 -07001747
John R Rose025d0ae2011-05-26 17:37:36 -07001748 // Step 1:
John R Rosec5b5f0d2013-10-05 05:30:39 -07001749 boolean fullPowerLookup = hasPrivateAccess();
1750 if (!fullPowerLookup ||
Christian Thalinger94bc7322013-05-08 12:09:35 -07001751 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
1752 ReflectUtil.checkPackageAccess(refc);
1753 }
Mandy Chung176ed8d2013-04-16 21:39:52 -07001754
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001755 if (m == null) { // findClass or accessClass
1756 // Step 2b:
1757 if (!fullPowerLookup) {
1758 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1759 }
1760 return;
1761 }
1762
1763 // Step 2a:
John R Rose025d0ae2011-05-26 17:37:36 -07001764 if (m.isPublic()) return;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001765 if (!fullPowerLookup) {
1766 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
Mandy Chung176ed8d2013-04-16 21:39:52 -07001767 }
1768
Mandy Chung5a360a72013-07-02 15:58:09 -07001769 // Step 3:
John R Rosec5b5f0d2013-10-05 05:30:39 -07001770 Class<?> defc = m.getDeclaringClass();
1771 if (!fullPowerLookup && defc != refc) {
Christian Thalinger94bc7322013-05-08 12:09:35 -07001772 ReflectUtil.checkPackageAccess(defc);
1773 }
John R Rose025d0ae2011-05-26 17:37:36 -07001774 }
1775
Christian Thalinger360d5122012-07-24 10:47:44 -07001776 void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1777 boolean wantStatic = (refKind == REF_invokeStatic);
John R Rose0d30a782010-04-30 23:48:23 -07001778 String message;
1779 if (m.isConstructor())
1780 message = "expected a method, not a constructor";
1781 else if (!m.isMethod())
1782 message = "expected a method";
1783 else if (wantStatic != m.isStatic())
1784 message = wantStatic ? "expected a static method" : "expected a non-static method";
1785 else
Christian Thalinger360d5122012-07-24 10:47:44 -07001786 { checkAccess(refKind, refc, m); return; }
John R Rosee7ebd472011-03-18 00:03:24 -07001787 throw m.makeAccessException(message, this);
John R Rose0d30a782010-04-30 23:48:23 -07001788 }
1789
Christian Thalinger360d5122012-07-24 10:47:44 -07001790 void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1791 boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
1792 String message;
1793 if (wantStatic != m.isStatic())
1794 message = wantStatic ? "expected a static field" : "expected a non-static field";
1795 else
1796 { checkAccess(refKind, refc, m); return; }
1797 throw m.makeAccessException(message, this);
1798 }
1799
John R Rosec5b5f0d2013-10-05 05:30:39 -07001800 /** Check public/protected/private bits on the symbolic reference class and its member. */
Christian Thalinger360d5122012-07-24 10:47:44 -07001801 void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
1802 assert(m.referenceKindIsConsistentWith(refKind) &&
1803 MethodHandleNatives.refKindIsValid(refKind) &&
1804 (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
John R Rose0d30a782010-04-30 23:48:23 -07001805 int allowedModes = this.allowedModes;
1806 if (allowedModes == TRUSTED) return;
1807 int mods = m.getModifiers();
John R Rose622186e2013-10-05 05:30:38 -07001808 if (Modifier.isProtected(mods) &&
1809 refKind == REF_invokeVirtual &&
1810 m.getDeclaringClass() == Object.class &&
1811 m.getName().equals("clone") &&
1812 refc.isArray()) {
1813 // The JVM does this hack also.
1814 // (See ClassVerifier::verify_invoke_instructions
1815 // and LinkResolver::check_method_accessability.)
1816 // Because the JVM does not allow separate methods on array types,
1817 // there is no separate method for int[].clone.
1818 // All arrays simply inherit Object.clone.
1819 // But for access checking logic, we make Object.clone
1820 // (normally protected) appear to be public.
1821 // Later on, when the DirectMethodHandle is created,
1822 // its leading argument will be restricted to the
1823 // requested array type.
1824 // N.B. The return type is not adjusted, because
1825 // that is *not* the bytecode behavior.
1826 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
1827 }
Christian Thalinger33ccc262014-07-14 13:57:44 +04001828 if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
1829 // cannot "new" a protected ctor in a different package
1830 mods ^= Modifier.PROTECTED;
1831 }
Christian Thalinger360d5122012-07-24 10:47:44 -07001832 if (Modifier.isFinal(mods) &&
1833 MethodHandleNatives.refKindIsSetter(refKind))
1834 throw m.makeAccessException("unexpected set of a final field", this);
John R Rose0d30a782010-04-30 23:48:23 -07001835 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE
Christian Thalinger360d5122012-07-24 10:47:44 -07001836 if ((requestedModes & allowedModes) != 0) {
1837 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
1838 mods, lookupClass(), allowedModes))
1839 return;
1840 } else {
John R Rose0d30a782010-04-30 23:48:23 -07001841 // Protected members can also be checked as if they were package-private.
Christian Thalinger360d5122012-07-24 10:47:44 -07001842 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
1843 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
1844 return;
1845 }
John R Rosee7ebd472011-03-18 00:03:24 -07001846 throw m.makeAccessException(accessFailedMessage(refc, m), this);
John R Rose0d30a782010-04-30 23:48:23 -07001847 }
1848
1849 String accessFailedMessage(Class<?> refc, MemberName m) {
1850 Class<?> defc = m.getDeclaringClass();
1851 int mods = m.getModifiers();
John R Rosef485ab52011-02-11 01:26:32 -08001852 // check the class first:
1853 boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
1854 (defc == refc ||
1855 Modifier.isPublic(refc.getModifiers())));
1856 if (!classOK && (allowedModes & PACKAGE) != 0) {
John R Rose6b14cf62012-05-18 20:31:28 -07001857 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
John R Rosef485ab52011-02-11 01:26:32 -08001858 (defc == refc ||
John R Rose6b14cf62012-05-18 20:31:28 -07001859 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
John R Rosef485ab52011-02-11 01:26:32 -08001860 }
1861 if (!classOK)
John R Rose0d30a782010-04-30 23:48:23 -07001862 return "class is not public";
John R Rose0d30a782010-04-30 23:48:23 -07001863 if (Modifier.isPublic(mods))
Alan Batemandb4d3832016-03-17 19:04:16 +00001864 return "access to public member failed"; // (how?, module not readable?)
John R Rose0d30a782010-04-30 23:48:23 -07001865 if (Modifier.isPrivate(mods))
1866 return "member is private";
1867 if (Modifier.isProtected(mods))
1868 return "member is protected";
1869 return "member is private to package";
1870 }
1871
John R Rose4f508ab2010-10-30 21:08:23 -07001872 private static final boolean ALLOW_NESTMATE_ACCESS = false;
1873
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001874 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001875 int allowedModes = this.allowedModes;
John R Rose0d30a782010-04-30 23:48:23 -07001876 if (allowedModes == TRUSTED) return;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001877 if (!hasPrivateAccess()
John R Rose4f508ab2010-10-30 21:08:23 -07001878 || (specialCaller != lookupClass()
Michael Haupt5b2c88e2015-11-20 15:34:12 +01001879 // ensure non-abstract methods in superinterfaces can be special-invoked
1880 && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))
John R Rose4f508ab2010-10-30 21:08:23 -07001881 && !(ALLOW_NESTMATE_ACCESS &&
1882 VerifyAccess.isSamePackageMember(specialCaller, lookupClass()))))
John R Rosee7ebd472011-03-18 00:03:24 -07001883 throw new MemberName(specialCaller).
1884 makeAccessException("no private access for invokespecial", this);
John R Rose0d30a782010-04-30 23:48:23 -07001885 }
1886
Christian Thalinger360d5122012-07-24 10:47:44 -07001887 private boolean restrictProtectedReceiver(MemberName method) {
John R Rose0d30a782010-04-30 23:48:23 -07001888 // The accessing class only has the right to use a protected member
1889 // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc.
1890 if (!method.isProtected() || method.isStatic()
1891 || allowedModes == TRUSTED
John R Rose4f508ab2010-10-30 21:08:23 -07001892 || method.getDeclaringClass() == lookupClass()
John R Rose8bb387d2011-05-17 19:48:19 -07001893 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass())
John R Rose4f508ab2010-10-30 21:08:23 -07001894 || (ALLOW_NESTMATE_ACCESS &&
1895 VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass())))
Christian Thalinger360d5122012-07-24 10:47:44 -07001896 return false;
1897 return true;
John R Rose0d30a782010-04-30 23:48:23 -07001898 }
John Rose71bae4a2014-09-10 19:19:49 +04001899 private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
John R Rose0d30a782010-04-30 23:48:23 -07001900 assert(!method.isStatic());
Christian Thalinger360d5122012-07-24 10:47:44 -07001901 // receiver type of mh is too wide; narrow to caller
1902 if (!method.getDeclaringClass().isAssignableFrom(caller)) {
John R Rosee7ebd472011-03-18 00:03:24 -07001903 throw method.makeAccessException("caller class must be a subclass below the method", caller);
John R Rose0d30a782010-04-30 23:48:23 -07001904 }
1905 MethodType rawType = mh.type();
1906 if (rawType.parameterType(0) == caller) return mh;
1907 MethodType narrowType = rawType.changeParameterType(0, caller);
John Rose71bae4a2014-09-10 19:19:49 +04001908 assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness
1909 assert(mh.viewAsTypeChecks(narrowType, true));
1910 return mh.copyWith(narrowType, mh.form);
John R Rose0d30a782010-04-30 23:48:23 -07001911 }
1912
John R Rosec5b5f0d2013-10-05 05:30:39 -07001913 /** Check access and get the requested method. */
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001914 private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
John R Rosec5b5f0d2013-10-05 05:30:39 -07001915 final boolean doRestrict = true;
1916 final boolean checkSecurity = true;
1917 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
Christian Thalinger360d5122012-07-24 10:47:44 -07001918 }
John R Rosec5b5f0d2013-10-05 05:30:39 -07001919 /** Check access and get the requested method, eliding receiver narrowing rules. */
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001920 private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
John R Rosec5b5f0d2013-10-05 05:30:39 -07001921 final boolean doRestrict = false;
1922 final boolean checkSecurity = true;
1923 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
Christian Thalinger360d5122012-07-24 10:47:44 -07001924 }
John R Rosec5b5f0d2013-10-05 05:30:39 -07001925 /** Check access and get the requested method, eliding security manager checks. */
1926 private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
1927 final boolean doRestrict = true;
1928 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
1929 return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass);
1930 }
1931 /** Common code for all methods; do not call directly except from immediately above. */
Christian Thalinger360d5122012-07-24 10:47:44 -07001932 private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
John R Rosec5b5f0d2013-10-05 05:30:39 -07001933 boolean checkSecurity,
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001934 boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07001935 checkMethod(refKind, refc, method);
John R Rosec5b5f0d2013-10-05 05:30:39 -07001936 // Optionally check with the security manager; this isn't needed for unreflect* calls.
1937 if (checkSecurity)
1938 checkSecurityManager(refc, method);
John Rose59440ee2013-09-03 21:42:56 -07001939 assert(!method.isMethodHandleInvoke());
Vladimir Ivanovfbc6f852013-03-01 04:45:12 +04001940
Vladimir Ivanovfbc6f852013-03-01 04:45:12 +04001941 if (refKind == REF_invokeSpecial &&
1942 refc != lookupClass() &&
John Rose59440ee2013-09-03 21:42:56 -07001943 !refc.isInterface() &&
Vladimir Ivanovb2e80172014-06-09 15:40:40 +04001944 refc != lookupClass().getSuperclass() &&
Vladimir Ivanovfbc6f852013-03-01 04:45:12 +04001945 refc.isAssignableFrom(lookupClass())) {
1946 assert(!method.getName().equals("<init>")); // not this code path
1947 // Per JVMS 6.5, desc. of invokespecial instruction:
1948 // If the method is in a superclass of the LC,
1949 // and if our original search was above LC.super,
Vladimir Ivanovb2e80172014-06-09 15:40:40 +04001950 // repeat the search (symbolic lookup) from LC.super
1951 // and continue with the direct superclass of that class,
1952 // and so forth, until a match is found or no further superclasses exist.
Vladimir Ivanovfbc6f852013-03-01 04:45:12 +04001953 // FIXME: MemberName.resolve should handle this instead.
Vladimir Ivanovb2e80172014-06-09 15:40:40 +04001954 Class<?> refcAsSuper = lookupClass();
1955 MemberName m2;
1956 do {
1957 refcAsSuper = refcAsSuper.getSuperclass();
1958 m2 = new MemberName(refcAsSuper,
1959 method.getName(),
1960 method.getMethodType(),
1961 REF_invokeSpecial);
1962 m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull());
1963 } while (m2 == null && // no method is found yet
1964 refc != refcAsSuper); // search up to refc
Vladimir Ivanovfbc6f852013-03-01 04:45:12 +04001965 if (m2 == null) throw new InternalError(method.toString());
1966 method = m2;
1967 refc = refcAsSuper;
1968 // redo basic checks
1969 checkMethod(refKind, refc, method);
1970 }
1971
John Rose71bae4a2014-09-10 19:19:49 +04001972 DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method);
1973 MethodHandle mh = dmh;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001974 // Optionally narrow the receiver argument to refc using restrictReceiver.
1975 if (doRestrict &&
1976 (refKind == REF_invokeSpecial ||
1977 (MethodHandleNatives.refKindHasReceiver(refKind) &&
John Rose71bae4a2014-09-10 19:19:49 +04001978 restrictProtectedReceiver(method)))) {
1979 mh = restrictReceiver(method, dmh, lookupClass());
1980 }
1981 mh = maybeBindCaller(method, mh, callerClass);
1982 mh = mh.setVarargs(method);
Christian Thalinger360d5122012-07-24 10:47:44 -07001983 return mh;
1984 }
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001985 private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
1986 Class<?> callerClass)
1987 throws IllegalAccessException {
John R Rose0a735e72012-09-20 14:02:55 -07001988 if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
1989 return mh;
1990 Class<?> hostClass = lookupClass;
John R Rosec5b5f0d2013-10-05 05:30:39 -07001991 if (!hasPrivateAccess()) // caller must have private access
Vladimir Ivanov98e5a4b2013-02-22 03:00:48 -08001992 hostClass = callerClass; // callerClass came from a security manager style stack walk
John R Rose0a735e72012-09-20 14:02:55 -07001993 MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
1994 // Note: caller will apply varargs after this step happens.
1995 return cbmh;
1996 }
John R Rosec5b5f0d2013-10-05 05:30:39 -07001997 /** Check access and get the requested field. */
Christian Thalinger360d5122012-07-24 10:47:44 -07001998 private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
John R Rosec5b5f0d2013-10-05 05:30:39 -07001999 final boolean checkSecurity = true;
2000 return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2001 }
2002 /** Check access and get the requested field, eliding security manager checks. */
2003 private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
2004 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
2005 return getDirectFieldCommon(refKind, refc, field, checkSecurity);
2006 }
2007 /** Common code for all fields; do not call directly except from immediately above. */
2008 private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
2009 boolean checkSecurity) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07002010 checkField(refKind, refc, field);
John R Rosec5b5f0d2013-10-05 05:30:39 -07002011 // Optionally check with the security manager; this isn't needed for unreflect* calls.
2012 if (checkSecurity)
2013 checkSecurityManager(refc, field);
John Rose71bae4a2014-09-10 19:19:49 +04002014 DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
Christian Thalinger360d5122012-07-24 10:47:44 -07002015 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
2016 restrictProtectedReceiver(field));
2017 if (doRestrict)
John Rose71bae4a2014-09-10 19:19:49 +04002018 return restrictReceiver(field, dmh, lookupClass());
2019 return dmh;
Christian Thalinger360d5122012-07-24 10:47:44 -07002020 }
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002021 private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
2022 Class<?> refc, MemberName getField, MemberName putField)
2023 throws IllegalAccessException {
2024 final boolean checkSecurity = true;
2025 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2026 }
2027 private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
2028 Class<?> refc, MemberName getField, MemberName putField)
2029 throws IllegalAccessException {
2030 final boolean checkSecurity = false;
2031 return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
2032 }
2033 private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
2034 Class<?> refc, MemberName getField, MemberName putField,
2035 boolean checkSecurity) throws IllegalAccessException {
2036 assert getField.isStatic() == putField.isStatic();
2037 assert getField.isGetter() && putField.isSetter();
2038 assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
2039 assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
2040
2041 checkField(getRefKind, refc, getField);
2042 if (checkSecurity)
2043 checkSecurityManager(refc, getField);
2044
2045 if (!putField.isFinal()) {
2046 // A VarHandle does not support updates to final fields, any
2047 // such VarHandle to a final field will be read-only and
2048 // therefore the following write-based accessibility checks are
2049 // only required for non-final fields
2050 checkField(putRefKind, refc, putField);
2051 if (checkSecurity)
2052 checkSecurityManager(refc, putField);
2053 }
2054
2055 boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
2056 restrictProtectedReceiver(getField));
2057 if (doRestrict) {
2058 assert !getField.isStatic();
2059 // receiver type of VarHandle is too wide; narrow to caller
2060 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
2061 throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
2062 }
2063 refc = lookupClass();
2064 }
2065 return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED);
2066 }
John R Rosec5b5f0d2013-10-05 05:30:39 -07002067 /** Check access and get the requested constructor. */
Christian Thalinger360d5122012-07-24 10:47:44 -07002068 private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
John R Rosec5b5f0d2013-10-05 05:30:39 -07002069 final boolean checkSecurity = true;
2070 return getDirectConstructorCommon(refc, ctor, checkSecurity);
2071 }
2072 /** Check access and get the requested constructor, eliding security manager checks. */
2073 private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
2074 final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants
2075 return getDirectConstructorCommon(refc, ctor, checkSecurity);
2076 }
2077 /** Common code for all constructors; do not call directly except from immediately above. */
2078 private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
2079 boolean checkSecurity) throws IllegalAccessException {
Christian Thalinger360d5122012-07-24 10:47:44 -07002080 assert(ctor.isConstructor());
2081 checkAccess(REF_newInvokeSpecial, refc, ctor);
John R Rosec5b5f0d2013-10-05 05:30:39 -07002082 // Optionally check with the security manager; this isn't needed for unreflect* calls.
2083 if (checkSecurity)
2084 checkSecurityManager(refc, ctor);
John R Rose0a735e72012-09-20 14:02:55 -07002085 assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here
Christian Thalinger360d5122012-07-24 10:47:44 -07002086 return DirectMethodHandle.make(ctor).setVarargs(ctor);
John R Rose0d30a782010-04-30 23:48:23 -07002087 }
John R Rosef3279532011-06-01 23:56:47 -07002088
2089 /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
2090 */
2091 /*non-public*/
Christian Thalinger360d5122012-07-24 10:47:44 -07002092 MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException {
John R Rose62ee2112013-10-05 05:30:38 -07002093 if (!(type instanceof Class || type instanceof MethodType))
2094 throw new InternalError("unresolved MemberName");
2095 MemberName member = new MemberName(refKind, defc, name, type);
2096 MethodHandle mh = LOOKASIDE_TABLE.get(member);
2097 if (mh != null) {
2098 checkSymbolicClass(defc);
2099 return mh;
Christian Thalinger360d5122012-07-24 10:47:44 -07002100 }
Christian Thalinger1ac02002013-10-24 10:52:15 -07002101 // Treat MethodHandle.invoke and invokeExact specially.
2102 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
2103 mh = findVirtualForMH(member.getName(), member.getMethodType());
2104 if (mh != null) {
2105 return mh;
2106 }
2107 }
John R Rose62ee2112013-10-05 05:30:38 -07002108 MemberName resolved = resolveOrFail(refKind, member);
John R Rosec5b5f0d2013-10-05 05:30:39 -07002109 mh = getDirectMethodForConstant(refKind, defc, resolved);
John R Rose62ee2112013-10-05 05:30:38 -07002110 if (mh instanceof DirectMethodHandle
2111 && canBeCached(refKind, defc, resolved)) {
2112 MemberName key = mh.internalMemberName();
2113 if (key != null) {
2114 key = key.asNormalOriginal();
2115 }
2116 if (member.equals(key)) { // better safe than sorry
2117 LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
2118 }
2119 }
2120 return mh;
2121 }
2122 private
2123 boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
2124 if (refKind == REF_invokeSpecial) {
2125 return false;
2126 }
2127 if (!Modifier.isPublic(defc.getModifiers()) ||
2128 !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
2129 !member.isPublic() ||
2130 member.isCallerSensitive()) {
2131 return false;
2132 }
2133 ClassLoader loader = defc.getClassLoader();
Chris Hegartyaa0ef2e2016-01-06 10:01:44 +00002134 if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {
John R Rose62ee2112013-10-05 05:30:38 -07002135 ClassLoader sysl = ClassLoader.getSystemClassLoader();
2136 boolean found = false;
2137 while (sysl != null) {
2138 if (loader == sysl) { found = true; break; }
2139 sysl = sysl.getParent();
2140 }
2141 if (!found) {
2142 return false;
2143 }
2144 }
2145 try {
2146 MemberName resolved2 = publicLookup().resolveOrFail(refKind,
2147 new MemberName(refKind, defc, member.getName(), member.getType()));
2148 checkSecurityManager(defc, resolved2);
2149 } catch (ReflectiveOperationException | SecurityException ex) {
2150 return false;
2151 }
2152 return true;
2153 }
2154 private
John R Rosec5b5f0d2013-10-05 05:30:39 -07002155 MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
2156 throws ReflectiveOperationException {
Christian Thalinger360d5122012-07-24 10:47:44 -07002157 if (MethodHandleNatives.refKindIsField(refKind)) {
John R Rosec5b5f0d2013-10-05 05:30:39 -07002158 return getDirectFieldNoSecurityManager(refKind, defc, member);
Christian Thalinger360d5122012-07-24 10:47:44 -07002159 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
John R Rosec5b5f0d2013-10-05 05:30:39 -07002160 return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
Christian Thalinger360d5122012-07-24 10:47:44 -07002161 } else if (refKind == REF_newInvokeSpecial) {
John R Rosec5b5f0d2013-10-05 05:30:39 -07002162 return getDirectConstructorNoSecurityManager(defc, member);
John R Rosef3279532011-06-01 23:56:47 -07002163 }
2164 // oops
John R Rose62ee2112013-10-05 05:30:38 -07002165 throw newIllegalArgumentException("bad MethodHandle constant #"+member);
John R Rosef3279532011-06-01 23:56:47 -07002166 }
John R Rose62ee2112013-10-05 05:30:38 -07002167
2168 static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
John R Rosefb6164c2009-05-05 22:40:09 -07002169 }
2170
2171 /**
Alan Batemandb4d3832016-03-17 19:04:16 +00002172 * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
2173 * in an <em>unnamed module</em>.
2174 *
2175 * @see Lookup#publicLookup
2176 */
2177 private static class LookupHelper {
2178 private static final String UNNAMED = "Unnamed";
2179 private static final String OBJECT = "java/lang/Object";
2180
2181 private static Class<?> createClass() {
2182 try {
2183 ClassWriter cw = new ClassWriter(0);
2184 cw.visit(Opcodes.V1_8,
2185 Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
2186 UNNAMED,
2187 null,
2188 OBJECT,
2189 null);
2190 cw.visitSource(UNNAMED, null);
2191 cw.visitEnd();
2192 byte[] bytes = cw.toByteArray();
2193 ClassLoader loader = new ClassLoader(null) {
2194 @Override
2195 protected Class<?> findClass(String cn) throws ClassNotFoundException {
2196 if (cn.equals(UNNAMED))
2197 return super.defineClass(UNNAMED, bytes, 0, bytes.length);
2198 throw new ClassNotFoundException(cn);
2199 }
2200 };
2201 return loader.loadClass(UNNAMED);
2202 } catch (Exception e) {
2203 throw new InternalError(e);
2204 }
2205 }
2206
2207 private static final Class<?> PUBLIC_LOOKUP_CLASS;
2208 static {
2209 PrivilegedAction<Class<?>> pa = new PrivilegedAction<Class<?>>() {
2210 public Class<?> run() {
2211 return createClass();
2212 }
2213 };
2214 PUBLIC_LOOKUP_CLASS = AccessController.doPrivileged(pa);
2215 }
2216
2217 /**
2218 * Lookup that is trusted minimally. It can only be used to create
2219 * method handles to publicly accessible members in exported packages.
2220 *
2221 * @see MethodHandles#publicLookup
2222 */
2223 static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
2224 }
2225
2226 /**
Michael Haupt0b777552016-04-27 20:18:49 +02002227 * Produces a method handle constructing arrays of a desired type.
2228 * The return type of the method handle will be the array type.
2229 * The type of its sole argument will be {@code int}, which specifies the size of the array.
2230 * @param arrayClass an array type
2231 * @return a method handle which can create arrays of the given type
2232 * @throws NullPointerException if the argument is {@code null}
2233 * @throws IllegalArgumentException if {@code arrayClass} is not an array type
2234 * @see java.lang.reflect.Array#newInstance(Class, int)
2235 * @since 9
2236 */
2237 public static
2238 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
2239 if (!arrayClass.isArray()) {
2240 throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
2241 }
2242 MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
2243 bindTo(arrayClass.getComponentType());
2244 return ani.asType(ani.type().changeReturnType(arrayClass));
2245 }
2246
2247 /**
John R Rose54e473f2011-02-11 01:26:28 -08002248 * Produces a method handle giving read access to elements of an array.
John R Rosefb6164c2009-05-05 22:40:09 -07002249 * The type of the method handle will have a return type of the array's
2250 * element type. Its first argument will be the array type,
2251 * and the second will be {@code int}.
2252 * @param arrayClass an array type
2253 * @return a method handle which can load values from the given array type
John R Rose54e473f2011-02-11 01:26:28 -08002254 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07002255 * @throws IllegalArgumentException if arrayClass is not an array type
2256 */
2257 public static
2258 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
Christian Thalinger360d5122012-07-24 10:47:44 -07002259 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, false);
John R Rosefb6164c2009-05-05 22:40:09 -07002260 }
2261
2262 /**
John R Rose54e473f2011-02-11 01:26:28 -08002263 * Produces a method handle giving write access to elements of an array.
John R Rosefb6164c2009-05-05 22:40:09 -07002264 * The type of the method handle will have a void return type.
2265 * Its last argument will be the array's element type.
2266 * The first and second arguments will be the array type and int.
Joe Darcy0e32f672013-06-27 19:02:02 -07002267 * @param arrayClass the class of an array
John R Rosefb6164c2009-05-05 22:40:09 -07002268 * @return a method handle which can store values into the array type
John R Rose54e473f2011-02-11 01:26:28 -08002269 * @throws NullPointerException if the argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07002270 * @throws IllegalArgumentException if arrayClass is not an array type
2271 */
2272 public static
2273 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
Christian Thalinger360d5122012-07-24 10:47:44 -07002274 return MethodHandleImpl.makeArrayElementAccessor(arrayClass, true);
John R Rosefb6164c2009-05-05 22:40:09 -07002275 }
2276
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002277 /**
2278 *
2279 * Produces a VarHandle giving access to elements of an array type
2280 * {@code T[]}, supporting shape {@code (T[], int : T)}.
2281 * <p>
2282 * Certain access modes of the returned VarHandle are unsupported under
2283 * the following conditions:
2284 * <ul>
2285 * <li>if the component type is anything other than {@code int},
2286 * {@code long} or a reference type, then atomic update access modes
2287 * are unsupported. (Future major platform releases of the JDK may
2288 * support additional types for certain currently unsupported access
2289 * modes.)
2290 * <li>if the component type is anything other than {@code int} or
2291 * {@code long}, then numeric atomic update access modes are
2292 * unsupported. (Future major platform releases of the JDK may
2293 * support additional numeric types for certain currently
2294 * unsupported access modes.)
2295 * </ul>
2296 * @param arrayClass the class of an array, of type {@code T[]}
2297 * @return a VarHandle giving access to elements of an array
2298 * @throws NullPointerException if the arrayClass is null
2299 * @throws IllegalArgumentException if arrayClass is not an array type
2300 * @since 9
2301 */
2302 public static
2303 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
2304 return VarHandles.makeArrayElementHandle(arrayClass);
2305 }
2306
2307 /**
2308 * Produces a VarHandle giving access to elements of a {@code byte[]} array
2309 * viewed as if it were a different primitive array type, such as
2310 * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is
2311 * {@code (byte[], int : T)}, where the {@code int} coordinate type
2312 * corresponds to an argument that is an index in a {@code byte[]} array,
2313 * and {@code T} is the component type of the given view array class. The
2314 * returned VarHandle accesses bytes at an index in a {@code byte[]} array,
2315 * composing bytes to or from a value of {@code T} according to the given
2316 * endianness.
2317 * <p>
2318 * The supported component types (variables types) are {@code short},
2319 * {@code char}, {@code int}, {@code long}, {@code float} and
2320 * {@code double}.
2321 * <p>
2322 * Access of bytes at a given index will result in an
2323 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2324 * or greater than the {@code byte[]} array length minus the size (in bytes)
2325 * of {@code T}.
2326 * <p>
2327 * Access of bytes at an index may be aligned or misaligned for {@code T},
2328 * with respect to the underlying memory address, {@code A} say, associated
2329 * with the array and index.
2330 * If access is misaligned then access for anything other than the
2331 * {@code get} and {@code set} access modes will result in an
2332 * {@code IllegalStateException}. In such cases atomic access is only
2333 * guaranteed with respect to the largest power of two that divides the GCD
2334 * of {@code A} and the size (in bytes) of {@code T}.
2335 * If access is aligned then following access modes are supported and are
2336 * guaranteed to support atomic access:
2337 * <ul>
2338 * <li>read write access modes for all {@code T};
2339 * <li>atomic update access modes for {@code int}, {@code long},
2340 * {@code float} or {@code double}.
2341 * (Future major platform releases of the JDK may support additional
2342 * types for certain currently unsupported access modes.)
2343 * <li>numeric atomic update access modes for {@code int} and {@code long}.
2344 * (Future major platform releases of the JDK may support additional
2345 * numeric types for certain currently unsupported access modes.)
2346 * </ul>
2347 * <p>
2348 * Misaligned access, and therefore atomicity guarantees, may be determined
2349 * for {@code byte[]} arrays without operating on a specific array. Given
2350 * an {@code index}, {@code T} and it's corresponding boxed type,
2351 * {@code T_BOX}, misalignment may be determined as follows:
2352 * <pre>{@code
2353 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
2354 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
2355 * alignmentOffset(0, sizeOfT);
2356 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
2357 * boolean isMisaligned = misalignedAtIndex != 0;
2358 * }</pre>
2359 *
2360 * @implNote
2361 * The variable types {@code float} and {@code double} are supported as if
2362 * by transformation to and access with the variable types {@code int} and
2363 * {@code long} respectively. For example, the transformation of a
2364 * {@code double} value to a long value is performed as if using
2365 * {@link Double#doubleToRawLongBits(double)}, and the reverse
2366 * transformation is performed as if using
2367 * {@link Double#longBitsToDouble(long)}.
2368 *
2369 * @param viewArrayClass the view array class, with a component type of
2370 * type {@code T}
Paul Sandoz1af28062016-04-26 18:30:00 -07002371 * @param byteOrder the endianness of the view array elements, as
2372 * stored in the underlying {@code byte} array
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002373 * @return a VarHandle giving access to elements of a {@code byte[]} array
2374 * viewed as if elements corresponding to the components type of the view
2375 * array class
Paul Sandoz1af28062016-04-26 18:30:00 -07002376 * @throws NullPointerException if viewArrayClass or byteOrder is null
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002377 * @throws IllegalArgumentException if viewArrayClass is not an array type
2378 * @throws UnsupportedOperationException if the component type of
2379 * viewArrayClass is not supported as a variable type
2380 * @since 9
2381 */
2382 public static
2383 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
Paul Sandoz1af28062016-04-26 18:30:00 -07002384 ByteOrder byteOrder) throws IllegalArgumentException {
2385 Objects.requireNonNull(byteOrder);
2386 return VarHandles.byteArrayViewHandle(viewArrayClass,
2387 byteOrder == ByteOrder.BIG_ENDIAN);
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002388 }
2389
2390 /**
2391 * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
2392 * viewed as if it were an array of elements of a different primitive
2393 * component type to that of {@code byte}, such as {@code int[]} or
2394 * {@code long[]}. The shape of the resulting VarHandle is
2395 * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type
2396 * corresponds to an argument that is an index in a {@code ByteBuffer}, and
2397 * {@code T} is the component type of the given view array class. The
2398 * returned VarHandle accesses bytes at an index in a {@code ByteBuffer},
2399 * composing bytes to or from a value of {@code T} according to the given
2400 * endianness.
2401 * <p>
2402 * The supported component types (variables types) are {@code short},
2403 * {@code char}, {@code int}, {@code long}, {@code float} and
2404 * {@code double}.
2405 * <p>
2406 * Access will result in a {@code ReadOnlyBufferException} for anything
2407 * other than the read access modes if the {@code ByteBuffer} is read-only.
2408 * <p>
2409 * Access of bytes at a given index will result in an
2410 * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
2411 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
2412 * {@code T}.
2413 * <p>
2414 * Access of bytes at an index may be aligned or misaligned for {@code T},
2415 * with respect to the underlying memory address, {@code A} say, associated
2416 * with the {@code ByteBuffer} and index.
2417 * If access is misaligned then access for anything other than the
2418 * {@code get} and {@code set} access modes will result in an
2419 * {@code IllegalStateException}. In such cases atomic access is only
2420 * guaranteed with respect to the largest power of two that divides the GCD
2421 * of {@code A} and the size (in bytes) of {@code T}.
2422 * If access is aligned then following access modes are supported and are
2423 * guaranteed to support atomic access:
2424 * <ul>
2425 * <li>read write access modes for all {@code T};
2426 * <li>atomic update access modes for {@code int}, {@code long},
2427 * {@code float} or {@code double}.
2428 * (Future major platform releases of the JDK may support additional
2429 * types for certain currently unsupported access modes.)
2430 * <li>numeric atomic update access modes for {@code int} and {@code long}.
2431 * (Future major platform releases of the JDK may support additional
2432 * numeric types for certain currently unsupported access modes.)
2433 * </ul>
2434 * <p>
2435 * Misaligned access, and therefore atomicity guarantees, may be determined
2436 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
2437 * {@code index}, {@code T} and it's corresponding boxed type,
2438 * {@code T_BOX}, as follows:
2439 * <pre>{@code
2440 * int sizeOfT = T_BOX.BYTES; // size in bytes of T
2441 * ByteBuffer bb = ...
2442 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
2443 * boolean isMisaligned = misalignedAtIndex != 0;
2444 * }</pre>
2445 *
2446 * @implNote
2447 * The variable types {@code float} and {@code double} are supported as if
2448 * by transformation to and access with the variable types {@code int} and
2449 * {@code long} respectively. For example, the transformation of a
2450 * {@code double} value to a long value is performed as if using
2451 * {@link Double#doubleToRawLongBits(double)}, and the reverse
2452 * transformation is performed as if using
2453 * {@link Double#longBitsToDouble(long)}.
2454 *
2455 * @param viewArrayClass the view array class, with a component type of
2456 * type {@code T}
Paul Sandoz1af28062016-04-26 18:30:00 -07002457 * @param byteOrder the endianness of the view array elements, as
2458 * stored in the underlying {@code ByteBuffer} (Note this overrides the
2459 * endianness of a {@code ByteBuffer})
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002460 * @return a VarHandle giving access to elements of a {@code ByteBuffer}
2461 * viewed as if elements corresponding to the components type of the view
2462 * array class
Paul Sandoz1af28062016-04-26 18:30:00 -07002463 * @throws NullPointerException if viewArrayClass or byteOrder is null
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002464 * @throws IllegalArgumentException if viewArrayClass is not an array type
2465 * @throws UnsupportedOperationException if the component type of
2466 * viewArrayClass is not supported as a variable type
2467 * @since 9
2468 */
2469 public static
2470 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
Paul Sandoz1af28062016-04-26 18:30:00 -07002471 ByteOrder byteOrder) throws IllegalArgumentException {
2472 Objects.requireNonNull(byteOrder);
2473 return VarHandles.makeByteBufferViewHandle(viewArrayClass,
2474 byteOrder == ByteOrder.BIG_ENDIAN);
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002475 }
2476
2477
John R Rosefb6164c2009-05-05 22:40:09 -07002478 /// method handle invocation (reflective style)
2479
2480 /**
John R Rose54e473f2011-02-11 01:26:28 -08002481 * Produces a method handle which will invoke any method handle of the
John R Rose025d0ae2011-05-26 17:37:36 -07002482 * given {@code type}, with a given number of trailing arguments replaced by
2483 * a single trailing {@code Object[]} array.
John R Rose020e5502010-01-07 16:16:45 -08002484 * The resulting invoker will be a method handle with the following
2485 * arguments:
2486 * <ul>
2487 * <li>a single {@code MethodHandle} target
John R Rose025d0ae2011-05-26 17:37:36 -07002488 * <li>zero or more leading values (counted by {@code leadingArgCount})
2489 * <li>an {@code Object[]} array containing trailing arguments
John R Rose020e5502010-01-07 16:16:45 -08002490 * </ul>
John R Rose4f508ab2010-10-30 21:08:23 -07002491 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07002492 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
John R Rose4f508ab2010-10-30 21:08:23 -07002493 * the indicated {@code type}.
2494 * That is, if the target is exactly of the given {@code type}, it will behave
John R Rose54e473f2011-02-11 01:26:28 -08002495 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
John R Rose4f508ab2010-10-30 21:08:23 -07002496 * is used to convert the target to the required {@code type}.
2497 * <p>
2498 * The type of the returned invoker will not be the given {@code type}, but rather
John R Rose025d0ae2011-05-26 17:37:36 -07002499 * will have all parameters except the first {@code leadingArgCount}
2500 * replaced by a single array of type {@code Object[]}, which will be
2501 * the final parameter.
John R Rose4f508ab2010-10-30 21:08:23 -07002502 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07002503 * Before invoking its target, the invoker will spread the final array, apply
John R Rose4f508ab2010-10-30 21:08:23 -07002504 * reference casts as necessary, and unbox and widen primitive arguments.
John R Rosee4df9dc2013-10-05 05:30:39 -07002505 * If, when the invoker is called, the supplied array argument does
2506 * not have the correct number of elements, the invoker will throw
2507 * an {@link IllegalArgumentException} instead of invoking the target.
John R Rose020e5502010-01-07 16:16:45 -08002508 * <p>
2509 * This method is equivalent to the following code (though it may be more efficient):
John R Rosebe5df962013-10-05 05:30:40 -07002510 * <blockquote><pre>{@code
John R Roseeb963252011-05-12 19:27:33 -07002511MethodHandle invoker = MethodHandles.invoker(type);
John R Rose025d0ae2011-05-26 17:37:36 -07002512int spreadArgCount = type.parameterCount() - leadingArgCount;
John R Roseeedbeda2011-02-11 01:26:24 -08002513invoker = invoker.asSpreader(Object[].class, spreadArgCount);
2514return invoker;
John R Rosebe5df962013-10-05 05:30:40 -07002515 * }</pre></blockquote>
John R Rose54e473f2011-02-11 01:26:28 -08002516 * This method throws no reflective or security exceptions.
John R Rose020e5502010-01-07 16:16:45 -08002517 * @param type the desired target type
John R Rose025d0ae2011-05-26 17:37:36 -07002518 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
John R Rose020e5502010-01-07 16:16:45 -08002519 * @return a method handle suitable for invoking any method handle of the given type
John R Rose025d0ae2011-05-26 17:37:36 -07002520 * @throws NullPointerException if {@code type} is null
2521 * @throws IllegalArgumentException if {@code leadingArgCount} is not in
John R Rose77dc59f2013-10-05 05:30:39 -07002522 * the range from 0 to {@code type.parameterCount()} inclusive,
2523 * or if the resulting method handle's type would have
2524 * <a href="MethodHandle.html#maxarity">too many parameters</a>
John R Rose020e5502010-01-07 16:16:45 -08002525 */
Martin Buchholza2f0fe32015-09-15 21:56:04 -07002526 public static
John R Rose025d0ae2011-05-26 17:37:36 -07002527 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
2528 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
John Roseda56d3f2014-09-10 19:19:47 +04002529 throw newIllegalArgumentException("bad argument count", leadingArgCount);
Michael Haupt5b2c88e2015-11-20 15:34:12 +01002530 type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
John R Rose025d0ae2011-05-26 17:37:36 -07002531 return type.invokers().spreadInvoker(leadingArgCount);
John R Rose020e5502010-01-07 16:16:45 -08002532 }
2533
2534 /**
John R Rose54e473f2011-02-11 01:26:28 -08002535 * Produces a special <em>invoker method handle</em> which can be used to
John R Roseeb963252011-05-12 19:27:33 -07002536 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
John R Rose54e473f2011-02-11 01:26:28 -08002537 * The resulting invoker will have a type which is
John R Rosefb6164c2009-05-05 22:40:09 -07002538 * exactly equal to the desired type, except that it will accept
2539 * an additional leading argument of type {@code MethodHandle}.
2540 * <p>
John R Rose020e5502010-01-07 16:16:45 -08002541 * This method is equivalent to the following code (though it may be more efficient):
John R Rosebe5df962013-10-05 05:30:40 -07002542 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
John R Rose54e473f2011-02-11 01:26:28 -08002543 *
2544 * <p style="font-size:smaller;">
2545 * <em>Discussion:</em>
2546 * Invoker method handles can be useful when working with variable method handles
2547 * of unknown types.
2548 * For example, to emulate an {@code invokeExact} call to a variable method
2549 * handle {@code M}, extract its type {@code T},
2550 * look up the invoker method {@code X} for {@code T},
John R Roseeb963252011-05-12 19:27:33 -07002551 * and call the invoker method, as {@code X.invoke(T, A...)}.
John R Rose54e473f2011-02-11 01:26:28 -08002552 * (It would not work to call {@code X.invokeExact}, since the type {@code T}
2553 * is unknown.)
2554 * If spreading, collecting, or other argument transformations are required,
2555 * they can be applied once to the invoker {@code X} and reused on many {@code M}
2556 * method handle values, as long as they are compatible with the type of {@code X}.
John R Rosebe5df962013-10-05 05:30:40 -07002557 * <p style="font-size:smaller;">
John R Rose54e473f2011-02-11 01:26:28 -08002558 * <em>(Note: The invoker method is not available via the Core Reflection API.
John R Rose025d0ae2011-05-26 17:37:36 -07002559 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
John R Roseeb963252011-05-12 19:27:33 -07002560 * on the declared {@code invokeExact} or {@code invoke} method will raise an
John R Rose54e473f2011-02-11 01:26:28 -08002561 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
2562 * <p>
2563 * This method throws no reflective or security exceptions.
John R Rosefb6164c2009-05-05 22:40:09 -07002564 * @param type the desired target type
2565 * @return a method handle suitable for invoking any method handle of the given type
John R Rose77dc59f2013-10-05 05:30:39 -07002566 * @throws IllegalArgumentException if the resulting method handle's type would have
2567 * <a href="MethodHandle.html#maxarity">too many parameters</a>
John R Rosefb6164c2009-05-05 22:40:09 -07002568 */
Martin Buchholza2f0fe32015-09-15 21:56:04 -07002569 public static
John R Rosefb6164c2009-05-05 22:40:09 -07002570 MethodHandle exactInvoker(MethodType type) {
John R Rosee7ebd472011-03-18 00:03:24 -07002571 return type.invokers().exactInvoker();
John R Rosefb6164c2009-05-05 22:40:09 -07002572 }
2573
John R Rose54e473f2011-02-11 01:26:28 -08002574 /**
2575 * Produces a special <em>invoker method handle</em> which can be used to
John R Roseeb963252011-05-12 19:27:33 -07002576 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
John R Rose54e473f2011-02-11 01:26:28 -08002577 * The resulting invoker will have a type which is
2578 * exactly equal to the desired type, except that it will accept
2579 * an additional leading argument of type {@code MethodHandle}.
2580 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07002581 * Before invoking its target, if the target differs from the expected type,
2582 * the invoker will apply reference casts as
John R Roseeb963252011-05-12 19:27:33 -07002583 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
2584 * Similarly, the return value will be converted as necessary.
2585 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
2586 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
John R Rose54e473f2011-02-11 01:26:28 -08002587 * <p>
John R Rosebe5df962013-10-05 05:30:40 -07002588 * This method is equivalent to the following code (though it may be more efficient):
2589 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
2590 * <p style="font-size:smaller;">
2591 * <em>Discussion:</em>
2592 * A {@linkplain MethodType#genericMethodType general method type} is one which
John R Rose025d0ae2011-05-26 17:37:36 -07002593 * mentions only {@code Object} arguments and return values.
2594 * An invoker for such a type is capable of calling any method handle
2595 * of the same arity as the general type.
John R Rosebe5df962013-10-05 05:30:40 -07002596 * <p style="font-size:smaller;">
2597 * <em>(Note: The invoker method is not available via the Core Reflection API.
2598 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
2599 * on the declared {@code invokeExact} or {@code invoke} method will raise an
2600 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
John R Rose54e473f2011-02-11 01:26:28 -08002601 * <p>
2602 * This method throws no reflective or security exceptions.
2603 * @param type the desired target type
2604 * @return a method handle suitable for invoking any method handle convertible to the given type
John R Rose77dc59f2013-10-05 05:30:39 -07002605 * @throws IllegalArgumentException if the resulting method handle's type would have
2606 * <a href="MethodHandle.html#maxarity">too many parameters</a>
John R Rose54e473f2011-02-11 01:26:28 -08002607 */
Martin Buchholza2f0fe32015-09-15 21:56:04 -07002608 public static
John R Roseeb963252011-05-12 19:27:33 -07002609 MethodHandle invoker(MethodType type) {
John Rose6a177f42014-09-10 19:19:48 +04002610 return type.invokers().genericInvoker();
John R Roseeb963252011-05-12 19:27:33 -07002611 }
2612
Paul Sandoz9fb30a32016-03-24 11:21:21 +01002613 /**
2614 * Produces a special <em>invoker method handle</em> which can be used to
2615 * invoke a signature-polymorphic access mode method on any VarHandle whose
2616 * associated access mode type is compatible with the given type.
2617 * The resulting invoker will have a type which is exactly equal to the
2618 * desired given type, except that it will accept an additional leading
2619 * argument of type {@code VarHandle}.
2620 *
2621 * @param accessMode the VarHandle access mode
2622 * @param type the desired target type
2623 * @return a method handle suitable for invoking an access mode method of
2624 * any VarHandle whose access mode type is of the given type.
2625 * @since 9
2626 */
2627 static public
2628 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2629 return type.invokers().varHandleMethodExactInvoker(accessMode);
2630 }
2631
2632 /**
2633 * Produces a special <em>invoker method handle</em> which can be used to
2634 * invoke a signature-polymorphic access mode method on any VarHandle whose
2635 * associated access mode type is compatible with the given type.
2636 * The resulting invoker will have a type which is exactly equal to the
2637 * desired given type, except that it will accept an additional leading
2638 * argument of type {@code VarHandle}.
2639 * <p>
2640 * Before invoking its target, if the access mode type differs from the
2641 * desired given type, the invoker will apply reference casts as necessary
2642 * and box, unbox, or widen primitive values, as if by
2643 * {@link MethodHandle#asType asType}. Similarly, the return value will be
2644 * converted as necessary.
2645 * <p>
2646 * This method is equivalent to the following code (though it may be more
2647 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
2648 *
2649 * @param accessMode the VarHandle access mode
2650 * @param type the desired target type
2651 * @return a method handle suitable for invoking an access mode method of
2652 * any VarHandle whose access mode type is convertible to the given
2653 * type.
2654 * @since 9
2655 */
2656 static public
2657 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
2658 return type.invokers().varHandleMethodInvoker(accessMode);
2659 }
2660
Christian Thalinger360d5122012-07-24 10:47:44 -07002661 static /*non-public*/
2662 MethodHandle basicInvoker(MethodType type) {
John Roseda56d3f2014-09-10 19:19:47 +04002663 return type.invokers().basicInvoker();
John R Rosefb6164c2009-05-05 22:40:09 -07002664 }
2665
Christian Thalinger360d5122012-07-24 10:47:44 -07002666 /// method handle modification (creation from other method handles)
John R Rosefb6164c2009-05-05 22:40:09 -07002667
2668 /**
John R Rose54e473f2011-02-11 01:26:28 -08002669 * Produces a method handle which adapts the type of the
John R Rose025d0ae2011-05-26 17:37:36 -07002670 * given method handle to a new type by pairwise argument and return type conversion.
John R Rose020e5502010-01-07 16:16:45 -08002671 * The original type and new type must have the same number of arguments.
John R Rose4f508ab2010-10-30 21:08:23 -07002672 * The resulting method handle is guaranteed to report a type
John R Rose020e5502010-01-07 16:16:45 -08002673 * which is equal to the desired new type.
John R Rosefb6164c2009-05-05 22:40:09 -07002674 * <p>
2675 * If the original type and new type are equal, returns target.
2676 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07002677 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
John R Rose4f508ab2010-10-30 21:08:23 -07002678 * and some additional conversions are also applied if those conversions fail.
John R Rose025d0ae2011-05-26 17:37:36 -07002679 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
2680 * if possible, before or instead of any conversions done by {@code asType}:
John R Rose4f508ab2010-10-30 21:08:23 -07002681 * <ul>
John R Rose025d0ae2011-05-26 17:37:36 -07002682 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
2683 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
John R Rose4f508ab2010-10-30 21:08:23 -07002684 * (This treatment of interfaces follows the usage of the bytecode verifier.)
John R Rose025d0ae2011-05-26 17:37:36 -07002685 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
2686 * the boolean is converted to a byte value, 1 for true, 0 for false.
John R Rose4f508ab2010-10-30 21:08:23 -07002687 * (This treatment follows the usage of the bytecode verifier.)
John R Rose025d0ae2011-05-26 17:37:36 -07002688 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
2689 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5),
2690 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
2691 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
2692 * then a Java casting conversion (JLS 5.5) is applied.
2693 * (Specifically, <em>T0</em> will convert to <em>T1</em> by
2694 * widening and/or narrowing.)
2695 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
2696 * conversion will be applied at runtime, possibly followed
2697 * by a Java casting conversion (JLS 5.5) on the primitive value,
2698 * possibly followed by a conversion from byte to boolean by testing
2699 * the low-order bit.
2700 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
2701 * and if the reference is null at runtime, a zero value is introduced.
John R Rose4f508ab2010-10-30 21:08:23 -07002702 * </ul>
2703 * @param target the method handle to invoke after arguments are retyped
2704 * @param newType the expected type of the new method handle
John R Rose025d0ae2011-05-26 17:37:36 -07002705 * @return a method handle which delegates to the target after performing
John R Rose4f508ab2010-10-30 21:08:23 -07002706 * any necessary argument conversions, and arranges for any
2707 * necessary return value conversions
John R Rose54e473f2011-02-11 01:26:28 -08002708 * @throws NullPointerException if either argument is null
John R Rose4f508ab2010-10-30 21:08:23 -07002709 * @throws WrongMethodTypeException if the conversion cannot be made
2710 * @see MethodHandle#asType
John R Rose4f508ab2010-10-30 21:08:23 -07002711 */
2712 public static
2713 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
Vladimir Ivanove490ad12014-09-16 18:05:01 +04002714 explicitCastArgumentsChecks(target, newType);
John Rose563b1c72014-09-10 19:19:51 +04002715 // use the asTypeCache when possible:
Vladimir Ivanove490ad12014-09-16 18:05:01 +04002716 MethodType oldType = target.type();
John Rose563b1c72014-09-10 19:19:51 +04002717 if (oldType == newType) return target;
2718 if (oldType.explicitCastEquivalentToAsType(newType)) {
Vladimir Ivanove0eba412014-12-09 09:22:07 -08002719 return target.asFixedArity().asType(newType);
Christian Thalinger360d5122012-07-24 10:47:44 -07002720 }
John Rosef365de52014-09-10 19:19:50 +04002721 return MethodHandleImpl.makePairwiseConvert(target, newType, false);
John R Rose4f508ab2010-10-30 21:08:23 -07002722 }
2723
Vladimir Ivanove490ad12014-09-16 18:05:01 +04002724 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
2725 if (target.type().parameterCount() != newType.parameterCount()) {
2726 throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
2727 }
2728 }
2729
John R Rose4f508ab2010-10-30 21:08:23 -07002730 /**
John R Rose54e473f2011-02-11 01:26:28 -08002731 * Produces a method handle which adapts the calling sequence of the
John R Rosefb6164c2009-05-05 22:40:09 -07002732 * given method handle to a new type, by reordering the arguments.
John R Rose4f508ab2010-10-30 21:08:23 -07002733 * The resulting method handle is guaranteed to report a type
John R Rosefb6164c2009-05-05 22:40:09 -07002734 * which is equal to the desired new type.
2735 * <p>
2736 * The given array controls the reordering.
2737 * Call {@code #I} the number of incoming parameters (the value
2738 * {@code newType.parameterCount()}, and call {@code #O} the number
2739 * of outgoing parameters (the value {@code target.type().parameterCount()}).
2740 * Then the length of the reordering array must be {@code #O},
2741 * and each element must be a non-negative number less than {@code #I}.
2742 * For every {@code N} less than {@code #O}, the {@code N}-th
2743 * outgoing argument will be taken from the {@code I}-th incoming
2744 * argument, where {@code I} is {@code reorder[N]}.
2745 * <p>
John R Rose4f508ab2010-10-30 21:08:23 -07002746 * No argument or return value conversions are applied.
2747 * The type of each incoming argument, as determined by {@code newType},
John R Rose025d0ae2011-05-26 17:37:36 -07002748 * must be identical to the type of the corresponding outgoing parameter
2749 * or parameters in the target method handle.
John R Rose4f508ab2010-10-30 21:08:23 -07002750 * The return type of {@code newType} must be identical to the return
2751 * type of the original target.
2752 * <p>
John R Rosefb6164c2009-05-05 22:40:09 -07002753 * The reordering array need not specify an actual permutation.
2754 * An incoming argument will be duplicated if its index appears
2755 * more than once in the array, and an incoming argument will be dropped
2756 * if its index does not appear in the array.
John R Rose4f508ab2010-10-30 21:08:23 -07002757 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
2758 * incoming arguments which are not mentioned in the reordering array
Michael Haupt5baf4fc2016-02-23 07:17:54 +01002759 * may be of any type, as determined only by {@code newType}.
Alan Bateman451a0032013-06-10 12:58:32 +01002760 * <blockquote><pre>{@code
John R Rose025d0ae2011-05-26 17:37:36 -07002761import static java.lang.invoke.MethodHandles.*;
2762import static java.lang.invoke.MethodType.*;
2763...
2764MethodType intfn1 = methodType(int.class, int.class);
2765MethodType intfn2 = methodType(int.class, int.class, int.class);
Joe Darcy0e32f672013-06-27 19:02:02 -07002766MethodHandle sub = ... (int x, int y) -> (x-y) ...;
John R Rose4f508ab2010-10-30 21:08:23 -07002767assert(sub.type().equals(intfn2));
John R Rose025d0ae2011-05-26 17:37:36 -07002768MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
2769MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
John R Rose4f508ab2010-10-30 21:08:23 -07002770assert((int)rsub.invokeExact(1, 100) == 99);
Joe Darcy0e32f672013-06-27 19:02:02 -07002771MethodHandle add = ... (int x, int y) -> (x+y) ...;
John R Rose4f508ab2010-10-30 21:08:23 -07002772assert(add.type().equals(intfn2));
John R Rose025d0ae2011-05-26 17:37:36 -07002773MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
John R Rose4f508ab2010-10-30 21:08:23 -07002774assert(twice.type().equals(intfn1));
2775assert((int)twice.invokeExact(21) == 42);
Alan Bateman451a0032013-06-10 12:58:32 +01002776 * }</pre></blockquote>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01002777 * <p>
2778 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
2779 * variable-arity method handle}, even if the original target method handle was.
John R Rosefb6164c2009-05-05 22:40:09 -07002780 * @param target the method handle to invoke after arguments are reordered
2781 * @param newType the expected type of the new method handle
John R Rose025d0ae2011-05-26 17:37:36 -07002782 * @param reorder an index array which controls the reordering
2783 * @return a method handle which delegates to the target after it
John R Rose4f508ab2010-10-30 21:08:23 -07002784 * drops unused arguments and moves and/or duplicates the other arguments
John R Rose54e473f2011-02-11 01:26:28 -08002785 * @throws NullPointerException if any argument is null
John R Rose025d0ae2011-05-26 17:37:36 -07002786 * @throws IllegalArgumentException if the index array length is not equal to
2787 * the arity of the target, or if any index array element
2788 * not a valid index for a parameter of {@code newType},
2789 * or if two corresponding parameter types in
2790 * {@code target.type()} and {@code newType} are not identical,
John R Rosefb6164c2009-05-05 22:40:09 -07002791 */
2792 public static
John R Rose4f508ab2010-10-30 21:08:23 -07002793 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
John Rosedbbce782014-09-10 19:19:52 +04002794 reorder = reorder.clone(); // get a private copy
2795 MethodType oldType = target.type();
2796 permuteArgumentChecks(reorder, newType, oldType);
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08002797 // first detect dropped arguments and handle them separately
2798 int[] originalReorder = reorder;
2799 BoundMethodHandle result = target.rebind();
2800 LambdaForm form = result.form;
2801 int newArity = newType.parameterCount();
2802 // Normalize the reordering into a real permutation,
2803 // by removing duplicates and adding dropped elements.
2804 // This somewhat improves lambda form caching, as well
2805 // as simplifying the transform by breaking it up into steps.
2806 for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
2807 if (ddIdx > 0) {
2808 // We found a duplicated entry at reorder[ddIdx].
2809 // Example: (x,y,z)->asList(x,y,z)
2810 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
2811 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
2812 // The starred element corresponds to the argument
2813 // deleted by the dupArgumentForm transform.
2814 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
2815 boolean killFirst = false;
2816 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
2817 // Set killFirst if the dup is larger than an intervening position.
2818 // This will remove at least one inversion from the permutation.
2819 if (dupVal > val) killFirst = true;
John Rosedbbce782014-09-10 19:19:52 +04002820 }
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08002821 if (!killFirst) {
2822 srcPos = dstPos;
2823 dstPos = ddIdx;
2824 }
2825 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
2826 assert (reorder[srcPos] == reorder[dstPos]);
2827 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
2828 // contract the reordering by removing the element at dstPos
2829 int tailPos = dstPos + 1;
2830 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
2831 reorder = Arrays.copyOf(reorder, reorder.length - 1);
2832 } else {
2833 int dropVal = ~ddIdx, insPos = 0;
2834 while (insPos < reorder.length && reorder[insPos] < dropVal) {
2835 // Find first element of reorder larger than dropVal.
2836 // This is where we will insert the dropVal.
2837 insPos += 1;
2838 }
2839 Class<?> ptype = newType.parameterType(dropVal);
2840 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
2841 oldType = oldType.insertParameterTypes(insPos, ptype);
2842 // expand the reordering by inserting an element at insPos
2843 int tailPos = insPos + 1;
2844 reorder = Arrays.copyOf(reorder, reorder.length + 1);
2845 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
2846 reorder[insPos] = dropVal;
John Rosedbbce782014-09-10 19:19:52 +04002847 }
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08002848 assert (permuteArgumentChecks(reorder, newType, oldType));
John Rose2f4b5e82014-09-10 19:19:48 +04002849 }
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08002850 assert (reorder.length == newArity); // a perfect permutation
2851 // Note: This may cache too many distinct LFs. Consider backing off to varargs code.
2852 form = form.editor().permuteArgumentsForm(1, reorder);
2853 if (newType == result.type() && form == result.internalForm())
2854 return result;
2855 return result.copyWith(newType, form);
John Rose2f4b5e82014-09-10 19:19:48 +04002856 }
2857
John Rosedbbce782014-09-10 19:19:52 +04002858 /**
2859 * Return an indication of any duplicate or omission in reorder.
2860 * If the reorder contains a duplicate entry, return the index of the second occurrence.
2861 * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
2862 * Otherwise, return zero.
2863 * If an element not in [0..newArity-1] is encountered, return reorder.length.
2864 */
2865 private static int findFirstDupOrDrop(int[] reorder, int newArity) {
2866 final int BIT_LIMIT = 63; // max number of bits in bit mask
2867 if (newArity < BIT_LIMIT) {
2868 long mask = 0;
2869 for (int i = 0; i < reorder.length; i++) {
2870 int arg = reorder[i];
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002871 if (arg >= newArity) {
2872 return reorder.length;
2873 }
2874 long bit = 1L << arg;
2875 if ((mask & bit) != 0) {
John Rosedbbce782014-09-10 19:19:52 +04002876 return i; // >0 indicates a dup
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002877 }
John Rosedbbce782014-09-10 19:19:52 +04002878 mask |= bit;
2879 }
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002880 if (mask == (1L << newArity) - 1) {
John Rosedbbce782014-09-10 19:19:52 +04002881 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
2882 return 0;
2883 }
2884 // find first zero
2885 long zeroBit = Long.lowestOneBit(~mask);
2886 int zeroPos = Long.numberOfTrailingZeros(zeroBit);
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002887 assert(zeroPos <= newArity);
2888 if (zeroPos == newArity) {
2889 return 0;
2890 }
John Rosedbbce782014-09-10 19:19:52 +04002891 return ~zeroPos;
2892 } else {
2893 // same algorithm, different bit set
2894 BitSet mask = new BitSet(newArity);
2895 for (int i = 0; i < reorder.length; i++) {
2896 int arg = reorder[i];
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002897 if (arg >= newArity) {
2898 return reorder.length;
2899 }
2900 if (mask.get(arg)) {
John Rosedbbce782014-09-10 19:19:52 +04002901 return i; // >0 indicates a dup
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002902 }
John Rosedbbce782014-09-10 19:19:52 +04002903 mask.set(arg);
2904 }
2905 int zeroPos = mask.nextClearBit(0);
Vladimir Ivanov475c0a72014-09-16 18:05:03 +04002906 assert(zeroPos <= newArity);
John Rosedbbce782014-09-10 19:19:52 +04002907 if (zeroPos == newArity) {
2908 return 0;
2909 }
2910 return ~zeroPos;
2911 }
2912 }
2913
John Rose2f4b5e82014-09-10 19:19:48 +04002914 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
John R Rose9a58e302011-05-12 19:27:49 -07002915 if (newType.returnType() != oldType.returnType())
2916 throw newIllegalArgumentException("return types do not match",
2917 oldType, newType);
John R Rosefb6164c2009-05-05 22:40:09 -07002918 if (reorder.length == oldType.parameterCount()) {
2919 int limit = newType.parameterCount();
2920 boolean bad = false;
John R Rose9a58e302011-05-12 19:27:49 -07002921 for (int j = 0; j < reorder.length; j++) {
2922 int i = reorder[j];
John R Rosefb6164c2009-05-05 22:40:09 -07002923 if (i < 0 || i >= limit) {
2924 bad = true; break;
2925 }
John R Rose9a58e302011-05-12 19:27:49 -07002926 Class<?> src = newType.parameterType(i);
2927 Class<?> dst = oldType.parameterType(j);
2928 if (src != dst)
2929 throw newIllegalArgumentException("parameter types do not match after reorder",
2930 oldType, newType);
John R Rosefb6164c2009-05-05 22:40:09 -07002931 }
John Rose2f4b5e82014-09-10 19:19:48 +04002932 if (!bad) return true;
John R Rosefb6164c2009-05-05 22:40:09 -07002933 }
John R Rose9a58e302011-05-12 19:27:49 -07002934 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder));
John R Rosefb6164c2009-05-05 22:40:09 -07002935 }
2936
2937 /**
John R Rose54e473f2011-02-11 01:26:28 -08002938 * Produces a method handle of the requested return type which returns the given
John R Rose4f508ab2010-10-30 21:08:23 -07002939 * constant value every time it is invoked.
2940 * <p>
2941 * Before the method handle is returned, the passed-in value is converted to the requested type.
2942 * If the requested type is primitive, widening primitive conversions are attempted,
2943 * else reference conversions are attempted.
John R Rose025d0ae2011-05-26 17:37:36 -07002944 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
John R Rose4f508ab2010-10-30 21:08:23 -07002945 * @param type the return type of the desired method handle
2946 * @param value the value to return
2947 * @return a method handle of the given return type and no arguments, which always returns the given value
John R Rose54e473f2011-02-11 01:26:28 -08002948 * @throws NullPointerException if the {@code type} argument is null
2949 * @throws ClassCastException if the value cannot be converted to the required return type
2950 * @throws IllegalArgumentException if the given type is {@code void.class}
John R Rose4f508ab2010-10-30 21:08:23 -07002951 */
2952 public static
2953 MethodHandle constant(Class<?> type, Object value) {
2954 if (type.isPrimitive()) {
John R Rose54e473f2011-02-11 01:26:28 -08002955 if (type == void.class)
2956 throw newIllegalArgumentException("void type");
John R Rose4f508ab2010-10-30 21:08:23 -07002957 Wrapper w = Wrapper.forPrimitiveType(type);
John Rose70c6eae2014-09-10 19:19:50 +04002958 value = w.convert(value, type);
2959 if (w.zero().equals(value))
2960 return zero(w, type);
2961 return insertArguments(identity(type), 0, value);
John R Rose4f508ab2010-10-30 21:08:23 -07002962 } else {
John Rose70c6eae2014-09-10 19:19:50 +04002963 if (value == null)
2964 return zero(Wrapper.OBJECT, type);
2965 return identity(type).bindTo(value);
John R Rose4f508ab2010-10-30 21:08:23 -07002966 }
2967 }
2968
2969 /**
John R Rose54e473f2011-02-11 01:26:28 -08002970 * Produces a method handle which returns its sole argument when invoked.
John R Rose54e473f2011-02-11 01:26:28 -08002971 * @param type the type of the sole parameter and return value of the desired method handle
2972 * @return a unary method handle which accepts and returns the given type
2973 * @throws NullPointerException if the argument is null
2974 * @throws IllegalArgumentException if the given type is {@code void.class}
John R Rose4f508ab2010-10-30 21:08:23 -07002975 */
2976 public static
John R Rose4f508ab2010-10-30 21:08:23 -07002977 MethodHandle identity(Class<?> type) {
John Rose9c808532014-09-10 19:19:50 +04002978 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
2979 int pos = btw.ordinal();
2980 MethodHandle ident = IDENTITY_MHS[pos];
2981 if (ident == null) {
2982 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
2983 }
2984 if (ident.type().returnType() == type)
2985 return ident;
2986 // something like identity(Foo.class); do not bother to intern these
Shilpi Rastogi284ec152016-04-13 15:48:14 +02002987 assert (btw == Wrapper.OBJECT);
John Rose9c808532014-09-10 19:19:50 +04002988 return makeIdentity(type);
2989 }
Shilpi Rastogi284ec152016-04-13 15:48:14 +02002990
2991 /**
2992 * Produces a constant method handle of the requested return type which
2993 * returns the default value for that type every time it is invoked.
2994 * The resulting constant method handle will have no side effects.
2995 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
2996 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
2997 * since {@code explicitCastArguments} converts {@code null} to default values.
2998 * @param type the expected return type of the desired method handle
2999 * @return a constant method handle that takes no arguments
3000 * and returns the default value of the given type (or void, if the type is void)
3001 * @throws NullPointerException if the argument is null
3002 * @see MethodHandles#constant
3003 * @see MethodHandles#empty
3004 * @since 9
3005 */
3006 public static MethodHandle zero(Class<?> type) {
3007 Objects.requireNonNull(type);
3008 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type);
3009 }
3010
3011 private static MethodHandle identityOrVoid(Class<?> type) {
3012 return type == void.class ? zero(type) : identity(type);
3013 }
3014
3015 /**
3016 * Produces a method handle of the requested type which ignores any arguments, does nothing,
3017 * and returns a suitable default depending on the return type.
3018 * That is, it returns a zero primitive value, a {@code null}, or {@code void}.
3019 * <p>The returned method handle is equivalent to
3020 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
3021 * <p>
3022 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
3023 * {@code guardWithTest(pred, target, empty(target.type())}.
3024 * @param type the type of the desired method handle
3025 * @return a constant method handle of the given type, which returns a default value of the given return type
3026 * @throws NullPointerException if the argument is null
3027 * @see MethodHandles#zero
3028 * @see MethodHandles#constant
3029 * @since 9
3030 */
3031 public static MethodHandle empty(MethodType type) {
3032 Objects.requireNonNull(type);
3033 return dropArguments(zero(type.returnType()), 0, type.parameterList());
3034 }
3035
John Rose9c808532014-09-10 19:19:50 +04003036 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.values().length];
3037 private static MethodHandle makeIdentity(Class<?> ptype) {
Michael Haupt402c4482016-04-19 14:39:35 +02003038 MethodType mtype = methodType(ptype, ptype);
John Rose9c808532014-09-10 19:19:50 +04003039 LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
3040 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
3041 }
John Rose70c6eae2014-09-10 19:19:50 +04003042
3043 private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
3044 int pos = btw.ordinal();
3045 MethodHandle zero = ZERO_MHS[pos];
3046 if (zero == null) {
3047 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
3048 }
3049 if (zero.type().returnType() == rtype)
3050 return zero;
3051 assert(btw == Wrapper.OBJECT);
3052 return makeZero(rtype);
3053 }
3054 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.values().length];
3055 private static MethodHandle makeZero(Class<?> rtype) {
Michael Haupt402c4482016-04-19 14:39:35 +02003056 MethodType mtype = methodType(rtype);
John Rose70c6eae2014-09-10 19:19:50 +04003057 LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
3058 return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
3059 }
3060
Martin Buchholza2f0fe32015-09-15 21:56:04 -07003061 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
John Rose9c808532014-09-10 19:19:50 +04003062 // Simulate a CAS, to avoid racy duplication of results.
3063 MethodHandle prev = cache[pos];
3064 if (prev != null) return prev;
3065 return cache[pos] = value;
John R Rose4f508ab2010-10-30 21:08:23 -07003066 }
3067
John R Rose4f508ab2010-10-30 21:08:23 -07003068 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003069 * Provides a target method handle with one or more <em>bound arguments</em>
3070 * in advance of the method handle's invocation.
3071 * The formal parameters to the target corresponding to the bound
3072 * arguments are called <em>bound parameters</em>.
3073 * Returns a new method handle which saves away the bound arguments.
3074 * When it is invoked, it receives arguments for any non-bound parameters,
3075 * binds the saved arguments to their corresponding parameters,
3076 * and calls the original target.
3077 * <p>
John R Rose020e5502010-01-07 16:16:45 -08003078 * The type of the new method handle will drop the types for the bound
3079 * parameters from the original target type, since the new method handle
3080 * will no longer require those arguments to be supplied by its callers.
John R Rosefb6164c2009-05-05 22:40:09 -07003081 * <p>
John R Rose020e5502010-01-07 16:16:45 -08003082 * Each given argument object must match the corresponding bound parameter type.
3083 * If a bound parameter type is a primitive, the argument object
3084 * must be a wrapper, and will be unboxed to produce the primitive value.
John R Rosefb6164c2009-05-05 22:40:09 -07003085 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003086 * The {@code pos} argument selects which parameters are to be bound.
3087 * It may range between zero and <i>N-L</i> (inclusively),
3088 * where <i>N</i> is the arity of the target method handle
3089 * and <i>L</i> is the length of the values array.
Michael Haupt5baf4fc2016-02-23 07:17:54 +01003090 * <p>
3091 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3092 * variable-arity method handle}, even if the original target method handle was.
John R Rosefb6164c2009-05-05 22:40:09 -07003093 * @param target the method handle to invoke after the argument is inserted
3094 * @param pos where to insert the argument (zero for the first)
John R Rose020e5502010-01-07 16:16:45 -08003095 * @param values the series of arguments to insert
John R Rose4f508ab2010-10-30 21:08:23 -07003096 * @return a method handle which inserts an additional argument,
John R Rosefb6164c2009-05-05 22:40:09 -07003097 * before calling the original method handle
John R Rose025d0ae2011-05-26 17:37:36 -07003098 * @throws NullPointerException if the target or the {@code values} array is null
John R Rose4f508ab2010-10-30 21:08:23 -07003099 * @see MethodHandle#bindTo
John R Rosefb6164c2009-05-05 22:40:09 -07003100 */
3101 public static
John R Rose020e5502010-01-07 16:16:45 -08003102 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
3103 int insCount = values.length;
John Rose2f4b5e82014-09-10 19:19:48 +04003104 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
3105 if (insCount == 0) return target;
3106 BoundMethodHandle result = target.rebind();
3107 for (int i = 0; i < insCount; i++) {
3108 Object value = values[i];
3109 Class<?> ptype = ptypes[pos+i];
3110 if (ptype.isPrimitive()) {
3111 result = insertArgumentPrimitive(result, pos, ptype, value);
3112 } else {
3113 value = ptype.cast(value); // throw CCE if needed
3114 result = result.bindArgumentL(pos, value);
3115 }
3116 }
3117 return result;
3118 }
3119
3120 private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
3121 Class<?> ptype, Object value) {
3122 Wrapper w = Wrapper.forPrimitiveType(ptype);
3123 // perform unboxing and/or primitive conversion
3124 value = w.convert(value, ptype);
3125 switch (w) {
3126 case INT: return result.bindArgumentI(pos, (int)value);
3127 case LONG: return result.bindArgumentJ(pos, (long)value);
3128 case FLOAT: return result.bindArgumentF(pos, (float)value);
3129 case DOUBLE: return result.bindArgumentD(pos, (double)value);
3130 default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value));
3131 }
3132 }
3133
3134 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
John R Rosefb6164c2009-05-05 22:40:09 -07003135 MethodType oldType = target.type();
John R Rosefb6164c2009-05-05 22:40:09 -07003136 int outargs = oldType.parameterCount();
John R Rose020e5502010-01-07 16:16:45 -08003137 int inargs = outargs - insCount;
3138 if (inargs < 0)
3139 throw newIllegalArgumentException("too many values to insert");
3140 if (pos < 0 || pos > inargs)
John R Rosefb6164c2009-05-05 22:40:09 -07003141 throw newIllegalArgumentException("no argument type to append");
John Rose2f4b5e82014-09-10 19:19:48 +04003142 return oldType.ptypes();
John R Rose020e5502010-01-07 16:16:45 -08003143 }
3144
John R Rosefb6164c2009-05-05 22:40:09 -07003145 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003146 * Produces a method handle which will discard some dummy arguments
3147 * before calling some other specified <i>target</i> method handle.
3148 * The type of the new method handle will be the same as the target's type,
3149 * except it will also include the dummy argument types,
3150 * at some given position.
John R Rosefb6164c2009-05-05 22:40:09 -07003151 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003152 * The {@code pos} argument may range between zero and <i>N</i>,
3153 * where <i>N</i> is the arity of the target.
3154 * If {@code pos} is zero, the dummy arguments will precede
3155 * the target's real arguments; if {@code pos} is <i>N</i>
3156 * they will come after.
John R Rose020e5502010-01-07 16:16:45 -08003157 * <p>
3158 * <b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04003159 * <blockquote><pre>{@code
John R Rose37188242011-03-23 23:02:31 -07003160import static java.lang.invoke.MethodHandles.*;
3161import static java.lang.invoke.MethodType.*;
John R Rose34cd7bc2010-12-16 15:59:27 -08003162...
3163MethodHandle cat = lookup().findVirtual(String.class,
3164 "concat", methodType(String.class, String.class));
3165assertEquals("xy", (String) cat.invokeExact("x", "y"));
John R Rose37188242011-03-23 23:02:31 -07003166MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
3167MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
3168assertEquals(bigType, d0.type());
3169assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
John R Rosebe5df962013-10-05 05:30:40 -07003170 * }</pre></blockquote>
John R Rose37188242011-03-23 23:02:31 -07003171 * <p>
3172 * This method is also equivalent to the following code:
Roger Riggs056189c2013-10-17 13:43:46 -04003173 * <blockquote><pre>
John R Rosebe5df962013-10-05 05:30:40 -07003174 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
John R Rose020e5502010-01-07 16:16:45 -08003175 * </pre></blockquote>
John R Rose4f508ab2010-10-30 21:08:23 -07003176 * @param target the method handle to invoke after the arguments are dropped
3177 * @param valueTypes the type(s) of the argument(s) to drop
3178 * @param pos position of first argument to drop (zero for the leftmost)
3179 * @return a method handle which drops arguments of the given types,
John R Rosefb6164c2009-05-05 22:40:09 -07003180 * before calling the original method handle
John R Rose025d0ae2011-05-26 17:37:36 -07003181 * @throws NullPointerException if the target is null,
John R Rose54e473f2011-02-11 01:26:28 -08003182 * or if the {@code valueTypes} list or any of its elements is null
John R Rose025d0ae2011-05-26 17:37:36 -07003183 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
3184 * or if {@code pos} is negative or greater than the arity of the target,
3185 * or if the new method handle's type would have too many parameters
John R Rosefb6164c2009-05-05 22:40:09 -07003186 */
3187 public static
John R Rose020e5502010-01-07 16:16:45 -08003188 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
John R Rose025d0ae2011-05-26 17:37:36 -07003189 MethodType oldType = target.type(); // get NPE
John Rose2f4b5e82014-09-10 19:19:48 +04003190 int dropped = dropArgumentChecks(oldType, pos, valueTypes);
Vladimir Ivanove490ad12014-09-16 18:05:01 +04003191 MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
John Rose2f4b5e82014-09-10 19:19:48 +04003192 if (dropped == 0) return target;
3193 BoundMethodHandle result = target.rebind();
3194 LambdaForm lform = result.form;
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08003195 int insertFormArg = 1 + pos;
3196 for (Class<?> ptype : valueTypes) {
3197 lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
John Rosedbbce782014-09-10 19:19:52 +04003198 }
John Rose2f4b5e82014-09-10 19:19:48 +04003199 result = result.copyWith(newType, lform);
3200 return result;
3201 }
3202
3203 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
Christian Thalinger360d5122012-07-24 10:47:44 -07003204 int dropped = valueTypes.size();
3205 MethodType.checkSlotCount(dropped);
John R Rosefb6164c2009-05-05 22:40:09 -07003206 int outargs = oldType.parameterCount();
Christian Thalinger360d5122012-07-24 10:47:44 -07003207 int inargs = outargs + dropped;
John Rose2f4b5e82014-09-10 19:19:48 +04003208 if (pos < 0 || pos > outargs)
3209 throw newIllegalArgumentException("no argument type to remove"
3210 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
3211 );
3212 return dropped;
John R Rosefb6164c2009-05-05 22:40:09 -07003213 }
3214
John R Rose4f508ab2010-10-30 21:08:23 -07003215 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003216 * Produces a method handle which will discard some dummy arguments
3217 * before calling some other specified <i>target</i> method handle.
3218 * The type of the new method handle will be the same as the target's type,
3219 * except it will also include the dummy argument types,
3220 * at some given position.
John R Rose37188242011-03-23 23:02:31 -07003221 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003222 * The {@code pos} argument may range between zero and <i>N</i>,
3223 * where <i>N</i> is the arity of the target.
3224 * If {@code pos} is zero, the dummy arguments will precede
3225 * the target's real arguments; if {@code pos} is <i>N</i>
3226 * they will come after.
Shilpi Rastogi284ec152016-04-13 15:48:14 +02003227 * @apiNote
Roger Riggs056189c2013-10-17 13:43:46 -04003228 * <blockquote><pre>{@code
John R Rose37188242011-03-23 23:02:31 -07003229import static java.lang.invoke.MethodHandles.*;
3230import static java.lang.invoke.MethodType.*;
3231...
3232MethodHandle cat = lookup().findVirtual(String.class,
3233 "concat", methodType(String.class, String.class));
3234assertEquals("xy", (String) cat.invokeExact("x", "y"));
3235MethodHandle d0 = dropArguments(cat, 0, String.class);
3236assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
3237MethodHandle d1 = dropArguments(cat, 1, String.class);
3238assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
3239MethodHandle d2 = dropArguments(cat, 2, String.class);
3240assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
3241MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
3242assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
John R Rosebe5df962013-10-05 05:30:40 -07003243 * }</pre></blockquote>
John R Rose37188242011-03-23 23:02:31 -07003244 * <p>
3245 * This method is also equivalent to the following code:
Roger Riggs056189c2013-10-17 13:43:46 -04003246 * <blockquote><pre>
John R Rosebe5df962013-10-05 05:30:40 -07003247 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
John R Rose37188242011-03-23 23:02:31 -07003248 * </pre></blockquote>
John R Rose4f508ab2010-10-30 21:08:23 -07003249 * @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
John R Rose025d0ae2011-05-26 17:37:36 -07003254 * @throws NullPointerException if the target is null,
John R Rose54e473f2011-02-11 01:26:28 -08003255 * or if the {@code valueTypes} array or any of its elements is null
John R Rose025d0ae2011-05-26 17:37:36 -07003256 * @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,
John R Rose77dc59f2013-10-05 05:30:39 -07003258 * or if the new method handle's type would have
3259 * <a href="MethodHandle.html#maxarity">too many parameters</a>
John R Rose4f508ab2010-10-30 21:08:23 -07003260 */
John R Rose020e5502010-01-07 16:16:45 -08003261 public static
3262 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
3263 return dropArguments(target, pos, Arrays.asList(valueTypes));
3264 }
3265
Shilpi Rastogi284ec152016-04-13 15:48:14 +02003266 // private version which allows caller some freedom with error handling
3267 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
3268 boolean nullOnFailure) {
3269 List<Class<?>> oldTypes = target.type().parameterList();
3270 int match = oldTypes.size();
3271 if (skip != 0) {
3272 if (skip < 0 || skip > match) {
3273 throw newIllegalArgumentException("illegal skip", skip, target);
3274 }
3275 oldTypes = oldTypes.subList(skip, match);
3276 match -= skip;
3277 }
3278 List<Class<?>> addTypes = newTypes;
3279 int add = addTypes.size();
3280 if (pos != 0) {
3281 if (pos < 0 || pos > add) {
3282 throw newIllegalArgumentException("illegal pos", pos, newTypes);
3283 }
3284 addTypes = addTypes.subList(pos, add);
3285 add -= pos; assert(addTypes.size() == add);
3286 }
3287 // Do not add types which already match the existing arguments.
3288 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
3289 if (nullOnFailure) {
3290 return null;
3291 }
3292 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
3293 }
3294 addTypes = addTypes.subList(match, add);
3295 add -= match; assert(addTypes.size() == add);
3296 // newTypes: ( P*[pos], M*[match], A*[add] )
3297 // target: ( S*[skip], M*[match] )
3298 MethodHandle adapter = target;
3299 if (add > 0) {
3300 adapter = dropArguments(adapter, skip+ match, addTypes);
3301 }
3302 // adapter: (S*[skip], M*[match], A*[add] )
3303 if (pos > 0) {
3304 adapter = dropArguments(adapter, skip, newTypes.subList(0, pos));
3305 }
3306 // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
3307 return adapter;
3308 }
3309
3310 /**
3311 * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments.
3312 * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored.
3313 * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list,
3314 * at the given position.
3315 * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding
3316 * positions of the target method handle's parameters, as if by {@link #dropArguments}.
3317 * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip},
3318 * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the
3319 * target list.)
3320 * The target's return type will be unchanged.
3321 * @apiNote
3322 * Two method handles whose argument lists are "effectively identical" (i.e., identical
3323 * in a common prefix) may be mutually converted to a common type
3324 * by two calls to {@code dropArgumentsToMatch}, as follows:
3325 * <blockquote><pre>{@code
3326import static java.lang.invoke.MethodHandles.*;
3327import static java.lang.invoke.MethodType.*;
3328...
3329...
3330MethodHandle h0 = constant(boolean.class, true);
3331MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
3332MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
3333MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
3334if (h1.type().parameterCount() < h2.type().parameterCount())
3335 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1
3336else
3337 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2
3338MethodHandle h3 = guardWithTest(h0, h1, h2);
3339assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
3340 * }</pre></blockquote>
3341 * @param target the method handle to adapt
3342 * @param skip number of targets parameters to disregard (they will be unchanged)
3343 * @param newTypes the desired argument list of the method handle
3344 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
3345 * @return a possibly adapted method handle
3346 * @throws NullPointerException if either argument is null
3347 * @throws IllegalArgumentException
3348 * if either index is out of range in its corresponding list, or
3349 * if the non-skipped target parameter types match the new types at {@code pos}
3350 * @since 9
3351 */
3352 public static
3353 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
3354 Objects.requireNonNull(target);
3355 Objects.requireNonNull(newTypes);
3356 return dropArgumentsToMatch(target, skip, newTypes, pos, false);
3357 }
3358
John R Rose020e5502010-01-07 16:16:45 -08003359 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003360 * Adapts a target method handle by pre-processing
John R Rose020e5502010-01-07 16:16:45 -08003361 * one or more of its arguments, each with its own unary filter function,
3362 * and then calling the target with each pre-processed argument
3363 * replaced by the result of its corresponding filter function.
3364 * <p>
3365 * The pre-processing is performed by one or more method handles,
John R Rose4f508ab2010-10-30 21:08:23 -07003366 * specified in the elements of the {@code filters} array.
John R Rose025d0ae2011-05-26 17:37:36 -07003367 * The first element of the filter array corresponds to the {@code pos}
3368 * argument of the target, and so on in sequence.
3369 * <p>
3370 * Null arguments in the array are treated as identity functions,
3371 * and the corresponding arguments left unchanged.
John R Rose54e473f2011-02-11 01:26:28 -08003372 * (If there are no non-null elements in the array, the original target is returned.)
John R Rose4f508ab2010-10-30 21:08:23 -07003373 * Each filter is applied to the corresponding argument of the adapter.
John R Rose020e5502010-01-07 16:16:45 -08003374 * <p>
3375 * If a filter {@code F} applies to the {@code N}th argument of
John R Rose025d0ae2011-05-26 17:37:36 -07003376 * the target, then {@code F} must be a method handle which
John R Rose020e5502010-01-07 16:16:45 -08003377 * takes exactly one argument. The type of {@code F}'s sole argument
3378 * replaces the corresponding argument type of the target
3379 * in the resulting adapted method handle.
3380 * The return type of {@code F} must be identical to the corresponding
3381 * parameter type of the target.
3382 * <p>
John R Rose4f508ab2010-10-30 21:08:23 -07003383 * It is an error if there are elements of {@code filters}
John R Rose025d0ae2011-05-26 17:37:36 -07003384 * (null or not)
John R Rose020e5502010-01-07 16:16:45 -08003385 * which do not correspond to argument positions in the target.
John R Rosebe5df962013-10-05 05:30:40 -07003386 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04003387 * <blockquote><pre>{@code
John R Rose37188242011-03-23 23:02:31 -07003388import static java.lang.invoke.MethodHandles.*;
3389import static java.lang.invoke.MethodType.*;
John R Rose4f508ab2010-10-30 21:08:23 -07003390...
3391MethodHandle cat = lookup().findVirtual(String.class,
3392 "concat", methodType(String.class, String.class));
3393MethodHandle upcase = lookup().findVirtual(String.class,
3394 "toUpperCase", methodType(String.class));
John R Rose34cd7bc2010-12-16 15:59:27 -08003395assertEquals("xy", (String) cat.invokeExact("x", "y"));
John R Rose4f508ab2010-10-30 21:08:23 -07003396MethodHandle f0 = filterArguments(cat, 0, upcase);
John R Rose34cd7bc2010-12-16 15:59:27 -08003397assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
John R Rose4f508ab2010-10-30 21:08:23 -07003398MethodHandle f1 = filterArguments(cat, 1, upcase);
John R Rose34cd7bc2010-12-16 15:59:27 -08003399assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
John R Rose4f508ab2010-10-30 21:08:23 -07003400MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
John R Rose34cd7bc2010-12-16 15:59:27 -08003401assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
John R Rosebe5df962013-10-05 05:30:40 -07003402 * }</pre></blockquote>
Michael Haupt19a07cb2016-02-23 09:49:04 +01003403 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3404 * denotes the return type of both the {@code target} and resulting adapter.
3405 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
3406 * of the parameters and arguments that precede and follow the filter position
3407 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
3408 * values of the filtered parameters and arguments; they also represent the
3409 * return types of the {@code filter[i]} handles. The latter accept arguments
3410 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
3411 * the resulting adapter.
John R Rosebe5df962013-10-05 05:30:40 -07003412 * <blockquote><pre>{@code
Michael Haupt19a07cb2016-02-23 09:49:04 +01003413 * T target(P... p, A[i]... a[i], B... b);
John R Rose025d0ae2011-05-26 17:37:36 -07003414 * A[i] filter[i](V[i]);
3415 * T adapter(P... p, V[i]... v[i], B... b) {
Michael Haupt19a07cb2016-02-23 09:49:04 +01003416 * return target(p..., filter[i](v[i])..., b...);
John R Rose025d0ae2011-05-26 17:37:36 -07003417 * }
John R Rosebe5df962013-10-05 05:30:40 -07003418 * }</pre></blockquote>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01003419 * <p>
3420 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3421 * variable-arity method handle}, even if the original target method handle was.
John R Rose54e473f2011-02-11 01:26:28 -08003422 *
John R Rose020e5502010-01-07 16:16:45 -08003423 * @param target the method handle to invoke after arguments are filtered
John R Rose4f508ab2010-10-30 21:08:23 -07003424 * @param pos the position of the first argument to filter
John R Rose020e5502010-01-07 16:16:45 -08003425 * @param filters method handles to call initially on filtered arguments
3426 * @return method handle which incorporates the specified argument filtering logic
John R Rose025d0ae2011-05-26 17:37:36 -07003427 * @throws NullPointerException if the target is null
John R Rose54e473f2011-02-11 01:26:28 -08003428 * or if the {@code filters} array is null
3429 * @throws IllegalArgumentException if a non-null element of {@code filters}
John R Rose025d0ae2011-05-26 17:37:36 -07003430 * does not match a corresponding argument type of target as described above,
John R Rose77dc59f2013-10-05 05:30:39 -07003431 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
3432 * or if the resulting method handle's type would have
3433 * <a href="MethodHandle.html#maxarity">too many parameters</a>
John R Rose020e5502010-01-07 16:16:45 -08003434 */
3435 public static
John R Rose4f508ab2010-10-30 21:08:23 -07003436 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
John Rose67504742014-09-10 19:19:51 +04003437 filterArgumentsCheckArity(target, pos, filters);
John R Rose020e5502010-01-07 16:16:45 -08003438 MethodHandle adapter = target;
John R Rose54e473f2011-02-11 01:26:28 -08003439 int curPos = pos-1; // pre-incremented
John R Rose020e5502010-01-07 16:16:45 -08003440 for (MethodHandle filter : filters) {
John R Rose54e473f2011-02-11 01:26:28 -08003441 curPos += 1;
3442 if (filter == null) continue; // ignore null elements of filters
John R Rose9a58e302011-05-12 19:27:49 -07003443 adapter = filterArgument(adapter, curPos, filter);
John R Rose020e5502010-01-07 16:16:45 -08003444 }
John R Rose020e5502010-01-07 16:16:45 -08003445 return adapter;
3446 }
3447
John R Rose9a58e302011-05-12 19:27:49 -07003448 /*non-public*/ static
3449 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
John Rose67504742014-09-10 19:19:51 +04003450 filterArgumentChecks(target, pos, filter);
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08003451 MethodType targetType = target.type();
3452 MethodType filterType = filter.type();
3453 BoundMethodHandle result = target.rebind();
3454 Class<?> newParamType = filterType.parameterType(0);
3455 LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
3456 MethodType newType = targetType.changeParameterType(pos, newParamType);
3457 result = result.copyWithExtendL(newType, lform, filter);
3458 return result;
John Rose67504742014-09-10 19:19:51 +04003459 }
3460
3461 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
3462 MethodType targetType = target.type();
3463 int maxPos = targetType.parameterCount();
3464 if (pos + filters.length > maxPos)
3465 throw newIllegalArgumentException("too many filters");
3466 }
3467
3468 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
John R Rose9a58e302011-05-12 19:27:49 -07003469 MethodType targetType = target.type();
3470 MethodType filterType = filter.type();
3471 if (filterType.parameterCount() != 1
3472 || filterType.returnType() != targetType.parameterType(pos))
3473 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
John R Rose9a58e302011-05-12 19:27:49 -07003474 }
3475
John R Rose32e77ea2013-10-05 05:30:39 -07003476 /**
3477 * Adapts a target method handle by pre-processing
3478 * a sub-sequence of its arguments with a filter (another method handle).
3479 * The pre-processed arguments are replaced by the result (if any) of the
3480 * filter function.
3481 * The target is then called on the modified (usually shortened) argument list.
3482 * <p>
3483 * If the filter returns a value, the target must accept that value as
3484 * its argument in position {@code pos}, preceded and/or followed by
3485 * any arguments not passed to the filter.
3486 * If the filter returns void, the target must accept all arguments
3487 * not passed to the filter.
3488 * No arguments are reordered, and a result returned from the filter
3489 * replaces (in order) the whole subsequence of arguments originally
3490 * passed to the adapter.
3491 * <p>
3492 * The argument types (if any) of the filter
3493 * replace zero or one argument types of the target, at position {@code pos},
3494 * in the resulting adapted method handle.
3495 * The return type of the filter (if any) must be identical to the
3496 * argument type of the target at position {@code pos}, and that target argument
3497 * is supplied by the return value of the filter.
3498 * <p>
3499 * In all cases, {@code pos} must be greater than or equal to zero, and
3500 * {@code pos} must also be less than or equal to the target's arity.
3501 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04003502 * <blockquote><pre>{@code
John R Rose32e77ea2013-10-05 05:30:39 -07003503import static java.lang.invoke.MethodHandles.*;
3504import static java.lang.invoke.MethodType.*;
3505...
3506MethodHandle deepToString = publicLookup()
3507 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
3508
3509MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
3510assertEquals("[strange]", (String) ts1.invokeExact("strange"));
3511
3512MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
3513assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
3514
3515MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
3516MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
3517assertEquals("[top, [up, down], strange]",
3518 (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
3519
3520MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
3521assertEquals("[top, [up, down], [strange]]",
3522 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
3523
3524MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
3525assertEquals("[top, [[up, down, strange], charm], bottom]",
3526 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
John R Rosebe5df962013-10-05 05:30:40 -07003527 * }</pre></blockquote>
Michael Haupt19a07cb2016-02-23 09:49:04 +01003528 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3529 * represents the return type of the {@code target} and resulting adapter.
3530 * {@code V}/{@code v} stand for the return type and value of the
3531 * {@code filter}, which are also found in the signature and arguments of
3532 * the {@code target}, respectively, unless {@code V} is {@code void}.
3533 * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
3534 * and values preceding and following the collection position, {@code pos},
3535 * in the {@code target}'s signature. They also turn up in the resulting
3536 * adapter's signature and arguments, where they surround
3537 * {@code B}/{@code b}, which represent the parameter types and arguments
3538 * to the {@code filter} (if any).
John R Rosebe5df962013-10-05 05:30:40 -07003539 * <blockquote><pre>{@code
John R Rose32e77ea2013-10-05 05:30:39 -07003540 * T target(A...,V,C...);
3541 * V filter(B...);
3542 * T adapter(A... a,B... b,C... c) {
3543 * V v = filter(b...);
3544 * return target(a...,v,c...);
3545 * }
3546 * // and if the filter has no arguments:
3547 * T target2(A...,V,C...);
3548 * V filter2();
3549 * T adapter2(A... a,C... c) {
3550 * V v = filter2();
3551 * return target2(a...,v,c...);
3552 * }
3553 * // and if the filter has a void return:
3554 * T target3(A...,C...);
3555 * void filter3(B...);
Michael Haupt19a07cb2016-02-23 09:49:04 +01003556 * T adapter3(A... a,B... b,C... c) {
John R Rose32e77ea2013-10-05 05:30:39 -07003557 * filter3(b...);
3558 * return target3(a...,c...);
3559 * }
John R Rosebe5df962013-10-05 05:30:40 -07003560 * }</pre></blockquote>
John R Rose32e77ea2013-10-05 05:30:39 -07003561 * <p>
3562 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
3563 * one which first "folds" the affected arguments, and then drops them, in separate
3564 * steps as follows:
3565 * <blockquote><pre>{@code
3566 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
3567 * mh = MethodHandles.foldArguments(mh, coll); //step 1
3568 * }</pre></blockquote>
3569 * If the target method handle consumes no arguments besides than the result
3570 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
3571 * is equivalent to {@code filterReturnValue(coll, mh)}.
3572 * If the filter method handle {@code coll} consumes one argument and produces
3573 * a non-void result, then {@code collectArguments(mh, N, coll)}
3574 * is equivalent to {@code filterArguments(mh, N, coll)}.
3575 * Other equivalences are possible but would require argument permutation.
Michael Haupt5baf4fc2016-02-23 07:17:54 +01003576 * <p>
3577 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3578 * variable-arity method handle}, even if the original target method handle was.
John R Rose32e77ea2013-10-05 05:30:39 -07003579 *
3580 * @param target the method handle to invoke after filtering the subsequence of arguments
3581 * @param pos the position of the first adapter argument to pass to the filter,
3582 * and/or the target argument which receives the result of the filter
3583 * @param filter method handle to call on the subsequence of arguments
3584 * @return method handle which incorporates the specified argument subsequence filtering logic
3585 * @throws NullPointerException if either argument is null
3586 * @throws IllegalArgumentException if the return type of {@code filter}
3587 * is non-void and is not the same as the {@code pos} argument of the target,
3588 * or if {@code pos} is not between 0 and the target's arity, inclusive,
3589 * or if the resulting method handle's type would have
3590 * <a href="MethodHandle.html#maxarity">too many parameters</a>
3591 * @see MethodHandles#foldArguments
3592 * @see MethodHandles#filterArguments
3593 * @see MethodHandles#filterReturnValue
3594 */
3595 public static
3596 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
John Rosedbbce782014-09-10 19:19:52 +04003597 MethodType newType = collectArgumentsChecks(target, pos, filter);
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08003598 MethodType collectorType = filter.type();
3599 BoundMethodHandle result = target.rebind();
3600 LambdaForm lform;
3601 if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) {
3602 lform = result.editor().collectArgumentArrayForm(1 + pos, filter);
3603 if (lform != null) {
3604 return result.copyWith(newType, lform);
John Rosedbbce782014-09-10 19:19:52 +04003605 }
John Rosedbbce782014-09-10 19:19:52 +04003606 }
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08003607 lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
3608 return result.copyWithExtendL(newType, lform, filter);
John Rosedbbce782014-09-10 19:19:52 +04003609 }
3610
3611 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
John R Rose9d9d7872012-08-17 13:42:25 -07003612 MethodType targetType = target.type();
John R Rose32e77ea2013-10-05 05:30:39 -07003613 MethodType filterType = filter.type();
John Rosedbbce782014-09-10 19:19:52 +04003614 Class<?> rtype = filterType.returnType();
3615 List<Class<?>> filterArgs = filterType.parameterList();
3616 if (rtype == void.class) {
3617 return targetType.insertParameterTypes(pos, filterArgs);
3618 }
3619 if (rtype != targetType.parameterType(pos)) {
John R Rose9d9d7872012-08-17 13:42:25 -07003620 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
John Rosedbbce782014-09-10 19:19:52 +04003621 }
3622 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
John R Rose9d9d7872012-08-17 13:42:25 -07003623 }
3624
John R Rose34cd7bc2010-12-16 15:59:27 -08003625 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003626 * Adapts a target method handle by post-processing
3627 * its return value (if any) with a filter (another method handle).
3628 * The result of the filter is returned from the adapter.
John R Rose4f508ab2010-10-30 21:08:23 -07003629 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003630 * If the target returns a value, the filter must accept that value as
3631 * its only argument.
3632 * If the target returns void, the filter must accept no arguments.
3633 * <p>
3634 * The return type of the filter
John R Rose4f508ab2010-10-30 21:08:23 -07003635 * replaces the return type of the target
3636 * in the resulting adapted method handle.
John R Rose025d0ae2011-05-26 17:37:36 -07003637 * The argument type of the filter (if any) must be identical to the
John R Rose4f508ab2010-10-30 21:08:23 -07003638 * return type of the target.
John R Rosebe5df962013-10-05 05:30:40 -07003639 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04003640 * <blockquote><pre>{@code
John R Rose37188242011-03-23 23:02:31 -07003641import static java.lang.invoke.MethodHandles.*;
3642import static java.lang.invoke.MethodType.*;
John R Rose4f508ab2010-10-30 21:08:23 -07003643...
3644MethodHandle cat = lookup().findVirtual(String.class,
3645 "concat", methodType(String.class, String.class));
3646MethodHandle length = lookup().findVirtual(String.class,
3647 "length", methodType(int.class));
3648System.out.println((String) cat.invokeExact("x", "y")); // xy
3649MethodHandle f0 = filterReturnValue(cat, length);
3650System.out.println((int) f0.invokeExact("x", "y")); // 2
John R Rosebe5df962013-10-05 05:30:40 -07003651 * }</pre></blockquote>
Michael Haupt19a07cb2016-02-23 09:49:04 +01003652 * <p>Here is pseudocode for the resulting adapter. In the code,
3653 * {@code T}/{@code t} represent the result type and value of the
3654 * {@code target}; {@code V}, the result type of the {@code filter}; and
3655 * {@code A}/{@code a}, the types and values of the parameters and arguments
3656 * of the {@code target} as well as the resulting adapter.
John R Rosebe5df962013-10-05 05:30:40 -07003657 * <blockquote><pre>{@code
Michael Haupt19a07cb2016-02-23 09:49:04 +01003658 * T target(A...);
3659 * V filter(T);
3660 * V adapter(A... a) {
3661 * T t = target(a...);
3662 * return filter(t);
John R Rose025d0ae2011-05-26 17:37:36 -07003663 * }
3664 * // and if the target has a void return:
3665 * void target2(A...);
Michael Haupt19a07cb2016-02-23 09:49:04 +01003666 * V filter2();
3667 * V adapter2(A... a) {
John R Rose025d0ae2011-05-26 17:37:36 -07003668 * target2(a...);
3669 * return filter2();
3670 * }
3671 * // and if the filter has a void return:
Michael Haupt19a07cb2016-02-23 09:49:04 +01003672 * T target3(A...);
John R Rose025d0ae2011-05-26 17:37:36 -07003673 * void filter3(V);
3674 * void adapter3(A... a) {
Michael Haupt19a07cb2016-02-23 09:49:04 +01003675 * T t = target3(a...);
3676 * filter3(t);
John R Rose025d0ae2011-05-26 17:37:36 -07003677 * }
John R Rosebe5df962013-10-05 05:30:40 -07003678 * }</pre></blockquote>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01003679 * <p>
3680 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3681 * variable-arity method handle}, even if the original target method handle was.
John R Rose4f508ab2010-10-30 21:08:23 -07003682 * @param target the method handle to invoke before filtering the return value
3683 * @param filter method handle to call on the return value
3684 * @return method handle which incorporates the specified return value filtering logic
John R Rose54e473f2011-02-11 01:26:28 -08003685 * @throws NullPointerException if either argument is null
John R Rose025d0ae2011-05-26 17:37:36 -07003686 * @throws IllegalArgumentException if the argument list of {@code filter}
3687 * does not match the return type of target as described above
John R Rose2a322bb2010-10-30 21:02:30 -07003688 */
John R Rose4f508ab2010-10-30 21:08:23 -07003689 public static
John R Rose2a322bb2010-10-30 21:02:30 -07003690 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
3691 MethodType targetType = target.type();
3692 MethodType filterType = filter.type();
John Rose67504742014-09-10 19:19:51 +04003693 filterReturnValueChecks(targetType, filterType);
Vladimir Ivanovb1ad8012014-11-24 07:16:38 -08003694 BoundMethodHandle result = target.rebind();
3695 BasicType rtype = BasicType.basicType(filterType.returnType());
3696 LambdaForm lform = result.editor().filterReturnForm(rtype, false);
3697 MethodType newType = targetType.changeReturnType(filterType.returnType());
3698 result = result.copyWithExtendL(newType, lform, filter);
3699 return result;
John Rose67504742014-09-10 19:19:51 +04003700 }
3701
3702 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
John R Rose9a58e302011-05-12 19:27:49 -07003703 Class<?> rtype = targetType.returnType();
3704 int filterValues = filterType.parameterCount();
3705 if (filterValues == 0
3706 ? (rtype != void.class)
3707 : (rtype != filterType.parameterType(0)))
John Rose67504742014-09-10 19:19:51 +04003708 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
John R Rose2a322bb2010-10-30 21:02:30 -07003709 }
3710
John R Rose020e5502010-01-07 16:16:45 -08003711 /**
John R Rose025d0ae2011-05-26 17:37:36 -07003712 * Adapts a target method handle by pre-processing
John R Rose020e5502010-01-07 16:16:45 -08003713 * some of its arguments, and then calling the target with
John R Rose025d0ae2011-05-26 17:37:36 -07003714 * the result of the pre-processing, inserted into the original
3715 * sequence of arguments.
John R Rose020e5502010-01-07 16:16:45 -08003716 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003717 * The pre-processing is performed by {@code combiner}, a second method handle.
3718 * Of the arguments passed to the adapter, the first {@code N} arguments
3719 * are copied to the combiner, which is then called.
3720 * (Here, {@code N} is defined as the parameter count of the combiner.)
3721 * After this, control passes to the target, with any result
3722 * from the combiner inserted before the original {@code N} incoming
3723 * arguments.
John R Rose020e5502010-01-07 16:16:45 -08003724 * <p>
John R Rose025d0ae2011-05-26 17:37:36 -07003725 * If the combiner returns a value, the first parameter type of the target
3726 * must be identical with the return type of the combiner, and the next
3727 * {@code N} parameter types of the target must exactly match the parameters
3728 * of the combiner.
3729 * <p>
3730 * If the combiner has a void return, no result will be inserted,
3731 * and the first {@code N} parameter types of the target
3732 * must exactly match the parameters of the combiner.
3733 * <p>
John R Rose020e5502010-01-07 16:16:45 -08003734 * The resulting adapter is the same type as the target, except that the
John R Rose025d0ae2011-05-26 17:37:36 -07003735 * first parameter type is dropped,
3736 * if it corresponds to the result of the combiner.
John R Rose020e5502010-01-07 16:16:45 -08003737 * <p>
John R Rose4f508ab2010-10-30 21:08:23 -07003738 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
John R Rose025d0ae2011-05-26 17:37:36 -07003739 * that either the combiner or the target does not wish to receive.
John R Rose020e5502010-01-07 16:16:45 -08003740 * If some of the incoming arguments are destined only for the combiner,
John R Rose54e473f2011-02-11 01:26:28 -08003741 * consider using {@link MethodHandle#asCollector asCollector} instead, since those
John R Rose020e5502010-01-07 16:16:45 -08003742 * arguments will not need to be live on the stack on entry to the
3743 * target.)
John R Rosebe5df962013-10-05 05:30:40 -07003744 * <p><b>Example:</b>
Roger Riggs056189c2013-10-17 13:43:46 -04003745 * <blockquote><pre>{@code
John R Rose025d0ae2011-05-26 17:37:36 -07003746import static java.lang.invoke.MethodHandles.*;
3747import static java.lang.invoke.MethodType.*;
3748...
3749MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
3750 "println", methodType(void.class, String.class))
3751 .bindTo(System.out);
3752MethodHandle cat = lookup().findVirtual(String.class,
3753 "concat", methodType(String.class, String.class));
3754assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
3755MethodHandle catTrace = foldArguments(cat, trace);
3756// also prints "boo":
3757assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
John R Rosebe5df962013-10-05 05:30:40 -07003758 * }</pre></blockquote>
Michael Haupt19a07cb2016-02-23 09:49:04 +01003759 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
3760 * represents the result type of the {@code target} and resulting adapter.
3761 * {@code V}/{@code v} represent the type and value of the parameter and argument
3762 * of {@code target} that precedes the folding position; {@code V} also is
3763 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
3764 * types and values of the {@code N} parameters and arguments at the folding
3765 * position. {@code B}/{@code b} represent the types and values of the
3766 * {@code target} parameters and arguments that follow the folded parameters
3767 * and arguments.
John R Rosebe5df962013-10-05 05:30:40 -07003768 * <blockquote><pre>{@code
John R Rose025d0ae2011-05-26 17:37:36 -07003769 * // there are N arguments in A...
John R Rose020e5502010-01-07 16:16:45 -08003770 * T target(V, A[N]..., B...);
3771 * V combiner(A...);
3772 * T adapter(A... a, B... b) {
3773 * V v = combiner(a...);
3774 * return target(v, a..., b...);
3775 * }
John R Rose025d0ae2011-05-26 17:37:36 -07003776 * // and if the combiner has a void return:
3777 * T target2(A[N]..., B...);
3778 * void combiner2(A...);
3779 * T adapter2(A... a, B... b) {
3780 * combiner2(a...);
3781 * return target2(a..., b...);
3782 * }
John R Rosebe5df962013-10-05 05:30:40 -07003783 * }</pre></blockquote>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01003784 * <p>
3785 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
3786 * variable-arity method handle}, even if the original target method handle was.
John R Rose020e5502010-01-07 16:16:45 -08003787 * @param target the method handle to invoke after arguments are combined
3788 * @param combiner method handle to call initially on the incoming arguments
3789 * @return method handle which incorporates the specified argument folding logic
John R Rose54e473f2011-02-11 01:26:28 -08003790 * @throws NullPointerException if either argument is null
John R Rose025d0ae2011-05-26 17:37:36 -07003791 * @throws IllegalArgumentException if {@code combiner}'s return type
3792 * is non-void and not the same as the first argument type of
3793 * the target, or if the initial {@code N} argument types
3794 * of the target
3795 * (skipping one matching the {@code combiner}'s return type)
John R Rose020e5502010-01-07 16:16:45 -08003796 * are not identical with the argument types of {@code combiner}
3797 */
3798 public static
3799 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01003800 return foldArguments(target, 0, combiner);
John Rose67504742014-09-10 19:19:51 +04003801 }
3802
3803 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
3804 int foldArgs = combinerType.parameterCount();
3805 Class<?> rtype = combinerType.returnType();
3806 int foldVals = rtype == void.class ? 0 : 1;
John R Rose9a58e302011-05-12 19:27:49 -07003807 int afterInsertPos = foldPos + foldVals;
3808 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
3809 if (ok && !(combinerType.parameterList()
3810 .equals(targetType.parameterList().subList(afterInsertPos,
3811 afterInsertPos + foldArgs))))
John R Rose2a322bb2010-10-30 21:02:30 -07003812 ok = false;
Michael Haupt5b2c88e2015-11-20 15:34:12 +01003813 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
John R Rose2a322bb2010-10-30 21:02:30 -07003814 ok = false;
John R Rose020e5502010-01-07 16:16:45 -08003815 if (!ok)
3816 throw misMatchedTypes("target and combiner types", targetType, combinerType);
John Rose67504742014-09-10 19:19:51 +04003817 return rtype;
John R Rose020e5502010-01-07 16:16:45 -08003818 }
3819
John R Rosefb6164c2009-05-05 22:40:09 -07003820 /**
John R Rose37188242011-03-23 23:02:31 -07003821 * Makes a method handle which adapts a target method handle,
John R Rosefb6164c2009-05-05 22:40:09 -07003822 * by guarding it with a test, a boolean-valued method handle.
3823 * If the guard fails, a fallback handle is called instead.
3824 * All three method handles must have the same corresponding
3825 * argument and return types, except that the return type
John R Rose020e5502010-01-07 16:16:45 -08003826 * of the test must be boolean, and the test is allowed
3827 * to have fewer arguments than the other two method handles.
Michael Haupt19a07cb2016-02-23 09:49:04 +01003828 * <p>
3829 * Here is pseudocode for the resulting adapter. In the code, {@code T}
3830 * represents the uniform result type of the three involved handles;
3831 * {@code A}/{@code a}, the types and values of the {@code target}
3832 * parameters and arguments that are consumed by the {@code test}; and
3833 * {@code B}/{@code b}, those types and values of the {@code target}
3834 * parameters and arguments that are not consumed by the {@code test}.
John R Rosebe5df962013-10-05 05:30:40 -07003835 * <blockquote><pre>{@code
John R Rosefb6164c2009-05-05 22:40:09 -07003836 * boolean test(A...);
John R Rose020e5502010-01-07 16:16:45 -08003837 * T target(A...,B...);
3838 * T fallback(A...,B...);
3839 * T adapter(A... a,B... b) {
John R Rosefb6164c2009-05-05 22:40:09 -07003840 * if (test(a...))
John R Rose020e5502010-01-07 16:16:45 -08003841 * return target(a..., b...);
John R Rosefb6164c2009-05-05 22:40:09 -07003842 * else
John R Rose020e5502010-01-07 16:16:45 -08003843 * return fallback(a..., b...);
John R Rosefb6164c2009-05-05 22:40:09 -07003844 * }
John R Rosebe5df962013-10-05 05:30:40 -07003845 * }</pre></blockquote>
John R Rose34cd7bc2010-12-16 15:59:27 -08003846 * Note that the test arguments ({@code a...} in the pseudocode) cannot
3847 * be modified by execution of the test, and so are passed unchanged
3848 * from the caller to the target or fallback as appropriate.
John R Rosefb6164c2009-05-05 22:40:09 -07003849 * @param test method handle used for test, must return boolean
3850 * @param target method handle to call if test passes
3851 * @param fallback method handle to call if test fails
3852 * @return method handle which incorporates the specified if/then/else logic
John R Rose54e473f2011-02-11 01:26:28 -08003853 * @throws NullPointerException if any argument is null
John R Rosefb6164c2009-05-05 22:40:09 -07003854 * @throws IllegalArgumentException if {@code test} does not return boolean,
3855 * or if all three method types do not match (with the return
John R Rose025d0ae2011-05-26 17:37:36 -07003856 * type of {@code test} changed to match that of the target).
John R Rosefb6164c2009-05-05 22:40:09 -07003857 */
3858 public static
3859 MethodHandle guardWithTest(MethodHandle test,
3860 MethodHandle target,
3861 MethodHandle fallback) {
John R Rose020e5502010-01-07 16:16:45 -08003862 MethodType gtype = test.type();
3863 MethodType ttype = target.type();
3864 MethodType ftype = fallback.type();
John R Rose34cd7bc2010-12-16 15:59:27 -08003865 if (!ttype.equals(ftype))
John R Rose020e5502010-01-07 16:16:45 -08003866 throw misMatchedTypes("target and fallback types", ttype, ftype);
John R Rose34cd7bc2010-12-16 15:59:27 -08003867 if (gtype.returnType() != boolean.class)
3868 throw newIllegalArgumentException("guard type is not a predicate "+gtype);
3869 List<Class<?>> targs = ttype.parameterList();
Shilpi Rastogi284ec152016-04-13 15:48:14 +02003870 test = dropArgumentsToMatch(test, 0, targs, 0, true);
3871 if (test == null) {
3872 throw misMatchedTypes("target and test types", ttype, gtype);
John R Rose020e5502010-01-07 16:16:45 -08003873 }
John R Rosee7ebd472011-03-18 00:03:24 -07003874 return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
John R Rosefb6164c2009-05-05 22:40:09 -07003875 }
3876
Michael Haupt5b2c88e2015-11-20 15:34:12 +01003877 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
John R Rose020e5502010-01-07 16:16:45 -08003878 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
John R Rosefb6164c2009-05-05 22:40:09 -07003879 }
3880
John R Rose020e5502010-01-07 16:16:45 -08003881 /**
John R Rose37188242011-03-23 23:02:31 -07003882 * Makes a method handle which adapts a target method handle,
John R Rose020e5502010-01-07 16:16:45 -08003883 * by running it inside an exception handler.
3884 * If the target returns normally, the adapter returns that value.
3885 * If an exception matching the specified type is thrown, the fallback
3886 * handle is called instead on the exception, plus the original arguments.
3887 * <p>
John R Rose34cd7bc2010-12-16 15:59:27 -08003888 * The target and handler must have the same corresponding
3889 * argument and return types, except that handler may omit trailing arguments
3890 * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
3891 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
Michael Haupt19a07cb2016-02-23 09:49:04 +01003892 * <p>
3893 * Here is pseudocode for the resulting adapter. In the code, {@code T}
3894 * represents the return type of the {@code target} and {@code handler},
3895 * and correspondingly that of the resulting adapter; {@code A}/{@code a},
3896 * the types and values of arguments to the resulting handle consumed by
3897 * {@code handler}; and {@code B}/{@code b}, those of arguments to the
3898 * resulting handle discarded by {@code handler}.
John R Rosebe5df962013-10-05 05:30:40 -07003899 * <blockquote><pre>{@code
John R Rose34cd7bc2010-12-16 15:59:27 -08003900 * T target(A..., B...);
John R Rose020e5502010-01-07 16:16:45 -08003901 * T handler(ExType, A...);
John R Rose34cd7bc2010-12-16 15:59:27 -08003902 * T adapter(A... a, B... b) {
John R Rose020e5502010-01-07 16:16:45 -08003903 * try {
John R Rose34cd7bc2010-12-16 15:59:27 -08003904 * return target(a..., b...);
John R Rose020e5502010-01-07 16:16:45 -08003905 * } catch (ExType ex) {
3906 * return handler(ex, a...);
3907 * }
3908 * }
John R Rosebe5df962013-10-05 05:30:40 -07003909 * }</pre></blockquote>
John R Rose34cd7bc2010-12-16 15:59:27 -08003910 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
3911 * be modified by execution of the target, and so are passed unchanged
3912 * from the caller to the handler, if the handler is invoked.
3913 * <p>
3914 * The target and handler must return the same type, even if the handler
3915 * always throws. (This might happen, for instance, because the handler
3916 * is simulating a {@code finally} clause).
3917 * To create such a throwing handler, compose the handler creation logic
3918 * with {@link #throwException throwException},
3919 * in order to create a method handle of the correct return type.
John R Rose020e5502010-01-07 16:16:45 -08003920 * @param target method handle to call
3921 * @param exType the type of exception which the handler will catch
3922 * @param handler method handle to call if a matching exception is thrown
3923 * @return method handle which incorporates the specified try/catch logic
John R Rose54e473f2011-02-11 01:26:28 -08003924 * @throws NullPointerException if any argument is null
John R Rose020e5502010-01-07 16:16:45 -08003925 * @throws IllegalArgumentException if {@code handler} does not accept
3926 * the given exception type, or if the method handle types do
3927 * not match in their return types and their
3928 * corresponding parameters
Michael Haupt5b2c88e2015-11-20 15:34:12 +01003929 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
John R Rose020e5502010-01-07 16:16:45 -08003930 */
3931 public static
3932 MethodHandle catchException(MethodHandle target,
3933 Class<? extends Throwable> exType,
3934 MethodHandle handler) {
John R Rose34cd7bc2010-12-16 15:59:27 -08003935 MethodType ttype = target.type();
3936 MethodType htype = handler.type();
Michael Hauptd64d6d82016-01-14 13:53:13 +01003937 if (!Throwable.class.isAssignableFrom(exType))
3938 throw new ClassCastException(exType.getName());
John R Rose34cd7bc2010-12-16 15:59:27 -08003939 if (htype.parameterCount() < 1 ||
3940 !htype.parameterType(0).isAssignableFrom(exType))
3941 throw newIllegalArgumentException("handler does not accept exception type "+exType);
3942 if (htype.returnType() != ttype.returnType())
3943 throw misMatchedTypes("target and handler return types", ttype, htype);
Shilpi Rastogi284ec152016-04-13 15:48:14 +02003944 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
3945 if (handler == null) {
3946 throw misMatchedTypes("target and handler types", ttype, htype);
John R Rose34cd7bc2010-12-16 15:59:27 -08003947 }
John R Rosee7ebd472011-03-18 00:03:24 -07003948 return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
John R Rose020e5502010-01-07 16:16:45 -08003949 }
3950
3951 /**
John R Rose54e473f2011-02-11 01:26:28 -08003952 * Produces a method handle which will throw exceptions of the given {@code exType}.
John R Rose020e5502010-01-07 16:16:45 -08003953 * The method handle will accept a single argument of {@code exType},
3954 * and immediately throw it as an exception.
3955 * The method type will nominally specify a return of {@code returnType}.
3956 * The return type may be anything convenient: It doesn't matter to the
3957 * method handle's behavior, since it will never return normally.
Joe Darcy0e32f672013-06-27 19:02:02 -07003958 * @param returnType the return type of the desired method handle
3959 * @param exType the parameter type of the desired method handle
John R Rose54e473f2011-02-11 01:26:28 -08003960 * @return method handle which can throw the given exceptions
3961 * @throws NullPointerException if either argument is null
John R Rose020e5502010-01-07 16:16:45 -08003962 */
3963 public static
3964 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
Christian Thalinger360d5122012-07-24 10:47:44 -07003965 if (!Throwable.class.isAssignableFrom(exType))
3966 throw new ClassCastException(exType.getName());
Michael Haupt402c4482016-04-19 14:39:35 +02003967 return MethodHandleImpl.throwException(methodType(returnType, exType));
John R Rose020e5502010-01-07 16:16:45 -08003968 }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01003969
3970 /**
3971 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
3972 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
3973 * delivers the loop's result, which is the return value of the resulting handle.
3974 * <p>
3975 * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop
3976 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
3977 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
3978 * terms of method handles, each clause will determine four actions:<ul>
3979 * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local.
3980 * <li>When a clause executes, an update step for the iteration variable.
3981 * <li>When a clause executes, a predicate execution to test for loop exit.
3982 * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
3983 * </ul>
3984 * <p>
3985 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
3986 * this case. See below for a detailed description.
3987 * <p>
3988 * Each clause function, with the exception of clause initializers, is able to observe the entire loop state,
3989 * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop
3990 * parameters. Most clause functions will not need all of this information, but they will be formally connected as
3991 * if by {@link #dropArguments}.
3992 * <p>
3993 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
3994 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
3995 * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met
3996 * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means
3997 * that they must be identical, or else one list must be a proper prefix of the other.
3998 * <p>
3999 * <em>Step 0: Determine clause structure.</em><ol type="a">
4000 * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element.
4001 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
4002 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
4003 * four. Padding takes place by appending elements to the array.
4004 * <li>Clauses with all {@code null}s are disregarded.
4005 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
4006 * </ol>
4007 * <p>
4008 * <em>Step 1A: Determine iteration variables.</em><ol type="a">
4009 * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type.
4010 * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else
4011 * use the common return type (they must be identical).
4012 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
4013 * <li>This list of types is called the "common prefix".
4014 * </ol>
4015 * <p>
Michael Haupt1619ac12016-03-02 20:16:11 +01004016 * <em>Step 1B: Determine loop parameters.</em><ul>
4017 * <li><b>If at least one init function is given,</b><ol type="a">
4018 * <li>Examine init function parameter lists.
4019 * <li>Omitted init functions are deemed to have {@code null} parameter lists.
4020 * <li>All init function parameter lists must be effectively identical.
4021 * <li>The longest parameter list (which is necessarily unique) is called the "common suffix".
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004022 * </ol>
Michael Haupt1619ac12016-03-02 20:16:11 +01004023 * <li><b>If no init function is given,</b><ol type="a">
4024 * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix".
4025 * <li>The longest of these suffixes is taken as the "common suffix".
4026 * </ol></ul>
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004027 * <p>
4028 * <em>Step 1C: Determine loop return type.</em><ol type="a">
4029 * <li>Examine fini function return types, disregarding omitted fini functions.
4030 * <li>If there are no fini functions, use {@code void} as the loop return type.
4031 * <li>Otherwise, use the common return type of the fini functions; they must all be identical.
4032 * </ol>
4033 * <p>
4034 * <em>Step 1D: Check other types.</em><ol type="a">
4035 * <li>There must be at least one non-omitted pred function.
4036 * <li>Every non-omitted pred function must have a {@code boolean} return type.
4037 * </ol>
4038 * <p>
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004039 * <em>Step 2: Determine parameter lists.</em><ol type="a">
4040 * <li>The parameter list for the resulting loop handle will be the "common suffix".
4041 * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter
4042 * lists are already effectively identical to the common suffix.)
4043 * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix
4044 * followed by the common suffix, called the "common parameter sequence".
4045 * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter
4046 * sequence.
4047 * </ol>
4048 * <p>
4049 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4050 * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate
4051 * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a
4052 * function which does nothing and returns {@code void}; it can be obtained from another constant function by
4053 * {@linkplain MethodHandle#asType type conversion}.)
4054 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4055 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4056 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4057 * <li>If a pred function is omitted, the corresponding fini function must also be omitted.
4058 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4059 * as this clause is concerned.)
4060 * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the
4061 * loop return type.
4062 * </ol>
4063 * <p>
4064 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4065 * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some
4066 * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by
4067 * {@linkplain #dropArguments dropping arguments}.
4068 * <li>At this point, every non-init function parameter list is effectively identical to the common parameter
4069 * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end
4070 * of the list by {@linkplain #dropArguments dropping arguments}.
4071 * </ol>
4072 * <p>
4073 * <em>Final observations.</em><ol type="a">
4074 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4075 * <li>All init functions have a common parameter type list, which the final loop handle will also have.
4076 * <li>All fini functions have a common return type, which the final loop handle will also have.
4077 * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of
4078 * (non-{@code void}) iteration variables followed by loop parameters.
4079 * <li>Each pair of init and step functions agrees in their return types.
4080 * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the
4081 * common prefix.
4082 * </ol>
4083 * <p>
4084 * <em>Loop execution.</em><ol type="a">
4085 * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to
4086 * every clause function. These locals are loop invariant.
4087 * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values
4088 * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity
4089 * functions, as noted above).
4090 * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of
4091 * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order).
4092 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
4093 * returns {@code false}.
4094 * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The
4095 * updated value is immediately visible to all subsequent function calls.
4096 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
4097 * is returned from the loop as a whole.
4098 * </ol>
4099 * <p>
4100 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values
4101 * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the
4102 * result types of finalizers as well as of the resulting loop.
4103 * <blockquote><pre>{@code
4104 * V... init...(A...);
4105 * boolean pred...(V..., A...);
4106 * V... step...(V..., A...);
4107 * R fini...(V..., A...);
4108 * R loop(A... a) {
4109 * V... v... = init...(a...);
4110 * for (;;) {
4111 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4112 * v = s(v..., a...);
4113 * if (!p(v..., a...)) {
4114 * return f(v..., a...);
4115 * }
4116 * }
4117 * }
4118 * }
4119 * }</pre></blockquote>
4120 * <p>
4121 * @apiNote Example:
4122 * <blockquote><pre>{@code
4123 * // iterative implementation of the factorial function as a loop handle
4124 * static int one(int k) { return 1; }
Michael Haupt1619ac12016-03-02 20:16:11 +01004125 * static int inc(int i, int acc, int k) { return i + 1; }
4126 * static int mult(int i, int acc, int k) { return i * acc; }
4127 * static boolean pred(int i, int acc, int k) { return i < k; }
4128 * static int fin(int i, int acc, int k) { return acc; }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004129 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4130 * // null initializer for counter, should initialize to 0
4131 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4132 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4133 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4134 * assertEquals(120, loop.invoke(5));
4135 * }</pre></blockquote>
4136 *
4137 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
4138 *
4139 * @return a method handle embodying the looping behavior as defined by the arguments.
4140 *
4141 * @throws IllegalArgumentException in case any of the constraints described above is violated.
4142 *
4143 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
4144 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
4145 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
4146 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
4147 * @since 9
4148 */
4149 public static MethodHandle loop(MethodHandle[]... clauses) {
4150 // Step 0: determine clause structure.
4151 checkLoop0(clauses);
4152
4153 List<MethodHandle> init = new ArrayList<>();
4154 List<MethodHandle> step = new ArrayList<>();
4155 List<MethodHandle> pred = new ArrayList<>();
4156 List<MethodHandle> fini = new ArrayList<>();
4157
4158 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
4159 init.add(clause[0]); // all clauses have at least length 1
4160 step.add(clause.length <= 1 ? null : clause[1]);
4161 pred.add(clause.length <= 2 ? null : clause[2]);
4162 fini.add(clause.length <= 3 ? null : clause[3]);
4163 });
4164
4165 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
4166 final int nclauses = init.size();
4167
4168 // Step 1A: determine iteration variables.
4169 final List<Class<?>> iterationVariableTypes = new ArrayList<>();
4170 for (int i = 0; i < nclauses; ++i) {
4171 MethodHandle in = init.get(i);
4172 MethodHandle st = step.get(i);
4173 if (in == null && st == null) {
4174 iterationVariableTypes.add(void.class);
4175 } else if (in != null && st != null) {
4176 checkLoop1a(i, in, st);
4177 iterationVariableTypes.add(in.type().returnType());
4178 } else {
4179 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
4180 }
4181 }
4182 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).
4183 collect(Collectors.toList());
4184
4185 // Step 1B: determine loop parameters.
Michael Haupt1619ac12016-03-02 20:16:11 +01004186 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004187 checkLoop1b(init, commonSuffix);
4188
4189 // Step 1C: determine loop return type.
4190 // Step 1D: check other types.
4191 final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type).
4192 map(MethodType::returnType).findFirst().orElse(void.class);
4193 checkLoop1cd(pred, fini, loopReturnType);
4194
4195 // Step 2: determine parameter lists.
4196 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
4197 commonParameterSequence.addAll(commonSuffix);
4198 checkLoop2(step, pred, fini, commonParameterSequence);
4199
4200 // Step 3: fill in omitted functions.
4201 for (int i = 0; i < nclauses; ++i) {
4202 Class<?> t = iterationVariableTypes.get(i);
4203 if (init.get(i) == null) {
Michael Haupt402c4482016-04-19 14:39:35 +02004204 init.set(i, empty(methodType(t, commonSuffix)));
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004205 }
4206 if (step.get(i) == null) {
Shilpi Rastogi284ec152016-04-13 15:48:14 +02004207 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004208 }
4209 if (pred.get(i) == null) {
Shilpi Rastogi284ec152016-04-13 15:48:14 +02004210 pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004211 }
4212 if (fini.get(i) == null) {
Michael Haupt402c4482016-04-19 14:39:35 +02004213 fini.set(i, empty(methodType(t, commonParameterSequence)));
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004214 }
4215 }
4216
4217 // Step 4: fill in missing parameter types.
4218 List<MethodHandle> finit = fillParameterTypes(init, commonSuffix);
4219 List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence);
4220 List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence);
4221 List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence);
4222
4223 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
4224 allMatch(pl -> pl.equals(commonSuffix));
4225 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
4226 allMatch(pl -> pl.equals(commonParameterSequence));
4227
4228 return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, commonPrefix, finit, fstep, fpred, ffini);
4229 }
4230
4231 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
4232 return hs.stream().map(h -> {
4233 int pc = h.type().parameterCount();
4234 int tpsize = targetParams.size();
4235 return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
4236 }).collect(Collectors.toList());
4237 }
4238
4239 /**
4240 * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for
4241 * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
4242 * <p>
4243 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4244 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4245 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4246 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4247 * generic loop combinator}.
4248 * <p>
4249 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4250 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4251 * passed to the loop.
4252 * <blockquote><pre>{@code
4253 * V init(A);
4254 * boolean pred(V, A);
4255 * V body(V, A);
4256 * V whileLoop(A a) {
4257 * V v = init(a);
4258 * while (pred(v, a)) {
4259 * v = body(v, a);
4260 * }
4261 * return v;
4262 * }
4263 * }</pre></blockquote>
4264 * <p>
4265 * @apiNote Example:
4266 * <blockquote><pre>{@code
4267 * // implement the zip function for lists as a loop handle
Michael Haupt1619ac12016-03-02 20:16:11 +01004268 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
4269 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
4270 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004271 * zip.add(a.next());
4272 * zip.add(b.next());
4273 * return zip;
4274 * }
4275 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
Michael Hauptfc2641e2016-03-02 14:15:15 +01004276 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004277 * List<String> a = Arrays.asList("a", "b", "c", "d");
4278 * List<String> b = Arrays.asList("e", "f", "g", "h");
4279 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
4280 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
4281 * }</pre></blockquote>
4282 *
4283 * <p>
4284 * @implSpec The implementation of this method is equivalent to:
4285 * <blockquote><pre>{@code
4286 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
4287 * MethodHandle[]
4288 * checkExit = {null, null, pred, identity(init.type().returnType())},
4289 * varBody = {init, body};
4290 * return loop(checkExit, varBody);
4291 * }
4292 * }</pre></blockquote>
4293 *
4294 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4295 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4296 * {@code void}.
4297 * @param pred condition for the loop, which may not be {@code null}.
4298 * @param body body of the loop, which may not be {@code null}.
4299 *
4300 * @return the value of the loop variable as the loop terminates.
4301 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4302 *
4303 * @see MethodHandles#loop(MethodHandle[][])
4304 * @since 9
4305 */
4306 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
Michael Haupt402c4482016-04-19 14:39:35 +02004307 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4308 identity(init.type().returnType());
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004309 MethodHandle[] checkExit = {null, null, pred, fin};
4310 MethodHandle[] varBody = {init, body};
4311 return loop(checkExit, varBody);
4312 }
4313
4314 /**
4315 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper
4316 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4317 * <p>
4318 * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}.
4319 * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle
4320 * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code
4321 * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][])
4322 * generic loop combinator}.
4323 * <p>
4324 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4325 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4326 * passed to the loop.
4327 * <blockquote><pre>{@code
4328 * V init(A);
4329 * boolean pred(V, A);
4330 * V body(V, A);
4331 * V doWhileLoop(A a) {
4332 * V v = init(a);
4333 * do {
4334 * v = body(v, a);
4335 * } while (pred(v, a));
4336 * return v;
4337 * }
4338 * }</pre></blockquote>
4339 * <p>
4340 * @apiNote Example:
4341 * <blockquote><pre>{@code
4342 * // int i = 0; while (i < limit) { ++i; } return i; => limit
Michael Haupt1619ac12016-03-02 20:16:11 +01004343 * static int zero(int limit) { return 0; }
4344 * static int step(int i, int limit) { return i + 1; }
4345 * static boolean pred(int i, int limit) { return i < limit; }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004346 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
4347 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
4348 * assertEquals(23, loop.invoke(23));
4349 * }</pre></blockquote>
4350 *
4351 * <p>
4352 * @implSpec The implementation of this method is equivalent to:
4353 * <blockquote><pre>{@code
4354 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
4355 * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) };
4356 * return loop(clause);
4357 * }
4358 * }</pre></blockquote>
4359 *
4360 *
4361 * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's
4362 * result type. Passing {@code null} or a {@code void} init function will make the loop's result type
4363 * {@code void}.
4364 * @param pred condition for the loop, which may not be {@code null}.
4365 * @param body body of the loop, which may not be {@code null}.
4366 *
4367 * @return the value of the loop variable as the loop terminates.
4368 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4369 *
4370 * @see MethodHandles#loop(MethodHandle[][])
4371 * @since 9
4372 */
4373 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
Michael Haupt402c4482016-04-19 14:39:35 +02004374 MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) :
4375 identity(init.type().returnType());
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004376 MethodHandle[] clause = {init, body, pred, fin};
4377 return loop(clause);
4378 }
4379
4380 /**
4381 * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the
4382 * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must
4383 * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional
4384 * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop
4385 * combinator}.
4386 * <p>
4387 * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code
4388 * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code
4389 * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter,
4390 * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described
4391 * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4392 * <p>
4393 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4394 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4395 * passed to the loop.
4396 * <blockquote><pre>{@code
4397 * int iterations(A);
4398 * V init(A);
4399 * V body(int, V, A);
4400 * V countedLoop(A a) {
4401 * int end = iterations(a);
4402 * V v = init(a);
4403 * for (int i = 0; i < end; ++i) {
4404 * v = body(i, v, a);
4405 * }
4406 * return v;
4407 * }
4408 * }</pre></blockquote>
4409 * <p>
4410 * @apiNote Example:
4411 * <blockquote><pre>{@code
4412 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
4413 * // => a variation on a well known theme
Michael Haupt1619ac12016-03-02 20:16:11 +01004414 * static String start(String arg) { return arg; }
4415 * static String step(int counter, String v, String arg) { return "na " + v; }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004416 * // assume MH_start and MH_step are handles to the two methods above
Michael Haupt03e64ce2015-12-03 15:36:20 +01004417 * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
4418 * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step);
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004419 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
4420 * }</pre></blockquote>
4421 *
4422 * <p>
4423 * @implSpec The implementation of this method is equivalent to:
4424 * <blockquote><pre>{@code
4425 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4426 * return countedLoop(null, iterations, init, body); // null => constant zero
4427 * }
4428 * }</pre></blockquote>
4429 *
4430 * @param iterations a handle to return the number of iterations this loop should run.
4431 * @param init initializer for additional loop state. This determines the loop's result type.
4432 * Passing {@code null} or a {@code void} init function will make the loop's result type
4433 * {@code void}.
4434 * @param body the body of the loop, which must not be {@code null}.
4435 * It must accept an initial {@code int} parameter (for the counter), and then any
4436 * additional loop-local variable plus loop parameters.
4437 *
4438 * @return a method handle representing the loop.
4439 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4440 *
4441 * @since 9
4442 */
4443 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
4444 return countedLoop(null, iterations, init, body);
4445 }
4446
4447 /**
4448 * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be
4449 * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the
4450 * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code
4451 * body} function in each iteration; it has to accept an initial {@code int} parameter
4452 * for that. The result of the loop execution is the final value of the additional local state
4453 * obtained by running {@code init}.
4454 * This is a
4455 * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}.
4456 * <p>
4457 * The constraints for the {@code init} and {@code body} handles are the same as for {@link
4458 * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles
4459 * must return an {@code int} and accept the same parameters as {@code init}.
4460 * <p>
4461 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4462 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
4463 * passed to the loop.
4464 * <blockquote><pre>{@code
4465 * int start(A);
4466 * int end(A);
4467 * V init(A);
4468 * V body(int, V, A);
4469 * V countedLoop(A a) {
4470 * int s = start(a);
4471 * int e = end(a);
4472 * V v = init(a);
4473 * for (int i = s; i < e; ++i) {
4474 * v = body(i, v, a);
4475 * }
4476 * return v;
4477 * }
4478 * }</pre></blockquote>
4479 *
4480 * <p>
4481 * @implSpec The implementation of this method is equivalent to:
4482 * <blockquote><pre>{@code
4483 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
4484 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
Michael Hauptc3041102016-04-13 09:20:22 +02004485 * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int,
4486 * // assume MH_decrement is a handle to x-1 of type int
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004487 * MethodHandle[]
4488 * indexVar = {start, MH_increment}, // i = start; i = i+1
4489 * loopLimit = {end, null, MH_lessThan, returnVar }, // i<end
Michael Hauptc3041102016-04-13 09:20:22 +02004490 * bodyClause = {init,
4491 * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v)
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004492 * return loop(indexVar, loopLimit, bodyClause);
4493 * }
4494 * }</pre></blockquote>
4495 *
4496 * @param start a handle to return the start value of the loop counter.
4497 * If it is {@code null}, a constant zero is assumed.
4498 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}).
4499 * @param init initializer for additional loop state. This determines the loop's result type.
4500 * Passing {@code null} or a {@code void} init function will make the loop's result type
4501 * {@code void}.
4502 * @param body the body of the loop, which must not be {@code null}.
4503 * It must accept an initial {@code int} parameter (for the counter), and then any
4504 * additional loop-local variable plus loop parameters.
4505 *
4506 * @return a method handle representing the loop.
4507 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4508 *
4509 * @since 9
4510 */
4511 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
Michael Hauptcafabca2016-04-22 15:05:54 +02004512 Class<?> resultType;
4513 MethodHandle actualInit;
4514 if (init == null) {
4515 resultType = body == null ? void.class : body.type().returnType();
4516 actualInit = empty(methodType(resultType));
4517 } else {
4518 resultType = init.type().returnType();
4519 actualInit = init;
4520 }
4521 MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType);
4522 MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body;
Michael Haupte53e2802016-04-22 15:05:26 +02004523 MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class);
Michael Hauptcafabca2016-04-22 15:05:54 +02004524 MethodHandle actualEnd = end == null ? constant(int.class, 0) : end;
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004525 MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)};
Michael Hauptcafabca2016-04-22 15:05:54 +02004526 MethodHandle[] loopLimit = {actualEnd, null,
4527 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), returnVar};
4528 MethodHandle[] bodyClause = {actualInit,
4529 filterArgument(dropArguments(actualBody, 1, int.class), 0,
Michael Hauptc3041102016-04-13 09:20:22 +02004530 MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter))};
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004531 return loop(indexVar, loopLimit, bodyClause);
4532 }
4533
4534 /**
4535 * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}.
4536 * The iterator will be produced by the evaluation of the {@code iterator} handle.
Michael Haupt402c4482016-04-19 14:39:35 +02004537 * This handle must have {@link java.util.Iterator} as its return type.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004538 * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead,
4539 * and will be applied to a leading argument of the loop handle.
4540 * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter.
4541 * The result of the loop execution is the final value of the additional local state
4542 * obtained by running {@code init}.
4543 * <p>
4544 * This is a convenience wrapper for the
4545 * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body}
4546 * handle follow directly from those described for the latter.
4547 * <p>
4548 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
4549 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
4550 * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop.
4551 * <blockquote><pre>{@code
4552 * Iterator<T> iterator(A); // defaults to Iterable::iterator
4553 * V init(A);
4554 * V body(T,V,A);
4555 * V iteratedLoop(A a) {
4556 * Iterator<T> it = iterator(a);
4557 * V v = init(a);
4558 * for (T t : it) {
4559 * v = body(t, v, a);
4560 * }
4561 * return v;
4562 * }
4563 * }</pre></blockquote>
4564 * <p>
4565 * The type {@code T} may be either a primitive or reference.
4566 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type
4567 * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body}
4568 * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method.
4569 * Therefore, if an iterator of the wrong type appears as the loop is executed,
4570 * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}.
4571 * <p>
4572 * @apiNote Example:
4573 * <blockquote><pre>{@code
4574 * // reverse a list
Michael Haupt1619ac12016-03-02 20:16:11 +01004575 * static List<String> reverseStep(String e, List<String> r, List<String> l) {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004576 * r.add(0, e);
4577 * return r;
4578 * }
Michael Haupt1619ac12016-03-02 20:16:11 +01004579 * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004580 * // assume MH_reverseStep, MH_newArrayList are handles to the above methods
4581 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
4582 * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
4583 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
4584 * assertEquals(reversedList, (List<String>) loop.invoke(list));
4585 * }</pre></blockquote>
4586 * <p>
Michael Haupt402c4482016-04-19 14:39:35 +02004587 * @implSpec The implementation of this method is equivalent to (excluding error handling):
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004588 * <blockquote><pre>{@code
4589 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
4590 * // assume MH_next and MH_hasNext are handles to methods of Iterator
4591 * Class<?> itype = iterator.type().returnType();
4592 * Class<?> ttype = body.type().parameterType(0);
4593 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype);
4594 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
4595 * MethodHandle[]
4596 * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext)
4597 * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a);
4598 * return loop(iterVar, bodyClause);
4599 * }
4600 * }</pre></blockquote>
4601 *
4602 * @param iterator a handle to return the iterator to start the loop.
Michael Haupt402c4482016-04-19 14:39:35 +02004603 * The handle must have {@link java.util.Iterator} as its return type.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004604 * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first
4605 * incoming value.
4606 * @param init initializer for additional loop state. This determines the loop's result type.
4607 * Passing {@code null} or a {@code void} init function will make the loop's result type
4608 * {@code void}.
4609 * @param body the body of the loop, which must not be {@code null}.
4610 * It must accept an initial {@code T} parameter (for the iterated values), and then any
4611 * additional loop-local variable plus loop parameters.
4612 *
4613 * @return a method handle embodying the iteration loop functionality.
4614 * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure
4615 *
4616 * @since 9
4617 */
4618 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
Michael Haupt402c4482016-04-19 14:39:35 +02004619 checkIteratedLoop(iterator, body);
Michael Haupt5b392c02016-04-22 13:36:22 +02004620 Class<?> resultType = init == null ?
4621 body == null ? void.class : body.type().returnType() :
4622 init.type().returnType();
4623 boolean voidResult = resultType == void.class;
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004624
Michael Haupt5b392c02016-04-22 13:36:22 +02004625 MethodHandle initIterator;
4626 if (iterator == null) {
4627 MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
4628 initIterator = initit.asType(initit.type().changeParameterType(0,
4629 body.type().parameterType(voidResult ? 1 : 2)));
4630 } else {
4631 initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class));
4632 }
4633
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004634 Class<?> ttype = body.type().parameterType(0);
4635
4636 MethodHandle returnVar =
Michael Haupt5b392c02016-04-22 13:36:22 +02004637 dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class);
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004638 MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
4639 MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype));
4640
Michael Haupt402c4482016-04-19 14:39:35 +02004641 MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred),
4642 returnVar};
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004643 MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)};
4644
4645 return loop(iterVar, bodyClause);
4646 }
4647
4648 /**
4649 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
4650 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
4651 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
4652 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The
4653 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
4654 * {@code try-finally} handle.
4655 * <p>
4656 * The {@code cleanup} handle will be passed one or two additional leading arguments.
4657 * The first is the exception thrown during the
4658 * execution of the {@code target} handle, or {@code null} if no exception was thrown.
4659 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
4660 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
4661 * The second argument is not present if the {@code target} handle has a {@code void} return type.
4662 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
4663 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
4664 * <p>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01004665 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
4666 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
4667 * two extra leading parameters:<ul>
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004668 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
4669 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
4670 * the result from the execution of the {@code target} handle.
4671 * This parameter is not present if the {@code target} returns {@code void}.
4672 * </ul>
4673 * <p>
4674 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
4675 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
4676 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
4677 * the cleanup.
4678 * <blockquote><pre>{@code
4679 * V target(A..., B...);
4680 * V cleanup(Throwable, V, A...);
4681 * V adapter(A... a, B... b) {
4682 * V result = (zero value for V);
4683 * Throwable throwable = null;
4684 * try {
4685 * result = target(a..., b...);
4686 * } catch (Throwable t) {
4687 * throwable = t;
4688 * throw t;
4689 * } finally {
4690 * result = cleanup(throwable, result, a...);
4691 * }
4692 * return result;
4693 * }
4694 * }</pre></blockquote>
4695 * <p>
4696 * Note that the saved arguments ({@code a...} in the pseudocode) cannot
4697 * be modified by execution of the target, and so are passed unchanged
4698 * from the caller to the cleanup, if it is invoked.
4699 * <p>
4700 * The target and cleanup must return the same type, even if the cleanup
4701 * always throws.
4702 * To create such a throwing cleanup, compose the cleanup logic
4703 * with {@link #throwException throwException},
4704 * in order to create a method handle of the correct return type.
4705 * <p>
4706 * Note that {@code tryFinally} never converts exceptions into normal returns.
4707 * In rare cases where exceptions must be converted in that way, first wrap
4708 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
4709 * to capture an outgoing exception, and then wrap with {@code tryFinally}.
4710 *
4711 * @param target the handle whose execution is to be wrapped in a {@code try} block.
4712 * @param cleanup the handle that is invoked in the finally block.
4713 *
4714 * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
4715 * @throws NullPointerException if any argument is null
4716 * @throws IllegalArgumentException if {@code cleanup} does not accept
4717 * the required leading arguments, or if the method handle types do
4718 * not match in their return types and their
4719 * corresponding trailing parameters
4720 *
4721 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
4722 * @since 9
4723 */
4724 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
4725 List<Class<?>> targetParamTypes = target.type().parameterList();
4726 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4727 Class<?> rtype = target.type().returnType();
4728
4729 checkTryFinally(target, cleanup);
4730
4731 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
Shilpi Rastogi284ec152016-04-13 15:48:14 +02004732 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4733 // target parameter list.
4734 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004735 MethodHandle aTarget = target.asSpreader(Object[].class, target.type().parameterCount());
Shilpi Rastogi284ec152016-04-13 15:48:14 +02004736 MethodHandle aCleanup = cleanup.asSpreader(Object[].class, targetParamTypes.size());
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004737
4738 return MethodHandleImpl.makeTryFinally(aTarget, aCleanup, rtype, targetParamTypes);
4739 }
4740
4741 /**
4742 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
4743 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
4744 * before the folded arguments.
4745 * <p>
4746 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
4747 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
4748 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
4749 * 0.
4750 * <p>
4751 * @apiNote Example:
4752 * <blockquote><pre>{@code
4753 import static java.lang.invoke.MethodHandles.*;
4754 import static java.lang.invoke.MethodType.*;
4755 ...
4756 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
4757 "println", methodType(void.class, String.class))
4758 .bindTo(System.out);
4759 MethodHandle cat = lookup().findVirtual(String.class,
4760 "concat", methodType(String.class, String.class));
4761 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
4762 MethodHandle catTrace = foldArguments(cat, 1, trace);
4763 // also prints "jum":
4764 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
4765 * }</pre></blockquote>
Michael Haupt19a07cb2016-02-23 09:49:04 +01004766 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
4767 * represents the result type of the {@code target} and resulting adapter.
4768 * {@code V}/{@code v} represent the type and value of the parameter and argument
4769 * of {@code target} that precedes the folding position; {@code V} also is
4770 * the result type of the {@code combiner}. {@code A}/{@code a} denote the
4771 * types and values of the {@code N} parameters and arguments at the folding
4772 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
4773 * and values of the {@code target} parameters and arguments that precede and
4774 * follow the folded parameters and arguments starting at {@code pos},
4775 * respectively.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004776 * <blockquote><pre>{@code
4777 * // there are N arguments in A...
4778 * T target(Z..., V, A[N]..., B...);
4779 * V combiner(A...);
4780 * T adapter(Z... z, A... a, B... b) {
4781 * V v = combiner(a...);
4782 * return target(z..., v, a..., b...);
4783 * }
4784 * // and if the combiner has a void return:
4785 * T target2(Z..., A[N]..., B...);
4786 * void combiner2(A...);
4787 * T adapter2(Z... z, A... a, B... b) {
4788 * combiner2(a...);
4789 * return target2(z..., a..., b...);
4790 * }
4791 * }</pre></blockquote>
Michael Haupt5baf4fc2016-02-23 07:17:54 +01004792 * <p>
4793 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4794 * variable-arity method handle}, even if the original target method handle was.
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004795 *
4796 * @param target the method handle to invoke after arguments are combined
4797 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
4798 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
4799 * @param combiner method handle to call initially on the incoming arguments
4800 * @return method handle which incorporates the specified argument folding logic
4801 * @throws NullPointerException if either argument is null
4802 * @throws IllegalArgumentException if {@code combiner}'s return type
4803 * is non-void and not the same as the argument type at position {@code pos} of
4804 * the target signature, or if the {@code N} argument types at position {@code pos}
4805 * of the target signature
4806 * (skipping one matching the {@code combiner}'s return type)
4807 * are not identical with the argument types of {@code combiner}
4808 *
4809 * @see #foldArguments(MethodHandle, MethodHandle)
4810 * @since 9
4811 */
4812 public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
4813 MethodType targetType = target.type();
4814 MethodType combinerType = combiner.type();
4815 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
4816 BoundMethodHandle result = target.rebind();
4817 boolean dropResult = rtype == void.class;
4818 LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
4819 MethodType newType = targetType;
4820 if (!dropResult) {
4821 newType = newType.dropParameterTypes(pos, pos + 1);
4822 }
4823 result = result.copyWithExtendL(newType, lform, combiner);
4824 return result;
4825 }
4826
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004827
4828 private static void checkLoop0(MethodHandle[][] clauses) {
4829 if (clauses == null || clauses.length == 0) {
4830 throw newIllegalArgumentException("null or no clauses passed");
4831 }
4832 if (Stream.of(clauses).anyMatch(Objects::isNull)) {
4833 throw newIllegalArgumentException("null clauses are not allowed");
4834 }
4835 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
4836 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
4837 }
4838 }
4839
4840 private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) {
4841 if (in.type().returnType() != st.type().returnType()) {
4842 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
4843 st.type().returnType());
4844 }
4845 }
4846
Michael Haupt1619ac12016-03-02 20:16:11 +01004847 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
4848 final List<Class<?>> empty = List.of();
4849 final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList());
4850 if (nonNullInits.isEmpty()) {
4851 final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).
4852 // take only those that can contribute to a common suffix because they are longer than the prefix
4853 map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList).
4854 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
4855 return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size());
4856 } else {
4857 return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList).
4858 reduce((p, q) -> p.size() >= q.size() ? p : q).get();
4859 }
4860 }
4861
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004862 private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
4863 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList).
4864 anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) {
4865 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
4866 " (common suffix: " + commonSuffix + ")");
4867 }
4868 }
4869
4870 private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
4871 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4872 anyMatch(t -> t != loopReturnType)) {
4873 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
4874 loopReturnType + ")");
4875 }
4876
4877 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
4878 throw newIllegalArgumentException("no predicate found", pred);
4879 }
4880 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
4881 anyMatch(t -> t != boolean.class)) {
4882 throw newIllegalArgumentException("predicates must have boolean return type", pred);
4883 }
4884 }
4885
4886 private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
Michael Haupt1619ac12016-03-02 20:16:11 +01004887 final int cpSize = commonParameterSequence.size();
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004888 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
Michael Haupt1619ac12016-03-02 20:16:11 +01004889 map(MethodType::parameterList).
4890 anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004891 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
4892 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
4893 }
4894 }
4895
Michael Haupt402c4482016-04-19 14:39:35 +02004896 private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) {
4897 if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) {
4898 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
4899 }
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004900 if (null == body) {
4901 throw newIllegalArgumentException("iterated loop body must not be null");
4902 }
4903 }
4904
4905 private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) {
4906 Class<?> rtype = target.type().returnType();
4907 if (rtype != cleanup.type().returnType()) {
4908 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
4909 }
4910 List<Class<?>> cleanupParamTypes = cleanup.type().parameterList();
4911 if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) {
4912 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
4913 }
4914 if (rtype != void.class && cleanupParamTypes.get(1) != rtype) {
4915 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
4916 }
4917 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
4918 // target parameter list.
4919 int cleanupArgIndex = rtype == void.class ? 1 : 2;
Michael Haupt2d20eec2016-02-29 14:16:20 +01004920 List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size());
4921 List<Class<?>> targetParamTypes = target.type().parameterList();
4922 if (targetParamTypes.size() < cleanupArgSuffix.size() ||
4923 !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) {
Michael Haupt5b2c88e2015-11-20 15:34:12 +01004924 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
4925 cleanup.type(), target.type());
4926 }
4927 }
4928
John R Rosefb6164c2009-05-05 22:40:09 -07004929}