blob: 734b1323ff6ad162ee2a57567a6fbcdb884ad2f3 [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
jrose4151b9c2010-06-18 15:23:57 -07002 * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
jrose55220c32009-10-21 23:19:48 -07003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
ohair2283b9d2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
jrose55220c32009-10-21 23:19:48 -07008 * particular file as subject to the "Classpath" exception as provided
ohair2283b9d2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
jrose55220c32009-10-21 23:19:48 -070010 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
ohair2283b9d2010-05-25 15:58:33 -070021 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
jrose55220c32009-10-21 23:19:48 -070024 */
25
26/* @test
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;
jrosea1ebbe62010-09-08 18:40:23 -0700452 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700453 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;
jrosea1ebbe62010-09-08 18:40:23 -0700516 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700517 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;
jrosea1ebbe62010-09-08 18:40:23 -0700570 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700571 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;
jrosea1ebbe62010-09-08 18:40:23 -0700626 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700627 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;
jrosea1ebbe62010-09-08 18:40:23 -0700691 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700692 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";
jrosea1ebbe62010-09-08 18:40:23 -07001091 try {
1092 return PRIVATE.findStatic(Callee.class, name, type);
1093 } catch (Exception ex) {
1094 throw new RuntimeException(ex);
1095 }
jrose55220c32009-10-21 23:19:48 -07001096 }
1097 }
1098
1099 @Test
1100 public void testConvertArguments() throws Throwable {
1101 if (CAN_SKIP_WORKING) return;
1102 startTest("convertArguments");
1103 testConvert(Callee.ofType(1), null, "id", int.class);
1104 testConvert(Callee.ofType(1), null, "id", String.class);
1105 testConvert(Callee.ofType(1), null, "id", Integer.class);
1106 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001107 testConvert(Callee.ofType(1), null, "id", char.class);
1108 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001109 }
1110
1111 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1112 testConvert(true, id, rtype, name, params);
1113 }
1114
1115 void testConvert(boolean positive, MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
1116 countTest(positive);
1117 MethodType idType = id.type();
1118 if (rtype == null) rtype = idType.returnType();
1119 for (int i = 0; i < params.length; i++) {
1120 if (params[i] == null) params[i] = idType.parameterType(i);
1121 }
1122 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001123 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001124 Object[] args = randomArgs(newType.parameterArray());
1125 Object[] convArgs = args.clone();
1126 for (int i = 0; i < args.length; i++) {
1127 Class<?> src = newType.parameterType(i);
1128 Class<?> dst = idType.parameterType(i);
1129 if (src != dst)
1130 convArgs[i] = castToWrapper(convArgs[i], dst);
1131 }
jrose10f3b682010-01-07 16:16:45 -08001132 Object convResult = id.invokeVarargs(convArgs);
jrose55220c32009-10-21 23:19:48 -07001133 {
1134 Class<?> dst = newType.returnType();
1135 Class<?> src = idType.returnType();
1136 if (src != dst)
1137 convResult = castToWrapper(convResult, dst);
1138 }
1139 MethodHandle target = null;
1140 RuntimeException error = null;
1141 try {
1142 target = MethodHandles.convertArguments(id, newType);
1143 } catch (RuntimeException ex) {
1144 error = ex;
1145 }
jrose2cc9c832010-04-30 23:48:23 -07001146 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001147 System.out.println("convert "+id+ " to "+newType+" => "+target
1148 +(error == null ? "" : " !! "+error));
1149 if (positive && error != null) throw error;
1150 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1151 if (!positive) return; // negative test failed as expected
1152 assertEquals(newType, target.type());
1153 printCalled(target, id.toString(), args);
jrose10f3b682010-01-07 16:16:45 -08001154 Object result = target.invokeVarargs(args);
jrose55220c32009-10-21 23:19:48 -07001155 assertCalled(name, convArgs);
1156 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001157 if (verbosity >= 1)
1158 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001159 }
1160
1161 @Test
jrose10f3b682010-01-07 16:16:45 -08001162 public void testPermuteArguments() throws Throwable {
1163 if (CAN_SKIP_WORKING) return;
1164 startTest("permuteArguments");
1165 testPermuteArguments(4, Integer.class, 2, String.class, 0);
1166 //testPermuteArguments(6, Integer.class, 0, null, 30);
1167 //testPermuteArguments(4, Integer.class, 1, int.class, 6);
1168 }
1169 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001170 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001171 System.out.println("permuteArguments "+max+"*"+type1.getName()
1172 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1173 +(dilution > 0 ? " with dilution "+dilution : ""));
1174 int t2pos = t2c == 0 ? 0 : 1;
1175 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1176 Class<?>[] types = new Class<?>[inargs];
1177 Arrays.fill(types, type1);
1178 if (t2c != 0) {
1179 // Fill in a middle range with type2:
1180 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1181 }
1182 Object[] args = randomArgs(types);
1183 int numcases = 1;
1184 for (int outargs = 0; outargs <= max; outargs++) {
1185 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
1186 int[] reorder = new int[outargs];
1187 int casStep = dilution + 1;
1188 // Avoid some common factors:
1189 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1190 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1191 casStep++;
1192 for (int cas = 0; cas < numcases; cas += casStep) {
1193 for (int i = 0, c = cas; i < outargs; i++) {
1194 reorder[i] = c % inargs;
1195 c /= inargs;
1196 }
1197 testPermuteArguments(args, types, reorder);
1198 }
1199 numcases *= inargs;
1200 if (dilution > 10 && outargs >= 4) {
1201 // Do some special patterns, which we probably missed.
1202 // Replication of a single argument or argument pair.
1203 for (int i = 0; i < inargs; i++) {
1204 Arrays.fill(reorder, i);
1205 testPermuteArguments(args, types, reorder);
1206 for (int d = 1; d <= 2; d++) {
1207 if (i + d >= inargs) continue;
1208 for (int j = 1; j < outargs; j += 2)
1209 reorder[j] += 1;
1210 testPermuteArguments(args, types, reorder);
1211 testPermuteArguments(args, types, reverse(reorder));
1212 }
1213 }
1214 // Repetition of a sequence of 3 or more arguments.
1215 for (int i = 1; i < inargs; i++) {
1216 for (int len = 3; len <= inargs; len++) {
1217 for (int j = 0; j < outargs; j++)
1218 reorder[j] = (i + (j % len)) % inargs;
1219 testPermuteArguments(args, types, reorder);
1220 testPermuteArguments(args, types, reverse(reorder));
1221 }
1222 }
1223 }
1224 }
1225 }
1226 }
1227
1228 static int[] reverse(int[] reorder) {
1229 reorder = reorder.clone();
1230 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1231 int j = reorder.length - 1 - i;
1232 int tem = reorder[i];
1233 reorder[i] = reorder[j];
1234 reorder[j] = tem;
1235 }
1236 return reorder;
1237 }
1238
1239 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1240 countTest();
1241 if (args == null && types == null) {
1242 int max = 0;
1243 for (int j : reorder) {
1244 if (max < j) max = j;
1245 }
1246 args = randomArgs(max+1, Integer.class);
1247 }
1248 if (args == null) {
1249 args = randomArgs(types);
1250 }
1251 if (types == null) {
1252 types = new Class<?>[args.length];
1253 for (int i = 0; i < args.length; i++)
1254 types[i] = args[i].getClass();
1255 }
1256 int inargs = args.length, outargs = reorder.length;
1257 assert(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001258 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001259 System.out.println("permuteArguments "+Arrays.toString(reorder));
1260 Object[] permArgs = new Object[outargs];
1261 Class<?>[] permTypes = new Class<?>[outargs];
1262 for (int i = 0; i < outargs; i++) {
1263 permArgs[i] = args[reorder[i]];
1264 permTypes[i] = types[reorder[i]];
1265 }
jrose2cc9c832010-04-30 23:48:23 -07001266 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001267 System.out.println("in args: "+Arrays.asList(args));
1268 System.out.println("out args: "+Arrays.asList(permArgs));
1269 System.out.println("in types: "+Arrays.asList(types));
1270 System.out.println("out types: "+Arrays.asList(permTypes));
1271 }
1272 MethodType inType = MethodType.methodType(Object.class, types);
1273 MethodType outType = MethodType.methodType(Object.class, permTypes);
1274 MethodHandle target = MethodHandles.convertArguments(ValueConversions.varargsList(outargs), outType);
1275 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
1276 Object result = newTarget.invokeVarargs(args);
1277 Object expected = Arrays.asList(permArgs);
1278 assertEquals(expected, result);
1279 }
1280
1281
1282 @Test
1283 public void testSpreadArguments() throws Throwable {
1284 if (CAN_SKIP_WORKING) return;
1285 startTest("spreadArguments");
1286 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001287 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001288 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001289 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001290 for (int nargs = 0; nargs < 10; nargs++) {
1291 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1292 for (int pos = 0; pos < nargs; pos++) {
1293 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001294 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001295 }
1296 }
1297 }
1298 }
1299 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1300 countTest();
1301 MethodHandle target = ValueConversions.varargsArray(nargs);
1302 MethodHandle target2 = changeArgTypes(target, argType);
jrose2cc9c832010-04-30 23:48:23 -07001303 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001304 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1305 Object[] args = randomArgs(target2.type().parameterArray());
1306 // make sure the target does what we think it does:
1307 if (pos == 0 && nargs < 5) {
1308 Object[] check = (Object[]) target.invokeVarargs(args);
1309 assertArrayEquals(args, check);
1310 switch (nargs) {
1311 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001312 check = target.<Object[]>invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001313 assertArrayEquals(args, check);
1314 break;
1315 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001316 check = target.<Object[]>invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001317 assertArrayEquals(args, check);
1318 break;
1319 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001320 check = target.<Object[]>invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001321 assertArrayEquals(args, check);
1322 break;
1323 }
1324 }
1325 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1326 { // modify newParams in place
1327 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
1328 spreadParams.clear(); spreadParams.add(Object[].class);
1329 }
1330 MethodType newType = MethodType.methodType(Object.class, newParams);
1331 MethodHandle result = MethodHandles.spreadArguments(target2, newType);
1332 Object[] returnValue;
1333 if (pos == 0) {
jrose6869c642010-09-08 18:40:11 -07001334 Object rawRetVal = result.invokeExact(args);
1335 returnValue = (Object[]) rawRetVal;
jrose10f3b682010-01-07 16:16:45 -08001336 } else {
1337 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
1338 args1[pos] = Arrays.copyOfRange(args, pos, args.length);
1339 returnValue = (Object[]) result.invokeVarargs(args1);
1340 }
1341 assertArrayEquals(args, returnValue);
1342 }
1343
1344 @Test
1345 public void testCollectArguments() throws Throwable {
1346 if (CAN_SKIP_WORKING) return;
1347 startTest("collectArguments");
1348 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001349 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001350 System.out.println("collectArguments "+argType);
1351 for (int nargs = 0; nargs < 10; nargs++) {
1352 for (int pos = 0; pos < nargs; pos++) {
1353 if (argType == int.class) continue; // FIXME Fail_4
1354 testCollectArguments(argType, pos, nargs);
1355 }
1356 }
1357 }
1358 }
1359 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1360 countTest();
1361 // fake up a MH with the same type as the desired adapter:
1362 MethodHandle fake = ValueConversions.varargsArray(nargs);
1363 fake = changeArgTypes(fake, argType);
1364 MethodType newType = fake.type();
1365 Object[] args = randomArgs(newType.parameterArray());
1366 // here is what should happen:
1367 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1368 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1369 // here is the MH which will witness the collected argument tail:
1370 MethodHandle target = ValueConversions.varargsArray(pos+1);
1371 target = changeArgTypes(target, 0, pos, argType);
1372 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001373 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001374 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
1375 MethodHandle result = MethodHandles.collectArguments(target, newType);
1376 Object[] returnValue = (Object[]) result.invokeVarargs(args);
1377// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1378// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1379// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1380 assertArrayEquals(collectedArgs, returnValue);
1381 }
1382
1383 @Test
jrose55220c32009-10-21 23:19:48 -07001384 public void testInsertArguments() throws Throwable {
1385 if (CAN_SKIP_WORKING) return;
1386 startTest("insertArguments");
1387 for (int nargs = 0; nargs <= 4; nargs++) {
1388 for (int ins = 0; ins <= 4; ins++) {
1389 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1390 for (int pos = 0; pos <= nargs; pos++) {
1391 testInsertArguments(nargs, pos, ins);
1392 }
1393 }
1394 }
1395 }
1396
1397 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001398 countTest();
1399 MethodHandle target = ValueConversions.varargsArray(nargs + ins);
1400 Object[] args = randomArgs(target.type().parameterArray());
1401 List<Object> resList = Arrays.asList(args);
1402 List<Object> argsToPass = new ArrayList<Object>(resList);
1403 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001404 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001405 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001406 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1407 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001408 argsToInsert.clear(); // remove from argsToInsert
jrose10f3b682010-01-07 16:16:45 -08001409 Object res2 = target2.invokeVarargs(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001410 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001411 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001412 System.out.println("result: "+res2List);
1413 //if (!resList.equals(res2List))
1414 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1415 assertEquals(resList, res2List);
1416 }
1417
jrose10f3b682010-01-07 16:16:45 -08001418 @Test
1419 public void testFilterArguments() throws Throwable {
1420 if (CAN_SKIP_WORKING) return;
1421 startTest("filterArguments");
1422 for (int nargs = 1; nargs <= 6; nargs++) {
1423 for (int pos = 0; pos < nargs; pos++) {
1424 testFilterArguments(nargs, pos);
1425 }
1426 }
1427 }
1428
1429 void testFilterArguments(int nargs, int pos) throws Throwable {
1430 countTest();
1431 MethodHandle target = ValueConversions.varargsList(nargs);
1432 MethodHandle filter = ValueConversions.varargsList(1);
1433 filter = MethodHandles.convertArguments(filter, filter.type().generic());
1434 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001435 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001436 System.out.println("filter "+target+" at "+pos+" with "+filter);
1437 MethodHandle[] filters = new MethodHandle[pos*2+1];
1438 filters[pos] = filter;
1439 MethodHandle target2 = MethodHandles.filterArguments(target, filters);
1440 // Simulate expected effect of filter on arglist:
1441 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001442 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001443 List<Object> expected = Arrays.asList(filteredArgs);
1444 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001445 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001446 System.out.println("result: "+result);
1447 if (!expected.equals(result))
1448 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+argsToPass+" => "+result);
1449 assertEquals(expected, result);
1450 }
1451
1452 @Test
1453 public void testFoldArguments() throws Throwable {
1454 if (CAN_SKIP_WORKING) return;
1455 startTest("foldArguments");
1456 for (int nargs = 0; nargs <= 4; nargs++) {
1457 for (int fold = 0; fold <= nargs; fold++) {
1458 for (int pos = 0; pos <= nargs; pos++) {
1459 testFoldArguments(nargs, pos, fold);
1460 }
1461 }
1462 }
1463 }
1464
1465 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1466 if (pos != 0) return; // can fold only at pos=0 for now
1467 countTest();
1468 MethodHandle target = ValueConversions.varargsList(1 + nargs);
1469 MethodHandle combine = ValueConversions.varargsList(fold);
1470 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001471 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001472 System.out.println("fold "+target+" with "+combine);
1473 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1474 // Simulate expected effect of combiner on arglist:
1475 List<Object> expected = new ArrayList<Object>(argsToPass);
1476 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001477 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001478 System.out.println("fold: "+argsToFold+" into "+target2);
1479 Object foldedArgs = combine.invokeVarargs(argsToFold);
1480 argsToFold.add(0, foldedArgs);
1481 Object result = target2.invokeVarargs(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001482 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001483 System.out.println("result: "+result);
1484 if (!expected.equals(result))
1485 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result);
1486 assertEquals(expected, result);
1487 }
1488
1489 @Test
1490 public void testDropArguments() throws Throwable {
1491 if (CAN_SKIP_WORKING) return;
1492 startTest("dropArguments");
1493 for (int nargs = 0; nargs <= 4; nargs++) {
1494 for (int drop = 1; drop <= 4; drop++) {
1495 for (int pos = 0; pos <= nargs; pos++) {
1496 testDropArguments(nargs, pos, drop);
1497 }
1498 }
1499 }
1500 }
1501
1502 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1503 countTest();
1504 MethodHandle target = ValueConversions.varargsArray(nargs);
1505 Object[] args = randomArgs(target.type().parameterArray());
1506 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1507 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1508 List<Object> resList = Arrays.asList(args);
1509 List<Object> argsToDrop = new ArrayList<Object>(resList);
1510 for (int i = drop; i > 0; i--) {
1511 argsToDrop.add(pos, "blort#"+i);
1512 }
1513 Object res2 = target2.invokeVarargs(argsToDrop);
1514 Object res2List = Arrays.asList((Object[])res2);
1515 //if (!resList.equals(res2List))
1516 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1517 assertEquals(resList, res2List);
1518 }
1519
1520 @Test
1521 public void testInvokers() throws Throwable {
1522 if (CAN_SKIP_WORKING) return;
1523 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1524 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1525 Set<MethodType> done = new HashSet<MethodType>();
1526 for (int i = 0; i <= 6; i++) {
1527 MethodType gtype = MethodType.genericMethodType(i);
1528 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1529 for (int j = -1; j < i; j++) {
1530 MethodType type = gtype;
1531 if (j < 0)
1532 type = type.changeReturnType(argType);
1533 else if (argType == void.class)
1534 continue;
1535 else
1536 type = type.changeParameterType(j, argType);
1537 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1538 if (done.add(type))
1539 testInvokers(type);
1540 MethodType vtype = type.changeReturnType(void.class);
1541 if (done.add(vtype))
1542 testInvokers(vtype);
1543 }
1544 }
1545 }
1546 }
1547
1548 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001549 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001550 System.out.println("test invokers for "+type);
1551 int nargs = type.parameterCount();
1552 boolean testRetCode = type.returnType() != void.class;
1553 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1554 MethodType.genericMethodType(0, true));
1555 target = MethodHandles.collectArguments(target, type);
1556 Object[] args = randomArgs(type.parameterArray());
1557 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1558 targetPlusArgs.add(0, target);
1559 int code = (Integer) invokee(args);
1560 Object log = logEntry("invokee", args);
1561 assertEquals(log.hashCode(), code);
1562 assertCalled("invokee", args);
1563 MethodHandle inv;
1564 Object result;
1565 // exact invoker
1566 countTest();
1567 calledLog.clear();
1568 inv = MethodHandles.exactInvoker(type);
1569 result = inv.invokeVarargs(targetPlusArgs);
1570 if (testRetCode) assertEquals(code, result);
1571 assertCalled("invokee", args);
1572 // generic invoker
1573 countTest();
1574 inv = MethodHandles.genericInvoker(type);
1575 if (nargs <= 3) {
1576 calledLog.clear();
1577 switch (nargs) {
1578 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001579 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001580 break;
1581 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001582 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001583 break;
1584 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001585 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001586 break;
1587 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001588 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001589 break;
1590 }
1591 if (testRetCode) assertEquals(code, result);
1592 assertCalled("invokee", args);
1593 }
1594 calledLog.clear();
1595 result = inv.invokeVarargs(targetPlusArgs);
1596 if (testRetCode) assertEquals(code, result);
1597 assertCalled("invokee", args);
1598 // varargs invoker #0
1599 calledLog.clear();
1600 inv = MethodHandles.varargsInvoker(type, 0);
jrose2cc9c832010-04-30 23:48:23 -07001601 result = inv.invokeExact(target, args);
jrose10f3b682010-01-07 16:16:45 -08001602 if (testRetCode) assertEquals(code, result);
1603 assertCalled("invokee", args);
1604 if (nargs >= 1) {
1605 // varargs invoker #1
1606 calledLog.clear();
1607 inv = MethodHandles.varargsInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001608 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001609 if (testRetCode) assertEquals(code, result);
1610 assertCalled("invokee", args);
1611 }
1612 if (nargs >= 2) {
1613 // varargs invoker #2
1614 calledLog.clear();
1615 inv = MethodHandles.varargsInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001616 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001617 if (testRetCode) assertEquals(code, result);
1618 assertCalled("invokee", args);
1619 }
1620 if (nargs >= 3) {
1621 // varargs invoker #3
1622 calledLog.clear();
1623 inv = MethodHandles.varargsInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001624 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001625 if (testRetCode) assertEquals(code, result);
1626 assertCalled("invokee", args);
1627 }
1628 for (int k = 0; k <= nargs; k++) {
1629 // varargs invoker #0..N
1630 countTest();
1631 calledLog.clear();
1632 inv = MethodHandles.varargsInvoker(type, k);
1633 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1634 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1635 Object[] tail = tailList.toArray();
1636 tailList.clear(); tailList.add(tail);
1637 result = inv.invokeVarargs(targetPlusVarArgs);
1638 if (testRetCode) assertEquals(code, result);
1639 assertCalled("invokee", args);
1640 }
1641 // dynamic invoker
1642 countTest();
1643 CallSite site = new CallSite(MethodHandlesTest.class, "foo", type);
1644 inv = MethodHandles.dynamicInvoker(site);
1645 site.setTarget(target);
1646 calledLog.clear();
1647 result = inv.invokeVarargs(args);
1648 if (testRetCode) assertEquals(code, result);
1649 assertCalled("invokee", args);
1650 }
1651
1652 static Object invokee(Object... args) {
1653 return called("invokee", args).hashCode();
1654 }
1655
jrose55220c32009-10-21 23:19:48 -07001656 private static final String MISSING_ARG = "missingArg";
1657 static Object targetIfEquals() {
1658 return called("targetIfEquals");
1659 }
1660 static Object fallbackIfNotEquals() {
1661 return called("fallbackIfNotEquals");
1662 }
1663 static Object targetIfEquals(Object x) {
1664 assertEquals(x, MISSING_ARG);
1665 return called("targetIfEquals", x);
1666 }
1667 static Object fallbackIfNotEquals(Object x) {
1668 assertFalse(x.toString(), x.equals(MISSING_ARG));
1669 return called("fallbackIfNotEquals", x);
1670 }
1671 static Object targetIfEquals(Object x, Object y) {
1672 assertEquals(x, y);
1673 return called("targetIfEquals", x, y);
1674 }
1675 static Object fallbackIfNotEquals(Object x, Object y) {
1676 assertFalse(x.toString(), x.equals(y));
1677 return called("fallbackIfNotEquals", x, y);
1678 }
1679 static Object targetIfEquals(Object x, Object y, Object z) {
1680 assertEquals(x, y);
1681 return called("targetIfEquals", x, y, z);
1682 }
1683 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1684 assertFalse(x.toString(), x.equals(y));
1685 return called("fallbackIfNotEquals", x, y, z);
1686 }
1687
jrose10f3b682010-01-07 16:16:45 -08001688 @Test
1689 public void testGuardWithTest() throws Throwable {
1690 if (CAN_SKIP_WORKING) return;
1691 startTest("guardWithTest");
1692 for (int nargs = 0; nargs <= 3; nargs++) {
1693 if (nargs != 2) continue; // FIXME: test more later
1694 testGuardWithTest(nargs, Object.class);
1695 testGuardWithTest(nargs, String.class);
1696 }
1697 }
1698 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1699 countTest();
1700 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1701 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1702 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1703 while (test.type().parameterCount() < nargs)
1704 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1705 while (test.type().parameterCount() > nargs)
1706 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1707 if (argClass != Object.class) {
1708 test = changeArgTypes(test, argClass);
1709 target = changeArgTypes(target, argClass);
1710 fallback = changeArgTypes(fallback, argClass);
1711 }
1712 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1713 assertEquals(target.type(), mh.type());
1714 Object[][] argLists = {
1715 { },
1716 { "foo" }, { MISSING_ARG },
1717 { "foo", "foo" }, { "foo", "bar" },
1718 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1719 };
1720 for (Object[] argList : argLists) {
1721 if (argList.length != nargs) continue;
1722 boolean equals;
1723 switch (nargs) {
1724 case 0: equals = true; break;
1725 case 1: equals = MISSING_ARG.equals(argList[0]); break;
1726 default: equals = argList[0].equals(argList[1]); break;
1727 }
1728 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07001729 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001730 System.out.println(logEntry(willCall, argList));
1731 Object result = mh.invokeVarargs(argList);
1732 assertCalled(willCall, argList);
1733 }
1734 }
1735
1736 @Test
1737 public void testCatchException() throws Throwable {
1738 if (CAN_SKIP_WORKING) return;
1739 startTest("catchException");
1740 for (int nargs = 2; nargs <= 6; nargs++) {
1741 for (int ti = 0; ti <= 1; ti++) {
1742 boolean throwIt = (ti != 0);
1743 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
1744 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
1745 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
1746 }
1747 }
1748 }
1749
1750 private static <T extends Throwable>
1751 Object throwOrReturn(Object normal, T exception) throws T {
1752 if (exception != null) throw exception;
1753 return normal;
1754 }
1755
1756 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
1757 countTest();
jrose2cc9c832010-04-30 23:48:23 -07001758 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001759 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
1760 Class<? extends Throwable> exType = thrown.getClass();
1761 MethodHandle throwOrReturn
1762 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
1763 MethodType.methodType(Object.class, Object.class, Throwable.class));
1764 MethodHandle thrower = throwOrReturn;
1765 while (thrower.type().parameterCount() < nargs)
1766 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
1767 MethodHandle target = MethodHandles.catchException(thrower,
1768 thrown.getClass(), ValueConversions.varargsList(1+nargs));
1769 assertEquals(thrower.type(), target.type());
1770 //System.out.println("catching with "+target+" : "+throwOrReturn);
1771 Object[] args = randomArgs(nargs, Object.class);
1772 args[1] = (throwIt ? thrown : null);
1773 Object returned = target.invokeVarargs(args);
1774 //System.out.println("return from "+target+" : "+returned);
1775 if (!throwIt) {
1776 assertSame(args[0], returned);
1777 } else {
1778 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
1779 catchArgs.add(0, thrown);
1780 assertEquals(catchArgs, returned);
1781 }
1782 }
1783
1784 @Test
1785 public void testThrowException() throws Throwable {
1786 if (CAN_SKIP_WORKING) return;
1787 startTest("throwException");
1788 testThrowException(int.class, new ClassCastException("testing"));
1789 testThrowException(void.class, new java.io.IOException("testing"));
1790 testThrowException(String.class, new LinkageError("testing"));
1791 }
1792
1793 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
1794 countTest();
1795 Class<? extends Throwable> exType = thrown.getClass();
1796 MethodHandle target = MethodHandles.throwException(returnType, exType);
1797 //System.out.println("throwing with "+target+" : "+thrown);
1798 MethodType expectedType = MethodType.methodType(returnType, exType);
1799 assertEquals(expectedType, target.type());
jrose2cc9c832010-04-30 23:48:23 -07001800 target = MethodHandles.convertArguments(target, target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001801 Throwable caught = null;
1802 try {
jrose2cc9c832010-04-30 23:48:23 -07001803 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08001804 fail("got "+res+" instead of throwing "+thrown);
1805 } catch (Throwable ex) {
1806 if (ex != thrown) {
1807 if (ex instanceof Error) throw (Error)ex;
1808 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
1809 }
1810 caught = ex;
1811 }
1812 assertSame(thrown, caught);
1813 }
1814
1815 @Test
1816 public void testCastFailure() throws Throwable {
1817 if (CAN_SKIP_WORKING) return;
1818 startTest("testCastFailure");
1819 testCastFailure("cast/argument", 11000);
1820 testCastFailure("unbox/argument", 11000);
1821 testCastFailure("cast/return", 11000);
1822 testCastFailure("unbox/return", 11000);
1823 }
1824
jrosea1ebbe62010-09-08 18:40:23 -07001825 static class Surprise implements MethodHandleProvider {
1826 public MethodHandle asMethodHandle() {
1827 return VALUE.bindTo(this);
1828 }
1829 public MethodHandle asMethodHandle(MethodType type) {
1830 return asMethodHandle().asType(type);
1831 }
jrose10f3b682010-01-07 16:16:45 -08001832 Object value(Object x) {
1833 trace("value", x);
1834 if (boo != null) return boo;
1835 return x;
1836 }
1837 Object boo;
1838 void boo(Object x) { boo = x; }
1839
1840 static void trace(String x, Object y) {
1841 if (verbosity > 8) System.out.println(x+"="+y);
1842 }
1843 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
1844 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
1845 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07001846 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
1847 static {
1848 try {
1849 VALUE = PRIVATE.findVirtual(
1850 Surprise.class, "value",
1851 MethodType.methodType(Object.class, Object.class));
1852 REF_IDENTITY = PRIVATE.findStatic(
1853 Surprise.class, "refIdentity",
1854 MethodType.methodType(Object.class, Object.class));
1855 BOX_IDENTITY = PRIVATE.findStatic(
1856 Surprise.class, "boxIdentity",
1857 MethodType.methodType(Integer.class, Integer.class));
1858 INT_IDENTITY = PRIVATE.findStatic(
1859 Surprise.class, "intIdentity",
1860 MethodType.methodType(int.class, int.class));
1861 } catch (Exception ex) {
1862 throw new RuntimeException(ex);
1863 }
1864 }
jrose10f3b682010-01-07 16:16:45 -08001865 }
1866
1867 void testCastFailure(String mode, int okCount) throws Throwable {
1868 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07001869 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08001870 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07001871 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08001872 if (mode.endsWith("/return")) {
1873 if (mode.equals("unbox/return")) {
1874 // fail on return to ((Integer)surprise).intValue
1875 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(int.class, Object.class));
1876 identity = MethodHandles.convertArguments(identity, MethodType.methodType(int.class, Object.class));
1877 } else if (mode.equals("cast/return")) {
1878 // fail on return to (Integer)surprise
1879 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(Integer.class, Object.class));
1880 identity = MethodHandles.convertArguments(identity, MethodType.methodType(Integer.class, Object.class));
1881 }
1882 } else if (mode.endsWith("/argument")) {
1883 MethodHandle callee = null;
1884 if (mode.equals("unbox/argument")) {
1885 // fail on handing surprise to int argument
1886 callee = Surprise.INT_IDENTITY;
1887 } else if (mode.equals("cast/argument")) {
1888 // fail on handing surprise to Integer argument
1889 callee = Surprise.BOX_IDENTITY;
1890 }
1891 if (callee != null) {
1892 callee = MethodHandles.convertArguments(callee, MethodType.genericMethodType(1));
1893 surprise = MethodHandles.filterArguments(callee, surprise);
1894 identity = MethodHandles.filterArguments(callee, identity);
1895 }
1896 }
jrosea1ebbe62010-09-08 18:40:23 -07001897 assertNotSame(mode, surprise, surprise0);
jrose10f3b682010-01-07 16:16:45 -08001898 identity = MethodHandles.convertArguments(identity, MethodType.genericMethodType(1));
1899 surprise = MethodHandles.convertArguments(surprise, MethodType.genericMethodType(1));
1900 Object x = 42;
1901 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07001902 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001903 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07001904 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001905 assertEquals(x, z);
1906 }
1907 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07001908 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001909 assertEquals(x, y);
1910 try {
jrose2cc9c832010-04-30 23:48:23 -07001911 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08001912 System.out.println("Failed to throw; got z="+z);
1913 assertTrue(false);
1914 } catch (Exception ex) {
jrose10f3b682010-01-07 16:16:45 -08001915 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07001916 System.out.println("caught "+ex);
1917 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08001918 ex.printStackTrace();
1919 assertTrue(ex instanceof ClassCastException
1920 // FIXME: accept only one of the two for any given unit test
1921 || ex instanceof WrongMethodTypeException
1922 );
1923 }
1924 }
1925
jrose45b7a332010-05-03 23:32:47 -07001926 static Example userMethod(Object o, String s, int i) {
1927 called("userMethod", o, s, i);
1928 return null;
1929 }
1930
1931 @Test
1932 public void testUserClassInSignature() throws Throwable {
1933 if (CAN_SKIP_WORKING) return;
1934 startTest("testUserClassInSignature");
1935 Lookup lookup = MethodHandles.lookup();
1936 String name; MethodType mt; MethodHandle mh;
1937 Object[] args;
1938
1939 // Try a static method.
1940 name = "userMethod";
1941 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
1942 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
1943 assertEquals(mt, mh.type());
1944 assertEquals(Example.class, mh.type().returnType());
1945 args = randomArgs(mh.type().parameterArray());
1946 mh.invokeVarargs(args);
1947 assertCalled(name, args);
1948
1949 // Try a virtual method.
1950 name = "v2";
1951 mt = MethodType.methodType(Object.class, Object.class, int.class);
1952 mh = lookup.findVirtual(Example.class, name, mt);
1953 assertEquals(mt, mh.type().dropParameterTypes(0,1));
1954 assertTrue(mh.type().parameterList().contains(Example.class));
1955 args = randomArgs(mh.type().parameterArray());
1956 mh.invokeVarargs(args);
1957 assertCalled(name, args);
1958 }
jrose55220c32009-10-21 23:19:48 -07001959}
1960// Local abbreviated copy of sun.dyn.util.ValueConversions
1961class ValueConversions {
1962 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
1963 private static final Object[] NO_ARGS_ARRAY = {};
1964 private static Object[] makeArray(Object... args) { return args; }
1965 private static Object[] array() { return NO_ARGS_ARRAY; }
1966 private static Object[] array(Object a0)
1967 { return makeArray(a0); }
1968 private static Object[] array(Object a0, Object a1)
1969 { return makeArray(a0, a1); }
1970 private static Object[] array(Object a0, Object a1, Object a2)
1971 { return makeArray(a0, a1, a2); }
1972 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1973 { return makeArray(a0, a1, a2, a3); }
1974 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1975 Object a4)
1976 { return makeArray(a0, a1, a2, a3, a4); }
1977 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1978 Object a4, Object a5)
1979 { return makeArray(a0, a1, a2, a3, a4, a5); }
1980 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1981 Object a4, Object a5, Object a6)
1982 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1983 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1984 Object a4, Object a5, Object a6, Object a7)
1985 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1986 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1987 Object a4, Object a5, Object a6, Object a7,
1988 Object a8)
1989 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1990 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1991 Object a4, Object a5, Object a6, Object a7,
1992 Object a8, Object a9)
1993 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1994 static MethodHandle[] makeArrays() {
1995 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
1996 MethodHandles.Lookup lookup = IMPL_LOOKUP;
1997 for (;;) {
1998 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08001999 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002000 String name = "array";
2001 MethodHandle array = null;
2002 try {
2003 array = lookup.findStatic(ValueConversions.class, name, type);
2004 } catch (NoAccessException ex) {
2005 }
2006 if (array == null) break;
2007 arrays.add(array);
2008 }
2009 assert(arrays.size() == 11); // current number of methods
2010 return arrays.toArray(new MethodHandle[0]);
2011 }
2012 static final MethodHandle[] ARRAYS = makeArrays();
2013
2014 /** Return a method handle that takes the indicated number of Object
2015 * arguments and returns an Object array of them, as if for varargs.
2016 */
2017 public static MethodHandle varargsArray(int nargs) {
2018 if (nargs < ARRAYS.length)
2019 return ARRAYS[nargs];
2020 // else need to spin bytecode or do something else fancy
jrose2cc9c832010-04-30 23:48:23 -07002021 throw new UnsupportedOperationException("NYI: cannot form a varargs array of length "+nargs);
jrose55220c32009-10-21 23:19:48 -07002022 }
jrose10f3b682010-01-07 16:16:45 -08002023
2024 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2025 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2026 private static List<Object> list() { return NO_ARGS_LIST; }
2027 private static List<Object> list(Object a0)
2028 { return makeList(a0); }
2029 private static List<Object> list(Object a0, Object a1)
2030 { return makeList(a0, a1); }
2031 private static List<Object> list(Object a0, Object a1, Object a2)
2032 { return makeList(a0, a1, a2); }
2033 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2034 { return makeList(a0, a1, a2, a3); }
2035 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2036 Object a4)
2037 { return makeList(a0, a1, a2, a3, a4); }
2038 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2039 Object a4, Object a5)
2040 { return makeList(a0, a1, a2, a3, a4, a5); }
2041 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2042 Object a4, Object a5, Object a6)
2043 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2044 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2045 Object a4, Object a5, Object a6, Object a7)
2046 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2047 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2048 Object a4, Object a5, Object a6, Object a7,
2049 Object a8)
2050 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2051 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2052 Object a4, Object a5, Object a6, Object a7,
2053 Object a8, Object a9)
2054 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2055 static MethodHandle[] makeLists() {
2056 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2057 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2058 for (;;) {
2059 int nargs = arrays.size();
2060 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2061 String name = "list";
2062 MethodHandle array = null;
2063 try {
2064 array = lookup.findStatic(ValueConversions.class, name, type);
2065 } catch (NoAccessException ex) {
2066 }
2067 if (array == null) break;
2068 arrays.add(array);
2069 }
2070 assert(arrays.size() == 11); // current number of methods
2071 return arrays.toArray(new MethodHandle[0]);
2072 }
2073 static final MethodHandle[] LISTS = makeLists();
2074
2075 /** Return a method handle that takes the indicated number of Object
2076 * arguments and returns List.
2077 */
2078 public static MethodHandle varargsList(int nargs) {
2079 if (nargs < LISTS.length)
2080 return LISTS[nargs];
2081 // else need to spin bytecode or do something else fancy
2082 throw new UnsupportedOperationException("NYI");
2083 }
jrose55220c32009-10-21 23:19:48 -07002084}
2085// This guy tests access from outside the same package member, but inside
2086// the package itself.
2087class PackageSibling {
2088 static Lookup lookup() {
2089 return MethodHandles.lookup();
2090 }
2091}