blob: 26142c8c5270b07c53ee06d7ede0edf47463c016 [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
2 * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26/* @test
27 * @summary unit tests for java.dyn.MethodHandles
28 * @compile -XDinvokedynamic MethodHandlesTest.java
29 * @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic jdk.java.dyn.MethodHandlesTest
30 */
31
32package jdk.java.dyn;
33
34import java.dyn.*;
35import java.dyn.MethodHandles.Lookup;
36import java.lang.reflect.*;
37import java.util.*;
38import org.junit.*;
39import static org.junit.Assert.*;
40import static org.junit.Assume.assumeTrue;
41
42
43/**
44 *
45 * @author jrose
46 */
47public class MethodHandlesTest {
48 // How much output?
49 static int verbosity = 1;
50
51 // Set this true during development if you want to fast-forward to
52 // a particular new, non-working test. Tests which are known to
53 // work (or have recently worked) test this flag and return on true.
54 static boolean CAN_SKIP_WORKING = false;
55 //static { CAN_SKIP_WORKING = true; }
56
57 // Set true to test more calls. If false, some tests are just
58 // lookups, without exercising the actual method handle.
59 static boolean DO_MORE_CALLS = false;
60
61
62 @Test
63 public void testFirst() throws Throwable {
64 verbosity += 9; try {
65 // left blank for debugging
66 } finally { verbosity -= 9; }
67 }
68
69 static final int MAX_ARG_INCREASE = 3;
70
71 public MethodHandlesTest() {
72 }
73
74 @Before
75 public void checkImplementedPlatform() {
76 boolean platformOK = false;
77 Properties properties = System.getProperties();
78 String vers = properties.getProperty("java.vm.version");
79 String name = properties.getProperty("java.vm.name");
80 String arch = properties.getProperty("os.arch");
81 if (arch.equals("i386") &&
82 (name.contains("Client") || name.contains("Server"))
83 ) {
84 platformOK = true;
85 } else {
86 System.err.println("Skipping tests for unsupported platform: "+Arrays.asList(vers, name, arch));
87 }
88 assumeTrue(platformOK);
89 }
90
91 String testName;
92 int posTests, negTests;
93 @After
94 public void printCounts() {
95 if (verbosity >= 1 && (posTests | negTests) != 0) {
96 System.out.println();
97 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
98 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
99 }
100 }
101 void countTest(boolean positive) {
102 if (positive) ++posTests;
103 else ++negTests;
104 }
105 void countTest() { countTest(true); }
106 void startTest(String name) {
107 if (testName != null) printCounts();
108 if (verbosity >= 0)
109 System.out.println(name);
110 posTests = negTests = 0;
111 testName = name;
112 }
113
114 @BeforeClass
115 public static void setUpClass() throws Exception {
116 calledLog.clear();
117 calledLog.add(null);
118 nextArg = 1000000;
119 }
120
121 @AfterClass
122 public static void tearDownClass() throws Exception {
123 }
124
125 static List<Object> calledLog = new ArrayList<Object>();
126 static Object logEntry(String name, Object... args) {
127 return Arrays.asList(name, Arrays.asList(args));
128 }
129 static Object called(String name, Object... args) {
130 Object entry = logEntry(name, args);
131 calledLog.add(entry);
132 return entry;
133 }
134 static void assertCalled(String name, Object... args) {
135 Object expected = logEntry(name, args);
136 Object actual = calledLog.get(calledLog.size() - 1);
137 if (expected.equals(actual)) return;
138 System.out.println("assertCalled "+name+":");
139 System.out.println("expected: "+expected);
140 System.out.println("actual: "+actual);
141 System.out.println("ex. types: "+getClasses(expected));
142 System.out.println("act. types: "+getClasses(actual));
143 assertEquals("previous method call types", expected, actual);
144 assertEquals("previous method call", expected, actual);
145 }
146 static void printCalled(MethodHandle target, String name, Object... args) {
147 if (verbosity >= 2)
148 System.out.println("calling "+logEntry(name, args)+" on "+target);
149 }
150
151 static Object castToWrapper(Object value, Class<?> dst) {
152 Object wrap = null;
153 if (value instanceof Number)
154 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
155 if (value instanceof Character)
156 wrap = castToWrapperOrNull((char)(Character)value, dst);
157 if (wrap != null) return wrap;
158 return dst.cast(value);
159 }
160
161 static Object castToWrapperOrNull(long value, Class<?> dst) {
162 if (dst == int.class || dst == Integer.class)
163 return (int)(value);
164 if (dst == long.class || dst == Long.class)
165 return (long)(value);
166 if (dst == char.class || dst == Character.class)
167 return (char)(value);
168 if (dst == short.class || dst == Short.class)
169 return (short)(value);
170 if (dst == float.class || dst == Float.class)
171 return (float)(value);
172 if (dst == double.class || dst == Double.class)
173 return (double)(value);
174 return null;
175 }
176
177 static int nextArg;
178 static Object randomArg(Class<?> param) {
179 Object wrap = castToWrapperOrNull(nextArg, param);
180 if (wrap != null) {
181 nextArg++;
182 return wrap;
183 }
184// import sun.dyn.util.Wrapper;
185// Wrapper wrap = Wrapper.forBasicType(dst);
186// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
187// wrap = Wrapper.forWrapperType(dst);
188// if (wrap != Wrapper.OBJECT)
189// return wrap.wrap(nextArg++);
190 if (param.isInterface() || param.isAssignableFrom(String.class))
191 return "#"+(nextArg++);
192 else
193 try {
194 return param.newInstance();
195 } catch (InstantiationException ex) {
196 } catch (IllegalAccessException ex) {
197 }
198 return null; // random class not Object, String, Integer, etc.
199 }
200 static Object[] randomArgs(Class<?>... params) {
201 Object[] args = new Object[params.length];
202 for (int i = 0; i < args.length; i++)
203 args[i] = randomArg(params[i]);
204 return args;
205 }
206 static Object[] randomArgs(int nargs, Class<?> param) {
207 Object[] args = new Object[nargs];
208 for (int i = 0; i < args.length; i++)
209 args[i] = randomArg(param);
210 return args;
211 }
212
213 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
214 return Arrays.copyOf(a, a.length, atype);
215 }
216 static <T> T[] cat(T[] a, T... b) {
217 int alen = a.length, blen = b.length;
218 if (blen == 0) return a;
219 T[] c = Arrays.copyOf(a, alen + blen);
220 System.arraycopy(b, 0, c, alen, blen);
221 return c;
222 }
223 static Integer[] boxAll(int... vx) {
224 Integer[] res = new Integer[vx.length];
225 for (int i = 0; i < res.length; i++) {
226 res[i] = vx[i];
227 }
228 return res;
229 }
230 static Object getClasses(Object x) {
231 if (x == null) return x;
232 if (x instanceof String) return x; // keep the name
233 if (x instanceof List) {
234 // recursively report classes of the list elements
235 Object[] xa = ((List)x).toArray();
236 for (int i = 0; i < xa.length; i++)
237 xa[i] = getClasses(xa[i]);
238 return Arrays.asList(xa);
239 }
240 return x.getClass().getSimpleName();
241 }
242
243 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
244 return changeArgTypes(target, 0, 999, argType);
245 }
246 static MethodHandle changeArgTypes(MethodHandle target,
247 int beg, int end, Class<?> argType) {
248 MethodType targetType = target.type();
249 end = Math.min(end, targetType.parameterCount());
250 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
251 Collections.fill(argTypes.subList(beg, end), argType);
252 MethodType ttype2 = MethodType.make(targetType.returnType(), argTypes);
253 return MethodHandles.convertArguments(target, ttype2);
254 }
255
256 // This lookup is good for all members in and under MethodHandlesTest.
257 static final Lookup PRIVATE = MethodHandles.lookup();
258 // This lookup is good for package-private members but not private ones.
259 static final Lookup PACKAGE = PackageSibling.lookup();
260 // This lookup is good only for public members.
261 static final Lookup PUBLIC = MethodHandles.Lookup.PUBLIC_LOOKUP;
262
263 // Subject methods...
264 static class Example implements IntExample {
265 final String name;
266 public Example() { name = "Example#"+(nextArg++); }
267 protected Example(String name) { this.name = name; }
268 protected Example(int x) { this(); called("protected <init>", this, x); }
269 @Override public String toString() { return name; }
270
271 public void v0() { called("v0", this); }
272 void pkg_v0() { called("pkg_v0", this); }
273 private void pri_v0() { called("pri_v0", this); }
274 public static void s0() { called("s0"); }
275 static void pkg_s0() { called("pkg_s0"); }
276 private static void pri_s0() { called("pri_s0"); }
277
278 public Object v1(Object x) { return called("v1", this, x); }
279 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
280 public Object v2(Object x, int y) { return called("v2", this, x, y); }
281 public Object v2(int x, Object y) { return called("v2", this, x, y); }
282 public Object v2(int x, int y) { return called("v2", this, x, y); }
283 public static Object s1(Object x) { return called("s1", x); }
284 public static Object s2(int x) { return called("s2", x); }
285 public static Object s3(long x) { return called("s3", x); }
286 public static Object s4(int x, int y) { return called("s4", x, y); }
287 public static Object s5(long x, int y) { return called("s5", x, y); }
288 public static Object s6(int x, long y) { return called("s6", x, y); }
289 public static Object s7(float x, double y) { return called("s7", x, y); }
290 }
291 public static class PubExample extends Example {
292 }
293 static class SubExample extends Example {
294 @Override public void v0() { called("Sub/v0", this); }
295 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
296 private SubExample(int x) { called("<init>", this, x); }
297 public SubExample() { super("SubExample#"+(nextArg++)); }
298 }
299 public static interface IntExample {
300 public void v0();
301 static class Impl implements IntExample {
302 public void v0() { called("Int/v0", this); }
303 final String name;
304 public Impl() { name = "Example#"+(nextArg++); }
305 }
306 }
307
308 static final Object[][][] ACCESS_CASES = {
309 { { true, PRIVATE } } // only one test case at present
310 };
311
312 static Object[][] accessCases(Class<?> defc, String name) {
313 return ACCESS_CASES[0];
314 }
315
316 @Test
317 public void testFindStatic() throws Throwable {
318 if (CAN_SKIP_WORKING) return;
319 startTest("findStatic");
320 testFindStatic(PubExample.class, void.class, "s0");
321 testFindStatic(Example.class, void.class, "s0");
322 testFindStatic(Example.class, void.class, "pkg_s0");
323 testFindStatic(Example.class, void.class, "pri_s0");
324
325 testFindStatic(Example.class, Object.class, "s1", Object.class);
326 testFindStatic(Example.class, Object.class, "s2", int.class);
327 testFindStatic(Example.class, Object.class, "s3", long.class);
328 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
329 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
330 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
331 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
332
333 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
334 }
335
336 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
337 for (Object[] ac : accessCases(defc, name)) {
338 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
339 }
340 }
341 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
342 testFindStatic(true, lookup, defc, ret, name, params);
343 }
344 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
345 countTest(positive);
346 MethodType type = MethodType.make(ret, params);
347 MethodHandle target = null;
348 RuntimeException noAccess = null;
349 try {
350 target = lookup.findStatic(defc, name, type);
351 } catch (NoAccessException ex) {
352 noAccess = ex;
353 }
354 if (verbosity >= 2)
355 System.out.println("findStatic "+lookup+": "+defc+"."+name+"/"+type+" => "+target
356 +(noAccess == null ? "" : " !! "+noAccess));
357 if (positive && noAccess != null) throw noAccess;
358 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
359 if (!positive) return; // negative test failed as expected
360 assertEquals(type, target.type());
361 assertTrue(target.toString().contains(name)); // rough check
362 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
363 Object[] args = randomArgs(params);
364 printCalled(target, name, args);
365 MethodHandles.invoke(target, args);
366 assertCalled(name, args);
367 System.out.print(':');
368 }
369
370 @Test
371 public void testFindVirtual() throws Throwable {
372 if (CAN_SKIP_WORKING) return;
373 startTest("findVirtual");
374 testFindVirtual(Example.class, void.class, "v0");
375 testFindVirtual(Example.class, void.class, "pkg_v0");
376 testFindVirtual(Example.class, void.class, "pri_v0");
377 testFindVirtual(Example.class, Object.class, "v1", Object.class);
378 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
379 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
380 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
381 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
382 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
383 // test dispatch
384 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
385 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
386 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
387 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
388 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
389 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
390 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
391 }
392
393 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
394 Class<?> rcvc = defc;
395 testFindVirtual(rcvc, defc, ret, name, params);
396 }
397 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
398 for (Object[] ac : accessCases(defc, name)) {
399 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
400 }
401 }
402 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
403 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
404 }
405 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
406 countTest(positive);
407 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
408 MethodType type = MethodType.make(ret, params);
409 MethodHandle target = null;
410 RuntimeException noAccess = null;
411 try {
412 target = lookup.findVirtual(defc, methodName, type);
413 } catch (NoAccessException ex) {
414 noAccess = ex;
415 }
416 if (verbosity >= 2)
417 System.out.println("findVirtual "+lookup+": "+defc+"."+name+"/"+type+" => "+target
418 +(noAccess == null ? "" : " !! "+noAccess));
419 if (positive && noAccess != null) throw noAccess;
420 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
421 if (!positive) return; // negative test failed as expected
422 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
423 MethodType typeWithSelf = MethodType.make(ret, paramsWithSelf);
424 MethodType ttype = target.type();
425 ttype = ttype.changeParameterType(0, defc); // FIXME: test this
426 assertEquals(typeWithSelf, ttype);
427 assertTrue(target.toString().contains(methodName)); // rough check
428 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
429 Object[] argsWithSelf = randomArgs(paramsWithSelf);
430 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
431 printCalled(target, name, argsWithSelf);
432 MethodHandles.invoke(target, argsWithSelf);
433 assertCalled(name, argsWithSelf);
434 System.out.print(':');
435 }
436
437 @Test
438 public void testFindSpecial() throws Throwable {
439 if (CAN_SKIP_WORKING) return;
440 startTest("findSpecial");
441 testFindSpecial(Example.class, void.class, "v0");
442 testFindSpecial(Example.class, void.class, "pkg_v0");
443 testFindSpecial(false, PRIVATE, Example.class, void.class, "<init>", int.class);
444 testFindSpecial(false, PRIVATE, Example.class, void.class, "bogus");
445 }
446
447 void testFindSpecial(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
448 testFindSpecial(true, PRIVATE, defc, ret, name, params);
449 testFindSpecial(false, PACKAGE, defc, ret, name, params);
450 testFindSpecial(false, PUBLIC, defc, ret, name, params);
451 }
452 void testFindSpecial(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
453 countTest(positive);
454 MethodType type = MethodType.make(ret, params);
455 MethodHandle target = null;
456 RuntimeException noAccess = null;
457 try {
458 target = lookup.findSpecial(defc, name, type, defc);
459 } catch (NoAccessException ex) {
460 noAccess = ex;
461 }
462 if (verbosity >= 2)
463 System.out.println("findSpecial "+defc+"."+name+"/"+type+" => "+target
464 +(noAccess == null ? "" : " !! "+noAccess));
465 if (positive && noAccess != null) throw noAccess;
466 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
467 if (!positive) return; // negative test failed as expected
468 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
469 MethodType typeWithSelf = MethodType.make(ret, paramsWithSelf);
470 MethodType ttype = target.type();
471 ttype = ttype.changeParameterType(0, defc); // FIXME: test this
472 assertEquals(typeWithSelf, ttype);
473 assertTrue(target.toString().contains(name)); // rough check
474 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
475 Object[] args = randomArgs(paramsWithSelf);
476 printCalled(target, name, args);
477 MethodHandles.invoke(target, args);
478 assertCalled(name, args);
479 System.out.print(':');
480 }
481
482 @Test
483 public void testBind() throws Throwable {
484 if (CAN_SKIP_WORKING) return;
485 startTest("bind");
486 testBind(Example.class, void.class, "v0");
487 testBind(Example.class, void.class, "pkg_v0");
488 testBind(Example.class, void.class, "pri_v0");
489 testBind(Example.class, Object.class, "v1", Object.class);
490 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
491 testBind(Example.class, Object.class, "v2", Object.class, int.class);
492 testBind(Example.class, Object.class, "v2", int.class, Object.class);
493 testBind(Example.class, Object.class, "v2", int.class, int.class);
494 testBind(false, PRIVATE, Example.class, void.class, "bogus");
495 testBind(SubExample.class, void.class, "Sub/v0");
496 testBind(SubExample.class, void.class, "Sub/pkg_v0");
497 testBind(IntExample.Impl.class, void.class, "Int/v0");
498 }
499
500 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
501 for (Object[] ac : accessCases(defc, name)) {
502 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
503 }
504 }
505
506 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
507 countTest(positive);
508 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
509 MethodType type = MethodType.make(ret, params);
510 Object receiver = randomArg(defc);
511 MethodHandle target = null;
512 RuntimeException noAccess = null;
513 try {
514 target = lookup.bind(receiver, methodName, type);
515 } catch (NoAccessException ex) {
516 noAccess = ex;
517 }
518 if (verbosity >= 2)
519 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
520 +(noAccess == null ? "" : " !! "+noAccess));
521 if (positive && noAccess != null) throw noAccess;
522 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
523 if (!positive) return; // negative test failed as expected
524 assertEquals(type, target.type());
525 Object[] args = randomArgs(params);
526 printCalled(target, name, args);
527 MethodHandles.invoke(target, args);
528 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
529 assertCalled(name, argsWithReceiver);
530 System.out.print(':');
531 }
532
533 @Test
534 public void testUnreflect() throws Throwable {
535 if (CAN_SKIP_WORKING) return;
536 startTest("unreflect");
537 testUnreflect(Example.class, true, void.class, "s0");
538 testUnreflect(Example.class, true, void.class, "pkg_s0");
539 testUnreflect(Example.class, true, void.class, "pri_s0");
540
541 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
542 testUnreflect(Example.class, true, Object.class, "s2", int.class);
543 //testUnreflect(Example.class, true, Object.class, "s3", long.class);
544 //testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
545 //testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
546 //testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
547
548 testUnreflect(Example.class, false, void.class, "v0");
549 testUnreflect(Example.class, false, void.class, "pkg_v0");
550 testUnreflect(Example.class, false, void.class, "pri_v0");
551 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
552 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
553 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
554 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
555 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
556 }
557
558 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
559 for (Object[] ac : accessCases(defc, name)) {
560 testUnreflect((Boolean)ac[0], (Lookup)ac[1], defc, isStatic, ret, name, params);
561 }
562 }
563 void testUnreflect(boolean positive, Lookup lookup, Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
564 countTest(positive);
565 MethodType type = MethodType.make(ret, params);
566 Method rmethod = null;
567 MethodHandle target = null;
568 RuntimeException noAccess = null;
569 try {
570 rmethod = defc.getDeclaredMethod(name, params);
571 } catch (NoSuchMethodException ex) {
572 throw new NoAccessException(ex);
573 }
574 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
575 try {
576 target = lookup.unreflect(rmethod);
577 } catch (NoAccessException ex) {
578 noAccess = ex;
579 }
580 if (verbosity >= 2)
581 System.out.println("unreflect "+defc+"."+name+"/"+type+" => "+target
582 +(noAccess == null ? "" : " !! "+noAccess));
583 if (positive && noAccess != null) throw noAccess;
584 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
585 if (!positive) return; // negative test failed as expected
586 Class<?>[] paramsMaybeWithSelf = params;
587 if (!isStatic) {
588 paramsMaybeWithSelf = cat(array(Class[].class, (Class)defc), params);
589 }
590 MethodType typeMaybeWithSelf = MethodType.make(ret, paramsMaybeWithSelf);
591 MethodType ttype = target.type();
592 if (!isStatic)
593 ttype = ttype.changeParameterType(0, defc); // FIXME: test this
594 assertEquals(typeMaybeWithSelf, ttype);
595 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
596 printCalled(target, name, argsMaybeWithSelf);
597 MethodHandles.invoke(target, argsMaybeWithSelf);
598 assertCalled(name, argsMaybeWithSelf);
599 System.out.print(':');
600 }
601
602 @Test @Ignore("unimplemented")
603 public void testUnreflectSpecial() throws Throwable {
604 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
605 startTest("unreflectSpecial");
606 Method m = null;
607 MethodHandle expResult = null;
608 MethodHandle result = lookup.unreflectSpecial(m, Example.class);
609 assertEquals(expResult, result);
610 fail("The test case is a prototype.");
611 }
612
613 @Test @Ignore("unimplemented")
614 public void testUnreflectGetter() throws Throwable {
615 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
616 startTest("unreflectGetter");
617 Field f = null;
618 MethodHandle expResult = null;
619 MethodHandle result = lookup.unreflectGetter(f);
620 assertEquals(expResult, result);
621 fail("The test case is a prototype.");
622 }
623
624 @Test @Ignore("unimplemented")
625 public void testUnreflectSetter() throws Throwable {
626 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
627 startTest("unreflectSetter");
628 Field f = null;
629 MethodHandle expResult = null;
630 MethodHandle result = lookup.unreflectSetter(f);
631 assertEquals(expResult, result);
632 fail("The test case is a prototype.");
633 }
634
635 @Test @Ignore("unimplemented")
636 public void testArrayElementGetter() throws Throwable {
637 startTest("arrayElementGetter");
638 Class<?> arrayClass = null;
639 MethodHandle expResult = null;
640 MethodHandle result = MethodHandles.arrayElementGetter(arrayClass);
641 assertEquals(expResult, result);
642 fail("The test case is a prototype.");
643 }
644
645 @Test @Ignore("unimplemented")
646 public void testArrayElementSetter() throws Throwable {
647 startTest("arrayElementSetter");
648 Class<?> arrayClass = null;
649 MethodHandle expResult = null;
650 MethodHandle result = MethodHandles.arrayElementSetter(arrayClass);
651 assertEquals(expResult, result);
652 fail("The test case is a prototype.");
653 }
654
655 static class Callee {
656 static Object id() { return called("id"); }
657 static Object id(Object x) { return called("id", x); }
658 static Object id(Object x, Object y) { return called("id", x, y); }
659 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
660 static Object id(Object... vx) { return called("id", vx); }
661 static MethodHandle ofType(int n) {
662 return ofType(Object.class, n);
663 }
664 static MethodHandle ofType(Class<?> rtype, int n) {
665 if (n == -1)
666 return ofType(MethodType.make(rtype, Object[].class));
667 return ofType(MethodType.makeGeneric(n).changeReturnType(rtype));
668 }
669 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
670 return ofType(MethodType.make(rtype, ptypes));
671 }
672 static MethodHandle ofType(MethodType type) {
673 Class<?> rtype = type.returnType();
674 String pfx = "";
675 if (rtype != Object.class)
676 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
677 String name = pfx+"id";
678 return PRIVATE.findStatic(Callee.class, name, type);
679 }
680 }
681
682 @Test
683 public void testConvertArguments() throws Throwable {
684 if (CAN_SKIP_WORKING) return;
685 startTest("convertArguments");
686 testConvert(Callee.ofType(1), null, "id", int.class);
687 testConvert(Callee.ofType(1), null, "id", String.class);
688 testConvert(Callee.ofType(1), null, "id", Integer.class);
689 testConvert(Callee.ofType(1), null, "id", short.class);
690 }
691
692 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
693 testConvert(true, id, rtype, name, params);
694 }
695
696 void testConvert(boolean positive, MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
697 countTest(positive);
698 MethodType idType = id.type();
699 if (rtype == null) rtype = idType.returnType();
700 for (int i = 0; i < params.length; i++) {
701 if (params[i] == null) params[i] = idType.parameterType(i);
702 }
703 // simulate the pairwise conversion
704 MethodType newType = MethodType.make(rtype, params);
705 Object[] args = randomArgs(newType.parameterArray());
706 Object[] convArgs = args.clone();
707 for (int i = 0; i < args.length; i++) {
708 Class<?> src = newType.parameterType(i);
709 Class<?> dst = idType.parameterType(i);
710 if (src != dst)
711 convArgs[i] = castToWrapper(convArgs[i], dst);
712 }
713 Object convResult = MethodHandles.invoke(id, convArgs);
714 {
715 Class<?> dst = newType.returnType();
716 Class<?> src = idType.returnType();
717 if (src != dst)
718 convResult = castToWrapper(convResult, dst);
719 }
720 MethodHandle target = null;
721 RuntimeException error = null;
722 try {
723 target = MethodHandles.convertArguments(id, newType);
724 } catch (RuntimeException ex) {
725 error = ex;
726 }
727 if (verbosity >= 2)
728 System.out.println("convert "+id+ " to "+newType+" => "+target
729 +(error == null ? "" : " !! "+error));
730 if (positive && error != null) throw error;
731 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
732 if (!positive) return; // negative test failed as expected
733 assertEquals(newType, target.type());
734 printCalled(target, id.toString(), args);
735 Object result = MethodHandles.invoke(target, args);
736 assertCalled(name, convArgs);
737 assertEquals(convResult, result);
738 System.out.print(':');
739 }
740
741 @Test
742 public void testInsertArguments() throws Throwable {
743 if (CAN_SKIP_WORKING) return;
744 startTest("insertArguments");
745 for (int nargs = 0; nargs <= 4; nargs++) {
746 for (int ins = 0; ins <= 4; ins++) {
747 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
748 for (int pos = 0; pos <= nargs; pos++) {
749 testInsertArguments(nargs, pos, ins);
750 }
751 }
752 }
753 }
754
755 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
756 if (pos != 0 || ins != 1) return; // temp. restriction until MHs.insertArguments
757 countTest();
758 MethodHandle target = ValueConversions.varargsArray(nargs + ins);
759 Object[] args = randomArgs(target.type().parameterArray());
760 List<Object> resList = Arrays.asList(args);
761 List<Object> argsToPass = new ArrayList<Object>(resList);
762 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
763 if (verbosity >= 2)
764 System.out.println("insert: "+argsToInsert+" into "+target);
765 MethodHandle target2 = MethodHandles.insertArgument(target, pos,
766 argsToInsert.get(0));
767 argsToInsert.clear(); // remove from argsToInsert
768 Object res2 = MethodHandles.invoke(target2, argsToPass.toArray());
769 Object res2List = Arrays.asList((Object[])res2);
770 if (verbosity >= 2)
771 System.out.println("result: "+res2List);
772 //if (!resList.equals(res2List))
773 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
774 assertEquals(resList, res2List);
775 }
776
777 private static final String MISSING_ARG = "missingArg";
778 static Object targetIfEquals() {
779 return called("targetIfEquals");
780 }
781 static Object fallbackIfNotEquals() {
782 return called("fallbackIfNotEquals");
783 }
784 static Object targetIfEquals(Object x) {
785 assertEquals(x, MISSING_ARG);
786 return called("targetIfEquals", x);
787 }
788 static Object fallbackIfNotEquals(Object x) {
789 assertFalse(x.toString(), x.equals(MISSING_ARG));
790 return called("fallbackIfNotEquals", x);
791 }
792 static Object targetIfEquals(Object x, Object y) {
793 assertEquals(x, y);
794 return called("targetIfEquals", x, y);
795 }
796 static Object fallbackIfNotEquals(Object x, Object y) {
797 assertFalse(x.toString(), x.equals(y));
798 return called("fallbackIfNotEquals", x, y);
799 }
800 static Object targetIfEquals(Object x, Object y, Object z) {
801 assertEquals(x, y);
802 return called("targetIfEquals", x, y, z);
803 }
804 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
805 assertFalse(x.toString(), x.equals(y));
806 return called("fallbackIfNotEquals", x, y, z);
807 }
808
809}
810// Local abbreviated copy of sun.dyn.util.ValueConversions
811class ValueConversions {
812 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
813 private static final Object[] NO_ARGS_ARRAY = {};
814 private static Object[] makeArray(Object... args) { return args; }
815 private static Object[] array() { return NO_ARGS_ARRAY; }
816 private static Object[] array(Object a0)
817 { return makeArray(a0); }
818 private static Object[] array(Object a0, Object a1)
819 { return makeArray(a0, a1); }
820 private static Object[] array(Object a0, Object a1, Object a2)
821 { return makeArray(a0, a1, a2); }
822 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
823 { return makeArray(a0, a1, a2, a3); }
824 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
825 Object a4)
826 { return makeArray(a0, a1, a2, a3, a4); }
827 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
828 Object a4, Object a5)
829 { return makeArray(a0, a1, a2, a3, a4, a5); }
830 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
831 Object a4, Object a5, Object a6)
832 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
833 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
834 Object a4, Object a5, Object a6, Object a7)
835 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
836 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
837 Object a4, Object a5, Object a6, Object a7,
838 Object a8)
839 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
840 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
841 Object a4, Object a5, Object a6, Object a7,
842 Object a8, Object a9)
843 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
844 static MethodHandle[] makeArrays() {
845 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
846 MethodHandles.Lookup lookup = IMPL_LOOKUP;
847 for (;;) {
848 int nargs = arrays.size();
849 MethodType type = MethodType.makeGeneric(nargs).changeReturnType(Object[].class);
850 String name = "array";
851 MethodHandle array = null;
852 try {
853 array = lookup.findStatic(ValueConversions.class, name, type);
854 } catch (NoAccessException ex) {
855 }
856 if (array == null) break;
857 arrays.add(array);
858 }
859 assert(arrays.size() == 11); // current number of methods
860 return arrays.toArray(new MethodHandle[0]);
861 }
862 static final MethodHandle[] ARRAYS = makeArrays();
863
864 /** Return a method handle that takes the indicated number of Object
865 * arguments and returns an Object array of them, as if for varargs.
866 */
867 public static MethodHandle varargsArray(int nargs) {
868 if (nargs < ARRAYS.length)
869 return ARRAYS[nargs];
870 // else need to spin bytecode or do something else fancy
871 throw new UnsupportedOperationException("NYI");
872 }
873}
874// This guy tests access from outside the same package member, but inside
875// the package itself.
876class PackageSibling {
877 static Lookup lookup() {
878 return MethodHandles.lookup();
879 }
880}
881