blob: ded00aec3d6abc42db01b34b58e04e9388930612 [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
jrosef108fc02011-02-11 01:26:24 -08002 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
jrose55220c32009-10-21 23:19:48 -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
ohair2283b9d2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
jrose55220c32009-10-21 23:19:48 -07008 * particular file as subject to the "Classpath" exception as provided
ohair2283b9d2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
jrose55220c32009-10-21 23:19:48 -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 *
ohair2283b9d2010-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.
jrose55220c32009-10-21 23:19:48 -070024 */
25
26/* @test
jroseada69fa2011-03-23 23:02:31 -070027 * @summary unit tests for java.lang.invoke.MethodHandles
jrose9633f5f2011-04-07 22:07:06 -070028 * @compile -source 7 -target 7 MethodHandlesTest.java
29 * @run junit/othervm test.java.lang.invoke.MethodHandlesTest
jrose55220c32009-10-21 23:19:48 -070030 */
31
jroseada69fa2011-03-23 23:02:31 -070032package test.java.lang.invoke;
jrose55220c32009-10-21 23:19:48 -070033
jroseada69fa2011-03-23 23:02:31 -070034import java.lang.invoke.*;
35import java.lang.invoke.MethodHandles.Lookup;
jrose55220c32009-10-21 23:19:48 -070036import java.lang.reflect.*;
37import java.util.*;
38import org.junit.*;
39import static org.junit.Assert.*;
jrose2cc9c832010-04-30 23:48:23 -070040import static org.junit.Assume.*;
jrose55220c32009-10-21 23:19:48 -070041
42
43/**
44 *
45 * @author jrose
46 */
47public class MethodHandlesTest {
48 // How much output?
jrose2cc9c832010-04-30 23:48:23 -070049 static int verbosity = 0;
jrosecf98d422010-06-08 23:08:56 -070050 static {
jroseada69fa2011-03-23 23:02:31 -070051 String vstr = System.getProperty("test.java.lang.invoke.MethodHandlesTest.verbosity");
jrosecf98d422010-06-08 23:08:56 -070052 if (vstr != null) verbosity = Integer.parseInt(vstr);
53 }
jrose55220c32009-10-21 23:19:48 -070054
55 // Set this true during development if you want to fast-forward to
56 // a particular new, non-working test. Tests which are known to
57 // work (or have recently worked) test this flag and return on true.
58 static boolean CAN_SKIP_WORKING = false;
59 //static { CAN_SKIP_WORKING = true; }
60
61 // Set true to test more calls. If false, some tests are just
62 // lookups, without exercising the actual method handle.
jrose2cc9c832010-04-30 23:48:23 -070063 static boolean DO_MORE_CALLS = true;
jrose55220c32009-10-21 23:19:48 -070064
jrose55220c32009-10-21 23:19:48 -070065 @Test
66 public void testFirst() throws Throwable {
67 verbosity += 9; try {
68 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070069 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070070 }
71
jrose10f3b682010-01-07 16:16:45 -080072 // current failures
73 @Test @Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
74 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070075 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080076 testSpreadArguments(int.class, 0, 6);
77 }
jrose2cc9c832010-04-30 23:48:23 -070078 @Test @Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080079 public void testFail_2() throws Throwable {
80 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
81 testSpreadArguments(Object.class, 0, 2);
82 }
83 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
84 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070085 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080086 testSpreadArguments(int.class, 1, 2);
87 }
88 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
89 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070090 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080091 testCollectArguments(int.class, 1, 2);
92 }
93 @Test @Ignore("cannot collect leading primitive types")
94 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070095 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080096 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
97 }
98 @Test @Ignore("should not insert arguments beyond MethodHandlePushLimit")
99 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700100 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
101 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800102 }
jrose55220c32009-10-21 23:19:48 -0700103 static final int MAX_ARG_INCREASE = 3;
104
105 public MethodHandlesTest() {
106 }
107
jrose55220c32009-10-21 23:19:48 -0700108 String testName;
jrosecf98d422010-06-08 23:08:56 -0700109 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700110 int posTests, negTests;
111 @After
112 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700113 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700114 System.out.println();
115 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
116 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700117 allPosTests += posTests;
118 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700119 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700120 }
121 }
122 void countTest(boolean positive) {
123 if (positive) ++posTests;
124 else ++negTests;
125 }
126 void countTest() { countTest(true); }
127 void startTest(String name) {
128 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700129 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700130 System.out.println(name);
131 posTests = negTests = 0;
132 testName = name;
133 }
134
135 @BeforeClass
136 public static void setUpClass() throws Exception {
137 calledLog.clear();
138 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700139 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700140 }
141
142 @AfterClass
143 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700144 int posTests = allPosTests, negTests = allNegTests;
145 if (verbosity >= 2 && (posTests | negTests) != 0) {
146 System.out.println();
147 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
148 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
149 }
jrose55220c32009-10-21 23:19:48 -0700150 }
151
152 static List<Object> calledLog = new ArrayList<Object>();
153 static Object logEntry(String name, Object... args) {
154 return Arrays.asList(name, Arrays.asList(args));
155 }
156 static Object called(String name, Object... args) {
157 Object entry = logEntry(name, args);
158 calledLog.add(entry);
159 return entry;
160 }
161 static void assertCalled(String name, Object... args) {
162 Object expected = logEntry(name, args);
163 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700164 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700165 System.out.println("assertCalled "+name+":");
166 System.out.println("expected: "+expected);
167 System.out.println("actual: "+actual);
168 System.out.println("ex. types: "+getClasses(expected));
169 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700170 assertEquals("previous method call", expected, actual);
171 }
172 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700173 if (verbosity >= 3)
174 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700175 }
176
177 static Object castToWrapper(Object value, Class<?> dst) {
178 Object wrap = null;
179 if (value instanceof Number)
180 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
181 if (value instanceof Character)
182 wrap = castToWrapperOrNull((char)(Character)value, dst);
183 if (wrap != null) return wrap;
184 return dst.cast(value);
185 }
186
187 static Object castToWrapperOrNull(long value, Class<?> dst) {
188 if (dst == int.class || dst == Integer.class)
189 return (int)(value);
190 if (dst == long.class || dst == Long.class)
191 return (long)(value);
192 if (dst == char.class || dst == Character.class)
193 return (char)(value);
194 if (dst == short.class || dst == Short.class)
195 return (short)(value);
196 if (dst == float.class || dst == Float.class)
197 return (float)(value);
198 if (dst == double.class || dst == Double.class)
199 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800200 if (dst == byte.class || dst == Byte.class)
201 return (byte)(value);
202 if (dst == boolean.class || dst == boolean.class)
203 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700204 return null;
205 }
206
jrose2cc9c832010-04-30 23:48:23 -0700207 static final int ONE_MILLION = (1000*1000), // first int value
208 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
209 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
210 static long nextArgVal;
211 static long nextArg(boolean moreBits) {
212 long val = nextArgVal++;
213 long sign = -(val & 1); // alternate signs
214 val >>= 1;
215 if (moreBits)
216 // Guarantee some bits in the high word.
217 // In any case keep the decimal representation simple-looking,
218 // with lots of zeroes, so as not to make the printed decimal
219 // strings unnecessarily noisy.
220 val += (val % ONE_MILLION) * TEN_BILLION;
221 return val ^ sign;
222 }
223 static int nextArg() {
224 // Produce a 32-bit result something like ONE_MILLION+(smallint).
225 // Example: 1_000_042.
226 return (int) nextArg(false);
227 }
228 static long nextArg(Class<?> kind) {
229 if (kind == long.class || kind == Long.class ||
230 kind == double.class || kind == Double.class)
231 // produce a 64-bit result something like
232 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
233 // Example: 10_000_420_001_000_042.
234 return nextArg(true);
235 return (long) nextArg();
236 }
237
jrose55220c32009-10-21 23:19:48 -0700238 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700239 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700240 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700241 return wrap;
242 }
jroseada69fa2011-03-23 23:02:31 -0700243// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700244// Wrapper wrap = Wrapper.forBasicType(dst);
245// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
246// wrap = Wrapper.forWrapperType(dst);
247// if (wrap != Wrapper.OBJECT)
248// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700249 if (param.isInterface()) {
250 for (Class<?> c : param.getClasses()) {
251 if (param.isAssignableFrom(c) && !c.isInterface())
252 { param = c; break; }
253 }
254 }
jrose55220c32009-10-21 23:19:48 -0700255 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700256 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700257 else
258 try {
259 return param.newInstance();
260 } catch (InstantiationException ex) {
261 } catch (IllegalAccessException ex) {
262 }
263 return null; // random class not Object, String, Integer, etc.
264 }
265 static Object[] randomArgs(Class<?>... params) {
266 Object[] args = new Object[params.length];
267 for (int i = 0; i < args.length; i++)
268 args[i] = randomArg(params[i]);
269 return args;
270 }
271 static Object[] randomArgs(int nargs, Class<?> param) {
272 Object[] args = new Object[nargs];
273 for (int i = 0; i < args.length; i++)
274 args[i] = randomArg(param);
275 return args;
276 }
277
278 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
279 return Arrays.copyOf(a, a.length, atype);
280 }
281 static <T> T[] cat(T[] a, T... b) {
282 int alen = a.length, blen = b.length;
283 if (blen == 0) return a;
284 T[] c = Arrays.copyOf(a, alen + blen);
285 System.arraycopy(b, 0, c, alen, blen);
286 return c;
287 }
288 static Integer[] boxAll(int... vx) {
289 Integer[] res = new Integer[vx.length];
290 for (int i = 0; i < res.length; i++) {
291 res[i] = vx[i];
292 }
293 return res;
294 }
295 static Object getClasses(Object x) {
296 if (x == null) return x;
297 if (x instanceof String) return x; // keep the name
298 if (x instanceof List) {
299 // recursively report classes of the list elements
300 Object[] xa = ((List)x).toArray();
301 for (int i = 0; i < xa.length; i++)
302 xa[i] = getClasses(xa[i]);
303 return Arrays.asList(xa);
304 }
305 return x.getClass().getSimpleName();
306 }
307
jroseadc650a2011-02-11 01:26:28 -0800308 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
309 static MethodHandle varargsList(int arity) {
310 return ValueConversions.varargsList(arity);
311 }
312 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
313 static MethodHandle varargsArray(int arity) {
314 return ValueConversions.varargsArray(arity);
315 }
jrose320b7692011-05-12 19:27:49 -0700316 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
317 return ValueConversions.varargsArray(arrayType, arity);
318 }
jroseadc650a2011-02-11 01:26:28 -0800319 /** Variation of varargsList, but with the given rtype. */
320 static MethodHandle varargsList(int arity, Class<?> rtype) {
321 MethodHandle list = varargsList(arity);
322 MethodType listType = list.type().changeReturnType(rtype);
323 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
324 // OK
325 } else if (rtype.isAssignableFrom(String.class)) {
326 if (LIST_TO_STRING == null)
327 try {
328 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
329 MethodType.methodType(String.class, List.class));
330 } catch (Exception ex) { throw new RuntimeException(ex); }
331 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
332 } else if (rtype.isPrimitive()) {
333 if (LIST_TO_INT == null)
334 try {
335 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
336 MethodType.methodType(int.class, List.class));
337 } catch (Exception ex) { throw new RuntimeException(ex); }
338 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
339 list = MethodHandles.explicitCastArguments(list, listType);
340 } else {
341 throw new RuntimeException("varargsList: "+rtype);
342 }
343 return list.asType(listType);
344 }
345 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
346 private static String listToString(List x) { return x.toString(); }
347 private static int listToInt(List x) { return x.toString().hashCode(); }
348
jrose55220c32009-10-21 23:19:48 -0700349 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
350 return changeArgTypes(target, 0, 999, argType);
351 }
352 static MethodHandle changeArgTypes(MethodHandle target,
353 int beg, int end, Class<?> argType) {
354 MethodType targetType = target.type();
355 end = Math.min(end, targetType.parameterCount());
356 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
357 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800358 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose55220c32009-10-21 23:19:48 -0700359 return MethodHandles.convertArguments(target, ttype2);
360 }
361
362 // This lookup is good for all members in and under MethodHandlesTest.
363 static final Lookup PRIVATE = MethodHandles.lookup();
364 // This lookup is good for package-private members but not private ones.
365 static final Lookup PACKAGE = PackageSibling.lookup();
366 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800367 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700368
369 // Subject methods...
370 static class Example implements IntExample {
371 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700372 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700373 protected Example(String name) { this.name = name; }
374 protected Example(int x) { this(); called("protected <init>", this, x); }
375 @Override public String toString() { return name; }
376
377 public void v0() { called("v0", this); }
378 void pkg_v0() { called("pkg_v0", this); }
379 private void pri_v0() { called("pri_v0", this); }
380 public static void s0() { called("s0"); }
381 static void pkg_s0() { called("pkg_s0"); }
382 private static void pri_s0() { called("pri_s0"); }
383
384 public Object v1(Object x) { return called("v1", this, x); }
385 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
386 public Object v2(Object x, int y) { return called("v2", this, x, y); }
387 public Object v2(int x, Object y) { return called("v2", this, x, y); }
388 public Object v2(int x, int y) { return called("v2", this, x, y); }
389 public static Object s1(Object x) { return called("s1", x); }
390 public static Object s2(int x) { return called("s2", x); }
391 public static Object s3(long x) { return called("s3", x); }
392 public static Object s4(int x, int y) { return called("s4", x, y); }
393 public static Object s5(long x, int y) { return called("s5", x, y); }
394 public static Object s6(int x, long y) { return called("s6", x, y); }
395 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700396
397 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700398 }
jrose2cc9c832010-04-30 23:48:23 -0700399 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700400 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700401 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700402 }
403 static class SubExample extends Example {
404 @Override public void v0() { called("Sub/v0", this); }
405 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
406 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700407 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700408 }
409 public static interface IntExample {
410 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700411 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700412 public void v0() { called("Int/v0", this); }
413 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700414 public Impl() { name = "Impl#"+nextArg(); }
415 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700416 }
417 }
418
419 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700420 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
421 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
422 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
423 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700424 };
425
jrose2cc9c832010-04-30 23:48:23 -0700426 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
427 Object[][] cases;
428 if (name.contains("pri_") || isSpecial) {
429 cases = ACCESS_CASES[1]; // PRIVATE only
430 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
431 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800432 } else {
433 assertTrue(name.indexOf('_') < 0);
434 boolean pubc = Modifier.isPublic(defc.getModifiers());
435 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700436 cases = ACCESS_CASES[3]; // all access levels
437 else
438 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800439 }
jrose2cc9c832010-04-30 23:48:23 -0700440 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
441 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
442 return cases;
443 }
444 static Object[][] accessCases(Class<?> defc, String name) {
445 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700446 }
447
448 @Test
449 public void testFindStatic() throws Throwable {
450 if (CAN_SKIP_WORKING) return;
451 startTest("findStatic");
452 testFindStatic(PubExample.class, void.class, "s0");
453 testFindStatic(Example.class, void.class, "s0");
454 testFindStatic(Example.class, void.class, "pkg_s0");
455 testFindStatic(Example.class, void.class, "pri_s0");
456
457 testFindStatic(Example.class, Object.class, "s1", Object.class);
458 testFindStatic(Example.class, Object.class, "s2", int.class);
459 testFindStatic(Example.class, Object.class, "s3", long.class);
460 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
461 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
462 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
463 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
464
465 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
466 }
467
468 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
469 for (Object[] ac : accessCases(defc, name)) {
470 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
471 }
472 }
473 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
474 testFindStatic(true, lookup, defc, ret, name, params);
475 }
476 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
477 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800478 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700479 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700480 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700481 try {
jrose2cc9c832010-04-30 23:48:23 -0700482 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700483 target = lookup.in(defc).findStatic(defc, name, type);
jrosef15905c2011-02-11 01:26:32 -0800484 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700485 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800486 if (name.contains("bogus"))
487 assertTrue(noAccess instanceof NoSuchMethodException);
488 else
489 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700490 }
jrose2cc9c832010-04-30 23:48:23 -0700491 if (verbosity >= 3)
492 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700493 +(noAccess == null ? "" : " !! "+noAccess));
494 if (positive && noAccess != null) throw noAccess;
495 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
496 if (!positive) return; // negative test failed as expected
497 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700498 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700499 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
500 Object[] args = randomArgs(params);
501 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700502 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700503 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700504 if (verbosity >= 1)
505 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700506 }
507
jrose73016262011-05-17 19:48:19 -0700508 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
509
jrose900bafd2010-10-30 21:08:23 -0700510 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700511 static void assertNameStringContains(MethodHandle x, String s) {
512 if (!DEBUG_METHOD_HANDLE_NAMES) {
513 // ignore s
514 assertEquals("MethodHandle"+x.type(), x.toString());
515 return;
516 }
jrose900bafd2010-10-30 21:08:23 -0700517 if (x.toString().contains(s)) return;
518 assertEquals(s, x);
519 }
520
jrose55220c32009-10-21 23:19:48 -0700521 @Test
522 public void testFindVirtual() throws Throwable {
523 if (CAN_SKIP_WORKING) return;
524 startTest("findVirtual");
525 testFindVirtual(Example.class, void.class, "v0");
526 testFindVirtual(Example.class, void.class, "pkg_v0");
527 testFindVirtual(Example.class, void.class, "pri_v0");
528 testFindVirtual(Example.class, Object.class, "v1", Object.class);
529 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
530 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
531 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
532 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
533 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
534 // test dispatch
535 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
536 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
537 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
538 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
539 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
540 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
541 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
542 }
543
544 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
545 Class<?> rcvc = defc;
546 testFindVirtual(rcvc, defc, ret, name, params);
547 }
548 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
549 for (Object[] ac : accessCases(defc, name)) {
550 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
551 }
552 }
553 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
554 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
555 }
556 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
557 countTest(positive);
558 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800559 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700560 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700561 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700562 try {
jrose2cc9c832010-04-30 23:48:23 -0700563 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700564 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800565 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700566 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800567 if (name.contains("bogus"))
568 assertTrue(noAccess instanceof NoSuchMethodException);
569 else
570 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700571 }
jrose2cc9c832010-04-30 23:48:23 -0700572 if (verbosity >= 3)
573 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700574 +(noAccess == null ? "" : " !! "+noAccess));
575 if (positive && noAccess != null) throw noAccess;
576 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
577 if (!positive) return; // negative test failed as expected
578 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800579 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700580 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700581 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700582 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
583 Object[] argsWithSelf = randomArgs(paramsWithSelf);
584 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
585 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700586 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700587 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700588 if (verbosity >= 1)
589 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700590 }
591
592 @Test
593 public void testFindSpecial() throws Throwable {
594 if (CAN_SKIP_WORKING) return;
595 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700596 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
597 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
598 // Do some negative testing:
jrosef15905c2011-02-11 01:26:32 -0800599 testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
600 testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700601 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
602 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
603 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
604 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700605 }
jrose55220c32009-10-21 23:19:48 -0700606 }
607
jrose2cc9c832010-04-30 23:48:23 -0700608 void testFindSpecial(Class<?> specialCaller,
609 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
610 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
611 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
612 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
613 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700614 }
jrose2cc9c832010-04-30 23:48:23 -0700615 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
616 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700617 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800618 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700619 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700620 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700621 try {
jrose2cc9c832010-04-30 23:48:23 -0700622 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700623 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
624 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800625 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700626 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800627 if (name.contains("bogus"))
628 assertTrue(noAccess instanceof NoSuchMethodException);
629 else
630 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700631 }
jrose2cc9c832010-04-30 23:48:23 -0700632 if (verbosity >= 3)
633 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
634 +(target == null ? "" : target.type())
635 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700636 if (positive && noAccess != null) throw noAccess;
637 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
638 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700639 assertEquals(specialCaller, target.type().parameterType(0));
640 assertEquals(type, target.type().dropParameterTypes(0,1));
641 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800642 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700643 assertNameStringContains(target, name);
jrose2cc9c832010-04-30 23:48:23 -0700644 if (!DO_MORE_CALLS && lookup != PRIVATE && lookup != EXAMPLE) return;
jrose55220c32009-10-21 23:19:48 -0700645 Object[] args = randomArgs(paramsWithSelf);
646 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700647 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700648 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700649 }
650
651 @Test
652 public void testBind() throws Throwable {
653 if (CAN_SKIP_WORKING) return;
654 startTest("bind");
655 testBind(Example.class, void.class, "v0");
656 testBind(Example.class, void.class, "pkg_v0");
657 testBind(Example.class, void.class, "pri_v0");
658 testBind(Example.class, Object.class, "v1", Object.class);
659 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
660 testBind(Example.class, Object.class, "v2", Object.class, int.class);
661 testBind(Example.class, Object.class, "v2", int.class, Object.class);
662 testBind(Example.class, Object.class, "v2", int.class, int.class);
663 testBind(false, PRIVATE, Example.class, void.class, "bogus");
664 testBind(SubExample.class, void.class, "Sub/v0");
665 testBind(SubExample.class, void.class, "Sub/pkg_v0");
666 testBind(IntExample.Impl.class, void.class, "Int/v0");
667 }
668
669 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
670 for (Object[] ac : accessCases(defc, name)) {
671 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
672 }
673 }
674
675 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
676 countTest(positive);
677 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800678 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700679 Object receiver = randomArg(defc);
680 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700681 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700682 try {
jrose2cc9c832010-04-30 23:48:23 -0700683 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700684 target = lookup.in(defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800685 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700686 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800687 if (name.contains("bogus"))
688 assertTrue(noAccess instanceof NoSuchMethodException);
689 else
690 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700691 }
jrose2cc9c832010-04-30 23:48:23 -0700692 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700693 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
694 +(noAccess == null ? "" : " !! "+noAccess));
695 if (positive && noAccess != null) throw noAccess;
696 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
697 if (!positive) return; // negative test failed as expected
698 assertEquals(type, target.type());
699 Object[] args = randomArgs(params);
700 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700701 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700702 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
703 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700704 if (verbosity >= 1)
705 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700706 }
707
708 @Test
709 public void testUnreflect() throws Throwable {
710 if (CAN_SKIP_WORKING) return;
711 startTest("unreflect");
712 testUnreflect(Example.class, true, void.class, "s0");
713 testUnreflect(Example.class, true, void.class, "pkg_s0");
714 testUnreflect(Example.class, true, void.class, "pri_s0");
715
716 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
717 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700718 testUnreflect(Example.class, true, Object.class, "s3", long.class);
719 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
720 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
721 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700722
723 testUnreflect(Example.class, false, void.class, "v0");
724 testUnreflect(Example.class, false, void.class, "pkg_v0");
725 testUnreflect(Example.class, false, void.class, "pri_v0");
726 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
727 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
728 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
729 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
730 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
731 }
732
733 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
734 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700735 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700736 }
737 }
jrose2cc9c832010-04-30 23:48:23 -0700738 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
739 for (Object[] ac : accessCases(defc, name)) {
740 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
741 }
742 }
743 void testUnreflectMaybeSpecial(Class<?> specialCaller,
744 boolean positive, Lookup lookup,
745 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700746 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800747 MethodType type = MethodType.methodType(ret, params);
jrosef15905c2011-02-11 01:26:32 -0800748 Method rmethod = defc.getDeclaredMethod(name, params);
jrose55220c32009-10-21 23:19:48 -0700749 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700750 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700751 boolean isStatic = (rcvc == null);
752 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700753 try {
jrose2cc9c832010-04-30 23:48:23 -0700754 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
755 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700756 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700757 else
jrose900bafd2010-10-30 21:08:23 -0700758 target = lookup.in(defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800759 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700760 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800761 if (name.contains("bogus"))
762 assertTrue(noAccess instanceof NoSuchMethodException);
763 else
764 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700765 }
jrose2cc9c832010-04-30 23:48:23 -0700766 if (verbosity >= 3)
767 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
768 +(!isSpecial ? "" : " specialCaller="+specialCaller)
769 +( isStatic ? "" : " receiver="+rcvc)
770 +" => "+target
771 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700772 if (positive && noAccess != null) throw noAccess;
773 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
774 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700775 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700776 Class<?>[] paramsMaybeWithSelf = params;
777 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700778 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700779 }
jrose10f3b682010-01-07 16:16:45 -0800780 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700781 if (isStatic) {
782 assertEquals(typeMaybeWithSelf, target.type());
783 } else {
jrose2cc9c832010-04-30 23:48:23 -0700784 if (isSpecial)
785 assertEquals(specialCaller, target.type().parameterType(0));
786 else
787 assertEquals(defc, target.type().parameterType(0));
788 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
789 }
jrose55220c32009-10-21 23:19:48 -0700790 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
791 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700792 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700793 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700794 if (verbosity >= 1)
795 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700796 }
797
jrose2cc9c832010-04-30 23:48:23 -0700798 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
799 for (Object[] ac : accessCases(defc, name, true)) {
800 Class<?> specialCaller = rcvc;
801 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
802 }
803 }
804
805 @Test
jrose55220c32009-10-21 23:19:48 -0700806 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700807 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700808 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700809 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
810 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
811 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
812 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
813 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
814 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
815 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700816 }
817
jrose10f3b682010-01-07 16:16:45 -0800818 public static class HasFields {
819 boolean fZ = false;
820 byte fB = (byte)'B';
821 short fS = (short)'S';
822 char fC = 'C';
823 int fI = 'I';
824 long fJ = 'J';
825 float fF = 'F';
826 double fD = 'D';
827 static boolean sZ = true;
828 static byte sB = 1+(byte)'B';
829 static short sS = 1+(short)'S';
830 static char sC = 1+'C';
831 static int sI = 1+'I';
832 static long sJ = 1+'J';
833 static float sF = 1+'F';
834 static double sD = 1+'D';
835
836 Object fL = 'L';
837 String fR = "R";
838 static Object sL = 'M';
839 static String sR = "S";
840
841 static final Object[][] CASES;
842 static {
843 ArrayList<Object[]> cases = new ArrayList<Object[]>();
844 Object types[][] = {
845 {'L',Object.class}, {'R',String.class},
846 {'I',int.class}, {'J',long.class},
847 {'F',float.class}, {'D',double.class},
848 {'Z',boolean.class}, {'B',byte.class},
849 {'S',short.class}, {'C',char.class},
850 };
851 HasFields fields = new HasFields();
852 for (Object[] t : types) {
853 for (int kind = 0; kind <= 1; kind++) {
854 boolean isStatic = (kind != 0);
855 char btc = (Character)t[0];
856 String name = (isStatic ? "s" : "f") + btc;
857 Class<?> type = (Class<?>) t[1];
858 Object value;
859 Field field;
jrose320b7692011-05-12 19:27:49 -0700860 try {
jrose10f3b682010-01-07 16:16:45 -0800861 field = HasFields.class.getDeclaredField(name);
862 } catch (Exception ex) {
863 throw new InternalError("no field HasFields."+name);
864 }
865 try {
866 value = field.get(fields);
867 } catch (Exception ex) {
868 throw new InternalError("cannot fetch field HasFields."+name);
869 }
870 if (type == float.class) {
871 float v = 'F';
872 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -0800873 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -0800874 }
jrosef15905c2011-02-11 01:26:32 -0800875 assertTrue(name.equals(field.getName()));
876 assertTrue(type.equals(field.getType()));
877 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -0800878 cases.add(new Object[]{ field, value });
879 }
880 }
jrosef15905c2011-02-11 01:26:32 -0800881 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
882 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -0800883 CASES = cases.toArray(new Object[0][]);
884 }
885 }
886
jrosef15905c2011-02-11 01:26:32 -0800887 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10;
jrosecf98d422010-06-08 23:08:56 -0700888 static boolean testModeMatches(int testMode, boolean isStatic) {
889 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -0800890 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -0700891 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -0800892 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -0700893 }
jrosef15905c2011-02-11 01:26:32 -0800894 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -0700895 }
896
jrose10f3b682010-01-07 16:16:45 -0800897 @Test
jrose55220c32009-10-21 23:19:48 -0700898 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700899 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700900 testGetter(TEST_UNREFLECT);
901 }
902 @Test
903 public void testFindGetter() throws Throwable {
904 startTest("findGetter");
905 testGetter(TEST_FIND_FIELD);
906 }
907 @Test
908 public void testFindStaticGetter() throws Throwable {
909 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -0800910 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -0700911 }
912 public void testGetter(int testMode) throws Throwable {
913 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800914 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -0800915 boolean positive = (c[1] != Error.class);
916 testGetter(positive, lookup, c[0], c[1], testMode);
917 }
918 testGetter(true, lookup,
919 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
920 System.out, testMode);
921 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
922 testGetter(false, lookup,
923 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
924 null, testMode);
jrose10f3b682010-01-07 16:16:45 -0800925 }
926 }
jrosef15905c2011-02-11 01:26:32 -0800927 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
928 Object fieldRef, Object value, int testMode) throws Throwable {
929 testAccessor(positive, lookup, fieldRef, value, testMode);
930 }
931
932 public void testAccessor(boolean positive, MethodHandles.Lookup lookup,
933 Object fieldRef, Object value, int testMode0) throws Throwable {
934 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
935 int testMode = testMode0 & ~TEST_SETTER;
936 boolean isStatic;
937 Class<?> fclass;
938 String fname;
939 Class<?> ftype;
940 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
941 if (f != null) {
942 isStatic = Modifier.isStatic(f.getModifiers());
943 fclass = f.getDeclaringClass();
944 fname = f.getName();
945 ftype = f.getType();
946 } else {
947 Object[] scnt = (Object[]) fieldRef;
948 isStatic = (Boolean) scnt[0];
949 fclass = (Class<?>) scnt[1];
950 fname = (String) scnt[2];
951 ftype = (Class<?>) scnt[3];
952 try {
953 f = fclass.getDeclaredField(fname);
954 } catch (ReflectiveOperationException ex) {
955 f = null;
956 }
957 }
jrosecf98d422010-06-08 23:08:56 -0700958 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -0800959 if (f == null && testMode == TEST_UNREFLECT) return;
960 countTest(positive);
961 MethodType expType;
962 if (isGetter)
963 expType = MethodType.methodType(ftype, HasFields.class);
964 else
965 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -0800966 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -0800967 Exception noAccess = null;
968 MethodHandle mh;
969 try {
970 switch (testMode0) {
971 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
972 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
973 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
974 case TEST_SETTER|
975 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
976 case TEST_SETTER|
977 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
978 case TEST_SETTER|
979 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
980 default:
981 throw new InternalError("testMode="+testMode);
982 }
983 } catch (ReflectiveOperationException ex) {
984 mh = null;
985 noAccess = ex;
986 if (fname.contains("bogus"))
987 assertTrue(noAccess instanceof NoSuchFieldException);
988 else
989 assertTrue(noAccess instanceof IllegalAccessException);
990 }
991 if (verbosity >= 3)
992 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
993 +" => "+mh
994 +(noAccess == null ? "" : " !! "+noAccess));
995 if (positive && noAccess != null) throw new RuntimeException(noAccess);
996 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, mh != null);
997 if (!positive) return; // negative test failed as expected
998 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
999
1000
jrose10f3b682010-01-07 16:16:45 -08001001 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -07001002 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -08001003 HasFields fields = new HasFields();
1004 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001005 Class<?> vtype = ftype;
1006 if (ftype != int.class) vtype = Object.class;
1007 if (isGetter) {
1008 mh = MethodHandles.convertArguments(mh, mh.type().generic()
1009 .changeReturnType(vtype));
1010 } else {
1011 int last = mh.type().parameterCount() - 1;
1012 mh = MethodHandles.convertArguments(mh, mh.type().generic()
1013 .changeReturnType(void.class)
1014 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001015 }
jrosef15905c2011-02-11 01:26:32 -08001016 if (f != null && f.getDeclaringClass() == HasFields.class) {
1017 assertEquals(f.get(fields), value); // clean to start with
1018 }
1019 if (isGetter) {
1020 Object expValue = value;
1021 for (int i = 0; i <= 1; i++) {
1022 if (isStatic) {
1023 if (ftype == int.class)
1024 sawValue = (int) mh.invokeExact(); // do these exactly
1025 else
1026 sawValue = mh.invokeExact();
1027 } else {
1028 if (ftype == int.class)
1029 sawValue = (int) mh.invokeExact((Object) fields);
1030 else
1031 sawValue = mh.invokeExact((Object) fields);
1032 }
1033 assertEquals(sawValue, expValue);
1034 if (f != null && f.getDeclaringClass() == HasFields.class
1035 && !Modifier.isFinal(f.getModifiers())) {
1036 Object random = randomArg(ftype);
1037 f.set(fields, random);
1038 expValue = random;
1039 } else {
1040 break;
1041 }
1042 }
1043 } else {
1044 for (int i = 0; i <= 1; i++) {
1045 Object putValue = randomArg(ftype);
1046 if (isStatic) {
1047 if (ftype == int.class)
1048 mh.invokeExact((int)putValue); // do these exactly
1049 else
1050 mh.invokeExact(putValue);
1051 } else {
1052 if (ftype == int.class)
1053 mh.invokeExact((Object) fields, (int)putValue);
1054 else
1055 mh.invokeExact((Object) fields, putValue);
1056 }
1057 if (f != null && f.getDeclaringClass() == HasFields.class) {
1058 assertEquals(f.get(fields), putValue);
1059 }
1060 }
1061 }
1062 if (f != null && f.getDeclaringClass() == HasFields.class) {
1063 f.set(fields, value); // put it back
1064 }
jrose55220c32009-10-21 23:19:48 -07001065 }
1066
jrose10f3b682010-01-07 16:16:45 -08001067
1068 @Test
jrose55220c32009-10-21 23:19:48 -07001069 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -07001070 startTest("unreflectSetter");
1071 testSetter(TEST_UNREFLECT);
1072 }
1073 @Test
1074 public void testFindSetter() throws Throwable {
1075 startTest("findSetter");
1076 testSetter(TEST_FIND_FIELD);
1077 }
1078 @Test
1079 public void testFindStaticSetter() throws Throwable {
1080 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001081 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001082 }
1083 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001084 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1085 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001086 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001087 boolean positive = (c[1] != Error.class);
1088 testSetter(positive, lookup, c[0], c[1], testMode);
1089 }
1090 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1091 testSetter(false, lookup,
1092 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1093 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001094 }
1095 }
jrosef15905c2011-02-11 01:26:32 -08001096 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1097 Object fieldRef, Object value, int testMode) throws Throwable {
1098 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001099 }
1100
jrose10f3b682010-01-07 16:16:45 -08001101 @Test
jrose55220c32009-10-21 23:19:48 -07001102 public void testArrayElementGetter() throws Throwable {
1103 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001104 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001105 }
1106
jrose10f3b682010-01-07 16:16:45 -08001107 @Test
jrose55220c32009-10-21 23:19:48 -07001108 public void testArrayElementSetter() throws Throwable {
1109 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001110 testArrayElementGetterSetter(true);
1111 }
1112
1113 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
1114 testArrayElementGetterSetter(new Object[10], testSetter);
1115 testArrayElementGetterSetter(new String[10], testSetter);
1116 testArrayElementGetterSetter(new boolean[10], testSetter);
1117 testArrayElementGetterSetter(new byte[10], testSetter);
1118 testArrayElementGetterSetter(new char[10], testSetter);
1119 testArrayElementGetterSetter(new short[10], testSetter);
1120 testArrayElementGetterSetter(new int[10], testSetter);
1121 testArrayElementGetterSetter(new float[10], testSetter);
1122 testArrayElementGetterSetter(new long[10], testSetter);
1123 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -08001124 }
1125
1126 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
1127 countTest(true);
jrose2cc9c832010-04-30 23:48:23 -07001128 if (verbosity >= 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -08001129 Class<?> arrayType = array.getClass();
1130 Class<?> elemType = arrayType.getComponentType();
1131 MethodType expType = !testSetter
1132 ? MethodType.methodType(elemType, arrayType, int.class)
1133 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1134 MethodHandle mh = !testSetter
1135 ? MethodHandles.arrayElementGetter(arrayType)
1136 : MethodHandles.arrayElementSetter(arrayType);
1137 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001138 if (elemType != int.class && elemType != boolean.class) {
jrose320b7692011-05-12 19:27:49 -07001139 // FIXME: change Integer.class and (Integer) below to int.class and (int) below.
1140 MethodType gtype = mh.type().generic().changeParameterType(1, Integer.class);
1141 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose2cc9c832010-04-30 23:48:23 -07001142 mh = MethodHandles.convertArguments(mh, gtype);
1143 }
jrose10f3b682010-01-07 16:16:45 -08001144 Object sawValue, expValue;
1145 List<Object> model = array2list(array);
1146 int length = Array.getLength(array);
1147 for (int i = 0; i < length; i++) {
1148 // update array element
1149 Object random = randomArg(elemType);
1150 model.set(i, random);
1151 if (testSetter) {
1152 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001153 mh.invokeExact((int[]) array, i, (int)random);
jrose2cc9c832010-04-30 23:48:23 -07001154 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001155 mh.invokeExact((boolean[]) array, i, (boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001156 else
jrose320b7692011-05-12 19:27:49 -07001157 mh.invokeExact(array, (Integer)i, random);
jrose10f3b682010-01-07 16:16:45 -08001158 assertEquals(model, array2list(array));
1159 } else {
1160 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001161 }
1162 if (verbosity >= 5) {
1163 List<Object> array2list = array2list(array);
1164 System.out.println("a["+i+"]="+random+" => "+array2list);
1165 if (!array2list.equals(model))
1166 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001167 }
1168 // observe array element
1169 sawValue = Array.get(array, i);
1170 if (!testSetter) {
1171 expValue = sawValue;
1172 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001173 sawValue = (int) mh.invokeExact((int[]) array, i);
jrose2cc9c832010-04-30 23:48:23 -07001174 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001175 sawValue = (boolean) mh.invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001176 else
jrose320b7692011-05-12 19:27:49 -07001177 sawValue = mh.invokeExact(array, (Integer)i);
jrose10f3b682010-01-07 16:16:45 -08001178 assertEquals(sawValue, expValue);
1179 assertEquals(model, array2list(array));
1180 }
1181 }
1182 }
1183
1184 List<Object> array2list(Object array) {
1185 int length = Array.getLength(array);
1186 ArrayList<Object> model = new ArrayList<Object>(length);
1187 for (int i = 0; i < length; i++)
1188 model.add(Array.get(array, i));
1189 return model;
jrose55220c32009-10-21 23:19:48 -07001190 }
1191
1192 static class Callee {
1193 static Object id() { return called("id"); }
1194 static Object id(Object x) { return called("id", x); }
1195 static Object id(Object x, Object y) { return called("id", x, y); }
1196 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1197 static Object id(Object... vx) { return called("id", vx); }
1198 static MethodHandle ofType(int n) {
1199 return ofType(Object.class, n);
1200 }
1201 static MethodHandle ofType(Class<?> rtype, int n) {
1202 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001203 return ofType(MethodType.methodType(rtype, Object[].class));
1204 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001205 }
1206 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001207 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001208 }
1209 static MethodHandle ofType(MethodType type) {
1210 Class<?> rtype = type.returnType();
1211 String pfx = "";
1212 if (rtype != Object.class)
1213 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1214 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001215 try {
1216 return PRIVATE.findStatic(Callee.class, name, type);
1217 } catch (Exception ex) {
1218 throw new RuntimeException(ex);
1219 }
jrose55220c32009-10-21 23:19:48 -07001220 }
1221 }
1222
1223 @Test
1224 public void testConvertArguments() throws Throwable {
1225 if (CAN_SKIP_WORKING) return;
1226 startTest("convertArguments");
1227 testConvert(Callee.ofType(1), null, "id", int.class);
1228 testConvert(Callee.ofType(1), null, "id", String.class);
1229 testConvert(Callee.ofType(1), null, "id", Integer.class);
1230 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001231 testConvert(Callee.ofType(1), null, "id", char.class);
1232 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001233 }
1234
1235 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose900bafd2010-10-30 21:08:23 -07001236 testConvert(true, false, id, rtype, name, params);
1237 testConvert(true, true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001238 }
1239
jrose900bafd2010-10-30 21:08:23 -07001240 void testConvert(boolean positive, boolean useAsType,
1241 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001242 countTest(positive);
1243 MethodType idType = id.type();
1244 if (rtype == null) rtype = idType.returnType();
1245 for (int i = 0; i < params.length; i++) {
1246 if (params[i] == null) params[i] = idType.parameterType(i);
1247 }
1248 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001249 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001250 Object[] args = randomArgs(newType.parameterArray());
1251 Object[] convArgs = args.clone();
1252 for (int i = 0; i < args.length; i++) {
1253 Class<?> src = newType.parameterType(i);
1254 Class<?> dst = idType.parameterType(i);
1255 if (src != dst)
1256 convArgs[i] = castToWrapper(convArgs[i], dst);
1257 }
jrose900bafd2010-10-30 21:08:23 -07001258 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001259 {
1260 Class<?> dst = newType.returnType();
1261 Class<?> src = idType.returnType();
1262 if (src != dst)
1263 convResult = castToWrapper(convResult, dst);
1264 }
1265 MethodHandle target = null;
1266 RuntimeException error = null;
1267 try {
jrose900bafd2010-10-30 21:08:23 -07001268 if (useAsType)
jrose900bafd2010-10-30 21:08:23 -07001269 target = id.asType(newType);
jrosef108fc02011-02-11 01:26:24 -08001270 else
1271 target = MethodHandles.convertArguments(id, newType);
jrose55220c32009-10-21 23:19:48 -07001272 } catch (RuntimeException ex) {
1273 error = ex;
1274 }
jrose2cc9c832010-04-30 23:48:23 -07001275 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001276 System.out.println("convert "+id+ " to "+newType+" => "+target
1277 +(error == null ? "" : " !! "+error));
1278 if (positive && error != null) throw error;
1279 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1280 if (!positive) return; // negative test failed as expected
1281 assertEquals(newType, target.type());
1282 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001283 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001284 assertCalled(name, convArgs);
1285 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001286 if (verbosity >= 1)
1287 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001288 }
1289
1290 @Test
jrosef108fc02011-02-11 01:26:24 -08001291 public void testVarargsCollector() throws Throwable {
1292 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1293 MethodType.methodType(Object.class, String.class, Object[].class));
1294 vac0 = vac0.bindTo("vac");
1295 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
1296 testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1297 testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1298 for (Class<?> at : new Class[] { Object.class, String.class, Integer.class }) {
1299 testConvert(true, true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1300 testConvert(true, true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
1301 }
1302 }
1303
1304 @Test
jrose10f3b682010-01-07 16:16:45 -08001305 public void testPermuteArguments() throws Throwable {
1306 if (CAN_SKIP_WORKING) return;
1307 startTest("permuteArguments");
1308 testPermuteArguments(4, Integer.class, 2, String.class, 0);
1309 //testPermuteArguments(6, Integer.class, 0, null, 30);
1310 //testPermuteArguments(4, Integer.class, 1, int.class, 6);
1311 }
1312 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001313 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001314 System.out.println("permuteArguments "+max+"*"+type1.getName()
1315 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1316 +(dilution > 0 ? " with dilution "+dilution : ""));
1317 int t2pos = t2c == 0 ? 0 : 1;
1318 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1319 Class<?>[] types = new Class<?>[inargs];
1320 Arrays.fill(types, type1);
1321 if (t2c != 0) {
1322 // Fill in a middle range with type2:
1323 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1324 }
1325 Object[] args = randomArgs(types);
1326 int numcases = 1;
1327 for (int outargs = 0; outargs <= max; outargs++) {
1328 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001329 int casStep = dilution + 1;
1330 // Avoid some common factors:
1331 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1332 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1333 casStep++;
jrose320b7692011-05-12 19:27:49 -07001334 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001335 numcases *= inargs;
1336 if (dilution > 10 && outargs >= 4) {
jrose320b7692011-05-12 19:27:49 -07001337 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001338 // Do some special patterns, which we probably missed.
1339 // Replication of a single argument or argument pair.
1340 for (int i = 0; i < inargs; i++) {
1341 Arrays.fill(reorder, i);
1342 testPermuteArguments(args, types, reorder);
1343 for (int d = 1; d <= 2; d++) {
1344 if (i + d >= inargs) continue;
1345 for (int j = 1; j < outargs; j += 2)
1346 reorder[j] += 1;
1347 testPermuteArguments(args, types, reorder);
1348 testPermuteArguments(args, types, reverse(reorder));
1349 }
1350 }
1351 // Repetition of a sequence of 3 or more arguments.
1352 for (int i = 1; i < inargs; i++) {
1353 for (int len = 3; len <= inargs; len++) {
1354 for (int j = 0; j < outargs; j++)
1355 reorder[j] = (i + (j % len)) % inargs;
1356 testPermuteArguments(args, types, reorder);
1357 testPermuteArguments(args, types, reverse(reorder));
1358 }
1359 }
1360 }
1361 }
1362 }
1363 }
1364
jrose320b7692011-05-12 19:27:49 -07001365 public void testPermuteArguments(Object[] args, Class<?>[] types,
1366 int outargs, int numcases, int casStep) throws Throwable {
1367 int inargs = args.length;
1368 int[] reorder = new int[outargs];
1369 for (int cas = 0; cas < numcases; cas += casStep) {
1370 for (int i = 0, c = cas; i < outargs; i++) {
1371 reorder[i] = c % inargs;
1372 c /= inargs;
1373 }
1374 testPermuteArguments(args, types, reorder);
1375 }
1376 }
1377
jrose10f3b682010-01-07 16:16:45 -08001378 static int[] reverse(int[] reorder) {
1379 reorder = reorder.clone();
1380 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1381 int j = reorder.length - 1 - i;
1382 int tem = reorder[i];
1383 reorder[i] = reorder[j];
1384 reorder[j] = tem;
1385 }
1386 return reorder;
1387 }
1388
1389 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1390 countTest();
1391 if (args == null && types == null) {
1392 int max = 0;
1393 for (int j : reorder) {
1394 if (max < j) max = j;
1395 }
1396 args = randomArgs(max+1, Integer.class);
1397 }
1398 if (args == null) {
1399 args = randomArgs(types);
1400 }
1401 if (types == null) {
1402 types = new Class<?>[args.length];
1403 for (int i = 0; i < args.length; i++)
1404 types[i] = args[i].getClass();
1405 }
1406 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001407 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001408 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001409 System.out.println("permuteArguments "+Arrays.toString(reorder));
1410 Object[] permArgs = new Object[outargs];
1411 Class<?>[] permTypes = new Class<?>[outargs];
1412 for (int i = 0; i < outargs; i++) {
1413 permArgs[i] = args[reorder[i]];
1414 permTypes[i] = types[reorder[i]];
1415 }
jrose2cc9c832010-04-30 23:48:23 -07001416 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001417 System.out.println("in args: "+Arrays.asList(args));
1418 System.out.println("out args: "+Arrays.asList(permArgs));
1419 System.out.println("in types: "+Arrays.asList(types));
1420 System.out.println("out types: "+Arrays.asList(permTypes));
1421 }
1422 MethodType inType = MethodType.methodType(Object.class, types);
1423 MethodType outType = MethodType.methodType(Object.class, permTypes);
jroseadc650a2011-02-11 01:26:28 -08001424 MethodHandle target = MethodHandles.convertArguments(varargsList(outargs), outType);
jrose10f3b682010-01-07 16:16:45 -08001425 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose900bafd2010-10-30 21:08:23 -07001426 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001427 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001428 if (!expected.equals(result)) {
1429 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1430 System.out.println("in args: "+Arrays.asList(args));
1431 System.out.println("out args: "+expected);
1432 System.out.println("bad args: "+result);
1433 }
jrose10f3b682010-01-07 16:16:45 -08001434 assertEquals(expected, result);
1435 }
1436
1437
1438 @Test
1439 public void testSpreadArguments() throws Throwable {
1440 if (CAN_SKIP_WORKING) return;
1441 startTest("spreadArguments");
1442 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001443 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001444 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001445 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001446 for (int nargs = 0; nargs < 10; nargs++) {
1447 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1448 for (int pos = 0; pos < nargs; pos++) {
1449 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001450 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001451 }
1452 }
1453 }
1454 }
1455 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1456 countTest();
jrose320b7692011-05-12 19:27:49 -07001457 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1458 MethodHandle target2 = varargsArray(arrayType, nargs);
1459 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001460 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001461 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1462 Object[] args = randomArgs(target2.type().parameterArray());
1463 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001464 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
1465 Object[] check = (Object[]) (Object) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001466 assertArrayEquals(args, check);
1467 switch (nargs) {
1468 case 0:
jrose320b7692011-05-12 19:27:49 -07001469 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001470 assertArrayEquals(args, check);
1471 break;
1472 case 1:
jrose320b7692011-05-12 19:27:49 -07001473 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001474 assertArrayEquals(args, check);
1475 break;
1476 case 2:
jrose320b7692011-05-12 19:27:49 -07001477 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001478 assertArrayEquals(args, check);
1479 break;
1480 }
1481 }
1482 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1483 { // modify newParams in place
1484 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001485 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001486 }
jrose320b7692011-05-12 19:27:49 -07001487 MethodType newType = MethodType.methodType(arrayType, newParams);
1488 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1489 assert(result.type() == newType) : Arrays.asList(result, newType);
1490 result = result.asType(newType.generic());
1491 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001492 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001493 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1494 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001495 } else {
1496 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001497 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1498 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001499 }
jrose320b7692011-05-12 19:27:49 -07001500 String argstr = Arrays.toString(args);
1501 if (!argType.isPrimitive()) {
1502 Object[] rv = (Object[]) returnValue;
1503 String rvs = Arrays.toString(rv);
1504 if (!Arrays.equals(args, rv)) {
1505 System.out.println("method: "+result);
1506 System.out.println("expected: "+argstr);
1507 System.out.println("returned: "+rvs);
1508 assertArrayEquals(args, rv);
1509 }
1510 } else if (argType == int.class) {
1511 String rvs = Arrays.toString((int[]) returnValue);
1512 if (!argstr.equals(rvs)) {
1513 System.out.println("method: "+result);
1514 System.out.println("expected: "+argstr);
1515 System.out.println("returned: "+rvs);
1516 assertEquals(argstr, rvs);
1517 }
1518 } else if (argType == long.class) {
1519 String rvs = Arrays.toString((long[]) returnValue);
1520 if (!argstr.equals(rvs)) {
1521 System.out.println("method: "+result);
1522 System.out.println("expected: "+argstr);
1523 System.out.println("returned: "+rvs);
1524 assertEquals(argstr, rvs);
1525 }
1526 } else {
1527 // cannot test...
1528 }
jrose10f3b682010-01-07 16:16:45 -08001529 }
1530
1531 @Test
1532 public void testCollectArguments() throws Throwable {
1533 if (CAN_SKIP_WORKING) return;
1534 startTest("collectArguments");
1535 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001536 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001537 System.out.println("collectArguments "+argType);
1538 for (int nargs = 0; nargs < 10; nargs++) {
1539 for (int pos = 0; pos < nargs; pos++) {
1540 if (argType == int.class) continue; // FIXME Fail_4
1541 testCollectArguments(argType, pos, nargs);
1542 }
1543 }
1544 }
1545 }
1546 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1547 countTest();
1548 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001549 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001550 fake = changeArgTypes(fake, argType);
1551 MethodType newType = fake.type();
1552 Object[] args = randomArgs(newType.parameterArray());
1553 // here is what should happen:
1554 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1555 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1556 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001557 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001558 target = changeArgTypes(target, 0, pos, argType);
1559 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001560 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001561 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001562 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001563 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001564// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1565// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1566// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1567 assertArrayEquals(collectedArgs, returnValue);
1568 }
1569
1570 @Test
jrose55220c32009-10-21 23:19:48 -07001571 public void testInsertArguments() throws Throwable {
1572 if (CAN_SKIP_WORKING) return;
1573 startTest("insertArguments");
1574 for (int nargs = 0; nargs <= 4; nargs++) {
1575 for (int ins = 0; ins <= 4; ins++) {
1576 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1577 for (int pos = 0; pos <= nargs; pos++) {
1578 testInsertArguments(nargs, pos, ins);
1579 }
1580 }
1581 }
1582 }
1583
1584 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001585 countTest();
jroseadc650a2011-02-11 01:26:28 -08001586 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001587 Object[] args = randomArgs(target.type().parameterArray());
1588 List<Object> resList = Arrays.asList(args);
1589 List<Object> argsToPass = new ArrayList<Object>(resList);
1590 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001591 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001592 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001593 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1594 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001595 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001596 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001597 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001598 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001599 System.out.println("result: "+res2List);
1600 //if (!resList.equals(res2List))
1601 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1602 assertEquals(resList, res2List);
1603 }
1604
jrose10f3b682010-01-07 16:16:45 -08001605 @Test
jroseadc650a2011-02-11 01:26:28 -08001606 public void testFilterReturnValue() throws Throwable {
1607 if (CAN_SKIP_WORKING) return;
1608 startTest("filterReturnValue");
1609 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1610 assertTrue(List.class.isAssignableFrom(classOfVCList));
1611 for (int nargs = 0; nargs <= 3; nargs++) {
1612 for (Class<?> rtype : new Class[] { Object.class,
1613 List.class,
1614 int.class,
1615 //byte.class, //FIXME: add this
1616 //long.class, //FIXME: add this
1617 CharSequence.class,
1618 String.class }) {
1619 testFilterReturnValue(nargs, rtype);
1620 }
1621 }
1622 }
1623
1624 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1625 countTest();
1626 MethodHandle target = varargsList(nargs, rtype);
1627 MethodHandle filter;
1628 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1629 filter = varargsList(1); // add another layer of list-ness
1630 else
1631 filter = MethodHandles.identity(rtype);
1632 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1633 Object[] argsToPass = randomArgs(nargs, Object.class);
1634 if (verbosity >= 3)
1635 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1636 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1637 if (verbosity >= 4)
1638 System.out.println("filtered target: "+target2);
1639 // Simulate expected effect of filter on return value:
1640 Object unfiltered = target.invokeWithArguments(argsToPass);
1641 Object expected = filter.invokeWithArguments(unfiltered);
1642 if (verbosity >= 4)
1643 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1644 if (verbosity >= 4)
1645 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1646 Object result = target2.invokeWithArguments(argsToPass);
1647 if (verbosity >= 3)
1648 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1649 if (!expected.equals(result))
1650 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1651 assertEquals(expected, result);
1652 }
1653
1654 @Test
jrose10f3b682010-01-07 16:16:45 -08001655 public void testFilterArguments() throws Throwable {
1656 if (CAN_SKIP_WORKING) return;
1657 startTest("filterArguments");
1658 for (int nargs = 1; nargs <= 6; nargs++) {
1659 for (int pos = 0; pos < nargs; pos++) {
1660 testFilterArguments(nargs, pos);
1661 }
1662 }
1663 }
1664
1665 void testFilterArguments(int nargs, int pos) throws Throwable {
1666 countTest();
jroseadc650a2011-02-11 01:26:28 -08001667 MethodHandle target = varargsList(nargs);
1668 MethodHandle filter = varargsList(1);
jrose10f3b682010-01-07 16:16:45 -08001669 filter = MethodHandles.convertArguments(filter, filter.type().generic());
1670 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001671 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001672 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001673 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001674 // Simulate expected effect of filter on arglist:
1675 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001676 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001677 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001678 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001679 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001680 System.out.println("result: "+result);
1681 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001682 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001683 assertEquals(expected, result);
1684 }
1685
1686 @Test
1687 public void testFoldArguments() throws Throwable {
1688 if (CAN_SKIP_WORKING) return;
1689 startTest("foldArguments");
1690 for (int nargs = 0; nargs <= 4; nargs++) {
1691 for (int fold = 0; fold <= nargs; fold++) {
1692 for (int pos = 0; pos <= nargs; pos++) {
1693 testFoldArguments(nargs, pos, fold);
1694 }
1695 }
1696 }
1697 }
1698
1699 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1700 if (pos != 0) return; // can fold only at pos=0 for now
1701 countTest();
jroseadc650a2011-02-11 01:26:28 -08001702 MethodHandle target = varargsList(1 + nargs);
1703 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001704 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001705 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001706 System.out.println("fold "+target+" with "+combine);
1707 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1708 // Simulate expected effect of combiner on arglist:
1709 List<Object> expected = new ArrayList<Object>(argsToPass);
1710 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001711 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001712 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001713 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001714 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001715 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001716 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001717 System.out.println("result: "+result);
1718 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001719 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001720 assertEquals(expected, result);
1721 }
1722
1723 @Test
1724 public void testDropArguments() throws Throwable {
1725 if (CAN_SKIP_WORKING) return;
1726 startTest("dropArguments");
1727 for (int nargs = 0; nargs <= 4; nargs++) {
1728 for (int drop = 1; drop <= 4; drop++) {
1729 for (int pos = 0; pos <= nargs; pos++) {
1730 testDropArguments(nargs, pos, drop);
1731 }
1732 }
1733 }
1734 }
1735
1736 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1737 countTest();
jroseadc650a2011-02-11 01:26:28 -08001738 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001739 Object[] args = randomArgs(target.type().parameterArray());
1740 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1741 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1742 List<Object> resList = Arrays.asList(args);
1743 List<Object> argsToDrop = new ArrayList<Object>(resList);
1744 for (int i = drop; i > 0; i--) {
1745 argsToDrop.add(pos, "blort#"+i);
1746 }
jrose900bafd2010-10-30 21:08:23 -07001747 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001748 Object res2List = Arrays.asList((Object[])res2);
1749 //if (!resList.equals(res2List))
1750 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1751 assertEquals(resList, res2List);
1752 }
1753
1754 @Test
1755 public void testInvokers() throws Throwable {
1756 if (CAN_SKIP_WORKING) return;
1757 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1758 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1759 Set<MethodType> done = new HashSet<MethodType>();
1760 for (int i = 0; i <= 6; i++) {
1761 MethodType gtype = MethodType.genericMethodType(i);
1762 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1763 for (int j = -1; j < i; j++) {
1764 MethodType type = gtype;
1765 if (j < 0)
1766 type = type.changeReturnType(argType);
1767 else if (argType == void.class)
1768 continue;
1769 else
1770 type = type.changeParameterType(j, argType);
1771 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1772 if (done.add(type))
1773 testInvokers(type);
1774 MethodType vtype = type.changeReturnType(void.class);
1775 if (done.add(vtype))
1776 testInvokers(vtype);
1777 }
1778 }
1779 }
1780 }
1781
1782 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001783 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001784 System.out.println("test invokers for "+type);
1785 int nargs = type.parameterCount();
1786 boolean testRetCode = type.returnType() != void.class;
1787 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1788 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001789 assertTrue(target.isVarargsCollector());
1790 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001791 Object[] args = randomArgs(type.parameterArray());
1792 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1793 targetPlusArgs.add(0, target);
1794 int code = (Integer) invokee(args);
1795 Object log = logEntry("invokee", args);
1796 assertEquals(log.hashCode(), code);
1797 assertCalled("invokee", args);
1798 MethodHandle inv;
1799 Object result;
1800 // exact invoker
1801 countTest();
1802 calledLog.clear();
1803 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07001804 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001805 if (testRetCode) assertEquals(code, result);
1806 assertCalled("invokee", args);
1807 // generic invoker
1808 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07001809 inv = MethodHandles.invoker(type);
jrose10f3b682010-01-07 16:16:45 -08001810 if (nargs <= 3) {
1811 calledLog.clear();
1812 switch (nargs) {
1813 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001814 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001815 break;
1816 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001817 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001818 break;
1819 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001820 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001821 break;
1822 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001823 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001824 break;
1825 }
1826 if (testRetCode) assertEquals(code, result);
1827 assertCalled("invokee", args);
1828 }
1829 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001830 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001831 if (testRetCode) assertEquals(code, result);
1832 assertCalled("invokee", args);
1833 // varargs invoker #0
1834 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001835 inv = MethodHandles.spreadInvoker(type, 0);
jrose2cc9c832010-04-30 23:48:23 -07001836 result = inv.invokeExact(target, args);
jrose10f3b682010-01-07 16:16:45 -08001837 if (testRetCode) assertEquals(code, result);
1838 assertCalled("invokee", args);
1839 if (nargs >= 1) {
1840 // varargs invoker #1
1841 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001842 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001843 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001844 if (testRetCode) assertEquals(code, result);
1845 assertCalled("invokee", args);
1846 }
1847 if (nargs >= 2) {
1848 // varargs invoker #2
1849 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001850 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001851 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001852 if (testRetCode) assertEquals(code, result);
1853 assertCalled("invokee", args);
1854 }
1855 if (nargs >= 3) {
1856 // varargs invoker #3
1857 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001858 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001859 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001860 if (testRetCode) assertEquals(code, result);
1861 assertCalled("invokee", args);
1862 }
1863 for (int k = 0; k <= nargs; k++) {
1864 // varargs invoker #0..N
1865 countTest();
1866 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001867 inv = MethodHandles.spreadInvoker(type, k);
jrose10f3b682010-01-07 16:16:45 -08001868 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1869 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1870 Object[] tail = tailList.toArray();
1871 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07001872 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08001873 if (testRetCode) assertEquals(code, result);
1874 assertCalled("invokee", args);
1875 }
jrose900bafd2010-10-30 21:08:23 -07001876
jrose10f3b682010-01-07 16:16:45 -08001877 // dynamic invoker
1878 countTest();
jroseb90d2e72010-12-16 15:59:27 -08001879 CallSite site = new MutableCallSite(type);
1880 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07001881
1882 // see if we get the result of the original target:
1883 try {
1884 result = inv.invokeWithArguments(args);
1885 assertTrue("should not reach here", false);
1886 } catch (IllegalStateException ex) {
1887 String msg = ex.getMessage();
1888 assertTrue(msg, msg.contains("site"));
1889 }
1890
1891 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08001892 site.setTarget(target);
1893 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001894 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001895 if (testRetCode) assertEquals(code, result);
1896 assertCalled("invokee", args);
1897 }
1898
1899 static Object invokee(Object... args) {
1900 return called("invokee", args).hashCode();
1901 }
1902
jrose55220c32009-10-21 23:19:48 -07001903 private static final String MISSING_ARG = "missingArg";
1904 static Object targetIfEquals() {
1905 return called("targetIfEquals");
1906 }
1907 static Object fallbackIfNotEquals() {
1908 return called("fallbackIfNotEquals");
1909 }
1910 static Object targetIfEquals(Object x) {
1911 assertEquals(x, MISSING_ARG);
1912 return called("targetIfEquals", x);
1913 }
1914 static Object fallbackIfNotEquals(Object x) {
1915 assertFalse(x.toString(), x.equals(MISSING_ARG));
1916 return called("fallbackIfNotEquals", x);
1917 }
1918 static Object targetIfEquals(Object x, Object y) {
1919 assertEquals(x, y);
1920 return called("targetIfEquals", x, y);
1921 }
1922 static Object fallbackIfNotEquals(Object x, Object y) {
1923 assertFalse(x.toString(), x.equals(y));
1924 return called("fallbackIfNotEquals", x, y);
1925 }
1926 static Object targetIfEquals(Object x, Object y, Object z) {
1927 assertEquals(x, y);
1928 return called("targetIfEquals", x, y, z);
1929 }
1930 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1931 assertFalse(x.toString(), x.equals(y));
1932 return called("fallbackIfNotEquals", x, y, z);
1933 }
1934
jrose10f3b682010-01-07 16:16:45 -08001935 @Test
1936 public void testGuardWithTest() throws Throwable {
1937 if (CAN_SKIP_WORKING) return;
1938 startTest("guardWithTest");
1939 for (int nargs = 0; nargs <= 3; nargs++) {
1940 if (nargs != 2) continue; // FIXME: test more later
1941 testGuardWithTest(nargs, Object.class);
1942 testGuardWithTest(nargs, String.class);
1943 }
1944 }
1945 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1946 countTest();
1947 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1948 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1949 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1950 while (test.type().parameterCount() < nargs)
1951 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1952 while (test.type().parameterCount() > nargs)
1953 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1954 if (argClass != Object.class) {
1955 test = changeArgTypes(test, argClass);
1956 target = changeArgTypes(target, argClass);
1957 fallback = changeArgTypes(fallback, argClass);
1958 }
1959 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1960 assertEquals(target.type(), mh.type());
1961 Object[][] argLists = {
1962 { },
1963 { "foo" }, { MISSING_ARG },
1964 { "foo", "foo" }, { "foo", "bar" },
1965 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1966 };
1967 for (Object[] argList : argLists) {
1968 if (argList.length != nargs) continue;
1969 boolean equals;
1970 switch (nargs) {
1971 case 0: equals = true; break;
1972 case 1: equals = MISSING_ARG.equals(argList[0]); break;
1973 default: equals = argList[0].equals(argList[1]); break;
1974 }
1975 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07001976 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001977 System.out.println(logEntry(willCall, argList));
jrose900bafd2010-10-30 21:08:23 -07001978 Object result = mh.invokeWithArguments(argList);
jrose10f3b682010-01-07 16:16:45 -08001979 assertCalled(willCall, argList);
1980 }
1981 }
1982
1983 @Test
1984 public void testCatchException() throws Throwable {
1985 if (CAN_SKIP_WORKING) return;
1986 startTest("catchException");
1987 for (int nargs = 2; nargs <= 6; nargs++) {
1988 for (int ti = 0; ti <= 1; ti++) {
1989 boolean throwIt = (ti != 0);
1990 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
1991 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
1992 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
1993 }
1994 }
1995 }
1996
1997 private static <T extends Throwable>
1998 Object throwOrReturn(Object normal, T exception) throws T {
1999 if (exception != null) throw exception;
2000 return normal;
2001 }
2002
2003 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
2004 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002005 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002006 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
2007 Class<? extends Throwable> exType = thrown.getClass();
2008 MethodHandle throwOrReturn
2009 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2010 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb90d2e72010-12-16 15:59:27 -08002011 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jrose10f3b682010-01-07 16:16:45 -08002012 while (thrower.type().parameterCount() < nargs)
2013 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
jroseadc650a2011-02-11 01:26:28 -08002014 MethodHandle catcher = varargsList(1+nargs).asType(MethodType.genericMethodType(1+nargs));
jrose10f3b682010-01-07 16:16:45 -08002015 MethodHandle target = MethodHandles.catchException(thrower,
jroseb90d2e72010-12-16 15:59:27 -08002016 thrown.getClass(), catcher);
jrose10f3b682010-01-07 16:16:45 -08002017 assertEquals(thrower.type(), target.type());
2018 //System.out.println("catching with "+target+" : "+throwOrReturn);
2019 Object[] args = randomArgs(nargs, Object.class);
2020 args[1] = (throwIt ? thrown : null);
jrose900bafd2010-10-30 21:08:23 -07002021 Object returned = target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08002022 //System.out.println("return from "+target+" : "+returned);
2023 if (!throwIt) {
2024 assertSame(args[0], returned);
2025 } else {
2026 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
2027 catchArgs.add(0, thrown);
2028 assertEquals(catchArgs, returned);
2029 }
2030 }
2031
2032 @Test
2033 public void testThrowException() throws Throwable {
2034 if (CAN_SKIP_WORKING) return;
2035 startTest("throwException");
2036 testThrowException(int.class, new ClassCastException("testing"));
2037 testThrowException(void.class, new java.io.IOException("testing"));
2038 testThrowException(String.class, new LinkageError("testing"));
2039 }
2040
2041 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2042 countTest();
2043 Class<? extends Throwable> exType = thrown.getClass();
2044 MethodHandle target = MethodHandles.throwException(returnType, exType);
2045 //System.out.println("throwing with "+target+" : "+thrown);
2046 MethodType expectedType = MethodType.methodType(returnType, exType);
2047 assertEquals(expectedType, target.type());
jrose2cc9c832010-04-30 23:48:23 -07002048 target = MethodHandles.convertArguments(target, target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002049 Throwable caught = null;
2050 try {
jrose2cc9c832010-04-30 23:48:23 -07002051 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002052 fail("got "+res+" instead of throwing "+thrown);
2053 } catch (Throwable ex) {
2054 if (ex != thrown) {
2055 if (ex instanceof Error) throw (Error)ex;
2056 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2057 }
2058 caught = ex;
2059 }
2060 assertSame(thrown, caught);
2061 }
2062
2063 @Test
2064 public void testCastFailure() throws Throwable {
2065 if (CAN_SKIP_WORKING) return;
2066 startTest("testCastFailure");
2067 testCastFailure("cast/argument", 11000);
2068 testCastFailure("unbox/argument", 11000);
2069 testCastFailure("cast/return", 11000);
2070 testCastFailure("unbox/return", 11000);
2071 }
2072
jrose900bafd2010-10-30 21:08:23 -07002073 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002074 public MethodHandle asMethodHandle() {
2075 return VALUE.bindTo(this);
2076 }
jrose10f3b682010-01-07 16:16:45 -08002077 Object value(Object x) {
2078 trace("value", x);
2079 if (boo != null) return boo;
2080 return x;
2081 }
2082 Object boo;
2083 void boo(Object x) { boo = x; }
2084
2085 static void trace(String x, Object y) {
2086 if (verbosity > 8) System.out.println(x+"="+y);
2087 }
2088 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2089 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2090 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002091 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2092 static {
2093 try {
2094 VALUE = PRIVATE.findVirtual(
2095 Surprise.class, "value",
2096 MethodType.methodType(Object.class, Object.class));
2097 REF_IDENTITY = PRIVATE.findStatic(
2098 Surprise.class, "refIdentity",
2099 MethodType.methodType(Object.class, Object.class));
2100 BOX_IDENTITY = PRIVATE.findStatic(
2101 Surprise.class, "boxIdentity",
2102 MethodType.methodType(Integer.class, Integer.class));
2103 INT_IDENTITY = PRIVATE.findStatic(
2104 Surprise.class, "intIdentity",
2105 MethodType.methodType(int.class, int.class));
2106 } catch (Exception ex) {
2107 throw new RuntimeException(ex);
2108 }
2109 }
jrose10f3b682010-01-07 16:16:45 -08002110 }
2111
2112 void testCastFailure(String mode, int okCount) throws Throwable {
2113 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002114 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002115 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002116 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002117 if (mode.endsWith("/return")) {
2118 if (mode.equals("unbox/return")) {
2119 // fail on return to ((Integer)surprise).intValue
2120 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(int.class, Object.class));
2121 identity = MethodHandles.convertArguments(identity, MethodType.methodType(int.class, Object.class));
2122 } else if (mode.equals("cast/return")) {
2123 // fail on return to (Integer)surprise
2124 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(Integer.class, Object.class));
2125 identity = MethodHandles.convertArguments(identity, MethodType.methodType(Integer.class, Object.class));
2126 }
2127 } else if (mode.endsWith("/argument")) {
2128 MethodHandle callee = null;
2129 if (mode.equals("unbox/argument")) {
2130 // fail on handing surprise to int argument
2131 callee = Surprise.INT_IDENTITY;
2132 } else if (mode.equals("cast/argument")) {
2133 // fail on handing surprise to Integer argument
2134 callee = Surprise.BOX_IDENTITY;
2135 }
2136 if (callee != null) {
2137 callee = MethodHandles.convertArguments(callee, MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002138 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2139 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002140 }
2141 }
jrosea1ebbe62010-09-08 18:40:23 -07002142 assertNotSame(mode, surprise, surprise0);
jrose10f3b682010-01-07 16:16:45 -08002143 identity = MethodHandles.convertArguments(identity, MethodType.genericMethodType(1));
2144 surprise = MethodHandles.convertArguments(surprise, MethodType.genericMethodType(1));
2145 Object x = 42;
2146 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002147 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002148 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002149 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002150 assertEquals(x, z);
2151 }
2152 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002153 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002154 assertEquals(x, y);
2155 try {
jrose2cc9c832010-04-30 23:48:23 -07002156 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002157 System.out.println("Failed to throw; got z="+z);
2158 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002159 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002160 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002161 System.out.println("caught "+ex);
2162 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002163 ex.printStackTrace();
jrose320b7692011-05-12 19:27:49 -07002164 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002165 }
2166 }
2167
jrose45b7a332010-05-03 23:32:47 -07002168 static Example userMethod(Object o, String s, int i) {
2169 called("userMethod", o, s, i);
2170 return null;
2171 }
2172
2173 @Test
2174 public void testUserClassInSignature() throws Throwable {
2175 if (CAN_SKIP_WORKING) return;
2176 startTest("testUserClassInSignature");
2177 Lookup lookup = MethodHandles.lookup();
2178 String name; MethodType mt; MethodHandle mh;
2179 Object[] args;
2180
2181 // Try a static method.
2182 name = "userMethod";
2183 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2184 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2185 assertEquals(mt, mh.type());
2186 assertEquals(Example.class, mh.type().returnType());
2187 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002188 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002189 assertCalled(name, args);
2190
2191 // Try a virtual method.
2192 name = "v2";
2193 mt = MethodType.methodType(Object.class, Object.class, int.class);
2194 mh = lookup.findVirtual(Example.class, name, mt);
2195 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2196 assertTrue(mh.type().parameterList().contains(Example.class));
2197 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002198 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002199 assertCalled(name, args);
2200 }
jrosebe2db602010-09-08 18:40:34 -07002201
2202 static void runForRunnable() {
2203 called("runForRunnable");
2204 }
2205 private interface Fooable {
2206 Object foo(Fooable x, Object y);
2207 // this is for randomArg:
2208 public class Impl implements Fooable {
2209 public Object foo(Fooable x, Object y) {
2210 throw new RuntimeException("do not call");
2211 }
2212 final String name;
2213 public Impl() { name = "Fooable#"+nextArg(); }
2214 @Override public String toString() { return name; }
2215 }
2216 }
2217 static Object fooForFooable(Fooable x, Object y) {
2218 return called("fooForFooable", x, y);
2219 }
2220 private static class MyCheckedException extends Exception {
2221 }
2222 private interface WillThrow {
2223 void willThrow() throws MyCheckedException;
2224 }
2225
2226 @Test
2227 public void testAsInstance() throws Throwable {
2228 if (CAN_SKIP_WORKING) return;
2229 Lookup lookup = MethodHandles.lookup();
2230 {
2231 MethodType mt = MethodType.methodType(void.class);
2232 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
2233 Runnable proxy = MethodHandles.asInstance(mh, Runnable.class);
2234 proxy.run();
2235 assertCalled("runForRunnable");
2236 }
2237 {
2238 MethodType mt = MethodType.methodType(Object.class, Fooable.class, Object.class);
2239 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable", mt);
2240 Fooable proxy = MethodHandles.asInstance(mh, Fooable.class);
2241 Object[] args = randomArgs(mt.parameterArray());
2242 Object result = proxy.foo((Fooable) args[0], args[1]);
2243 assertCalled("fooForFooable", args);
2244 assertEquals(result, logEntry("fooForFooable", args));
2245 }
2246 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2247 new InternalError("ok"),
2248 new Throwable("fail"),
2249 new Exception("fail"),
2250 new MyCheckedException()
2251 }) {
2252 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2253 mh = MethodHandles.insertArguments(mh, 0, ex);
2254 WillThrow proxy = MethodHandles.asInstance(mh, WillThrow.class);
2255 try {
2256 proxy.willThrow();
2257 System.out.println("Failed to throw: "+ex);
2258 assertTrue(false);
2259 } catch (Throwable ex1) {
2260 if (verbosity > 2) {
2261 System.out.println("throw "+ex);
2262 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2263 }
2264 if (ex instanceof RuntimeException ||
2265 ex instanceof Error) {
2266 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2267 } else if (ex instanceof MyCheckedException) {
2268 assertSame("must pass declared exception out without wrapping", ex, ex1);
2269 } else {
2270 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
2271 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
2272 assertSame(ex, utex.getCause());
2273 }
2274 }
2275 }
2276 // Test error checking:
jrosebe2db602010-09-08 18:40:34 -07002277 for (Class<?> nonSAM : new Class[] { Object.class,
2278 String.class,
2279 CharSequence.class,
2280 Example.class }) {
2281 try {
jroseadc650a2011-02-11 01:26:28 -08002282 MethodHandles.asInstance(varargsArray(0), nonSAM);
jrosebe2db602010-09-08 18:40:34 -07002283 System.out.println("Failed to throw");
2284 assertTrue(false);
2285 } catch (IllegalArgumentException ex) {
2286 }
2287 }
2288 }
jrose55220c32009-10-21 23:19:48 -07002289}
jroseada69fa2011-03-23 23:02:31 -07002290// Local abbreviated copy of sun.invoke.util.ValueConversions
jrose55220c32009-10-21 23:19:48 -07002291class ValueConversions {
2292 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2293 private static final Object[] NO_ARGS_ARRAY = {};
2294 private static Object[] makeArray(Object... args) { return args; }
2295 private static Object[] array() { return NO_ARGS_ARRAY; }
2296 private static Object[] array(Object a0)
2297 { return makeArray(a0); }
2298 private static Object[] array(Object a0, Object a1)
2299 { return makeArray(a0, a1); }
2300 private static Object[] array(Object a0, Object a1, Object a2)
2301 { return makeArray(a0, a1, a2); }
2302 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2303 { return makeArray(a0, a1, a2, a3); }
2304 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2305 Object a4)
2306 { return makeArray(a0, a1, a2, a3, a4); }
2307 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2308 Object a4, Object a5)
2309 { return makeArray(a0, a1, a2, a3, a4, a5); }
2310 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2311 Object a4, Object a5, Object a6)
2312 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2313 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2314 Object a4, Object a5, Object a6, Object a7)
2315 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2316 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2317 Object a4, Object a5, Object a6, Object a7,
2318 Object a8)
2319 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2320 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2321 Object a4, Object a5, Object a6, Object a7,
2322 Object a8, Object a9)
2323 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2324 static MethodHandle[] makeArrays() {
2325 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2326 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2327 for (;;) {
2328 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002329 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002330 String name = "array";
2331 MethodHandle array = null;
2332 try {
2333 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002334 } catch (ReflectiveOperationException ex) {
2335 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002336 }
2337 if (array == null) break;
2338 arrays.add(array);
2339 }
jrosef15905c2011-02-11 01:26:32 -08002340 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002341 return arrays.toArray(new MethodHandle[0]);
2342 }
2343 static final MethodHandle[] ARRAYS = makeArrays();
2344
2345 /** Return a method handle that takes the indicated number of Object
2346 * arguments and returns an Object array of them, as if for varargs.
2347 */
2348 public static MethodHandle varargsArray(int nargs) {
2349 if (nargs < ARRAYS.length)
2350 return ARRAYS[nargs];
2351 // else need to spin bytecode or do something else fancy
jrose2cc9c832010-04-30 23:48:23 -07002352 throw new UnsupportedOperationException("NYI: cannot form a varargs array of length "+nargs);
jrose55220c32009-10-21 23:19:48 -07002353 }
jrose320b7692011-05-12 19:27:49 -07002354 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2355 Class<?> elemType = arrayType.getComponentType();
2356 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2357 MethodHandle mh = varargsArray(nargs);
2358 if (arrayType != Object[].class)
2359 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2360 return mh.asType(vaType);
2361 }
2362 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2363 Class<?> elemType = arrayType.getComponentType();
2364 if (!elemType.isPrimitive())
2365 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2366 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2367 for (int i = 0; i < a.length; i++)
2368 java.lang.reflect.Array.set(b, i, a[i]);
2369 return b;
2370 }
2371 private static final MethodHandle CHANGE_ARRAY_TYPE;
2372 static {
2373 try {
2374 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2375 MethodType.methodType(Object.class, Class.class, Object[].class));
2376 } catch (NoSuchMethodException | IllegalAccessException ex) {
2377 Error err = new InternalError("uncaught exception");
2378 err.initCause(ex);
2379 throw err;
2380 }
2381 }
jrose10f3b682010-01-07 16:16:45 -08002382
2383 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2384 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2385 private static List<Object> list() { return NO_ARGS_LIST; }
2386 private static List<Object> list(Object a0)
2387 { return makeList(a0); }
2388 private static List<Object> list(Object a0, Object a1)
2389 { return makeList(a0, a1); }
2390 private static List<Object> list(Object a0, Object a1, Object a2)
2391 { return makeList(a0, a1, a2); }
2392 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2393 { return makeList(a0, a1, a2, a3); }
2394 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2395 Object a4)
2396 { return makeList(a0, a1, a2, a3, a4); }
2397 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2398 Object a4, Object a5)
2399 { return makeList(a0, a1, a2, a3, a4, a5); }
2400 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2401 Object a4, Object a5, Object a6)
2402 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2403 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2404 Object a4, Object a5, Object a6, Object a7)
2405 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2406 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2407 Object a4, Object a5, Object a6, Object a7,
2408 Object a8)
2409 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2410 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2411 Object a4, Object a5, Object a6, Object a7,
2412 Object a8, Object a9)
2413 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2414 static MethodHandle[] makeLists() {
jroseadc650a2011-02-11 01:26:28 -08002415 ArrayList<MethodHandle> lists = new ArrayList<MethodHandle>();
jrose10f3b682010-01-07 16:16:45 -08002416 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2417 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002418 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002419 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2420 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002421 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002422 try {
jroseadc650a2011-02-11 01:26:28 -08002423 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002424 } catch (ReflectiveOperationException ex) {
2425 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08002426 }
jroseadc650a2011-02-11 01:26:28 -08002427 if (list == null) break;
2428 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002429 }
jrosef15905c2011-02-11 01:26:32 -08002430 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08002431 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002432 }
2433 static final MethodHandle[] LISTS = makeLists();
2434
2435 /** Return a method handle that takes the indicated number of Object
2436 * arguments and returns List.
2437 */
2438 public static MethodHandle varargsList(int nargs) {
2439 if (nargs < LISTS.length)
2440 return LISTS[nargs];
2441 // else need to spin bytecode or do something else fancy
2442 throw new UnsupportedOperationException("NYI");
2443 }
jrose55220c32009-10-21 23:19:48 -07002444}
2445// This guy tests access from outside the same package member, but inside
2446// the package itself.
2447class PackageSibling {
2448 static Lookup lookup() {
2449 return MethodHandles.lookup();
2450 }
2451}