blob: 16abfb5cef9e64592f7394e93d43ce2a0fcedc41 [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
jrose2cc9c832010-04-30 23:48:23 -07002 * Copyright 2009-2010 Sun Microsystems, Inc. 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
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
jrose2cc9c832010-04-30 23:48:23 -070029 * @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableInvokeDynamic test.java.dyn.MethodHandlesTest
jrose55220c32009-10-21 23:19:48 -070030 */
31
jrose2cc9c832010-04-30 23:48:23 -070032package test.java.dyn;
jrose55220c32009-10-21 23:19:48 -070033
34import java.dyn.*;
35import java.dyn.MethodHandles.Lookup;
36import 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;
jrose55220c32009-10-21 23:19:48 -070050
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.
jrose2cc9c832010-04-30 23:48:23 -070059 static boolean DO_MORE_CALLS = true;
jrose55220c32009-10-21 23:19:48 -070060
61
62 @Test
63 public void testFirst() throws Throwable {
64 verbosity += 9; try {
65 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070066 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070067 }
68
jrose10f3b682010-01-07 16:16:45 -080069 // current failures
70 @Test @Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
71 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070072 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080073 testSpreadArguments(int.class, 0, 6);
74 }
jrose2cc9c832010-04-30 23:48:23 -070075 @Test @Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080076 public void testFail_2() throws Throwable {
77 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
78 testSpreadArguments(Object.class, 0, 2);
79 }
80 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
81 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070082 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080083 testSpreadArguments(int.class, 1, 2);
84 }
85 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
86 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070087 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080088 testCollectArguments(int.class, 1, 2);
89 }
90 @Test @Ignore("cannot collect leading primitive types")
91 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070092 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080093 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
94 }
95 @Test @Ignore("should not insert arguments beyond MethodHandlePushLimit")
96 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070097 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
98 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -080099 }
jrose55220c32009-10-21 23:19:48 -0700100 static final int MAX_ARG_INCREASE = 3;
101
102 public MethodHandlesTest() {
103 }
104
jrose2cc9c832010-04-30 23:48:23 -0700105 @Before
106 public void checkImplementedPlatform() {
107 boolean platformOK = false;
108 Properties properties = System.getProperties();
109 String vers = properties.getProperty("java.vm.version");
110 String name = properties.getProperty("java.vm.name");
111 String arch = properties.getProperty("os.arch");
112 if ((arch.equals("i386") || arch.equals("amd64") ||
113 arch.equals("sparc") || arch.equals("sparcv9")) &&
114 (name.contains("Client") || name.contains("Server"))
115 ) {
116 platformOK = true;
117 } else {
118 System.err.println("Skipping tests for unsupported platform: "+Arrays.asList(vers, name, arch));
119 }
120 assumeTrue(platformOK);
121 }
122
jrose55220c32009-10-21 23:19:48 -0700123 String testName;
124 int posTests, negTests;
125 @After
126 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700127 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700128 System.out.println();
129 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
130 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrose2cc9c832010-04-30 23:48:23 -0700131 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700132 }
133 }
134 void countTest(boolean positive) {
135 if (positive) ++posTests;
136 else ++negTests;
137 }
138 void countTest() { countTest(true); }
139 void startTest(String name) {
140 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700141 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700142 System.out.println(name);
143 posTests = negTests = 0;
144 testName = name;
145 }
146
147 @BeforeClass
148 public static void setUpClass() throws Exception {
149 calledLog.clear();
150 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700151 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700152 }
153
154 @AfterClass
155 public static void tearDownClass() throws Exception {
156 }
157
158 static List<Object> calledLog = new ArrayList<Object>();
159 static Object logEntry(String name, Object... args) {
160 return Arrays.asList(name, Arrays.asList(args));
161 }
162 static Object called(String name, Object... args) {
163 Object entry = logEntry(name, args);
164 calledLog.add(entry);
165 return entry;
166 }
167 static void assertCalled(String name, Object... args) {
168 Object expected = logEntry(name, args);
169 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700170 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700171 System.out.println("assertCalled "+name+":");
172 System.out.println("expected: "+expected);
173 System.out.println("actual: "+actual);
174 System.out.println("ex. types: "+getClasses(expected));
175 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700176 assertEquals("previous method call", expected, actual);
177 }
178 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700179 if (verbosity >= 3)
180 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700181 }
182
183 static Object castToWrapper(Object value, Class<?> dst) {
184 Object wrap = null;
185 if (value instanceof Number)
186 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
187 if (value instanceof Character)
188 wrap = castToWrapperOrNull((char)(Character)value, dst);
189 if (wrap != null) return wrap;
190 return dst.cast(value);
191 }
192
193 static Object castToWrapperOrNull(long value, Class<?> dst) {
194 if (dst == int.class || dst == Integer.class)
195 return (int)(value);
196 if (dst == long.class || dst == Long.class)
197 return (long)(value);
198 if (dst == char.class || dst == Character.class)
199 return (char)(value);
200 if (dst == short.class || dst == Short.class)
201 return (short)(value);
202 if (dst == float.class || dst == Float.class)
203 return (float)(value);
204 if (dst == double.class || dst == Double.class)
205 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800206 if (dst == byte.class || dst == Byte.class)
207 return (byte)(value);
208 if (dst == boolean.class || dst == boolean.class)
209 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700210 return null;
211 }
212
jrose2cc9c832010-04-30 23:48:23 -0700213 static final int ONE_MILLION = (1000*1000), // first int value
214 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
215 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
216 static long nextArgVal;
217 static long nextArg(boolean moreBits) {
218 long val = nextArgVal++;
219 long sign = -(val & 1); // alternate signs
220 val >>= 1;
221 if (moreBits)
222 // Guarantee some bits in the high word.
223 // In any case keep the decimal representation simple-looking,
224 // with lots of zeroes, so as not to make the printed decimal
225 // strings unnecessarily noisy.
226 val += (val % ONE_MILLION) * TEN_BILLION;
227 return val ^ sign;
228 }
229 static int nextArg() {
230 // Produce a 32-bit result something like ONE_MILLION+(smallint).
231 // Example: 1_000_042.
232 return (int) nextArg(false);
233 }
234 static long nextArg(Class<?> kind) {
235 if (kind == long.class || kind == Long.class ||
236 kind == double.class || kind == Double.class)
237 // produce a 64-bit result something like
238 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
239 // Example: 10_000_420_001_000_042.
240 return nextArg(true);
241 return (long) nextArg();
242 }
243
jrose55220c32009-10-21 23:19:48 -0700244 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700245 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700246 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700247 return wrap;
248 }
249// import sun.dyn.util.Wrapper;
250// Wrapper wrap = Wrapper.forBasicType(dst);
251// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
252// wrap = Wrapper.forWrapperType(dst);
253// if (wrap != Wrapper.OBJECT)
254// return wrap.wrap(nextArg++);
255 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
308 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
309 return changeArgTypes(target, 0, 999, argType);
310 }
311 static MethodHandle changeArgTypes(MethodHandle target,
312 int beg, int end, Class<?> argType) {
313 MethodType targetType = target.type();
314 end = Math.min(end, targetType.parameterCount());
315 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
316 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800317 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose55220c32009-10-21 23:19:48 -0700318 return MethodHandles.convertArguments(target, ttype2);
319 }
320
321 // This lookup is good for all members in and under MethodHandlesTest.
322 static final Lookup PRIVATE = MethodHandles.lookup();
323 // This lookup is good for package-private members but not private ones.
324 static final Lookup PACKAGE = PackageSibling.lookup();
325 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800326 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700327
328 // Subject methods...
329 static class Example implements IntExample {
330 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700331 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700332 protected Example(String name) { this.name = name; }
333 protected Example(int x) { this(); called("protected <init>", this, x); }
334 @Override public String toString() { return name; }
335
336 public void v0() { called("v0", this); }
337 void pkg_v0() { called("pkg_v0", this); }
338 private void pri_v0() { called("pri_v0", this); }
339 public static void s0() { called("s0"); }
340 static void pkg_s0() { called("pkg_s0"); }
341 private static void pri_s0() { called("pri_s0"); }
342
343 public Object v1(Object x) { return called("v1", this, x); }
344 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
345 public Object v2(Object x, int y) { return called("v2", this, x, y); }
346 public Object v2(int x, Object y) { return called("v2", this, x, y); }
347 public Object v2(int x, int y) { return called("v2", this, x, y); }
348 public static Object s1(Object x) { return called("s1", x); }
349 public static Object s2(int x) { return called("s2", x); }
350 public static Object s3(long x) { return called("s3", x); }
351 public static Object s4(int x, int y) { return called("s4", x, y); }
352 public static Object s5(long x, int y) { return called("s5", x, y); }
353 public static Object s6(int x, long y) { return called("s6", x, y); }
354 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700355
356 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700357 }
jrose2cc9c832010-04-30 23:48:23 -0700358 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700359 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700360 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700361 }
362 static class SubExample extends Example {
363 @Override public void v0() { called("Sub/v0", this); }
364 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
365 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700366 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700367 }
368 public static interface IntExample {
369 public void v0();
370 static class Impl implements IntExample {
371 public void v0() { called("Int/v0", this); }
372 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700373 public Impl() { name = "Impl#"+nextArg(); }
374 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700375 }
376 }
377
378 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700379 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
380 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
381 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
382 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700383 };
384
jrose2cc9c832010-04-30 23:48:23 -0700385 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
386 Object[][] cases;
387 if (name.contains("pri_") || isSpecial) {
388 cases = ACCESS_CASES[1]; // PRIVATE only
389 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
390 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800391 } else {
392 assertTrue(name.indexOf('_') < 0);
393 boolean pubc = Modifier.isPublic(defc.getModifiers());
394 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700395 cases = ACCESS_CASES[3]; // all access levels
396 else
397 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800398 }
jrose2cc9c832010-04-30 23:48:23 -0700399 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
400 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
401 return cases;
402 }
403 static Object[][] accessCases(Class<?> defc, String name) {
404 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700405 }
406
407 @Test
408 public void testFindStatic() throws Throwable {
409 if (CAN_SKIP_WORKING) return;
410 startTest("findStatic");
411 testFindStatic(PubExample.class, void.class, "s0");
412 testFindStatic(Example.class, void.class, "s0");
413 testFindStatic(Example.class, void.class, "pkg_s0");
414 testFindStatic(Example.class, void.class, "pri_s0");
415
416 testFindStatic(Example.class, Object.class, "s1", Object.class);
417 testFindStatic(Example.class, Object.class, "s2", int.class);
418 testFindStatic(Example.class, Object.class, "s3", long.class);
419 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
420 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
421 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
422 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
423
424 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
425 }
426
427 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
428 for (Object[] ac : accessCases(defc, name)) {
429 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
430 }
431 }
432 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
433 testFindStatic(true, lookup, defc, ret, name, params);
434 }
435 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
436 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800437 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700438 MethodHandle target = null;
439 RuntimeException noAccess = null;
440 try {
jrose2cc9c832010-04-30 23:48:23 -0700441 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700442 target = lookup.findStatic(defc, name, type);
443 } catch (NoAccessException ex) {
444 noAccess = ex;
445 }
jrose2cc9c832010-04-30 23:48:23 -0700446 if (verbosity >= 3)
447 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700448 +(noAccess == null ? "" : " !! "+noAccess));
449 if (positive && noAccess != null) throw noAccess;
450 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
451 if (!positive) return; // negative test failed as expected
452 assertEquals(type, target.type());
453 assertTrue(target.toString().contains(name)); // rough check
454 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
455 Object[] args = randomArgs(params);
456 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800457 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700458 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700459 if (verbosity >= 1)
460 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700461 }
462
463 @Test
464 public void testFindVirtual() throws Throwable {
465 if (CAN_SKIP_WORKING) return;
466 startTest("findVirtual");
467 testFindVirtual(Example.class, void.class, "v0");
468 testFindVirtual(Example.class, void.class, "pkg_v0");
469 testFindVirtual(Example.class, void.class, "pri_v0");
470 testFindVirtual(Example.class, Object.class, "v1", Object.class);
471 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
472 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
473 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
474 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
475 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
476 // test dispatch
477 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
478 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
479 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
480 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
481 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
482 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
483 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
484 }
485
486 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
487 Class<?> rcvc = defc;
488 testFindVirtual(rcvc, defc, ret, name, params);
489 }
490 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
491 for (Object[] ac : accessCases(defc, name)) {
492 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
493 }
494 }
495 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
496 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
497 }
498 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
499 countTest(positive);
500 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800501 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700502 MethodHandle target = null;
503 RuntimeException noAccess = null;
504 try {
jrose2cc9c832010-04-30 23:48:23 -0700505 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700506 target = lookup.findVirtual(defc, methodName, type);
507 } catch (NoAccessException ex) {
508 noAccess = ex;
509 }
jrose2cc9c832010-04-30 23:48:23 -0700510 if (verbosity >= 3)
511 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700512 +(noAccess == null ? "" : " !! "+noAccess));
513 if (positive && noAccess != null) throw noAccess;
514 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
515 if (!positive) return; // negative test failed as expected
516 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800517 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700518 assertEquals(typeWithSelf, target.type());
jrose55220c32009-10-21 23:19:48 -0700519 assertTrue(target.toString().contains(methodName)); // rough check
520 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
521 Object[] argsWithSelf = randomArgs(paramsWithSelf);
522 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
523 printCalled(target, name, argsWithSelf);
jrose10f3b682010-01-07 16:16:45 -0800524 target.invokeVarargs(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700525 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700526 if (verbosity >= 1)
527 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700528 }
529
530 @Test
531 public void testFindSpecial() throws Throwable {
532 if (CAN_SKIP_WORKING) return;
533 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700534 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
535 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
536 // Do some negative testing:
537 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
538 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
539 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
540 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
541 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "bogus");
542 }
jrose55220c32009-10-21 23:19:48 -0700543 }
544
jrose2cc9c832010-04-30 23:48:23 -0700545 void testFindSpecial(Class<?> specialCaller,
546 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
547 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
548 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
549 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
550 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700551 }
jrose2cc9c832010-04-30 23:48:23 -0700552 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
553 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700554 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800555 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700556 MethodHandle target = null;
557 RuntimeException noAccess = null;
558 try {
jrose2cc9c832010-04-30 23:48:23 -0700559 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
560 target = lookup.findSpecial(defc, name, type, specialCaller);
jrose55220c32009-10-21 23:19:48 -0700561 } catch (NoAccessException ex) {
562 noAccess = ex;
563 }
jrose2cc9c832010-04-30 23:48:23 -0700564 if (verbosity >= 3)
565 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
566 +(target == null ? "" : target.type())
567 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700568 if (positive && noAccess != null) throw noAccess;
569 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
570 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700571 assertEquals(specialCaller, target.type().parameterType(0));
572 assertEquals(type, target.type().dropParameterTypes(0,1));
573 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800574 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700575 assertTrue(target.toString().contains(name)); // rough check
jrose2cc9c832010-04-30 23:48:23 -0700576 if (!DO_MORE_CALLS && lookup != PRIVATE && lookup != EXAMPLE) return;
jrose55220c32009-10-21 23:19:48 -0700577 Object[] args = randomArgs(paramsWithSelf);
578 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800579 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700580 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700581 }
582
583 @Test
584 public void testBind() throws Throwable {
585 if (CAN_SKIP_WORKING) return;
586 startTest("bind");
587 testBind(Example.class, void.class, "v0");
588 testBind(Example.class, void.class, "pkg_v0");
589 testBind(Example.class, void.class, "pri_v0");
590 testBind(Example.class, Object.class, "v1", Object.class);
591 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
592 testBind(Example.class, Object.class, "v2", Object.class, int.class);
593 testBind(Example.class, Object.class, "v2", int.class, Object.class);
594 testBind(Example.class, Object.class, "v2", int.class, int.class);
595 testBind(false, PRIVATE, Example.class, void.class, "bogus");
596 testBind(SubExample.class, void.class, "Sub/v0");
597 testBind(SubExample.class, void.class, "Sub/pkg_v0");
598 testBind(IntExample.Impl.class, void.class, "Int/v0");
599 }
600
601 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
602 for (Object[] ac : accessCases(defc, name)) {
603 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
604 }
605 }
606
607 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
608 countTest(positive);
609 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800610 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700611 Object receiver = randomArg(defc);
612 MethodHandle target = null;
613 RuntimeException noAccess = null;
614 try {
jrose2cc9c832010-04-30 23:48:23 -0700615 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700616 target = lookup.bind(receiver, methodName, type);
617 } catch (NoAccessException ex) {
618 noAccess = ex;
619 }
jrose2cc9c832010-04-30 23:48:23 -0700620 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700621 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
622 +(noAccess == null ? "" : " !! "+noAccess));
623 if (positive && noAccess != null) throw noAccess;
624 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
625 if (!positive) return; // negative test failed as expected
626 assertEquals(type, target.type());
627 Object[] args = randomArgs(params);
628 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800629 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700630 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
631 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700632 if (verbosity >= 1)
633 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700634 }
635
636 @Test
637 public void testUnreflect() throws Throwable {
638 if (CAN_SKIP_WORKING) return;
639 startTest("unreflect");
640 testUnreflect(Example.class, true, void.class, "s0");
641 testUnreflect(Example.class, true, void.class, "pkg_s0");
642 testUnreflect(Example.class, true, void.class, "pri_s0");
643
644 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
645 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700646 testUnreflect(Example.class, true, Object.class, "s3", long.class);
647 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
648 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
649 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700650
651 testUnreflect(Example.class, false, void.class, "v0");
652 testUnreflect(Example.class, false, void.class, "pkg_v0");
653 testUnreflect(Example.class, false, void.class, "pri_v0");
654 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
655 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
656 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
657 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
658 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
659 }
660
661 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
662 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700663 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700664 }
665 }
jrose2cc9c832010-04-30 23:48:23 -0700666 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
667 for (Object[] ac : accessCases(defc, name)) {
668 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
669 }
670 }
671 void testUnreflectMaybeSpecial(Class<?> specialCaller,
672 boolean positive, Lookup lookup,
673 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700674 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800675 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700676 Method rmethod = null;
677 MethodHandle target = null;
678 RuntimeException noAccess = null;
679 try {
680 rmethod = defc.getDeclaredMethod(name, params);
681 } catch (NoSuchMethodException ex) {
682 throw new NoAccessException(ex);
683 }
jrose2cc9c832010-04-30 23:48:23 -0700684 boolean isStatic = (rcvc == null);
685 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700686 try {
jrose2cc9c832010-04-30 23:48:23 -0700687 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
688 if (isSpecial)
689 target = lookup.unreflectSpecial(rmethod, specialCaller);
690 else
691 target = lookup.unreflect(rmethod);
jrose55220c32009-10-21 23:19:48 -0700692 } catch (NoAccessException ex) {
693 noAccess = ex;
694 }
jrose2cc9c832010-04-30 23:48:23 -0700695 if (verbosity >= 3)
696 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
697 +(!isSpecial ? "" : " specialCaller="+specialCaller)
698 +( isStatic ? "" : " receiver="+rcvc)
699 +" => "+target
700 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700701 if (positive && noAccess != null) throw noAccess;
702 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
703 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700704 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700705 Class<?>[] paramsMaybeWithSelf = params;
706 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700707 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700708 }
jrose10f3b682010-01-07 16:16:45 -0800709 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700710 if (isStatic) {
711 assertEquals(typeMaybeWithSelf, target.type());
712 } else {
jrose2cc9c832010-04-30 23:48:23 -0700713 if (isSpecial)
714 assertEquals(specialCaller, target.type().parameterType(0));
715 else
716 assertEquals(defc, target.type().parameterType(0));
717 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
718 }
jrose55220c32009-10-21 23:19:48 -0700719 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
720 printCalled(target, name, argsMaybeWithSelf);
jrose10f3b682010-01-07 16:16:45 -0800721 target.invokeVarargs(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700722 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700723 if (verbosity >= 1)
724 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700725 }
726
jrose2cc9c832010-04-30 23:48:23 -0700727 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
728 for (Object[] ac : accessCases(defc, name, true)) {
729 Class<?> specialCaller = rcvc;
730 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
731 }
732 }
733
734 @Test
jrose55220c32009-10-21 23:19:48 -0700735 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700736 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700737 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700738 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
739 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
740 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
741 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
742 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
743 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
744 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700745 }
746
jrose10f3b682010-01-07 16:16:45 -0800747 public static class HasFields {
748 boolean fZ = false;
749 byte fB = (byte)'B';
750 short fS = (short)'S';
751 char fC = 'C';
752 int fI = 'I';
753 long fJ = 'J';
754 float fF = 'F';
755 double fD = 'D';
756 static boolean sZ = true;
757 static byte sB = 1+(byte)'B';
758 static short sS = 1+(short)'S';
759 static char sC = 1+'C';
760 static int sI = 1+'I';
761 static long sJ = 1+'J';
762 static float sF = 1+'F';
763 static double sD = 1+'D';
764
765 Object fL = 'L';
766 String fR = "R";
767 static Object sL = 'M';
768 static String sR = "S";
769
770 static final Object[][] CASES;
771 static {
772 ArrayList<Object[]> cases = new ArrayList<Object[]>();
773 Object types[][] = {
774 {'L',Object.class}, {'R',String.class},
775 {'I',int.class}, {'J',long.class},
776 {'F',float.class}, {'D',double.class},
777 {'Z',boolean.class}, {'B',byte.class},
778 {'S',short.class}, {'C',char.class},
779 };
780 HasFields fields = new HasFields();
781 for (Object[] t : types) {
782 for (int kind = 0; kind <= 1; kind++) {
783 boolean isStatic = (kind != 0);
784 char btc = (Character)t[0];
785 String name = (isStatic ? "s" : "f") + btc;
786 Class<?> type = (Class<?>) t[1];
787 Object value;
788 Field field;
789 try {
790 field = HasFields.class.getDeclaredField(name);
791 } catch (Exception ex) {
792 throw new InternalError("no field HasFields."+name);
793 }
794 try {
795 value = field.get(fields);
796 } catch (Exception ex) {
797 throw new InternalError("cannot fetch field HasFields."+name);
798 }
799 if (type == float.class) {
800 float v = 'F';
801 if (isStatic) v++;
802 assert(value.equals(v));
803 }
804 assert(name.equals(field.getName()));
805 assert(type.equals(field.getType()));
806 assert(isStatic == (Modifier.isStatic(field.getModifiers())));
807 cases.add(new Object[]{ field, value });
808 }
809 }
810 CASES = cases.toArray(new Object[0][]);
811 }
812 }
813
814 @Test
jrose55220c32009-10-21 23:19:48 -0700815 public void testUnreflectGetter() throws Throwable {
816 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
817 startTest("unreflectGetter");
jrose10f3b682010-01-07 16:16:45 -0800818 for (Object[] c : HasFields.CASES) {
819 Field f = (Field)c[0];
820 Object value = c[1];
821 Class<?> type = f.getType();
822 if (type.isPrimitive() && type != int.class)
823 continue; //FIXME
824 testUnreflectGetter(lookup, f, type, value);
825 }
826 }
827 public void testUnreflectGetter(MethodHandles.Lookup lookup,
828 Field f, Class<?> type, Object value) throws Throwable {
829 countTest(true);
830 boolean isStatic = Modifier.isStatic(f.getModifiers());
831 MethodType expType = MethodType.methodType(type, HasFields.class);
832 if (isStatic) expType = expType.dropParameterTypes(0, 1);
833 MethodHandle mh = lookup.unreflectGetter(f);
834 assertSame(mh.type(), expType);
835 assertEquals(mh.toString(), f.getName());
836 HasFields fields = new HasFields();
837 Object sawValue;
838 Class<?> rtype = type;
839 if (type != int.class) rtype = Object.class;
840 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(rtype));
841 Object expValue = value;
842 for (int i = 0; i <= 1; i++) {
843 if (isStatic) {
844 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700845 sawValue = mh.<int>invokeExact(); // do these exactly
jrose10f3b682010-01-07 16:16:45 -0800846 else
jrose2cc9c832010-04-30 23:48:23 -0700847 sawValue = mh.invokeExact();
jrose10f3b682010-01-07 16:16:45 -0800848 } else {
849 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700850 sawValue = mh.<int>invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800851 else
jrose2cc9c832010-04-30 23:48:23 -0700852 sawValue = mh.invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800853 }
854 assertEquals(sawValue, expValue);
855 Object random = randomArg(type);
856 f.set(fields, random);
857 expValue = random;
858 }
859 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -0700860 }
861
jrose10f3b682010-01-07 16:16:45 -0800862
863 @Test
jrose55220c32009-10-21 23:19:48 -0700864 public void testUnreflectSetter() throws Throwable {
865 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
866 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -0800867 for (Object[] c : HasFields.CASES) {
868 Field f = (Field)c[0];
869 Object value = c[1];
870 Class<?> type = f.getType();
871 if (type.isPrimitive() && type != int.class)
872 continue; //FIXME
873 testUnreflectSetter(lookup, f, type, value);
874 }
875 }
876 public void testUnreflectSetter(MethodHandles.Lookup lookup,
877 Field f, Class<?> type, Object value) throws Throwable {
878 countTest(true);
879 boolean isStatic = Modifier.isStatic(f.getModifiers());
880 MethodType expType = MethodType.methodType(void.class, HasFields.class, type);
881 if (isStatic) expType = expType.dropParameterTypes(0, 1);
882 MethodHandle mh = lookup.unreflectSetter(f);
883 assertSame(mh.type(), expType);
884 assertEquals(mh.toString(), f.getName());
885 HasFields fields = new HasFields();
886 Object sawValue;
887 Class<?> vtype = type;
888 if (type != int.class) vtype = Object.class;
889 int last = mh.type().parameterCount() - 1;
890 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(void.class).changeParameterType(last, vtype));
891 assertEquals(f.get(fields), value); // clean to start with
892 for (int i = 0; i <= 1; i++) {
893 Object putValue = randomArg(type);
894 if (isStatic) {
895 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700896 mh.<void>invokeExact((int)(Integer)putValue); // do these exactly
jrose10f3b682010-01-07 16:16:45 -0800897 else
jrose2cc9c832010-04-30 23:48:23 -0700898 mh.<void>invokeExact(putValue);
jrose10f3b682010-01-07 16:16:45 -0800899 } else {
900 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700901 mh.<void>invokeExact((Object) fields, (int)(Integer)putValue);
jrose10f3b682010-01-07 16:16:45 -0800902 else
jrose2cc9c832010-04-30 23:48:23 -0700903 mh.<void>invokeExact((Object) fields, putValue);
jrose10f3b682010-01-07 16:16:45 -0800904 }
905 assertEquals(f.get(fields), putValue);
906 }
907 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -0700908 }
909
jrose10f3b682010-01-07 16:16:45 -0800910 @Test
jrose55220c32009-10-21 23:19:48 -0700911 public void testArrayElementGetter() throws Throwable {
912 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -0700913 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -0700914 }
915
jrose10f3b682010-01-07 16:16:45 -0800916 @Test
jrose55220c32009-10-21 23:19:48 -0700917 public void testArrayElementSetter() throws Throwable {
918 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -0700919 testArrayElementGetterSetter(true);
920 }
921
922 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
923 testArrayElementGetterSetter(new Object[10], testSetter);
924 testArrayElementGetterSetter(new String[10], testSetter);
925 testArrayElementGetterSetter(new boolean[10], testSetter);
926 testArrayElementGetterSetter(new byte[10], testSetter);
927 testArrayElementGetterSetter(new char[10], testSetter);
928 testArrayElementGetterSetter(new short[10], testSetter);
929 testArrayElementGetterSetter(new int[10], testSetter);
930 testArrayElementGetterSetter(new float[10], testSetter);
931 testArrayElementGetterSetter(new long[10], testSetter);
932 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -0800933 }
934
935 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
936 countTest(true);
jrose2cc9c832010-04-30 23:48:23 -0700937 if (verbosity >= 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -0800938 Class<?> arrayType = array.getClass();
939 Class<?> elemType = arrayType.getComponentType();
940 MethodType expType = !testSetter
941 ? MethodType.methodType(elemType, arrayType, int.class)
942 : MethodType.methodType(void.class, arrayType, int.class, elemType);
943 MethodHandle mh = !testSetter
944 ? MethodHandles.arrayElementGetter(arrayType)
945 : MethodHandles.arrayElementSetter(arrayType);
946 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -0700947 if (elemType != int.class && elemType != boolean.class) {
948 MethodType gtype;
949 if (true) { // FIXME: remove this path (and remove <void> below in the mh.invokes)
950 gtype = mh.type().changeParameterType(0, Object.class);
951 if (testSetter)
952 gtype = gtype.changeParameterType(2, Object.class);
953 else
954 gtype = gtype.changeReturnType(Object.class);
955 } else
956 // FIXME: This simpler path hits a bug in convertArguments => ToGeneric
957 gtype = mh.type().generic().changeParameterType(1, int.class);
958 mh = MethodHandles.convertArguments(mh, gtype);
959 }
jrose10f3b682010-01-07 16:16:45 -0800960 Object sawValue, expValue;
961 List<Object> model = array2list(array);
962 int length = Array.getLength(array);
963 for (int i = 0; i < length; i++) {
964 // update array element
965 Object random = randomArg(elemType);
966 model.set(i, random);
967 if (testSetter) {
968 if (elemType == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700969 mh.<void>invokeExact((int[]) array, i, (int)(Integer)random);
970 else if (elemType == boolean.class)
971 mh.<void>invokeExact((boolean[]) array, i, (boolean)(Boolean)random);
jrose10f3b682010-01-07 16:16:45 -0800972 else
jrose2cc9c832010-04-30 23:48:23 -0700973 mh.<void>invokeExact(array, i, random);
jrose10f3b682010-01-07 16:16:45 -0800974 assertEquals(model, array2list(array));
975 } else {
976 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -0700977 }
978 if (verbosity >= 5) {
979 List<Object> array2list = array2list(array);
980 System.out.println("a["+i+"]="+random+" => "+array2list);
981 if (!array2list.equals(model))
982 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -0800983 }
984 // observe array element
985 sawValue = Array.get(array, i);
986 if (!testSetter) {
987 expValue = sawValue;
988 if (elemType == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700989 sawValue = mh.<int>invokeExact((int[]) array, i);
990 else if (elemType == boolean.class)
991 sawValue = mh.<boolean>invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -0800992 else
jrose2cc9c832010-04-30 23:48:23 -0700993 sawValue = mh.invokeExact(array, i);
jrose10f3b682010-01-07 16:16:45 -0800994 assertEquals(sawValue, expValue);
995 assertEquals(model, array2list(array));
996 }
997 }
998 }
999
1000 List<Object> array2list(Object array) {
1001 int length = Array.getLength(array);
1002 ArrayList<Object> model = new ArrayList<Object>(length);
1003 for (int i = 0; i < length; i++)
1004 model.add(Array.get(array, i));
1005 return model;
jrose55220c32009-10-21 23:19:48 -07001006 }
1007
1008 static class Callee {
1009 static Object id() { return called("id"); }
1010 static Object id(Object x) { return called("id", x); }
1011 static Object id(Object x, Object y) { return called("id", x, y); }
1012 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1013 static Object id(Object... vx) { return called("id", vx); }
1014 static MethodHandle ofType(int n) {
1015 return ofType(Object.class, n);
1016 }
1017 static MethodHandle ofType(Class<?> rtype, int n) {
1018 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001019 return ofType(MethodType.methodType(rtype, Object[].class));
1020 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001021 }
1022 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001023 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001024 }
1025 static MethodHandle ofType(MethodType type) {
1026 Class<?> rtype = type.returnType();
1027 String pfx = "";
1028 if (rtype != Object.class)
1029 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1030 String name = pfx+"id";
1031 return PRIVATE.findStatic(Callee.class, name, type);
1032 }
1033 }
1034
1035 @Test
1036 public void testConvertArguments() throws Throwable {
1037 if (CAN_SKIP_WORKING) return;
1038 startTest("convertArguments");
1039 testConvert(Callee.ofType(1), null, "id", int.class);
1040 testConvert(Callee.ofType(1), null, "id", String.class);
1041 testConvert(Callee.ofType(1), null, "id", Integer.class);
1042 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001043 testConvert(Callee.ofType(1), null, "id", char.class);
1044 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001045 }
1046
1047 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1048 testConvert(true, id, rtype, name, params);
1049 }
1050
1051 void testConvert(boolean positive, MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1052 countTest(positive);
1053 MethodType idType = id.type();
1054 if (rtype == null) rtype = idType.returnType();
1055 for (int i = 0; i < params.length; i++) {
1056 if (params[i] == null) params[i] = idType.parameterType(i);
1057 }
1058 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001059 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001060 Object[] args = randomArgs(newType.parameterArray());
1061 Object[] convArgs = args.clone();
1062 for (int i = 0; i < args.length; i++) {
1063 Class<?> src = newType.parameterType(i);
1064 Class<?> dst = idType.parameterType(i);
1065 if (src != dst)
1066 convArgs[i] = castToWrapper(convArgs[i], dst);
1067 }
jrose10f3b682010-01-07 16:16:45 -08001068 Object convResult = id.invokeVarargs(convArgs);
jrose55220c32009-10-21 23:19:48 -07001069 {
1070 Class<?> dst = newType.returnType();
1071 Class<?> src = idType.returnType();
1072 if (src != dst)
1073 convResult = castToWrapper(convResult, dst);
1074 }
1075 MethodHandle target = null;
1076 RuntimeException error = null;
1077 try {
1078 target = MethodHandles.convertArguments(id, newType);
1079 } catch (RuntimeException ex) {
1080 error = ex;
1081 }
jrose2cc9c832010-04-30 23:48:23 -07001082 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001083 System.out.println("convert "+id+ " to "+newType+" => "+target
1084 +(error == null ? "" : " !! "+error));
1085 if (positive && error != null) throw error;
1086 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1087 if (!positive) return; // negative test failed as expected
1088 assertEquals(newType, target.type());
1089 printCalled(target, id.toString(), args);
jrose10f3b682010-01-07 16:16:45 -08001090 Object result = target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -07001091 assertCalled(name, convArgs);
1092 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001093 if (verbosity >= 1)
1094 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001095 }
1096
1097 @Test
jrose10f3b682010-01-07 16:16:45 -08001098 public void testPermuteArguments() throws Throwable {
1099 if (CAN_SKIP_WORKING) return;
1100 startTest("permuteArguments");
1101 testPermuteArguments(4, Integer.class, 2, String.class, 0);
1102 //testPermuteArguments(6, Integer.class, 0, null, 30);
1103 //testPermuteArguments(4, Integer.class, 1, int.class, 6);
1104 }
1105 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001106 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001107 System.out.println("permuteArguments "+max+"*"+type1.getName()
1108 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1109 +(dilution > 0 ? " with dilution "+dilution : ""));
1110 int t2pos = t2c == 0 ? 0 : 1;
1111 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1112 Class<?>[] types = new Class<?>[inargs];
1113 Arrays.fill(types, type1);
1114 if (t2c != 0) {
1115 // Fill in a middle range with type2:
1116 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1117 }
1118 Object[] args = randomArgs(types);
1119 int numcases = 1;
1120 for (int outargs = 0; outargs <= max; outargs++) {
1121 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
1122 int[] reorder = new int[outargs];
1123 int casStep = dilution + 1;
1124 // Avoid some common factors:
1125 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1126 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1127 casStep++;
1128 for (int cas = 0; cas < numcases; cas += casStep) {
1129 for (int i = 0, c = cas; i < outargs; i++) {
1130 reorder[i] = c % inargs;
1131 c /= inargs;
1132 }
1133 testPermuteArguments(args, types, reorder);
1134 }
1135 numcases *= inargs;
1136 if (dilution > 10 && outargs >= 4) {
1137 // Do some special patterns, which we probably missed.
1138 // Replication of a single argument or argument pair.
1139 for (int i = 0; i < inargs; i++) {
1140 Arrays.fill(reorder, i);
1141 testPermuteArguments(args, types, reorder);
1142 for (int d = 1; d <= 2; d++) {
1143 if (i + d >= inargs) continue;
1144 for (int j = 1; j < outargs; j += 2)
1145 reorder[j] += 1;
1146 testPermuteArguments(args, types, reorder);
1147 testPermuteArguments(args, types, reverse(reorder));
1148 }
1149 }
1150 // Repetition of a sequence of 3 or more arguments.
1151 for (int i = 1; i < inargs; i++) {
1152 for (int len = 3; len <= inargs; len++) {
1153 for (int j = 0; j < outargs; j++)
1154 reorder[j] = (i + (j % len)) % inargs;
1155 testPermuteArguments(args, types, reorder);
1156 testPermuteArguments(args, types, reverse(reorder));
1157 }
1158 }
1159 }
1160 }
1161 }
1162 }
1163
1164 static int[] reverse(int[] reorder) {
1165 reorder = reorder.clone();
1166 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1167 int j = reorder.length - 1 - i;
1168 int tem = reorder[i];
1169 reorder[i] = reorder[j];
1170 reorder[j] = tem;
1171 }
1172 return reorder;
1173 }
1174
1175 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1176 countTest();
1177 if (args == null && types == null) {
1178 int max = 0;
1179 for (int j : reorder) {
1180 if (max < j) max = j;
1181 }
1182 args = randomArgs(max+1, Integer.class);
1183 }
1184 if (args == null) {
1185 args = randomArgs(types);
1186 }
1187 if (types == null) {
1188 types = new Class<?>[args.length];
1189 for (int i = 0; i < args.length; i++)
1190 types[i] = args[i].getClass();
1191 }
1192 int inargs = args.length, outargs = reorder.length;
1193 assert(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001194 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001195 System.out.println("permuteArguments "+Arrays.toString(reorder));
1196 Object[] permArgs = new Object[outargs];
1197 Class<?>[] permTypes = new Class<?>[outargs];
1198 for (int i = 0; i < outargs; i++) {
1199 permArgs[i] = args[reorder[i]];
1200 permTypes[i] = types[reorder[i]];
1201 }
jrose2cc9c832010-04-30 23:48:23 -07001202 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001203 System.out.println("in args: "+Arrays.asList(args));
1204 System.out.println("out args: "+Arrays.asList(permArgs));
1205 System.out.println("in types: "+Arrays.asList(types));
1206 System.out.println("out types: "+Arrays.asList(permTypes));
1207 }
1208 MethodType inType = MethodType.methodType(Object.class, types);
1209 MethodType outType = MethodType.methodType(Object.class, permTypes);
1210 MethodHandle target = MethodHandles.convertArguments(ValueConversions.varargsList(outargs), outType);
1211 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
1212 Object result = newTarget.invokeVarargs(args);
1213 Object expected = Arrays.asList(permArgs);
1214 assertEquals(expected, result);
1215 }
1216
1217
1218 @Test
1219 public void testSpreadArguments() throws Throwable {
1220 if (CAN_SKIP_WORKING) return;
1221 startTest("spreadArguments");
1222 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001223 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001224 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001225 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001226 for (int nargs = 0; nargs < 10; nargs++) {
1227 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1228 for (int pos = 0; pos < nargs; pos++) {
1229 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001230 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001231 }
1232 }
1233 }
1234 }
1235 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1236 countTest();
1237 MethodHandle target = ValueConversions.varargsArray(nargs);
1238 MethodHandle target2 = changeArgTypes(target, argType);
jrose2cc9c832010-04-30 23:48:23 -07001239 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001240 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1241 Object[] args = randomArgs(target2.type().parameterArray());
1242 // make sure the target does what we think it does:
1243 if (pos == 0 && nargs < 5) {
1244 Object[] check = (Object[]) target.invokeVarargs(args);
1245 assertArrayEquals(args, check);
1246 switch (nargs) {
1247 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001248 check = target.<Object[]>invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001249 assertArrayEquals(args, check);
1250 break;
1251 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001252 check = target.<Object[]>invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001253 assertArrayEquals(args, check);
1254 break;
1255 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001256 check = target.<Object[]>invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001257 assertArrayEquals(args, check);
1258 break;
1259 }
1260 }
1261 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1262 { // modify newParams in place
1263 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
1264 spreadParams.clear(); spreadParams.add(Object[].class);
1265 }
1266 MethodType newType = MethodType.methodType(Object.class, newParams);
1267 MethodHandle result = MethodHandles.spreadArguments(target2, newType);
1268 Object[] returnValue;
1269 if (pos == 0) {
jrose2cc9c832010-04-30 23:48:23 -07001270 returnValue = (Object[]) result.invokeExact(args);
jrose10f3b682010-01-07 16:16:45 -08001271 } else {
1272 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
1273 args1[pos] = Arrays.copyOfRange(args, pos, args.length);
1274 returnValue = (Object[]) result.invokeVarargs(args1);
1275 }
1276 assertArrayEquals(args, returnValue);
1277 }
1278
1279 @Test
1280 public void testCollectArguments() throws Throwable {
1281 if (CAN_SKIP_WORKING) return;
1282 startTest("collectArguments");
1283 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001284 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001285 System.out.println("collectArguments "+argType);
1286 for (int nargs = 0; nargs < 10; nargs++) {
1287 for (int pos = 0; pos < nargs; pos++) {
1288 if (argType == int.class) continue; // FIXME Fail_4
1289 testCollectArguments(argType, pos, nargs);
1290 }
1291 }
1292 }
1293 }
1294 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1295 countTest();
1296 // fake up a MH with the same type as the desired adapter:
1297 MethodHandle fake = ValueConversions.varargsArray(nargs);
1298 fake = changeArgTypes(fake, argType);
1299 MethodType newType = fake.type();
1300 Object[] args = randomArgs(newType.parameterArray());
1301 // here is what should happen:
1302 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1303 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1304 // here is the MH which will witness the collected argument tail:
1305 MethodHandle target = ValueConversions.varargsArray(pos+1);
1306 target = changeArgTypes(target, 0, pos, argType);
1307 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001308 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001309 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
1310 MethodHandle result = MethodHandles.collectArguments(target, newType);
1311 Object[] returnValue = (Object[]) result.invokeVarargs(args);
1312// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1313// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1314// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1315 assertArrayEquals(collectedArgs, returnValue);
1316 }
1317
1318 @Test
jrose55220c32009-10-21 23:19:48 -07001319 public void testInsertArguments() throws Throwable {
1320 if (CAN_SKIP_WORKING) return;
1321 startTest("insertArguments");
1322 for (int nargs = 0; nargs <= 4; nargs++) {
1323 for (int ins = 0; ins <= 4; ins++) {
1324 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1325 for (int pos = 0; pos <= nargs; pos++) {
1326 testInsertArguments(nargs, pos, ins);
1327 }
1328 }
1329 }
1330 }
1331
1332 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001333 countTest();
1334 MethodHandle target = ValueConversions.varargsArray(nargs + ins);
1335 Object[] args = randomArgs(target.type().parameterArray());
1336 List<Object> resList = Arrays.asList(args);
1337 List<Object> argsToPass = new ArrayList<Object>(resList);
1338 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001339 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001340 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001341 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1342 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001343 argsToInsert.clear(); // remove from argsToInsert
jrose10f3b682010-01-07 16:16:45 -08001344 Object res2 = target2.invokeVarargs(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001345 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001346 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001347 System.out.println("result: "+res2List);
1348 //if (!resList.equals(res2List))
1349 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1350 assertEquals(resList, res2List);
1351 }
1352
jrose10f3b682010-01-07 16:16:45 -08001353 @Test
1354 public void testFilterArguments() throws Throwable {
1355 if (CAN_SKIP_WORKING) return;
1356 startTest("filterArguments");
1357 for (int nargs = 1; nargs <= 6; nargs++) {
1358 for (int pos = 0; pos < nargs; pos++) {
1359 testFilterArguments(nargs, pos);
1360 }
1361 }
1362 }
1363
1364 void testFilterArguments(int nargs, int pos) throws Throwable {
1365 countTest();
1366 MethodHandle target = ValueConversions.varargsList(nargs);
1367 MethodHandle filter = ValueConversions.varargsList(1);
1368 filter = MethodHandles.convertArguments(filter, filter.type().generic());
1369 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001370 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001371 System.out.println("filter "+target+" at "+pos+" with "+filter);
1372 MethodHandle[] filters = new MethodHandle[pos*2+1];
1373 filters[pos] = filter;
1374 MethodHandle target2 = MethodHandles.filterArguments(target, filters);
1375 // Simulate expected effect of filter on arglist:
1376 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001377 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001378 List<Object> expected = Arrays.asList(filteredArgs);
1379 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001380 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001381 System.out.println("result: "+result);
1382 if (!expected.equals(result))
1383 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+argsToPass+" => "+result);
1384 assertEquals(expected, result);
1385 }
1386
1387 @Test
1388 public void testFoldArguments() throws Throwable {
1389 if (CAN_SKIP_WORKING) return;
1390 startTest("foldArguments");
1391 for (int nargs = 0; nargs <= 4; nargs++) {
1392 for (int fold = 0; fold <= nargs; fold++) {
1393 for (int pos = 0; pos <= nargs; pos++) {
1394 testFoldArguments(nargs, pos, fold);
1395 }
1396 }
1397 }
1398 }
1399
1400 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1401 if (pos != 0) return; // can fold only at pos=0 for now
1402 countTest();
1403 MethodHandle target = ValueConversions.varargsList(1 + nargs);
1404 MethodHandle combine = ValueConversions.varargsList(fold);
1405 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001406 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001407 System.out.println("fold "+target+" with "+combine);
1408 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1409 // Simulate expected effect of combiner on arglist:
1410 List<Object> expected = new ArrayList<Object>(argsToPass);
1411 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001412 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001413 System.out.println("fold: "+argsToFold+" into "+target2);
1414 Object foldedArgs = combine.invokeVarargs(argsToFold);
1415 argsToFold.add(0, foldedArgs);
1416 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001417 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001418 System.out.println("result: "+result);
1419 if (!expected.equals(result))
1420 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result);
1421 assertEquals(expected, result);
1422 }
1423
1424 @Test
1425 public void testDropArguments() throws Throwable {
1426 if (CAN_SKIP_WORKING) return;
1427 startTest("dropArguments");
1428 for (int nargs = 0; nargs <= 4; nargs++) {
1429 for (int drop = 1; drop <= 4; drop++) {
1430 for (int pos = 0; pos <= nargs; pos++) {
1431 testDropArguments(nargs, pos, drop);
1432 }
1433 }
1434 }
1435 }
1436
1437 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1438 countTest();
1439 MethodHandle target = ValueConversions.varargsArray(nargs);
1440 Object[] args = randomArgs(target.type().parameterArray());
1441 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1442 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1443 List<Object> resList = Arrays.asList(args);
1444 List<Object> argsToDrop = new ArrayList<Object>(resList);
1445 for (int i = drop; i > 0; i--) {
1446 argsToDrop.add(pos, "blort#"+i);
1447 }
1448 Object res2 = target2.invokeVarargs(argsToDrop);
1449 Object res2List = Arrays.asList((Object[])res2);
1450 //if (!resList.equals(res2List))
1451 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1452 assertEquals(resList, res2List);
1453 }
1454
1455 @Test
1456 public void testInvokers() throws Throwable {
1457 if (CAN_SKIP_WORKING) return;
1458 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1459 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1460 Set<MethodType> done = new HashSet<MethodType>();
1461 for (int i = 0; i <= 6; i++) {
1462 MethodType gtype = MethodType.genericMethodType(i);
1463 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1464 for (int j = -1; j < i; j++) {
1465 MethodType type = gtype;
1466 if (j < 0)
1467 type = type.changeReturnType(argType);
1468 else if (argType == void.class)
1469 continue;
1470 else
1471 type = type.changeParameterType(j, argType);
1472 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1473 if (done.add(type))
1474 testInvokers(type);
1475 MethodType vtype = type.changeReturnType(void.class);
1476 if (done.add(vtype))
1477 testInvokers(vtype);
1478 }
1479 }
1480 }
1481 }
1482
1483 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001484 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001485 System.out.println("test invokers for "+type);
1486 int nargs = type.parameterCount();
1487 boolean testRetCode = type.returnType() != void.class;
1488 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1489 MethodType.genericMethodType(0, true));
1490 target = MethodHandles.collectArguments(target, type);
1491 Object[] args = randomArgs(type.parameterArray());
1492 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1493 targetPlusArgs.add(0, target);
1494 int code = (Integer) invokee(args);
1495 Object log = logEntry("invokee", args);
1496 assertEquals(log.hashCode(), code);
1497 assertCalled("invokee", args);
1498 MethodHandle inv;
1499 Object result;
1500 // exact invoker
1501 countTest();
1502 calledLog.clear();
1503 inv = MethodHandles.exactInvoker(type);
1504 result = inv.invokeVarargs(targetPlusArgs);
1505 if (testRetCode) assertEquals(code, result);
1506 assertCalled("invokee", args);
1507 // generic invoker
1508 countTest();
1509 inv = MethodHandles.genericInvoker(type);
1510 if (nargs <= 3) {
1511 calledLog.clear();
1512 switch (nargs) {
1513 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001514 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001515 break;
1516 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001517 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001518 break;
1519 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001520 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001521 break;
1522 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001523 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001524 break;
1525 }
1526 if (testRetCode) assertEquals(code, result);
1527 assertCalled("invokee", args);
1528 }
1529 calledLog.clear();
1530 result = inv.invokeVarargs(targetPlusArgs);
1531 if (testRetCode) assertEquals(code, result);
1532 assertCalled("invokee", args);
1533 // varargs invoker #0
1534 calledLog.clear();
1535 inv = MethodHandles.varargsInvoker(type, 0);
jrose2cc9c832010-04-30 23:48:23 -07001536 result = inv.invokeExact(target, args);
jrose10f3b682010-01-07 16:16:45 -08001537 if (testRetCode) assertEquals(code, result);
1538 assertCalled("invokee", args);
1539 if (nargs >= 1) {
1540 // varargs invoker #1
1541 calledLog.clear();
1542 inv = MethodHandles.varargsInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001543 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001544 if (testRetCode) assertEquals(code, result);
1545 assertCalled("invokee", args);
1546 }
1547 if (nargs >= 2) {
1548 // varargs invoker #2
1549 calledLog.clear();
1550 inv = MethodHandles.varargsInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001551 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001552 if (testRetCode) assertEquals(code, result);
1553 assertCalled("invokee", args);
1554 }
1555 if (nargs >= 3) {
1556 // varargs invoker #3
1557 calledLog.clear();
1558 inv = MethodHandles.varargsInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001559 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001560 if (testRetCode) assertEquals(code, result);
1561 assertCalled("invokee", args);
1562 }
1563 for (int k = 0; k <= nargs; k++) {
1564 // varargs invoker #0..N
1565 countTest();
1566 calledLog.clear();
1567 inv = MethodHandles.varargsInvoker(type, k);
1568 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1569 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1570 Object[] tail = tailList.toArray();
1571 tailList.clear(); tailList.add(tail);
1572 result = inv.invokeVarargs(targetPlusVarArgs);
1573 if (testRetCode) assertEquals(code, result);
1574 assertCalled("invokee", args);
1575 }
1576 // dynamic invoker
1577 countTest();
1578 CallSite site = new CallSite(MethodHandlesTest.class, "foo", type);
1579 inv = MethodHandles.dynamicInvoker(site);
1580 site.setTarget(target);
1581 calledLog.clear();
1582 result = inv.invokeVarargs(args);
1583 if (testRetCode) assertEquals(code, result);
1584 assertCalled("invokee", args);
1585 }
1586
1587 static Object invokee(Object... args) {
1588 return called("invokee", args).hashCode();
1589 }
1590
jrose55220c32009-10-21 23:19:48 -07001591 private static final String MISSING_ARG = "missingArg";
1592 static Object targetIfEquals() {
1593 return called("targetIfEquals");
1594 }
1595 static Object fallbackIfNotEquals() {
1596 return called("fallbackIfNotEquals");
1597 }
1598 static Object targetIfEquals(Object x) {
1599 assertEquals(x, MISSING_ARG);
1600 return called("targetIfEquals", x);
1601 }
1602 static Object fallbackIfNotEquals(Object x) {
1603 assertFalse(x.toString(), x.equals(MISSING_ARG));
1604 return called("fallbackIfNotEquals", x);
1605 }
1606 static Object targetIfEquals(Object x, Object y) {
1607 assertEquals(x, y);
1608 return called("targetIfEquals", x, y);
1609 }
1610 static Object fallbackIfNotEquals(Object x, Object y) {
1611 assertFalse(x.toString(), x.equals(y));
1612 return called("fallbackIfNotEquals", x, y);
1613 }
1614 static Object targetIfEquals(Object x, Object y, Object z) {
1615 assertEquals(x, y);
1616 return called("targetIfEquals", x, y, z);
1617 }
1618 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1619 assertFalse(x.toString(), x.equals(y));
1620 return called("fallbackIfNotEquals", x, y, z);
1621 }
1622
jrose10f3b682010-01-07 16:16:45 -08001623 @Test
1624 public void testGuardWithTest() throws Throwable {
1625 if (CAN_SKIP_WORKING) return;
1626 startTest("guardWithTest");
1627 for (int nargs = 0; nargs <= 3; nargs++) {
1628 if (nargs != 2) continue; // FIXME: test more later
1629 testGuardWithTest(nargs, Object.class);
1630 testGuardWithTest(nargs, String.class);
1631 }
1632 }
1633 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1634 countTest();
1635 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1636 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1637 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1638 while (test.type().parameterCount() < nargs)
1639 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1640 while (test.type().parameterCount() > nargs)
1641 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1642 if (argClass != Object.class) {
1643 test = changeArgTypes(test, argClass);
1644 target = changeArgTypes(target, argClass);
1645 fallback = changeArgTypes(fallback, argClass);
1646 }
1647 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1648 assertEquals(target.type(), mh.type());
1649 Object[][] argLists = {
1650 { },
1651 { "foo" }, { MISSING_ARG },
1652 { "foo", "foo" }, { "foo", "bar" },
1653 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1654 };
1655 for (Object[] argList : argLists) {
1656 if (argList.length != nargs) continue;
1657 boolean equals;
1658 switch (nargs) {
1659 case 0: equals = true; break;
1660 case 1: equals = MISSING_ARG.equals(argList[0]); break;
1661 default: equals = argList[0].equals(argList[1]); break;
1662 }
1663 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07001664 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001665 System.out.println(logEntry(willCall, argList));
1666 Object result = mh.invokeVarargs(argList);
1667 assertCalled(willCall, argList);
1668 }
1669 }
1670
1671 @Test
1672 public void testCatchException() throws Throwable {
1673 if (CAN_SKIP_WORKING) return;
1674 startTest("catchException");
1675 for (int nargs = 2; nargs <= 6; nargs++) {
1676 for (int ti = 0; ti <= 1; ti++) {
1677 boolean throwIt = (ti != 0);
1678 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
1679 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
1680 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
1681 }
1682 }
1683 }
1684
1685 private static <T extends Throwable>
1686 Object throwOrReturn(Object normal, T exception) throws T {
1687 if (exception != null) throw exception;
1688 return normal;
1689 }
1690
1691 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
1692 countTest();
jrose2cc9c832010-04-30 23:48:23 -07001693 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001694 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
1695 Class<? extends Throwable> exType = thrown.getClass();
1696 MethodHandle throwOrReturn
1697 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
1698 MethodType.methodType(Object.class, Object.class, Throwable.class));
1699 MethodHandle thrower = throwOrReturn;
1700 while (thrower.type().parameterCount() < nargs)
1701 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
1702 MethodHandle target = MethodHandles.catchException(thrower,
1703 thrown.getClass(), ValueConversions.varargsList(1+nargs));
1704 assertEquals(thrower.type(), target.type());
1705 //System.out.println("catching with "+target+" : "+throwOrReturn);
1706 Object[] args = randomArgs(nargs, Object.class);
1707 args[1] = (throwIt ? thrown : null);
1708 Object returned = target.invokeVarargs(args);
1709 //System.out.println("return from "+target+" : "+returned);
1710 if (!throwIt) {
1711 assertSame(args[0], returned);
1712 } else {
1713 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
1714 catchArgs.add(0, thrown);
1715 assertEquals(catchArgs, returned);
1716 }
1717 }
1718
1719 @Test
1720 public void testThrowException() throws Throwable {
1721 if (CAN_SKIP_WORKING) return;
1722 startTest("throwException");
1723 testThrowException(int.class, new ClassCastException("testing"));
1724 testThrowException(void.class, new java.io.IOException("testing"));
1725 testThrowException(String.class, new LinkageError("testing"));
1726 }
1727
1728 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
1729 countTest();
1730 Class<? extends Throwable> exType = thrown.getClass();
1731 MethodHandle target = MethodHandles.throwException(returnType, exType);
1732 //System.out.println("throwing with "+target+" : "+thrown);
1733 MethodType expectedType = MethodType.methodType(returnType, exType);
1734 assertEquals(expectedType, target.type());
jrose2cc9c832010-04-30 23:48:23 -07001735 target = MethodHandles.convertArguments(target, target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001736 Throwable caught = null;
1737 try {
jrose2cc9c832010-04-30 23:48:23 -07001738 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08001739 fail("got "+res+" instead of throwing "+thrown);
1740 } catch (Throwable ex) {
1741 if (ex != thrown) {
1742 if (ex instanceof Error) throw (Error)ex;
1743 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
1744 }
1745 caught = ex;
1746 }
1747 assertSame(thrown, caught);
1748 }
1749
1750 @Test
1751 public void testCastFailure() throws Throwable {
1752 if (CAN_SKIP_WORKING) return;
1753 startTest("testCastFailure");
1754 testCastFailure("cast/argument", 11000);
1755 testCastFailure("unbox/argument", 11000);
1756 testCastFailure("cast/return", 11000);
1757 testCastFailure("unbox/return", 11000);
1758 }
1759
1760 static class Surprise extends JavaMethodHandle {
1761 Surprise() { super("value"); }
1762 Object value(Object x) {
1763 trace("value", x);
1764 if (boo != null) return boo;
1765 return x;
1766 }
1767 Object boo;
1768 void boo(Object x) { boo = x; }
1769
1770 static void trace(String x, Object y) {
1771 if (verbosity > 8) System.out.println(x+"="+y);
1772 }
1773 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
1774 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
1775 static int intIdentity(int x) { trace("int.x", x); return x; }
1776 static MethodHandle REF_IDENTITY = PRIVATE.findStatic(
1777 Surprise.class, "refIdentity",
1778 MethodType.methodType(Object.class, Object.class));
1779 static MethodHandle BOX_IDENTITY = PRIVATE.findStatic(
1780 Surprise.class, "boxIdentity",
1781 MethodType.methodType(Integer.class, Integer.class));
1782 static MethodHandle INT_IDENTITY = PRIVATE.findStatic(
1783 Surprise.class, "intIdentity",
1784 MethodType.methodType(int.class, int.class));
1785 }
1786
1787 void testCastFailure(String mode, int okCount) throws Throwable {
1788 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07001789 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08001790 Surprise boo = new Surprise();
1791 MethodHandle identity = Surprise.REF_IDENTITY, surprise = boo;
1792 if (mode.endsWith("/return")) {
1793 if (mode.equals("unbox/return")) {
1794 // fail on return to ((Integer)surprise).intValue
1795 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(int.class, Object.class));
1796 identity = MethodHandles.convertArguments(identity, MethodType.methodType(int.class, Object.class));
1797 } else if (mode.equals("cast/return")) {
1798 // fail on return to (Integer)surprise
1799 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(Integer.class, Object.class));
1800 identity = MethodHandles.convertArguments(identity, MethodType.methodType(Integer.class, Object.class));
1801 }
1802 } else if (mode.endsWith("/argument")) {
1803 MethodHandle callee = null;
1804 if (mode.equals("unbox/argument")) {
1805 // fail on handing surprise to int argument
1806 callee = Surprise.INT_IDENTITY;
1807 } else if (mode.equals("cast/argument")) {
1808 // fail on handing surprise to Integer argument
1809 callee = Surprise.BOX_IDENTITY;
1810 }
1811 if (callee != null) {
1812 callee = MethodHandles.convertArguments(callee, MethodType.genericMethodType(1));
1813 surprise = MethodHandles.filterArguments(callee, surprise);
1814 identity = MethodHandles.filterArguments(callee, identity);
1815 }
1816 }
1817 assertNotSame(mode, surprise, boo);
1818 identity = MethodHandles.convertArguments(identity, MethodType.genericMethodType(1));
1819 surprise = MethodHandles.convertArguments(surprise, MethodType.genericMethodType(1));
1820 Object x = 42;
1821 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07001822 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001823 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07001824 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001825 assertEquals(x, z);
1826 }
1827 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07001828 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001829 assertEquals(x, y);
1830 try {
jrose2cc9c832010-04-30 23:48:23 -07001831 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001832 System.out.println("Failed to throw; got z="+z);
1833 assertTrue(false);
1834 } catch (Exception ex) {
jrose10f3b682010-01-07 16:16:45 -08001835 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07001836 System.out.println("caught "+ex);
1837 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08001838 ex.printStackTrace();
1839 assertTrue(ex instanceof ClassCastException
1840 // FIXME: accept only one of the two for any given unit test
1841 || ex instanceof WrongMethodTypeException
1842 );
1843 }
1844 }
1845
jrose45b7a332010-05-03 23:32:47 -07001846 static Example userMethod(Object o, String s, int i) {
1847 called("userMethod", o, s, i);
1848 return null;
1849 }
1850
1851 @Test
1852 public void testUserClassInSignature() throws Throwable {
1853 if (CAN_SKIP_WORKING) return;
1854 startTest("testUserClassInSignature");
1855 Lookup lookup = MethodHandles.lookup();
1856 String name; MethodType mt; MethodHandle mh;
1857 Object[] args;
1858
1859 // Try a static method.
1860 name = "userMethod";
1861 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
1862 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
1863 assertEquals(mt, mh.type());
1864 assertEquals(Example.class, mh.type().returnType());
1865 args = randomArgs(mh.type().parameterArray());
1866 mh.invokeVarargs(args);
1867 assertCalled(name, args);
1868
1869 // Try a virtual method.
1870 name = "v2";
1871 mt = MethodType.methodType(Object.class, Object.class, int.class);
1872 mh = lookup.findVirtual(Example.class, name, mt);
1873 assertEquals(mt, mh.type().dropParameterTypes(0,1));
1874 assertTrue(mh.type().parameterList().contains(Example.class));
1875 args = randomArgs(mh.type().parameterArray());
1876 mh.invokeVarargs(args);
1877 assertCalled(name, args);
1878 }
jrose55220c32009-10-21 23:19:48 -07001879}
1880// Local abbreviated copy of sun.dyn.util.ValueConversions
1881class ValueConversions {
1882 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
1883 private static final Object[] NO_ARGS_ARRAY = {};
1884 private static Object[] makeArray(Object... args) { return args; }
1885 private static Object[] array() { return NO_ARGS_ARRAY; }
1886 private static Object[] array(Object a0)
1887 { return makeArray(a0); }
1888 private static Object[] array(Object a0, Object a1)
1889 { return makeArray(a0, a1); }
1890 private static Object[] array(Object a0, Object a1, Object a2)
1891 { return makeArray(a0, a1, a2); }
1892 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1893 { return makeArray(a0, a1, a2, a3); }
1894 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1895 Object a4)
1896 { return makeArray(a0, a1, a2, a3, a4); }
1897 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1898 Object a4, Object a5)
1899 { return makeArray(a0, a1, a2, a3, a4, a5); }
1900 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1901 Object a4, Object a5, Object a6)
1902 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1903 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1904 Object a4, Object a5, Object a6, Object a7)
1905 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1906 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1907 Object a4, Object a5, Object a6, Object a7,
1908 Object a8)
1909 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1910 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1911 Object a4, Object a5, Object a6, Object a7,
1912 Object a8, Object a9)
1913 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1914 static MethodHandle[] makeArrays() {
1915 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
1916 MethodHandles.Lookup lookup = IMPL_LOOKUP;
1917 for (;;) {
1918 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08001919 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07001920 String name = "array";
1921 MethodHandle array = null;
1922 try {
1923 array = lookup.findStatic(ValueConversions.class, name, type);
1924 } catch (NoAccessException ex) {
1925 }
1926 if (array == null) break;
1927 arrays.add(array);
1928 }
1929 assert(arrays.size() == 11); // current number of methods
1930 return arrays.toArray(new MethodHandle[0]);
1931 }
1932 static final MethodHandle[] ARRAYS = makeArrays();
1933
1934 /** Return a method handle that takes the indicated number of Object
1935 * arguments and returns an Object array of them, as if for varargs.
1936 */
1937 public static MethodHandle varargsArray(int nargs) {
1938 if (nargs < ARRAYS.length)
1939 return ARRAYS[nargs];
1940 // else need to spin bytecode or do something else fancy
jrose2cc9c832010-04-30 23:48:23 -07001941 throw new UnsupportedOperationException("NYI: cannot form a varargs array of length "+nargs);
jrose55220c32009-10-21 23:19:48 -07001942 }
jrose10f3b682010-01-07 16:16:45 -08001943
1944 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
1945 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
1946 private static List<Object> list() { return NO_ARGS_LIST; }
1947 private static List<Object> list(Object a0)
1948 { return makeList(a0); }
1949 private static List<Object> list(Object a0, Object a1)
1950 { return makeList(a0, a1); }
1951 private static List<Object> list(Object a0, Object a1, Object a2)
1952 { return makeList(a0, a1, a2); }
1953 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
1954 { return makeList(a0, a1, a2, a3); }
1955 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1956 Object a4)
1957 { return makeList(a0, a1, a2, a3, a4); }
1958 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1959 Object a4, Object a5)
1960 { return makeList(a0, a1, a2, a3, a4, a5); }
1961 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1962 Object a4, Object a5, Object a6)
1963 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
1964 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1965 Object a4, Object a5, Object a6, Object a7)
1966 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
1967 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1968 Object a4, Object a5, Object a6, Object a7,
1969 Object a8)
1970 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1971 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
1972 Object a4, Object a5, Object a6, Object a7,
1973 Object a8, Object a9)
1974 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1975 static MethodHandle[] makeLists() {
1976 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
1977 MethodHandles.Lookup lookup = IMPL_LOOKUP;
1978 for (;;) {
1979 int nargs = arrays.size();
1980 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
1981 String name = "list";
1982 MethodHandle array = null;
1983 try {
1984 array = lookup.findStatic(ValueConversions.class, name, type);
1985 } catch (NoAccessException ex) {
1986 }
1987 if (array == null) break;
1988 arrays.add(array);
1989 }
1990 assert(arrays.size() == 11); // current number of methods
1991 return arrays.toArray(new MethodHandle[0]);
1992 }
1993 static final MethodHandle[] LISTS = makeLists();
1994
1995 /** Return a method handle that takes the indicated number of Object
1996 * arguments and returns List.
1997 */
1998 public static MethodHandle varargsList(int nargs) {
1999 if (nargs < LISTS.length)
2000 return LISTS[nargs];
2001 // else need to spin bytecode or do something else fancy
2002 throw new UnsupportedOperationException("NYI");
2003 }
jrose55220c32009-10-21 23:19:48 -07002004}
2005// This guy tests access from outside the same package member, but inside
2006// the package itself.
2007class PackageSibling {
2008 static Lookup lookup() {
2009 return MethodHandles.lookup();
2010 }
2011}