blob: 00b48392f96906ea734b98e585b9c79210076557 [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;
jrosecf98d422010-06-08 23:08:56 -070050 static {
51 String vstr = System.getProperty("test.java.dyn.MethodHandlesTest.verbosity");
52 if (vstr != null) verbosity = Integer.parseInt(vstr);
53 }
jrose55220c32009-10-21 23:19:48 -070054
55 // Set this true during development if you want to fast-forward to
56 // a particular new, non-working test. Tests which are known to
57 // work (or have recently worked) test this flag and return on true.
58 static boolean CAN_SKIP_WORKING = false;
59 //static { CAN_SKIP_WORKING = true; }
60
61 // Set true to test more calls. If false, some tests are just
62 // lookups, without exercising the actual method handle.
jrose2cc9c832010-04-30 23:48:23 -070063 static boolean DO_MORE_CALLS = true;
jrose55220c32009-10-21 23:19:48 -070064
65
66 @Test
67 public void testFirst() throws Throwable {
68 verbosity += 9; try {
69 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070070 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070071 }
72
jrose10f3b682010-01-07 16:16:45 -080073 // current failures
74 @Test @Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
75 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070076 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080077 testSpreadArguments(int.class, 0, 6);
78 }
jrose2cc9c832010-04-30 23:48:23 -070079 @Test @Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080080 public void testFail_2() throws Throwable {
81 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
82 testSpreadArguments(Object.class, 0, 2);
83 }
84 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
85 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070086 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080087 testSpreadArguments(int.class, 1, 2);
88 }
89 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
90 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070091 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080092 testCollectArguments(int.class, 1, 2);
93 }
94 @Test @Ignore("cannot collect leading primitive types")
95 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070096 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080097 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
98 }
99 @Test @Ignore("should not insert arguments beyond MethodHandlePushLimit")
100 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700101 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
102 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800103 }
jrose55220c32009-10-21 23:19:48 -0700104 static final int MAX_ARG_INCREASE = 3;
105
106 public MethodHandlesTest() {
107 }
108
jrose2cc9c832010-04-30 23:48:23 -0700109 @Before
110 public void checkImplementedPlatform() {
111 boolean platformOK = false;
112 Properties properties = System.getProperties();
113 String vers = properties.getProperty("java.vm.version");
114 String name = properties.getProperty("java.vm.name");
115 String arch = properties.getProperty("os.arch");
jrosecf98d422010-06-08 23:08:56 -0700116 if ((arch.equals("amd64") || arch.equals("i386") || arch.equals("x86") ||
jrose2cc9c832010-04-30 23:48:23 -0700117 arch.equals("sparc") || arch.equals("sparcv9")) &&
118 (name.contains("Client") || name.contains("Server"))
119 ) {
120 platformOK = true;
121 } else {
122 System.err.println("Skipping tests for unsupported platform: "+Arrays.asList(vers, name, arch));
123 }
124 assumeTrue(platformOK);
125 }
126
jrose55220c32009-10-21 23:19:48 -0700127 String testName;
jrosecf98d422010-06-08 23:08:56 -0700128 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700129 int posTests, negTests;
130 @After
131 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700132 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700133 System.out.println();
134 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
135 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700136 allPosTests += posTests;
137 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700138 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700139 }
140 }
141 void countTest(boolean positive) {
142 if (positive) ++posTests;
143 else ++negTests;
144 }
145 void countTest() { countTest(true); }
146 void startTest(String name) {
147 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700148 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700149 System.out.println(name);
150 posTests = negTests = 0;
151 testName = name;
152 }
153
154 @BeforeClass
155 public static void setUpClass() throws Exception {
156 calledLog.clear();
157 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700158 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700159 }
160
161 @AfterClass
162 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700163 int posTests = allPosTests, negTests = allNegTests;
164 if (verbosity >= 2 && (posTests | negTests) != 0) {
165 System.out.println();
166 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
167 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
168 }
jrose55220c32009-10-21 23:19:48 -0700169 }
170
171 static List<Object> calledLog = new ArrayList<Object>();
172 static Object logEntry(String name, Object... args) {
173 return Arrays.asList(name, Arrays.asList(args));
174 }
175 static Object called(String name, Object... args) {
176 Object entry = logEntry(name, args);
177 calledLog.add(entry);
178 return entry;
179 }
180 static void assertCalled(String name, Object... args) {
181 Object expected = logEntry(name, args);
182 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700183 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700184 System.out.println("assertCalled "+name+":");
185 System.out.println("expected: "+expected);
186 System.out.println("actual: "+actual);
187 System.out.println("ex. types: "+getClasses(expected));
188 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700189 assertEquals("previous method call", expected, actual);
190 }
191 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700192 if (verbosity >= 3)
193 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700194 }
195
196 static Object castToWrapper(Object value, Class<?> dst) {
197 Object wrap = null;
198 if (value instanceof Number)
199 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
200 if (value instanceof Character)
201 wrap = castToWrapperOrNull((char)(Character)value, dst);
202 if (wrap != null) return wrap;
203 return dst.cast(value);
204 }
205
206 static Object castToWrapperOrNull(long value, Class<?> dst) {
207 if (dst == int.class || dst == Integer.class)
208 return (int)(value);
209 if (dst == long.class || dst == Long.class)
210 return (long)(value);
211 if (dst == char.class || dst == Character.class)
212 return (char)(value);
213 if (dst == short.class || dst == Short.class)
214 return (short)(value);
215 if (dst == float.class || dst == Float.class)
216 return (float)(value);
217 if (dst == double.class || dst == Double.class)
218 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800219 if (dst == byte.class || dst == Byte.class)
220 return (byte)(value);
221 if (dst == boolean.class || dst == boolean.class)
222 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700223 return null;
224 }
225
jrose2cc9c832010-04-30 23:48:23 -0700226 static final int ONE_MILLION = (1000*1000), // first int value
227 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
228 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
229 static long nextArgVal;
230 static long nextArg(boolean moreBits) {
231 long val = nextArgVal++;
232 long sign = -(val & 1); // alternate signs
233 val >>= 1;
234 if (moreBits)
235 // Guarantee some bits in the high word.
236 // In any case keep the decimal representation simple-looking,
237 // with lots of zeroes, so as not to make the printed decimal
238 // strings unnecessarily noisy.
239 val += (val % ONE_MILLION) * TEN_BILLION;
240 return val ^ sign;
241 }
242 static int nextArg() {
243 // Produce a 32-bit result something like ONE_MILLION+(smallint).
244 // Example: 1_000_042.
245 return (int) nextArg(false);
246 }
247 static long nextArg(Class<?> kind) {
248 if (kind == long.class || kind == Long.class ||
249 kind == double.class || kind == Double.class)
250 // produce a 64-bit result something like
251 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
252 // Example: 10_000_420_001_000_042.
253 return nextArg(true);
254 return (long) nextArg();
255 }
256
jrose55220c32009-10-21 23:19:48 -0700257 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700258 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700259 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700260 return wrap;
261 }
262// import sun.dyn.util.Wrapper;
263// Wrapper wrap = Wrapper.forBasicType(dst);
264// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
265// wrap = Wrapper.forWrapperType(dst);
266// if (wrap != Wrapper.OBJECT)
267// return wrap.wrap(nextArg++);
268 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700269 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700270 else
271 try {
272 return param.newInstance();
273 } catch (InstantiationException ex) {
274 } catch (IllegalAccessException ex) {
275 }
276 return null; // random class not Object, String, Integer, etc.
277 }
278 static Object[] randomArgs(Class<?>... params) {
279 Object[] args = new Object[params.length];
280 for (int i = 0; i < args.length; i++)
281 args[i] = randomArg(params[i]);
282 return args;
283 }
284 static Object[] randomArgs(int nargs, Class<?> param) {
285 Object[] args = new Object[nargs];
286 for (int i = 0; i < args.length; i++)
287 args[i] = randomArg(param);
288 return args;
289 }
290
291 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
292 return Arrays.copyOf(a, a.length, atype);
293 }
294 static <T> T[] cat(T[] a, T... b) {
295 int alen = a.length, blen = b.length;
296 if (blen == 0) return a;
297 T[] c = Arrays.copyOf(a, alen + blen);
298 System.arraycopy(b, 0, c, alen, blen);
299 return c;
300 }
301 static Integer[] boxAll(int... vx) {
302 Integer[] res = new Integer[vx.length];
303 for (int i = 0; i < res.length; i++) {
304 res[i] = vx[i];
305 }
306 return res;
307 }
308 static Object getClasses(Object x) {
309 if (x == null) return x;
310 if (x instanceof String) return x; // keep the name
311 if (x instanceof List) {
312 // recursively report classes of the list elements
313 Object[] xa = ((List)x).toArray();
314 for (int i = 0; i < xa.length; i++)
315 xa[i] = getClasses(xa[i]);
316 return Arrays.asList(xa);
317 }
318 return x.getClass().getSimpleName();
319 }
320
321 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
322 return changeArgTypes(target, 0, 999, argType);
323 }
324 static MethodHandle changeArgTypes(MethodHandle target,
325 int beg, int end, Class<?> argType) {
326 MethodType targetType = target.type();
327 end = Math.min(end, targetType.parameterCount());
328 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
329 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800330 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose55220c32009-10-21 23:19:48 -0700331 return MethodHandles.convertArguments(target, ttype2);
332 }
333
334 // This lookup is good for all members in and under MethodHandlesTest.
335 static final Lookup PRIVATE = MethodHandles.lookup();
336 // This lookup is good for package-private members but not private ones.
337 static final Lookup PACKAGE = PackageSibling.lookup();
338 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800339 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700340
341 // Subject methods...
342 static class Example implements IntExample {
343 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700344 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700345 protected Example(String name) { this.name = name; }
346 protected Example(int x) { this(); called("protected <init>", this, x); }
347 @Override public String toString() { return name; }
348
349 public void v0() { called("v0", this); }
350 void pkg_v0() { called("pkg_v0", this); }
351 private void pri_v0() { called("pri_v0", this); }
352 public static void s0() { called("s0"); }
353 static void pkg_s0() { called("pkg_s0"); }
354 private static void pri_s0() { called("pri_s0"); }
355
356 public Object v1(Object x) { return called("v1", this, x); }
357 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
358 public Object v2(Object x, int y) { return called("v2", this, x, y); }
359 public Object v2(int x, Object y) { return called("v2", this, x, y); }
360 public Object v2(int x, int y) { return called("v2", this, x, y); }
361 public static Object s1(Object x) { return called("s1", x); }
362 public static Object s2(int x) { return called("s2", x); }
363 public static Object s3(long x) { return called("s3", x); }
364 public static Object s4(int x, int y) { return called("s4", x, y); }
365 public static Object s5(long x, int y) { return called("s5", x, y); }
366 public static Object s6(int x, long y) { return called("s6", x, y); }
367 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700368
369 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700370 }
jrose2cc9c832010-04-30 23:48:23 -0700371 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700372 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700373 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700374 }
375 static class SubExample extends Example {
376 @Override public void v0() { called("Sub/v0", this); }
377 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
378 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700379 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700380 }
381 public static interface IntExample {
382 public void v0();
383 static class Impl implements IntExample {
384 public void v0() { called("Int/v0", this); }
385 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700386 public Impl() { name = "Impl#"+nextArg(); }
387 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700388 }
389 }
390
391 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700392 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
393 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
394 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
395 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700396 };
397
jrose2cc9c832010-04-30 23:48:23 -0700398 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
399 Object[][] cases;
400 if (name.contains("pri_") || isSpecial) {
401 cases = ACCESS_CASES[1]; // PRIVATE only
402 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
403 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800404 } else {
405 assertTrue(name.indexOf('_') < 0);
406 boolean pubc = Modifier.isPublic(defc.getModifiers());
407 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700408 cases = ACCESS_CASES[3]; // all access levels
409 else
410 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800411 }
jrose2cc9c832010-04-30 23:48:23 -0700412 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
413 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
414 return cases;
415 }
416 static Object[][] accessCases(Class<?> defc, String name) {
417 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700418 }
419
420 @Test
421 public void testFindStatic() throws Throwable {
422 if (CAN_SKIP_WORKING) return;
423 startTest("findStatic");
424 testFindStatic(PubExample.class, void.class, "s0");
425 testFindStatic(Example.class, void.class, "s0");
426 testFindStatic(Example.class, void.class, "pkg_s0");
427 testFindStatic(Example.class, void.class, "pri_s0");
428
429 testFindStatic(Example.class, Object.class, "s1", Object.class);
430 testFindStatic(Example.class, Object.class, "s2", int.class);
431 testFindStatic(Example.class, Object.class, "s3", long.class);
432 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
433 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
434 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
435 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
436
437 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
438 }
439
440 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
441 for (Object[] ac : accessCases(defc, name)) {
442 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
443 }
444 }
445 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
446 testFindStatic(true, lookup, defc, ret, name, params);
447 }
448 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
449 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800450 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700451 MethodHandle target = null;
452 RuntimeException noAccess = null;
453 try {
jrose2cc9c832010-04-30 23:48:23 -0700454 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700455 target = lookup.findStatic(defc, name, type);
456 } catch (NoAccessException ex) {
457 noAccess = ex;
458 }
jrose2cc9c832010-04-30 23:48:23 -0700459 if (verbosity >= 3)
460 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700461 +(noAccess == null ? "" : " !! "+noAccess));
462 if (positive && noAccess != null) throw noAccess;
463 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
464 if (!positive) return; // negative test failed as expected
465 assertEquals(type, target.type());
466 assertTrue(target.toString().contains(name)); // rough check
467 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
468 Object[] args = randomArgs(params);
469 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800470 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700471 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700472 if (verbosity >= 1)
473 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700474 }
475
476 @Test
477 public void testFindVirtual() throws Throwable {
478 if (CAN_SKIP_WORKING) return;
479 startTest("findVirtual");
480 testFindVirtual(Example.class, void.class, "v0");
481 testFindVirtual(Example.class, void.class, "pkg_v0");
482 testFindVirtual(Example.class, void.class, "pri_v0");
483 testFindVirtual(Example.class, Object.class, "v1", Object.class);
484 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
485 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
486 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
487 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
488 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
489 // test dispatch
490 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
491 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
492 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
493 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
494 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
495 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
496 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
497 }
498
499 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
500 Class<?> rcvc = defc;
501 testFindVirtual(rcvc, defc, ret, name, params);
502 }
503 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
504 for (Object[] ac : accessCases(defc, name)) {
505 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
506 }
507 }
508 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
509 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
510 }
511 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
512 countTest(positive);
513 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800514 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700515 MethodHandle target = null;
516 RuntimeException noAccess = null;
517 try {
jrose2cc9c832010-04-30 23:48:23 -0700518 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700519 target = lookup.findVirtual(defc, methodName, type);
520 } catch (NoAccessException ex) {
521 noAccess = ex;
522 }
jrose2cc9c832010-04-30 23:48:23 -0700523 if (verbosity >= 3)
524 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700525 +(noAccess == null ? "" : " !! "+noAccess));
526 if (positive && noAccess != null) throw noAccess;
527 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
528 if (!positive) return; // negative test failed as expected
529 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800530 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700531 assertEquals(typeWithSelf, target.type());
jrose55220c32009-10-21 23:19:48 -0700532 assertTrue(target.toString().contains(methodName)); // rough check
533 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
534 Object[] argsWithSelf = randomArgs(paramsWithSelf);
535 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
536 printCalled(target, name, argsWithSelf);
jrose10f3b682010-01-07 16:16:45 -0800537 target.invokeVarargs(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700538 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700539 if (verbosity >= 1)
540 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700541 }
542
543 @Test
544 public void testFindSpecial() throws Throwable {
545 if (CAN_SKIP_WORKING) return;
546 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700547 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
548 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
549 // Do some negative testing:
550 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
551 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
552 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
553 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
554 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "bogus");
555 }
jrose55220c32009-10-21 23:19:48 -0700556 }
557
jrose2cc9c832010-04-30 23:48:23 -0700558 void testFindSpecial(Class<?> specialCaller,
559 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
560 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
561 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
562 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
563 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700564 }
jrose2cc9c832010-04-30 23:48:23 -0700565 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
566 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700567 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800568 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700569 MethodHandle target = null;
570 RuntimeException noAccess = null;
571 try {
jrose2cc9c832010-04-30 23:48:23 -0700572 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
573 target = lookup.findSpecial(defc, name, type, specialCaller);
jrose55220c32009-10-21 23:19:48 -0700574 } catch (NoAccessException ex) {
575 noAccess = ex;
576 }
jrose2cc9c832010-04-30 23:48:23 -0700577 if (verbosity >= 3)
578 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
579 +(target == null ? "" : target.type())
580 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700581 if (positive && noAccess != null) throw noAccess;
582 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
583 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700584 assertEquals(specialCaller, target.type().parameterType(0));
585 assertEquals(type, target.type().dropParameterTypes(0,1));
586 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800587 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700588 assertTrue(target.toString().contains(name)); // rough check
jrose2cc9c832010-04-30 23:48:23 -0700589 if (!DO_MORE_CALLS && lookup != PRIVATE && lookup != EXAMPLE) return;
jrose55220c32009-10-21 23:19:48 -0700590 Object[] args = randomArgs(paramsWithSelf);
591 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800592 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700593 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700594 }
595
596 @Test
597 public void testBind() throws Throwable {
598 if (CAN_SKIP_WORKING) return;
599 startTest("bind");
600 testBind(Example.class, void.class, "v0");
601 testBind(Example.class, void.class, "pkg_v0");
602 testBind(Example.class, void.class, "pri_v0");
603 testBind(Example.class, Object.class, "v1", Object.class);
604 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
605 testBind(Example.class, Object.class, "v2", Object.class, int.class);
606 testBind(Example.class, Object.class, "v2", int.class, Object.class);
607 testBind(Example.class, Object.class, "v2", int.class, int.class);
608 testBind(false, PRIVATE, Example.class, void.class, "bogus");
609 testBind(SubExample.class, void.class, "Sub/v0");
610 testBind(SubExample.class, void.class, "Sub/pkg_v0");
611 testBind(IntExample.Impl.class, void.class, "Int/v0");
612 }
613
614 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
615 for (Object[] ac : accessCases(defc, name)) {
616 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
617 }
618 }
619
620 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
621 countTest(positive);
622 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800623 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700624 Object receiver = randomArg(defc);
625 MethodHandle target = null;
626 RuntimeException noAccess = null;
627 try {
jrose2cc9c832010-04-30 23:48:23 -0700628 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose55220c32009-10-21 23:19:48 -0700629 target = lookup.bind(receiver, methodName, type);
630 } catch (NoAccessException ex) {
631 noAccess = ex;
632 }
jrose2cc9c832010-04-30 23:48:23 -0700633 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700634 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
635 +(noAccess == null ? "" : " !! "+noAccess));
636 if (positive && noAccess != null) throw noAccess;
637 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
638 if (!positive) return; // negative test failed as expected
639 assertEquals(type, target.type());
640 Object[] args = randomArgs(params);
641 printCalled(target, name, args);
jrose10f3b682010-01-07 16:16:45 -0800642 target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -0700643 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
644 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700645 if (verbosity >= 1)
646 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700647 }
648
649 @Test
650 public void testUnreflect() throws Throwable {
651 if (CAN_SKIP_WORKING) return;
652 startTest("unreflect");
653 testUnreflect(Example.class, true, void.class, "s0");
654 testUnreflect(Example.class, true, void.class, "pkg_s0");
655 testUnreflect(Example.class, true, void.class, "pri_s0");
656
657 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
658 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700659 testUnreflect(Example.class, true, Object.class, "s3", long.class);
660 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
661 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
662 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700663
664 testUnreflect(Example.class, false, void.class, "v0");
665 testUnreflect(Example.class, false, void.class, "pkg_v0");
666 testUnreflect(Example.class, false, void.class, "pri_v0");
667 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
668 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
669 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
670 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
671 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
672 }
673
674 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
675 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700676 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700677 }
678 }
jrose2cc9c832010-04-30 23:48:23 -0700679 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
680 for (Object[] ac : accessCases(defc, name)) {
681 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
682 }
683 }
684 void testUnreflectMaybeSpecial(Class<?> specialCaller,
685 boolean positive, Lookup lookup,
686 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700687 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800688 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700689 Method rmethod = null;
690 MethodHandle target = null;
691 RuntimeException noAccess = null;
692 try {
693 rmethod = defc.getDeclaredMethod(name, params);
694 } catch (NoSuchMethodException ex) {
695 throw new NoAccessException(ex);
696 }
jrose2cc9c832010-04-30 23:48:23 -0700697 boolean isStatic = (rcvc == null);
698 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700699 try {
jrose2cc9c832010-04-30 23:48:23 -0700700 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
701 if (isSpecial)
702 target = lookup.unreflectSpecial(rmethod, specialCaller);
703 else
704 target = lookup.unreflect(rmethod);
jrose55220c32009-10-21 23:19:48 -0700705 } catch (NoAccessException ex) {
706 noAccess = ex;
707 }
jrose2cc9c832010-04-30 23:48:23 -0700708 if (verbosity >= 3)
709 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
710 +(!isSpecial ? "" : " specialCaller="+specialCaller)
711 +( isStatic ? "" : " receiver="+rcvc)
712 +" => "+target
713 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700714 if (positive && noAccess != null) throw noAccess;
715 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
716 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700717 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700718 Class<?>[] paramsMaybeWithSelf = params;
719 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700720 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700721 }
jrose10f3b682010-01-07 16:16:45 -0800722 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700723 if (isStatic) {
724 assertEquals(typeMaybeWithSelf, target.type());
725 } else {
jrose2cc9c832010-04-30 23:48:23 -0700726 if (isSpecial)
727 assertEquals(specialCaller, target.type().parameterType(0));
728 else
729 assertEquals(defc, target.type().parameterType(0));
730 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
731 }
jrose55220c32009-10-21 23:19:48 -0700732 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
733 printCalled(target, name, argsMaybeWithSelf);
jrose10f3b682010-01-07 16:16:45 -0800734 target.invokeVarargs(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700735 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700736 if (verbosity >= 1)
737 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700738 }
739
jrose2cc9c832010-04-30 23:48:23 -0700740 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
741 for (Object[] ac : accessCases(defc, name, true)) {
742 Class<?> specialCaller = rcvc;
743 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
744 }
745 }
746
747 @Test
jrose55220c32009-10-21 23:19:48 -0700748 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700749 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700750 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700751 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
752 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
753 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
754 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
755 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
756 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
757 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700758 }
759
jrose10f3b682010-01-07 16:16:45 -0800760 public static class HasFields {
761 boolean fZ = false;
762 byte fB = (byte)'B';
763 short fS = (short)'S';
764 char fC = 'C';
765 int fI = 'I';
766 long fJ = 'J';
767 float fF = 'F';
768 double fD = 'D';
769 static boolean sZ = true;
770 static byte sB = 1+(byte)'B';
771 static short sS = 1+(short)'S';
772 static char sC = 1+'C';
773 static int sI = 1+'I';
774 static long sJ = 1+'J';
775 static float sF = 1+'F';
776 static double sD = 1+'D';
777
778 Object fL = 'L';
779 String fR = "R";
780 static Object sL = 'M';
781 static String sR = "S";
782
783 static final Object[][] CASES;
784 static {
785 ArrayList<Object[]> cases = new ArrayList<Object[]>();
786 Object types[][] = {
787 {'L',Object.class}, {'R',String.class},
788 {'I',int.class}, {'J',long.class},
789 {'F',float.class}, {'D',double.class},
790 {'Z',boolean.class}, {'B',byte.class},
791 {'S',short.class}, {'C',char.class},
792 };
793 HasFields fields = new HasFields();
794 for (Object[] t : types) {
795 for (int kind = 0; kind <= 1; kind++) {
796 boolean isStatic = (kind != 0);
797 char btc = (Character)t[0];
798 String name = (isStatic ? "s" : "f") + btc;
799 Class<?> type = (Class<?>) t[1];
800 Object value;
801 Field field;
802 try {
803 field = HasFields.class.getDeclaredField(name);
804 } catch (Exception ex) {
805 throw new InternalError("no field HasFields."+name);
806 }
807 try {
808 value = field.get(fields);
809 } catch (Exception ex) {
810 throw new InternalError("cannot fetch field HasFields."+name);
811 }
812 if (type == float.class) {
813 float v = 'F';
814 if (isStatic) v++;
815 assert(value.equals(v));
816 }
817 assert(name.equals(field.getName()));
818 assert(type.equals(field.getType()));
819 assert(isStatic == (Modifier.isStatic(field.getModifiers())));
820 cases.add(new Object[]{ field, value });
821 }
822 }
823 CASES = cases.toArray(new Object[0][]);
824 }
825 }
826
jrosecf98d422010-06-08 23:08:56 -0700827 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC_FIELD = 3;
828 static boolean testModeMatches(int testMode, boolean isStatic) {
829 switch (testMode) {
830 case TEST_FIND_STATIC_FIELD: return isStatic;
831 case TEST_FIND_FIELD: return !isStatic;
832 default: return true; // unreflect matches both
833 }
834 }
835
jrose10f3b682010-01-07 16:16:45 -0800836 @Test
jrose55220c32009-10-21 23:19:48 -0700837 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700838 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700839 testGetter(TEST_UNREFLECT);
840 }
841 @Test
842 public void testFindGetter() throws Throwable {
843 startTest("findGetter");
844 testGetter(TEST_FIND_FIELD);
845 }
846 @Test
847 public void testFindStaticGetter() throws Throwable {
848 startTest("findStaticGetter");
849 testGetter(TEST_FIND_STATIC_FIELD);
850 }
851 public void testGetter(int testMode) throws Throwable {
852 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800853 for (Object[] c : HasFields.CASES) {
854 Field f = (Field)c[0];
855 Object value = c[1];
856 Class<?> type = f.getType();
jrosecf98d422010-06-08 23:08:56 -0700857 testGetter(lookup, f, type, value, testMode);
jrose10f3b682010-01-07 16:16:45 -0800858 }
859 }
jrosecf98d422010-06-08 23:08:56 -0700860 public void testGetter(MethodHandles.Lookup lookup,
861 Field f, Class<?> type, Object value, int testMode) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -0800862 boolean isStatic = Modifier.isStatic(f.getModifiers());
jrosecf98d422010-06-08 23:08:56 -0700863 Class<?> fclass = f.getDeclaringClass();
864 String fname = f.getName();
865 Class<?> ftype = f.getType();
866 if (!testModeMatches(testMode, isStatic)) return;
867 countTest(true);
jrose10f3b682010-01-07 16:16:45 -0800868 MethodType expType = MethodType.methodType(type, HasFields.class);
869 if (isStatic) expType = expType.dropParameterTypes(0, 1);
870 MethodHandle mh = lookup.unreflectGetter(f);
871 assertSame(mh.type(), expType);
jrosecf98d422010-06-08 23:08:56 -0700872 assertEquals(mh.toString(), fname);
jrose10f3b682010-01-07 16:16:45 -0800873 HasFields fields = new HasFields();
874 Object sawValue;
875 Class<?> rtype = type;
876 if (type != int.class) rtype = Object.class;
877 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(rtype));
878 Object expValue = value;
879 for (int i = 0; i <= 1; i++) {
880 if (isStatic) {
881 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700882 sawValue = mh.<int>invokeExact(); // do these exactly
jrose10f3b682010-01-07 16:16:45 -0800883 else
jrose2cc9c832010-04-30 23:48:23 -0700884 sawValue = mh.invokeExact();
jrose10f3b682010-01-07 16:16:45 -0800885 } else {
886 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700887 sawValue = mh.<int>invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800888 else
jrose2cc9c832010-04-30 23:48:23 -0700889 sawValue = mh.invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800890 }
891 assertEquals(sawValue, expValue);
892 Object random = randomArg(type);
893 f.set(fields, random);
894 expValue = random;
895 }
896 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -0700897 }
898
jrose10f3b682010-01-07 16:16:45 -0800899
900 @Test
jrose55220c32009-10-21 23:19:48 -0700901 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -0700902 startTest("unreflectSetter");
903 testSetter(TEST_UNREFLECT);
904 }
905 @Test
906 public void testFindSetter() throws Throwable {
907 startTest("findSetter");
908 testSetter(TEST_FIND_FIELD);
909 }
910 @Test
911 public void testFindStaticSetter() throws Throwable {
912 startTest("findStaticSetter");
913 testSetter(TEST_FIND_STATIC_FIELD);
914 }
915 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700916 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
917 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -0800918 for (Object[] c : HasFields.CASES) {
919 Field f = (Field)c[0];
920 Object value = c[1];
921 Class<?> type = f.getType();
jrosecf98d422010-06-08 23:08:56 -0700922 testSetter(lookup, f, type, value, testMode);
jrose10f3b682010-01-07 16:16:45 -0800923 }
924 }
jrosecf98d422010-06-08 23:08:56 -0700925 public void testSetter(MethodHandles.Lookup lookup,
926 Field f, Class<?> type, Object value, int testMode) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -0800927 boolean isStatic = Modifier.isStatic(f.getModifiers());
jrosecf98d422010-06-08 23:08:56 -0700928 Class<?> fclass = f.getDeclaringClass();
929 String fname = f.getName();
930 Class<?> ftype = f.getType();
931 if (!testModeMatches(testMode, isStatic)) return;
932 countTest(true);
jrose10f3b682010-01-07 16:16:45 -0800933 MethodType expType = MethodType.methodType(void.class, HasFields.class, type);
934 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosecf98d422010-06-08 23:08:56 -0700935 MethodHandle mh;
936 if (testMode == TEST_UNREFLECT)
937 mh = lookup.unreflectSetter(f);
938 else if (testMode == TEST_FIND_FIELD)
939 mh = lookup.findSetter(fclass, fname, ftype);
940 else if (testMode == TEST_FIND_STATIC_FIELD)
941 mh = lookup.findStaticSetter(fclass, fname, ftype);
942 else throw new InternalError();
jrose10f3b682010-01-07 16:16:45 -0800943 assertSame(mh.type(), expType);
jrosecf98d422010-06-08 23:08:56 -0700944 assertEquals(mh.toString(), fname);
jrose10f3b682010-01-07 16:16:45 -0800945 HasFields fields = new HasFields();
946 Object sawValue;
947 Class<?> vtype = type;
948 if (type != int.class) vtype = Object.class;
949 int last = mh.type().parameterCount() - 1;
950 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(void.class).changeParameterType(last, vtype));
951 assertEquals(f.get(fields), value); // clean to start with
952 for (int i = 0; i <= 1; i++) {
953 Object putValue = randomArg(type);
954 if (isStatic) {
955 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700956 mh.<void>invokeExact((int)(Integer)putValue); // do these exactly
jrose10f3b682010-01-07 16:16:45 -0800957 else
jrose2cc9c832010-04-30 23:48:23 -0700958 mh.<void>invokeExact(putValue);
jrose10f3b682010-01-07 16:16:45 -0800959 } else {
960 if (type == int.class)
jrose2cc9c832010-04-30 23:48:23 -0700961 mh.<void>invokeExact((Object) fields, (int)(Integer)putValue);
jrose10f3b682010-01-07 16:16:45 -0800962 else
jrose2cc9c832010-04-30 23:48:23 -0700963 mh.<void>invokeExact((Object) fields, putValue);
jrose10f3b682010-01-07 16:16:45 -0800964 }
965 assertEquals(f.get(fields), putValue);
966 }
967 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -0700968 }
969
jrose10f3b682010-01-07 16:16:45 -0800970 @Test
jrose55220c32009-10-21 23:19:48 -0700971 public void testArrayElementGetter() throws Throwable {
972 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -0700973 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -0700974 }
975
jrose10f3b682010-01-07 16:16:45 -0800976 @Test
jrose55220c32009-10-21 23:19:48 -0700977 public void testArrayElementSetter() throws Throwable {
978 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -0700979 testArrayElementGetterSetter(true);
980 }
981
982 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
983 testArrayElementGetterSetter(new Object[10], testSetter);
984 testArrayElementGetterSetter(new String[10], testSetter);
985 testArrayElementGetterSetter(new boolean[10], testSetter);
986 testArrayElementGetterSetter(new byte[10], testSetter);
987 testArrayElementGetterSetter(new char[10], testSetter);
988 testArrayElementGetterSetter(new short[10], testSetter);
989 testArrayElementGetterSetter(new int[10], testSetter);
990 testArrayElementGetterSetter(new float[10], testSetter);
991 testArrayElementGetterSetter(new long[10], testSetter);
992 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -0800993 }
994
995 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
996 countTest(true);
jrose2cc9c832010-04-30 23:48:23 -0700997 if (verbosity >= 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -0800998 Class<?> arrayType = array.getClass();
999 Class<?> elemType = arrayType.getComponentType();
1000 MethodType expType = !testSetter
1001 ? MethodType.methodType(elemType, arrayType, int.class)
1002 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1003 MethodHandle mh = !testSetter
1004 ? MethodHandles.arrayElementGetter(arrayType)
1005 : MethodHandles.arrayElementSetter(arrayType);
1006 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001007 if (elemType != int.class && elemType != boolean.class) {
1008 MethodType gtype;
1009 if (true) { // FIXME: remove this path (and remove <void> below in the mh.invokes)
1010 gtype = mh.type().changeParameterType(0, Object.class);
1011 if (testSetter)
1012 gtype = gtype.changeParameterType(2, Object.class);
1013 else
1014 gtype = gtype.changeReturnType(Object.class);
1015 } else
1016 // FIXME: This simpler path hits a bug in convertArguments => ToGeneric
1017 gtype = mh.type().generic().changeParameterType(1, int.class);
1018 mh = MethodHandles.convertArguments(mh, gtype);
1019 }
jrose10f3b682010-01-07 16:16:45 -08001020 Object sawValue, expValue;
1021 List<Object> model = array2list(array);
1022 int length = Array.getLength(array);
1023 for (int i = 0; i < length; i++) {
1024 // update array element
1025 Object random = randomArg(elemType);
1026 model.set(i, random);
1027 if (testSetter) {
1028 if (elemType == int.class)
jrose2cc9c832010-04-30 23:48:23 -07001029 mh.<void>invokeExact((int[]) array, i, (int)(Integer)random);
1030 else if (elemType == boolean.class)
1031 mh.<void>invokeExact((boolean[]) array, i, (boolean)(Boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001032 else
jrose2cc9c832010-04-30 23:48:23 -07001033 mh.<void>invokeExact(array, i, random);
jrose10f3b682010-01-07 16:16:45 -08001034 assertEquals(model, array2list(array));
1035 } else {
1036 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001037 }
1038 if (verbosity >= 5) {
1039 List<Object> array2list = array2list(array);
1040 System.out.println("a["+i+"]="+random+" => "+array2list);
1041 if (!array2list.equals(model))
1042 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001043 }
1044 // observe array element
1045 sawValue = Array.get(array, i);
1046 if (!testSetter) {
1047 expValue = sawValue;
1048 if (elemType == int.class)
jrose2cc9c832010-04-30 23:48:23 -07001049 sawValue = mh.<int>invokeExact((int[]) array, i);
1050 else if (elemType == boolean.class)
1051 sawValue = mh.<boolean>invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001052 else
jrose2cc9c832010-04-30 23:48:23 -07001053 sawValue = mh.invokeExact(array, i);
jrose10f3b682010-01-07 16:16:45 -08001054 assertEquals(sawValue, expValue);
1055 assertEquals(model, array2list(array));
1056 }
1057 }
1058 }
1059
1060 List<Object> array2list(Object array) {
1061 int length = Array.getLength(array);
1062 ArrayList<Object> model = new ArrayList<Object>(length);
1063 for (int i = 0; i < length; i++)
1064 model.add(Array.get(array, i));
1065 return model;
jrose55220c32009-10-21 23:19:48 -07001066 }
1067
1068 static class Callee {
1069 static Object id() { return called("id"); }
1070 static Object id(Object x) { return called("id", x); }
1071 static Object id(Object x, Object y) { return called("id", x, y); }
1072 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1073 static Object id(Object... vx) { return called("id", vx); }
1074 static MethodHandle ofType(int n) {
1075 return ofType(Object.class, n);
1076 }
1077 static MethodHandle ofType(Class<?> rtype, int n) {
1078 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001079 return ofType(MethodType.methodType(rtype, Object[].class));
1080 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001081 }
1082 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001083 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001084 }
1085 static MethodHandle ofType(MethodType type) {
1086 Class<?> rtype = type.returnType();
1087 String pfx = "";
1088 if (rtype != Object.class)
1089 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1090 String name = pfx+"id";
1091 return PRIVATE.findStatic(Callee.class, name, type);
1092 }
1093 }
1094
1095 @Test
1096 public void testConvertArguments() throws Throwable {
1097 if (CAN_SKIP_WORKING) return;
1098 startTest("convertArguments");
1099 testConvert(Callee.ofType(1), null, "id", int.class);
1100 testConvert(Callee.ofType(1), null, "id", String.class);
1101 testConvert(Callee.ofType(1), null, "id", Integer.class);
1102 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001103 testConvert(Callee.ofType(1), null, "id", char.class);
1104 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001105 }
1106
1107 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1108 testConvert(true, id, rtype, name, params);
1109 }
1110
1111 void testConvert(boolean positive, MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1112 countTest(positive);
1113 MethodType idType = id.type();
1114 if (rtype == null) rtype = idType.returnType();
1115 for (int i = 0; i < params.length; i++) {
1116 if (params[i] == null) params[i] = idType.parameterType(i);
1117 }
1118 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001119 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001120 Object[] args = randomArgs(newType.parameterArray());
1121 Object[] convArgs = args.clone();
1122 for (int i = 0; i < args.length; i++) {
1123 Class<?> src = newType.parameterType(i);
1124 Class<?> dst = idType.parameterType(i);
1125 if (src != dst)
1126 convArgs[i] = castToWrapper(convArgs[i], dst);
1127 }
jrose10f3b682010-01-07 16:16:45 -08001128 Object convResult = id.invokeVarargs(convArgs);
jrose55220c32009-10-21 23:19:48 -07001129 {
1130 Class<?> dst = newType.returnType();
1131 Class<?> src = idType.returnType();
1132 if (src != dst)
1133 convResult = castToWrapper(convResult, dst);
1134 }
1135 MethodHandle target = null;
1136 RuntimeException error = null;
1137 try {
1138 target = MethodHandles.convertArguments(id, newType);
1139 } catch (RuntimeException ex) {
1140 error = ex;
1141 }
jrose2cc9c832010-04-30 23:48:23 -07001142 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001143 System.out.println("convert "+id+ " to "+newType+" => "+target
1144 +(error == null ? "" : " !! "+error));
1145 if (positive && error != null) throw error;
1146 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1147 if (!positive) return; // negative test failed as expected
1148 assertEquals(newType, target.type());
1149 printCalled(target, id.toString(), args);
jrose10f3b682010-01-07 16:16:45 -08001150 Object result = target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -07001151 assertCalled(name, convArgs);
1152 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001153 if (verbosity >= 1)
1154 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001155 }
1156
1157 @Test
jrose10f3b682010-01-07 16:16:45 -08001158 public void testPermuteArguments() throws Throwable {
1159 if (CAN_SKIP_WORKING) return;
1160 startTest("permuteArguments");
1161 testPermuteArguments(4, Integer.class, 2, String.class, 0);
1162 //testPermuteArguments(6, Integer.class, 0, null, 30);
1163 //testPermuteArguments(4, Integer.class, 1, int.class, 6);
1164 }
1165 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001166 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001167 System.out.println("permuteArguments "+max+"*"+type1.getName()
1168 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1169 +(dilution > 0 ? " with dilution "+dilution : ""));
1170 int t2pos = t2c == 0 ? 0 : 1;
1171 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1172 Class<?>[] types = new Class<?>[inargs];
1173 Arrays.fill(types, type1);
1174 if (t2c != 0) {
1175 // Fill in a middle range with type2:
1176 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1177 }
1178 Object[] args = randomArgs(types);
1179 int numcases = 1;
1180 for (int outargs = 0; outargs <= max; outargs++) {
1181 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
1182 int[] reorder = new int[outargs];
1183 int casStep = dilution + 1;
1184 // Avoid some common factors:
1185 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1186 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1187 casStep++;
1188 for (int cas = 0; cas < numcases; cas += casStep) {
1189 for (int i = 0, c = cas; i < outargs; i++) {
1190 reorder[i] = c % inargs;
1191 c /= inargs;
1192 }
1193 testPermuteArguments(args, types, reorder);
1194 }
1195 numcases *= inargs;
1196 if (dilution > 10 && outargs >= 4) {
1197 // Do some special patterns, which we probably missed.
1198 // Replication of a single argument or argument pair.
1199 for (int i = 0; i < inargs; i++) {
1200 Arrays.fill(reorder, i);
1201 testPermuteArguments(args, types, reorder);
1202 for (int d = 1; d <= 2; d++) {
1203 if (i + d >= inargs) continue;
1204 for (int j = 1; j < outargs; j += 2)
1205 reorder[j] += 1;
1206 testPermuteArguments(args, types, reorder);
1207 testPermuteArguments(args, types, reverse(reorder));
1208 }
1209 }
1210 // Repetition of a sequence of 3 or more arguments.
1211 for (int i = 1; i < inargs; i++) {
1212 for (int len = 3; len <= inargs; len++) {
1213 for (int j = 0; j < outargs; j++)
1214 reorder[j] = (i + (j % len)) % inargs;
1215 testPermuteArguments(args, types, reorder);
1216 testPermuteArguments(args, types, reverse(reorder));
1217 }
1218 }
1219 }
1220 }
1221 }
1222 }
1223
1224 static int[] reverse(int[] reorder) {
1225 reorder = reorder.clone();
1226 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1227 int j = reorder.length - 1 - i;
1228 int tem = reorder[i];
1229 reorder[i] = reorder[j];
1230 reorder[j] = tem;
1231 }
1232 return reorder;
1233 }
1234
1235 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1236 countTest();
1237 if (args == null && types == null) {
1238 int max = 0;
1239 for (int j : reorder) {
1240 if (max < j) max = j;
1241 }
1242 args = randomArgs(max+1, Integer.class);
1243 }
1244 if (args == null) {
1245 args = randomArgs(types);
1246 }
1247 if (types == null) {
1248 types = new Class<?>[args.length];
1249 for (int i = 0; i < args.length; i++)
1250 types[i] = args[i].getClass();
1251 }
1252 int inargs = args.length, outargs = reorder.length;
1253 assert(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001254 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001255 System.out.println("permuteArguments "+Arrays.toString(reorder));
1256 Object[] permArgs = new Object[outargs];
1257 Class<?>[] permTypes = new Class<?>[outargs];
1258 for (int i = 0; i < outargs; i++) {
1259 permArgs[i] = args[reorder[i]];
1260 permTypes[i] = types[reorder[i]];
1261 }
jrose2cc9c832010-04-30 23:48:23 -07001262 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001263 System.out.println("in args: "+Arrays.asList(args));
1264 System.out.println("out args: "+Arrays.asList(permArgs));
1265 System.out.println("in types: "+Arrays.asList(types));
1266 System.out.println("out types: "+Arrays.asList(permTypes));
1267 }
1268 MethodType inType = MethodType.methodType(Object.class, types);
1269 MethodType outType = MethodType.methodType(Object.class, permTypes);
1270 MethodHandle target = MethodHandles.convertArguments(ValueConversions.varargsList(outargs), outType);
1271 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
1272 Object result = newTarget.invokeVarargs(args);
1273 Object expected = Arrays.asList(permArgs);
1274 assertEquals(expected, result);
1275 }
1276
1277
1278 @Test
1279 public void testSpreadArguments() throws Throwable {
1280 if (CAN_SKIP_WORKING) return;
1281 startTest("spreadArguments");
1282 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001283 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001284 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001285 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001286 for (int nargs = 0; nargs < 10; nargs++) {
1287 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1288 for (int pos = 0; pos < nargs; pos++) {
1289 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001290 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001291 }
1292 }
1293 }
1294 }
1295 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1296 countTest();
1297 MethodHandle target = ValueConversions.varargsArray(nargs);
1298 MethodHandle target2 = changeArgTypes(target, argType);
jrose2cc9c832010-04-30 23:48:23 -07001299 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001300 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1301 Object[] args = randomArgs(target2.type().parameterArray());
1302 // make sure the target does what we think it does:
1303 if (pos == 0 && nargs < 5) {
1304 Object[] check = (Object[]) target.invokeVarargs(args);
1305 assertArrayEquals(args, check);
1306 switch (nargs) {
1307 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001308 check = target.<Object[]>invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001309 assertArrayEquals(args, check);
1310 break;
1311 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001312 check = target.<Object[]>invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001313 assertArrayEquals(args, check);
1314 break;
1315 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001316 check = target.<Object[]>invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001317 assertArrayEquals(args, check);
1318 break;
1319 }
1320 }
1321 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1322 { // modify newParams in place
1323 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
1324 spreadParams.clear(); spreadParams.add(Object[].class);
1325 }
1326 MethodType newType = MethodType.methodType(Object.class, newParams);
1327 MethodHandle result = MethodHandles.spreadArguments(target2, newType);
1328 Object[] returnValue;
1329 if (pos == 0) {
jrose2cc9c832010-04-30 23:48:23 -07001330 returnValue = (Object[]) result.invokeExact(args);
jrose10f3b682010-01-07 16:16:45 -08001331 } else {
1332 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
1333 args1[pos] = Arrays.copyOfRange(args, pos, args.length);
1334 returnValue = (Object[]) result.invokeVarargs(args1);
1335 }
1336 assertArrayEquals(args, returnValue);
1337 }
1338
1339 @Test
1340 public void testCollectArguments() throws Throwable {
1341 if (CAN_SKIP_WORKING) return;
1342 startTest("collectArguments");
1343 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001344 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001345 System.out.println("collectArguments "+argType);
1346 for (int nargs = 0; nargs < 10; nargs++) {
1347 for (int pos = 0; pos < nargs; pos++) {
1348 if (argType == int.class) continue; // FIXME Fail_4
1349 testCollectArguments(argType, pos, nargs);
1350 }
1351 }
1352 }
1353 }
1354 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1355 countTest();
1356 // fake up a MH with the same type as the desired adapter:
1357 MethodHandle fake = ValueConversions.varargsArray(nargs);
1358 fake = changeArgTypes(fake, argType);
1359 MethodType newType = fake.type();
1360 Object[] args = randomArgs(newType.parameterArray());
1361 // here is what should happen:
1362 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1363 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1364 // here is the MH which will witness the collected argument tail:
1365 MethodHandle target = ValueConversions.varargsArray(pos+1);
1366 target = changeArgTypes(target, 0, pos, argType);
1367 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001368 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001369 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
1370 MethodHandle result = MethodHandles.collectArguments(target, newType);
1371 Object[] returnValue = (Object[]) result.invokeVarargs(args);
1372// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1373// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1374// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1375 assertArrayEquals(collectedArgs, returnValue);
1376 }
1377
1378 @Test
jrose55220c32009-10-21 23:19:48 -07001379 public void testInsertArguments() throws Throwable {
1380 if (CAN_SKIP_WORKING) return;
1381 startTest("insertArguments");
1382 for (int nargs = 0; nargs <= 4; nargs++) {
1383 for (int ins = 0; ins <= 4; ins++) {
1384 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1385 for (int pos = 0; pos <= nargs; pos++) {
1386 testInsertArguments(nargs, pos, ins);
1387 }
1388 }
1389 }
1390 }
1391
1392 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001393 countTest();
1394 MethodHandle target = ValueConversions.varargsArray(nargs + ins);
1395 Object[] args = randomArgs(target.type().parameterArray());
1396 List<Object> resList = Arrays.asList(args);
1397 List<Object> argsToPass = new ArrayList<Object>(resList);
1398 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001399 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001400 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001401 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1402 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001403 argsToInsert.clear(); // remove from argsToInsert
jrose10f3b682010-01-07 16:16:45 -08001404 Object res2 = target2.invokeVarargs(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001405 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001406 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001407 System.out.println("result: "+res2List);
1408 //if (!resList.equals(res2List))
1409 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1410 assertEquals(resList, res2List);
1411 }
1412
jrose10f3b682010-01-07 16:16:45 -08001413 @Test
1414 public void testFilterArguments() throws Throwable {
1415 if (CAN_SKIP_WORKING) return;
1416 startTest("filterArguments");
1417 for (int nargs = 1; nargs <= 6; nargs++) {
1418 for (int pos = 0; pos < nargs; pos++) {
1419 testFilterArguments(nargs, pos);
1420 }
1421 }
1422 }
1423
1424 void testFilterArguments(int nargs, int pos) throws Throwable {
1425 countTest();
1426 MethodHandle target = ValueConversions.varargsList(nargs);
1427 MethodHandle filter = ValueConversions.varargsList(1);
1428 filter = MethodHandles.convertArguments(filter, filter.type().generic());
1429 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001430 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001431 System.out.println("filter "+target+" at "+pos+" with "+filter);
1432 MethodHandle[] filters = new MethodHandle[pos*2+1];
1433 filters[pos] = filter;
1434 MethodHandle target2 = MethodHandles.filterArguments(target, filters);
1435 // Simulate expected effect of filter on arglist:
1436 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001437 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001438 List<Object> expected = Arrays.asList(filteredArgs);
1439 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001440 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001441 System.out.println("result: "+result);
1442 if (!expected.equals(result))
1443 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+argsToPass+" => "+result);
1444 assertEquals(expected, result);
1445 }
1446
1447 @Test
1448 public void testFoldArguments() throws Throwable {
1449 if (CAN_SKIP_WORKING) return;
1450 startTest("foldArguments");
1451 for (int nargs = 0; nargs <= 4; nargs++) {
1452 for (int fold = 0; fold <= nargs; fold++) {
1453 for (int pos = 0; pos <= nargs; pos++) {
1454 testFoldArguments(nargs, pos, fold);
1455 }
1456 }
1457 }
1458 }
1459
1460 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1461 if (pos != 0) return; // can fold only at pos=0 for now
1462 countTest();
1463 MethodHandle target = ValueConversions.varargsList(1 + nargs);
1464 MethodHandle combine = ValueConversions.varargsList(fold);
1465 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001466 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001467 System.out.println("fold "+target+" with "+combine);
1468 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1469 // Simulate expected effect of combiner on arglist:
1470 List<Object> expected = new ArrayList<Object>(argsToPass);
1471 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001472 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001473 System.out.println("fold: "+argsToFold+" into "+target2);
1474 Object foldedArgs = combine.invokeVarargs(argsToFold);
1475 argsToFold.add(0, foldedArgs);
1476 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001477 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001478 System.out.println("result: "+result);
1479 if (!expected.equals(result))
1480 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result);
1481 assertEquals(expected, result);
1482 }
1483
1484 @Test
1485 public void testDropArguments() throws Throwable {
1486 if (CAN_SKIP_WORKING) return;
1487 startTest("dropArguments");
1488 for (int nargs = 0; nargs <= 4; nargs++) {
1489 for (int drop = 1; drop <= 4; drop++) {
1490 for (int pos = 0; pos <= nargs; pos++) {
1491 testDropArguments(nargs, pos, drop);
1492 }
1493 }
1494 }
1495 }
1496
1497 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1498 countTest();
1499 MethodHandle target = ValueConversions.varargsArray(nargs);
1500 Object[] args = randomArgs(target.type().parameterArray());
1501 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1502 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1503 List<Object> resList = Arrays.asList(args);
1504 List<Object> argsToDrop = new ArrayList<Object>(resList);
1505 for (int i = drop; i > 0; i--) {
1506 argsToDrop.add(pos, "blort#"+i);
1507 }
1508 Object res2 = target2.invokeVarargs(argsToDrop);
1509 Object res2List = Arrays.asList((Object[])res2);
1510 //if (!resList.equals(res2List))
1511 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1512 assertEquals(resList, res2List);
1513 }
1514
1515 @Test
1516 public void testInvokers() throws Throwable {
1517 if (CAN_SKIP_WORKING) return;
1518 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1519 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1520 Set<MethodType> done = new HashSet<MethodType>();
1521 for (int i = 0; i <= 6; i++) {
1522 MethodType gtype = MethodType.genericMethodType(i);
1523 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1524 for (int j = -1; j < i; j++) {
1525 MethodType type = gtype;
1526 if (j < 0)
1527 type = type.changeReturnType(argType);
1528 else if (argType == void.class)
1529 continue;
1530 else
1531 type = type.changeParameterType(j, argType);
1532 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1533 if (done.add(type))
1534 testInvokers(type);
1535 MethodType vtype = type.changeReturnType(void.class);
1536 if (done.add(vtype))
1537 testInvokers(vtype);
1538 }
1539 }
1540 }
1541 }
1542
1543 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001544 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001545 System.out.println("test invokers for "+type);
1546 int nargs = type.parameterCount();
1547 boolean testRetCode = type.returnType() != void.class;
1548 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1549 MethodType.genericMethodType(0, true));
1550 target = MethodHandles.collectArguments(target, type);
1551 Object[] args = randomArgs(type.parameterArray());
1552 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1553 targetPlusArgs.add(0, target);
1554 int code = (Integer) invokee(args);
1555 Object log = logEntry("invokee", args);
1556 assertEquals(log.hashCode(), code);
1557 assertCalled("invokee", args);
1558 MethodHandle inv;
1559 Object result;
1560 // exact invoker
1561 countTest();
1562 calledLog.clear();
1563 inv = MethodHandles.exactInvoker(type);
1564 result = inv.invokeVarargs(targetPlusArgs);
1565 if (testRetCode) assertEquals(code, result);
1566 assertCalled("invokee", args);
1567 // generic invoker
1568 countTest();
1569 inv = MethodHandles.genericInvoker(type);
1570 if (nargs <= 3) {
1571 calledLog.clear();
1572 switch (nargs) {
1573 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001574 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001575 break;
1576 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001577 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001578 break;
1579 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001580 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001581 break;
1582 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001583 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001584 break;
1585 }
1586 if (testRetCode) assertEquals(code, result);
1587 assertCalled("invokee", args);
1588 }
1589 calledLog.clear();
1590 result = inv.invokeVarargs(targetPlusArgs);
1591 if (testRetCode) assertEquals(code, result);
1592 assertCalled("invokee", args);
1593 // varargs invoker #0
1594 calledLog.clear();
1595 inv = MethodHandles.varargsInvoker(type, 0);
jrose2cc9c832010-04-30 23:48:23 -07001596 result = inv.invokeExact(target, args);
jrose10f3b682010-01-07 16:16:45 -08001597 if (testRetCode) assertEquals(code, result);
1598 assertCalled("invokee", args);
1599 if (nargs >= 1) {
1600 // varargs invoker #1
1601 calledLog.clear();
1602 inv = MethodHandles.varargsInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001603 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001604 if (testRetCode) assertEquals(code, result);
1605 assertCalled("invokee", args);
1606 }
1607 if (nargs >= 2) {
1608 // varargs invoker #2
1609 calledLog.clear();
1610 inv = MethodHandles.varargsInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001611 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001612 if (testRetCode) assertEquals(code, result);
1613 assertCalled("invokee", args);
1614 }
1615 if (nargs >= 3) {
1616 // varargs invoker #3
1617 calledLog.clear();
1618 inv = MethodHandles.varargsInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001619 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001620 if (testRetCode) assertEquals(code, result);
1621 assertCalled("invokee", args);
1622 }
1623 for (int k = 0; k <= nargs; k++) {
1624 // varargs invoker #0..N
1625 countTest();
1626 calledLog.clear();
1627 inv = MethodHandles.varargsInvoker(type, k);
1628 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1629 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1630 Object[] tail = tailList.toArray();
1631 tailList.clear(); tailList.add(tail);
1632 result = inv.invokeVarargs(targetPlusVarArgs);
1633 if (testRetCode) assertEquals(code, result);
1634 assertCalled("invokee", args);
1635 }
1636 // dynamic invoker
1637 countTest();
1638 CallSite site = new CallSite(MethodHandlesTest.class, "foo", type);
1639 inv = MethodHandles.dynamicInvoker(site);
1640 site.setTarget(target);
1641 calledLog.clear();
1642 result = inv.invokeVarargs(args);
1643 if (testRetCode) assertEquals(code, result);
1644 assertCalled("invokee", args);
1645 }
1646
1647 static Object invokee(Object... args) {
1648 return called("invokee", args).hashCode();
1649 }
1650
jrose55220c32009-10-21 23:19:48 -07001651 private static final String MISSING_ARG = "missingArg";
1652 static Object targetIfEquals() {
1653 return called("targetIfEquals");
1654 }
1655 static Object fallbackIfNotEquals() {
1656 return called("fallbackIfNotEquals");
1657 }
1658 static Object targetIfEquals(Object x) {
1659 assertEquals(x, MISSING_ARG);
1660 return called("targetIfEquals", x);
1661 }
1662 static Object fallbackIfNotEquals(Object x) {
1663 assertFalse(x.toString(), x.equals(MISSING_ARG));
1664 return called("fallbackIfNotEquals", x);
1665 }
1666 static Object targetIfEquals(Object x, Object y) {
1667 assertEquals(x, y);
1668 return called("targetIfEquals", x, y);
1669 }
1670 static Object fallbackIfNotEquals(Object x, Object y) {
1671 assertFalse(x.toString(), x.equals(y));
1672 return called("fallbackIfNotEquals", x, y);
1673 }
1674 static Object targetIfEquals(Object x, Object y, Object z) {
1675 assertEquals(x, y);
1676 return called("targetIfEquals", x, y, z);
1677 }
1678 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1679 assertFalse(x.toString(), x.equals(y));
1680 return called("fallbackIfNotEquals", x, y, z);
1681 }
1682
jrose10f3b682010-01-07 16:16:45 -08001683 @Test
1684 public void testGuardWithTest() throws Throwable {
1685 if (CAN_SKIP_WORKING) return;
1686 startTest("guardWithTest");
1687 for (int nargs = 0; nargs <= 3; nargs++) {
1688 if (nargs != 2) continue; // FIXME: test more later
1689 testGuardWithTest(nargs, Object.class);
1690 testGuardWithTest(nargs, String.class);
1691 }
1692 }
1693 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1694 countTest();
1695 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1696 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1697 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1698 while (test.type().parameterCount() < nargs)
1699 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1700 while (test.type().parameterCount() > nargs)
1701 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1702 if (argClass != Object.class) {
1703 test = changeArgTypes(test, argClass);
1704 target = changeArgTypes(target, argClass);
1705 fallback = changeArgTypes(fallback, argClass);
1706 }
1707 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1708 assertEquals(target.type(), mh.type());
1709 Object[][] argLists = {
1710 { },
1711 { "foo" }, { MISSING_ARG },
1712 { "foo", "foo" }, { "foo", "bar" },
1713 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1714 };
1715 for (Object[] argList : argLists) {
1716 if (argList.length != nargs) continue;
1717 boolean equals;
1718 switch (nargs) {
1719 case 0: equals = true; break;
1720 case 1: equals = MISSING_ARG.equals(argList[0]); break;
1721 default: equals = argList[0].equals(argList[1]); break;
1722 }
1723 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07001724 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001725 System.out.println(logEntry(willCall, argList));
1726 Object result = mh.invokeVarargs(argList);
1727 assertCalled(willCall, argList);
1728 }
1729 }
1730
1731 @Test
1732 public void testCatchException() throws Throwable {
1733 if (CAN_SKIP_WORKING) return;
1734 startTest("catchException");
1735 for (int nargs = 2; nargs <= 6; nargs++) {
1736 for (int ti = 0; ti <= 1; ti++) {
1737 boolean throwIt = (ti != 0);
1738 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
1739 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
1740 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
1741 }
1742 }
1743 }
1744
1745 private static <T extends Throwable>
1746 Object throwOrReturn(Object normal, T exception) throws T {
1747 if (exception != null) throw exception;
1748 return normal;
1749 }
1750
1751 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
1752 countTest();
jrose2cc9c832010-04-30 23:48:23 -07001753 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001754 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
1755 Class<? extends Throwable> exType = thrown.getClass();
1756 MethodHandle throwOrReturn
1757 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
1758 MethodType.methodType(Object.class, Object.class, Throwable.class));
1759 MethodHandle thrower = throwOrReturn;
1760 while (thrower.type().parameterCount() < nargs)
1761 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
1762 MethodHandle target = MethodHandles.catchException(thrower,
1763 thrown.getClass(), ValueConversions.varargsList(1+nargs));
1764 assertEquals(thrower.type(), target.type());
1765 //System.out.println("catching with "+target+" : "+throwOrReturn);
1766 Object[] args = randomArgs(nargs, Object.class);
1767 args[1] = (throwIt ? thrown : null);
1768 Object returned = target.invokeVarargs(args);
1769 //System.out.println("return from "+target+" : "+returned);
1770 if (!throwIt) {
1771 assertSame(args[0], returned);
1772 } else {
1773 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
1774 catchArgs.add(0, thrown);
1775 assertEquals(catchArgs, returned);
1776 }
1777 }
1778
1779 @Test
1780 public void testThrowException() throws Throwable {
1781 if (CAN_SKIP_WORKING) return;
1782 startTest("throwException");
1783 testThrowException(int.class, new ClassCastException("testing"));
1784 testThrowException(void.class, new java.io.IOException("testing"));
1785 testThrowException(String.class, new LinkageError("testing"));
1786 }
1787
1788 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
1789 countTest();
1790 Class<? extends Throwable> exType = thrown.getClass();
1791 MethodHandle target = MethodHandles.throwException(returnType, exType);
1792 //System.out.println("throwing with "+target+" : "+thrown);
1793 MethodType expectedType = MethodType.methodType(returnType, exType);
1794 assertEquals(expectedType, target.type());
jrose2cc9c832010-04-30 23:48:23 -07001795 target = MethodHandles.convertArguments(target, target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001796 Throwable caught = null;
1797 try {
jrose2cc9c832010-04-30 23:48:23 -07001798 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08001799 fail("got "+res+" instead of throwing "+thrown);
1800 } catch (Throwable ex) {
1801 if (ex != thrown) {
1802 if (ex instanceof Error) throw (Error)ex;
1803 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
1804 }
1805 caught = ex;
1806 }
1807 assertSame(thrown, caught);
1808 }
1809
1810 @Test
1811 public void testCastFailure() throws Throwable {
1812 if (CAN_SKIP_WORKING) return;
1813 startTest("testCastFailure");
1814 testCastFailure("cast/argument", 11000);
1815 testCastFailure("unbox/argument", 11000);
1816 testCastFailure("cast/return", 11000);
1817 testCastFailure("unbox/return", 11000);
1818 }
1819
1820 static class Surprise extends JavaMethodHandle {
1821 Surprise() { super("value"); }
1822 Object value(Object x) {
1823 trace("value", x);
1824 if (boo != null) return boo;
1825 return x;
1826 }
1827 Object boo;
1828 void boo(Object x) { boo = x; }
1829
1830 static void trace(String x, Object y) {
1831 if (verbosity > 8) System.out.println(x+"="+y);
1832 }
1833 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
1834 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
1835 static int intIdentity(int x) { trace("int.x", x); return x; }
1836 static MethodHandle REF_IDENTITY = PRIVATE.findStatic(
1837 Surprise.class, "refIdentity",
1838 MethodType.methodType(Object.class, Object.class));
1839 static MethodHandle BOX_IDENTITY = PRIVATE.findStatic(
1840 Surprise.class, "boxIdentity",
1841 MethodType.methodType(Integer.class, Integer.class));
1842 static MethodHandle INT_IDENTITY = PRIVATE.findStatic(
1843 Surprise.class, "intIdentity",
1844 MethodType.methodType(int.class, int.class));
1845 }
1846
1847 void testCastFailure(String mode, int okCount) throws Throwable {
1848 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07001849 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08001850 Surprise boo = new Surprise();
1851 MethodHandle identity = Surprise.REF_IDENTITY, surprise = boo;
1852 if (mode.endsWith("/return")) {
1853 if (mode.equals("unbox/return")) {
1854 // fail on return to ((Integer)surprise).intValue
1855 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(int.class, Object.class));
1856 identity = MethodHandles.convertArguments(identity, MethodType.methodType(int.class, Object.class));
1857 } else if (mode.equals("cast/return")) {
1858 // fail on return to (Integer)surprise
1859 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(Integer.class, Object.class));
1860 identity = MethodHandles.convertArguments(identity, MethodType.methodType(Integer.class, Object.class));
1861 }
1862 } else if (mode.endsWith("/argument")) {
1863 MethodHandle callee = null;
1864 if (mode.equals("unbox/argument")) {
1865 // fail on handing surprise to int argument
1866 callee = Surprise.INT_IDENTITY;
1867 } else if (mode.equals("cast/argument")) {
1868 // fail on handing surprise to Integer argument
1869 callee = Surprise.BOX_IDENTITY;
1870 }
1871 if (callee != null) {
1872 callee = MethodHandles.convertArguments(callee, MethodType.genericMethodType(1));
1873 surprise = MethodHandles.filterArguments(callee, surprise);
1874 identity = MethodHandles.filterArguments(callee, identity);
1875 }
1876 }
1877 assertNotSame(mode, surprise, boo);
1878 identity = MethodHandles.convertArguments(identity, MethodType.genericMethodType(1));
1879 surprise = MethodHandles.convertArguments(surprise, MethodType.genericMethodType(1));
1880 Object x = 42;
1881 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07001882 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001883 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07001884 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001885 assertEquals(x, z);
1886 }
1887 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07001888 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001889 assertEquals(x, y);
1890 try {
jrose2cc9c832010-04-30 23:48:23 -07001891 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001892 System.out.println("Failed to throw; got z="+z);
1893 assertTrue(false);
1894 } catch (Exception ex) {
jrose10f3b682010-01-07 16:16:45 -08001895 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07001896 System.out.println("caught "+ex);
1897 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08001898 ex.printStackTrace();
1899 assertTrue(ex instanceof ClassCastException
1900 // FIXME: accept only one of the two for any given unit test
1901 || ex instanceof WrongMethodTypeException
1902 );
1903 }
1904 }
1905
jrose45b7a332010-05-03 23:32:47 -07001906 static Example userMethod(Object o, String s, int i) {
1907 called("userMethod", o, s, i);
1908 return null;
1909 }
1910
1911 @Test
1912 public void testUserClassInSignature() throws Throwable {
1913 if (CAN_SKIP_WORKING) return;
1914 startTest("testUserClassInSignature");
1915 Lookup lookup = MethodHandles.lookup();
1916 String name; MethodType mt; MethodHandle mh;
1917 Object[] args;
1918
1919 // Try a static method.
1920 name = "userMethod";
1921 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
1922 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
1923 assertEquals(mt, mh.type());
1924 assertEquals(Example.class, mh.type().returnType());
1925 args = randomArgs(mh.type().parameterArray());
1926 mh.invokeVarargs(args);
1927 assertCalled(name, args);
1928
1929 // Try a virtual method.
1930 name = "v2";
1931 mt = MethodType.methodType(Object.class, Object.class, int.class);
1932 mh = lookup.findVirtual(Example.class, name, mt);
1933 assertEquals(mt, mh.type().dropParameterTypes(0,1));
1934 assertTrue(mh.type().parameterList().contains(Example.class));
1935 args = randomArgs(mh.type().parameterArray());
1936 mh.invokeVarargs(args);
1937 assertCalled(name, args);
1938 }
jrose55220c32009-10-21 23:19:48 -07001939}
1940// Local abbreviated copy of sun.dyn.util.ValueConversions
1941class ValueConversions {
1942 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
1943 private static final Object[] NO_ARGS_ARRAY = {};
1944 private static Object[] makeArray(Object... args) { return args; }
1945 private static Object[] array() { return NO_ARGS_ARRAY; }
1946 private static Object[] array(Object a0)
1947 { return makeArray(a0); }
1948 private static Object[] array(Object a0, Object a1)
1949 { return makeArray(a0, a1); }
1950 private static Object[] array(Object a0, Object a1, Object a2)
1951 { return makeArray(a0, a1, a2); }
1952 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1953 { return makeArray(a0, a1, a2, a3); }
1954 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1955 Object a4)
1956 { return makeArray(a0, a1, a2, a3, a4); }
1957 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1958 Object a4, Object a5)
1959 { return makeArray(a0, a1, a2, a3, a4, a5); }
1960 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1961 Object a4, Object a5, Object a6)
1962 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1963 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1964 Object a4, Object a5, Object a6, Object a7)
1965 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1966 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1967 Object a4, Object a5, Object a6, Object a7,
1968 Object a8)
1969 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1970 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1971 Object a4, Object a5, Object a6, Object a7,
1972 Object a8, Object a9)
1973 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1974 static MethodHandle[] makeArrays() {
1975 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
1976 MethodHandles.Lookup lookup = IMPL_LOOKUP;
1977 for (;;) {
1978 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08001979 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07001980 String name = "array";
1981 MethodHandle array = null;
1982 try {
1983 array = lookup.findStatic(ValueConversions.class, name, type);
1984 } catch (NoAccessException ex) {
1985 }
1986 if (array == null) break;
1987 arrays.add(array);
1988 }
1989 assert(arrays.size() == 11); // current number of methods
1990 return arrays.toArray(new MethodHandle[0]);
1991 }
1992 static final MethodHandle[] ARRAYS = makeArrays();
1993
1994 /** Return a method handle that takes the indicated number of Object
1995 * arguments and returns an Object array of them, as if for varargs.
1996 */
1997 public static MethodHandle varargsArray(int nargs) {
1998 if (nargs < ARRAYS.length)
1999 return ARRAYS[nargs];
2000 // else need to spin bytecode or do something else fancy
jrose2cc9c832010-04-30 23:48:23 -07002001 throw new UnsupportedOperationException("NYI: cannot form a varargs array of length "+nargs);
jrose55220c32009-10-21 23:19:48 -07002002 }
jrose10f3b682010-01-07 16:16:45 -08002003
2004 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2005 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2006 private static List<Object> list() { return NO_ARGS_LIST; }
2007 private static List<Object> list(Object a0)
2008 { return makeList(a0); }
2009 private static List<Object> list(Object a0, Object a1)
2010 { return makeList(a0, a1); }
2011 private static List<Object> list(Object a0, Object a1, Object a2)
2012 { return makeList(a0, a1, a2); }
2013 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2014 { return makeList(a0, a1, a2, a3); }
2015 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2016 Object a4)
2017 { return makeList(a0, a1, a2, a3, a4); }
2018 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2019 Object a4, Object a5)
2020 { return makeList(a0, a1, a2, a3, a4, a5); }
2021 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2022 Object a4, Object a5, Object a6)
2023 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2024 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2025 Object a4, Object a5, Object a6, Object a7)
2026 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2027 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2028 Object a4, Object a5, Object a6, Object a7,
2029 Object a8)
2030 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2031 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2032 Object a4, Object a5, Object a6, Object a7,
2033 Object a8, Object a9)
2034 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2035 static MethodHandle[] makeLists() {
2036 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2037 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2038 for (;;) {
2039 int nargs = arrays.size();
2040 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2041 String name = "list";
2042 MethodHandle array = null;
2043 try {
2044 array = lookup.findStatic(ValueConversions.class, name, type);
2045 } catch (NoAccessException ex) {
2046 }
2047 if (array == null) break;
2048 arrays.add(array);
2049 }
2050 assert(arrays.size() == 11); // current number of methods
2051 return arrays.toArray(new MethodHandle[0]);
2052 }
2053 static final MethodHandle[] LISTS = makeLists();
2054
2055 /** Return a method handle that takes the indicated number of Object
2056 * arguments and returns List.
2057 */
2058 public static MethodHandle varargsList(int nargs) {
2059 if (nargs < LISTS.length)
2060 return LISTS[nargs];
2061 // else need to spin bytecode or do something else fancy
2062 throw new UnsupportedOperationException("NYI");
2063 }
jrose55220c32009-10-21 23:19:48 -07002064}
2065// This guy tests access from outside the same package member, but inside
2066// the package itself.
2067class PackageSibling {
2068 static Lookup lookup() {
2069 return MethodHandles.lookup();
2070 }
2071}