blob: ce06a4a478d4d10b7af0864d5480716a12d298bd [file] [log] [blame]
jrose55220c32009-10-21 23:19:48 -07001/*
jrosef108fc02011-02-11 01:26:24 -08002 * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
jrose55220c32009-10-21 23:19:48 -07003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
ohair2283b9d2010-05-25 15:58:33 -07007 * published by the Free Software Foundation. Oracle designates this
jrose55220c32009-10-21 23:19:48 -07008 * particular file as subject to the "Classpath" exception as provided
ohair2283b9d2010-05-25 15:58:33 -07009 * by Oracle in the LICENSE file that accompanied this code.
jrose55220c32009-10-21 23:19:48 -070010 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
ohair2283b9d2010-05-25 15:58:33 -070021 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
jrose55220c32009-10-21 23:19:48 -070024 */
25
26/* @test
27 * @summary unit tests for java.dyn.MethodHandles
jrose1c1bfac2010-11-22 22:41:31 -080028 * @compile -source 7 -target 7 -XDallowTransitionalJSR292=no MethodHandlesTest.java
29 * @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableMethodHandles 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
jrose55220c32009-10-21 23:19:48 -070065 @Test
66 public void testFirst() throws Throwable {
67 verbosity += 9; try {
68 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070069 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070070 }
71
jrose10f3b682010-01-07 16:16:45 -080072 // current failures
73 @Test @Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
74 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070075 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080076 testSpreadArguments(int.class, 0, 6);
77 }
jrose2cc9c832010-04-30 23:48:23 -070078 @Test @Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080079 public void testFail_2() throws Throwable {
80 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
81 testSpreadArguments(Object.class, 0, 2);
82 }
83 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
84 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070085 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080086 testSpreadArguments(int.class, 1, 2);
87 }
88 @Test @Ignore("IllArgEx failure in call to ToGeneric.make")
89 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070090 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080091 testCollectArguments(int.class, 1, 2);
92 }
93 @Test @Ignore("cannot collect leading primitive types")
94 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070095 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080096 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
97 }
98 @Test @Ignore("should not insert arguments beyond MethodHandlePushLimit")
99 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700100 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
101 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800102 }
jrose55220c32009-10-21 23:19:48 -0700103 static final int MAX_ARG_INCREASE = 3;
104
105 public MethodHandlesTest() {
106 }
107
jrose2cc9c832010-04-30 23:48:23 -0700108 @Before
109 public void checkImplementedPlatform() {
110 boolean platformOK = false;
111 Properties properties = System.getProperties();
112 String vers = properties.getProperty("java.vm.version");
113 String name = properties.getProperty("java.vm.name");
114 String arch = properties.getProperty("os.arch");
jrosecf98d422010-06-08 23:08:56 -0700115 if ((arch.equals("amd64") || arch.equals("i386") || arch.equals("x86") ||
jrose2cc9c832010-04-30 23:48:23 -0700116 arch.equals("sparc") || arch.equals("sparcv9")) &&
117 (name.contains("Client") || name.contains("Server"))
118 ) {
119 platformOK = true;
120 } else {
121 System.err.println("Skipping tests for unsupported platform: "+Arrays.asList(vers, name, arch));
122 }
123 assumeTrue(platformOK);
124 }
125
jrose55220c32009-10-21 23:19:48 -0700126 String testName;
jrosecf98d422010-06-08 23:08:56 -0700127 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700128 int posTests, negTests;
129 @After
130 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700131 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700132 System.out.println();
133 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
134 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700135 allPosTests += posTests;
136 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700137 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700138 }
139 }
140 void countTest(boolean positive) {
141 if (positive) ++posTests;
142 else ++negTests;
143 }
144 void countTest() { countTest(true); }
145 void startTest(String name) {
146 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700147 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700148 System.out.println(name);
149 posTests = negTests = 0;
150 testName = name;
151 }
152
153 @BeforeClass
154 public static void setUpClass() throws Exception {
155 calledLog.clear();
156 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700157 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700158 }
159
160 @AfterClass
161 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700162 int posTests = allPosTests, negTests = allNegTests;
163 if (verbosity >= 2 && (posTests | negTests) != 0) {
164 System.out.println();
165 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
166 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
167 }
jrose55220c32009-10-21 23:19:48 -0700168 }
169
170 static List<Object> calledLog = new ArrayList<Object>();
171 static Object logEntry(String name, Object... args) {
172 return Arrays.asList(name, Arrays.asList(args));
173 }
174 static Object called(String name, Object... args) {
175 Object entry = logEntry(name, args);
176 calledLog.add(entry);
177 return entry;
178 }
179 static void assertCalled(String name, Object... args) {
180 Object expected = logEntry(name, args);
181 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700182 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700183 System.out.println("assertCalled "+name+":");
184 System.out.println("expected: "+expected);
185 System.out.println("actual: "+actual);
186 System.out.println("ex. types: "+getClasses(expected));
187 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700188 assertEquals("previous method call", expected, actual);
189 }
190 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700191 if (verbosity >= 3)
192 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700193 }
194
195 static Object castToWrapper(Object value, Class<?> dst) {
196 Object wrap = null;
197 if (value instanceof Number)
198 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
199 if (value instanceof Character)
200 wrap = castToWrapperOrNull((char)(Character)value, dst);
201 if (wrap != null) return wrap;
202 return dst.cast(value);
203 }
204
205 static Object castToWrapperOrNull(long value, Class<?> dst) {
206 if (dst == int.class || dst == Integer.class)
207 return (int)(value);
208 if (dst == long.class || dst == Long.class)
209 return (long)(value);
210 if (dst == char.class || dst == Character.class)
211 return (char)(value);
212 if (dst == short.class || dst == Short.class)
213 return (short)(value);
214 if (dst == float.class || dst == Float.class)
215 return (float)(value);
216 if (dst == double.class || dst == Double.class)
217 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800218 if (dst == byte.class || dst == Byte.class)
219 return (byte)(value);
220 if (dst == boolean.class || dst == boolean.class)
221 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700222 return null;
223 }
224
jrose2cc9c832010-04-30 23:48:23 -0700225 static final int ONE_MILLION = (1000*1000), // first int value
226 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
227 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
228 static long nextArgVal;
229 static long nextArg(boolean moreBits) {
230 long val = nextArgVal++;
231 long sign = -(val & 1); // alternate signs
232 val >>= 1;
233 if (moreBits)
234 // Guarantee some bits in the high word.
235 // In any case keep the decimal representation simple-looking,
236 // with lots of zeroes, so as not to make the printed decimal
237 // strings unnecessarily noisy.
238 val += (val % ONE_MILLION) * TEN_BILLION;
239 return val ^ sign;
240 }
241 static int nextArg() {
242 // Produce a 32-bit result something like ONE_MILLION+(smallint).
243 // Example: 1_000_042.
244 return (int) nextArg(false);
245 }
246 static long nextArg(Class<?> kind) {
247 if (kind == long.class || kind == Long.class ||
248 kind == double.class || kind == Double.class)
249 // produce a 64-bit result something like
250 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
251 // Example: 10_000_420_001_000_042.
252 return nextArg(true);
253 return (long) nextArg();
254 }
255
jrose55220c32009-10-21 23:19:48 -0700256 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700257 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700258 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700259 return wrap;
260 }
261// import sun.dyn.util.Wrapper;
262// Wrapper wrap = Wrapper.forBasicType(dst);
263// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
264// wrap = Wrapper.forWrapperType(dst);
265// if (wrap != Wrapper.OBJECT)
266// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700267 if (param.isInterface()) {
268 for (Class<?> c : param.getClasses()) {
269 if (param.isAssignableFrom(c) && !c.isInterface())
270 { param = c; break; }
271 }
272 }
jrose55220c32009-10-21 23:19:48 -0700273 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700274 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700275 else
276 try {
277 return param.newInstance();
278 } catch (InstantiationException ex) {
279 } catch (IllegalAccessException ex) {
280 }
281 return null; // random class not Object, String, Integer, etc.
282 }
283 static Object[] randomArgs(Class<?>... params) {
284 Object[] args = new Object[params.length];
285 for (int i = 0; i < args.length; i++)
286 args[i] = randomArg(params[i]);
287 return args;
288 }
289 static Object[] randomArgs(int nargs, Class<?> param) {
290 Object[] args = new Object[nargs];
291 for (int i = 0; i < args.length; i++)
292 args[i] = randomArg(param);
293 return args;
294 }
295
296 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
297 return Arrays.copyOf(a, a.length, atype);
298 }
299 static <T> T[] cat(T[] a, T... b) {
300 int alen = a.length, blen = b.length;
301 if (blen == 0) return a;
302 T[] c = Arrays.copyOf(a, alen + blen);
303 System.arraycopy(b, 0, c, alen, blen);
304 return c;
305 }
306 static Integer[] boxAll(int... vx) {
307 Integer[] res = new Integer[vx.length];
308 for (int i = 0; i < res.length; i++) {
309 res[i] = vx[i];
310 }
311 return res;
312 }
313 static Object getClasses(Object x) {
314 if (x == null) return x;
315 if (x instanceof String) return x; // keep the name
316 if (x instanceof List) {
317 // recursively report classes of the list elements
318 Object[] xa = ((List)x).toArray();
319 for (int i = 0; i < xa.length; i++)
320 xa[i] = getClasses(xa[i]);
321 return Arrays.asList(xa);
322 }
323 return x.getClass().getSimpleName();
324 }
325
jroseadc650a2011-02-11 01:26:28 -0800326 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
327 static MethodHandle varargsList(int arity) {
328 return ValueConversions.varargsList(arity);
329 }
330 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
331 static MethodHandle varargsArray(int arity) {
332 return ValueConversions.varargsArray(arity);
333 }
334 /** Variation of varargsList, but with the given rtype. */
335 static MethodHandle varargsList(int arity, Class<?> rtype) {
336 MethodHandle list = varargsList(arity);
337 MethodType listType = list.type().changeReturnType(rtype);
338 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
339 // OK
340 } else if (rtype.isAssignableFrom(String.class)) {
341 if (LIST_TO_STRING == null)
342 try {
343 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
344 MethodType.methodType(String.class, List.class));
345 } catch (Exception ex) { throw new RuntimeException(ex); }
346 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
347 } else if (rtype.isPrimitive()) {
348 if (LIST_TO_INT == null)
349 try {
350 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
351 MethodType.methodType(int.class, List.class));
352 } catch (Exception ex) { throw new RuntimeException(ex); }
353 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
354 list = MethodHandles.explicitCastArguments(list, listType);
355 } else {
356 throw new RuntimeException("varargsList: "+rtype);
357 }
358 return list.asType(listType);
359 }
360 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
361 private static String listToString(List x) { return x.toString(); }
362 private static int listToInt(List x) { return x.toString().hashCode(); }
363
jrose55220c32009-10-21 23:19:48 -0700364 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
365 return changeArgTypes(target, 0, 999, argType);
366 }
367 static MethodHandle changeArgTypes(MethodHandle target,
368 int beg, int end, Class<?> argType) {
369 MethodType targetType = target.type();
370 end = Math.min(end, targetType.parameterCount());
371 ArrayList<Class<?>> argTypes = new ArrayList<Class<?>>(targetType.parameterList());
372 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800373 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose55220c32009-10-21 23:19:48 -0700374 return MethodHandles.convertArguments(target, ttype2);
375 }
376
377 // This lookup is good for all members in and under MethodHandlesTest.
378 static final Lookup PRIVATE = MethodHandles.lookup();
379 // This lookup is good for package-private members but not private ones.
380 static final Lookup PACKAGE = PackageSibling.lookup();
381 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800382 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700383
384 // Subject methods...
385 static class Example implements IntExample {
386 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700387 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700388 protected Example(String name) { this.name = name; }
389 protected Example(int x) { this(); called("protected <init>", this, x); }
390 @Override public String toString() { return name; }
391
392 public void v0() { called("v0", this); }
393 void pkg_v0() { called("pkg_v0", this); }
394 private void pri_v0() { called("pri_v0", this); }
395 public static void s0() { called("s0"); }
396 static void pkg_s0() { called("pkg_s0"); }
397 private static void pri_s0() { called("pri_s0"); }
398
399 public Object v1(Object x) { return called("v1", this, x); }
400 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
401 public Object v2(Object x, int y) { return called("v2", this, x, y); }
402 public Object v2(int x, Object y) { return called("v2", this, x, y); }
403 public Object v2(int x, int y) { return called("v2", this, x, y); }
404 public static Object s1(Object x) { return called("s1", x); }
405 public static Object s2(int x) { return called("s2", x); }
406 public static Object s3(long x) { return called("s3", x); }
407 public static Object s4(int x, int y) { return called("s4", x, y); }
408 public static Object s5(long x, int y) { return called("s5", x, y); }
409 public static Object s6(int x, long y) { return called("s6", x, y); }
410 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700411
412 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700413 }
jrose2cc9c832010-04-30 23:48:23 -0700414 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700415 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700416 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700417 }
418 static class SubExample extends Example {
419 @Override public void v0() { called("Sub/v0", this); }
420 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
421 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700422 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700423 }
424 public static interface IntExample {
425 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700426 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700427 public void v0() { called("Int/v0", this); }
428 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700429 public Impl() { name = "Impl#"+nextArg(); }
430 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700431 }
432 }
433
434 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700435 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
436 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
437 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
438 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700439 };
440
jrose2cc9c832010-04-30 23:48:23 -0700441 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
442 Object[][] cases;
443 if (name.contains("pri_") || isSpecial) {
444 cases = ACCESS_CASES[1]; // PRIVATE only
445 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
446 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800447 } else {
448 assertTrue(name.indexOf('_') < 0);
449 boolean pubc = Modifier.isPublic(defc.getModifiers());
450 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700451 cases = ACCESS_CASES[3]; // all access levels
452 else
453 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800454 }
jrose2cc9c832010-04-30 23:48:23 -0700455 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
456 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
457 return cases;
458 }
459 static Object[][] accessCases(Class<?> defc, String name) {
460 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700461 }
462
463 @Test
464 public void testFindStatic() throws Throwable {
465 if (CAN_SKIP_WORKING) return;
466 startTest("findStatic");
467 testFindStatic(PubExample.class, void.class, "s0");
468 testFindStatic(Example.class, void.class, "s0");
469 testFindStatic(Example.class, void.class, "pkg_s0");
470 testFindStatic(Example.class, void.class, "pri_s0");
471
472 testFindStatic(Example.class, Object.class, "s1", Object.class);
473 testFindStatic(Example.class, Object.class, "s2", int.class);
474 testFindStatic(Example.class, Object.class, "s3", long.class);
475 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
476 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
477 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
478 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
479
480 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
481 }
482
483 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
484 for (Object[] ac : accessCases(defc, name)) {
485 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
486 }
487 }
488 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
489 testFindStatic(true, lookup, defc, ret, name, params);
490 }
491 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
492 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800493 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700494 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700495 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700496 try {
jrose2cc9c832010-04-30 23:48:23 -0700497 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700498 target = lookup.in(defc).findStatic(defc, name, type);
jrose55220c32009-10-21 23:19:48 -0700499 } catch (NoAccessException ex) {
500 noAccess = ex;
501 }
jrose2cc9c832010-04-30 23:48:23 -0700502 if (verbosity >= 3)
503 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700504 +(noAccess == null ? "" : " !! "+noAccess));
505 if (positive && noAccess != null) throw noAccess;
506 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
507 if (!positive) return; // negative test failed as expected
508 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700509 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700510 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
511 Object[] args = randomArgs(params);
512 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700513 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700514 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700515 if (verbosity >= 1)
516 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700517 }
518
jrose900bafd2010-10-30 21:08:23 -0700519 // rough check of name string
520 static void assertNameStringContains(Object x, String s) {
521 if (x.toString().contains(s)) return;
522 assertEquals(s, x);
523 }
524
jrose55220c32009-10-21 23:19:48 -0700525 @Test
526 public void testFindVirtual() throws Throwable {
527 if (CAN_SKIP_WORKING) return;
528 startTest("findVirtual");
529 testFindVirtual(Example.class, void.class, "v0");
530 testFindVirtual(Example.class, void.class, "pkg_v0");
531 testFindVirtual(Example.class, void.class, "pri_v0");
532 testFindVirtual(Example.class, Object.class, "v1", Object.class);
533 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
534 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
535 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
536 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
537 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
538 // test dispatch
539 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
540 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
541 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
542 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
543 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
544 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
545 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
546 }
547
548 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
549 Class<?> rcvc = defc;
550 testFindVirtual(rcvc, defc, ret, name, params);
551 }
552 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
553 for (Object[] ac : accessCases(defc, name)) {
554 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
555 }
556 }
557 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
558 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
559 }
560 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
561 countTest(positive);
562 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800563 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700564 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700565 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700566 try {
jrose2cc9c832010-04-30 23:48:23 -0700567 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700568 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrose55220c32009-10-21 23:19:48 -0700569 } catch (NoAccessException ex) {
570 noAccess = ex;
571 }
jrose2cc9c832010-04-30 23:48:23 -0700572 if (verbosity >= 3)
573 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700574 +(noAccess == null ? "" : " !! "+noAccess));
575 if (positive && noAccess != null) throw noAccess;
576 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
577 if (!positive) return; // negative test failed as expected
578 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800579 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700580 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700581 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700582 if (!DO_MORE_CALLS && lookup != PRIVATE) return;
583 Object[] argsWithSelf = randomArgs(paramsWithSelf);
584 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
585 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700586 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700587 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700588 if (verbosity >= 1)
589 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700590 }
591
592 @Test
593 public void testFindSpecial() throws Throwable {
594 if (CAN_SKIP_WORKING) return;
595 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700596 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
597 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
598 // Do some negative testing:
599 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
600 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
601 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
602 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
603 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "bogus");
604 }
jrose55220c32009-10-21 23:19:48 -0700605 }
606
jrose2cc9c832010-04-30 23:48:23 -0700607 void testFindSpecial(Class<?> specialCaller,
608 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
609 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
610 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
611 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
612 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700613 }
jrose2cc9c832010-04-30 23:48:23 -0700614 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
615 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700616 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800617 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700618 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700619 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700620 try {
jrose2cc9c832010-04-30 23:48:23 -0700621 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700622 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
623 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrose55220c32009-10-21 23:19:48 -0700624 } catch (NoAccessException ex) {
625 noAccess = ex;
626 }
jrose2cc9c832010-04-30 23:48:23 -0700627 if (verbosity >= 3)
628 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
629 +(target == null ? "" : target.type())
630 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700631 if (positive && noAccess != null) throw noAccess;
632 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
633 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700634 assertEquals(specialCaller, target.type().parameterType(0));
635 assertEquals(type, target.type().dropParameterTypes(0,1));
636 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800637 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700638 assertNameStringContains(target, name);
jrose2cc9c832010-04-30 23:48:23 -0700639 if (!DO_MORE_CALLS && lookup != PRIVATE && lookup != EXAMPLE) return;
jrose55220c32009-10-21 23:19:48 -0700640 Object[] args = randomArgs(paramsWithSelf);
641 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700642 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700643 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700644 }
645
646 @Test
647 public void testBind() throws Throwable {
648 if (CAN_SKIP_WORKING) return;
649 startTest("bind");
650 testBind(Example.class, void.class, "v0");
651 testBind(Example.class, void.class, "pkg_v0");
652 testBind(Example.class, void.class, "pri_v0");
653 testBind(Example.class, Object.class, "v1", Object.class);
654 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
655 testBind(Example.class, Object.class, "v2", Object.class, int.class);
656 testBind(Example.class, Object.class, "v2", int.class, Object.class);
657 testBind(Example.class, Object.class, "v2", int.class, int.class);
658 testBind(false, PRIVATE, Example.class, void.class, "bogus");
659 testBind(SubExample.class, void.class, "Sub/v0");
660 testBind(SubExample.class, void.class, "Sub/pkg_v0");
661 testBind(IntExample.Impl.class, void.class, "Int/v0");
662 }
663
664 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
665 for (Object[] ac : accessCases(defc, name)) {
666 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
667 }
668 }
669
670 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
671 countTest(positive);
672 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800673 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700674 Object receiver = randomArg(defc);
675 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700676 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700677 try {
jrose2cc9c832010-04-30 23:48:23 -0700678 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700679 target = lookup.in(defc).bind(receiver, methodName, type);
jrose55220c32009-10-21 23:19:48 -0700680 } catch (NoAccessException ex) {
681 noAccess = ex;
682 }
jrose2cc9c832010-04-30 23:48:23 -0700683 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700684 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
685 +(noAccess == null ? "" : " !! "+noAccess));
686 if (positive && noAccess != null) throw noAccess;
687 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
688 if (!positive) return; // negative test failed as expected
689 assertEquals(type, target.type());
690 Object[] args = randomArgs(params);
691 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700692 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700693 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
694 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700695 if (verbosity >= 1)
696 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700697 }
698
699 @Test
700 public void testUnreflect() throws Throwable {
701 if (CAN_SKIP_WORKING) return;
702 startTest("unreflect");
703 testUnreflect(Example.class, true, void.class, "s0");
704 testUnreflect(Example.class, true, void.class, "pkg_s0");
705 testUnreflect(Example.class, true, void.class, "pri_s0");
706
707 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
708 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700709 testUnreflect(Example.class, true, Object.class, "s3", long.class);
710 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
711 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
712 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700713
714 testUnreflect(Example.class, false, void.class, "v0");
715 testUnreflect(Example.class, false, void.class, "pkg_v0");
716 testUnreflect(Example.class, false, void.class, "pri_v0");
717 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
718 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
719 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
720 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
721 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
722 }
723
724 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
725 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700726 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700727 }
728 }
jrose2cc9c832010-04-30 23:48:23 -0700729 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
730 for (Object[] ac : accessCases(defc, name)) {
731 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
732 }
733 }
734 void testUnreflectMaybeSpecial(Class<?> specialCaller,
735 boolean positive, Lookup lookup,
736 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700737 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800738 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700739 Method rmethod = null;
740 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700741 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700742 try {
743 rmethod = defc.getDeclaredMethod(name, params);
744 } catch (NoSuchMethodException ex) {
745 throw new NoAccessException(ex);
746 }
jrose2cc9c832010-04-30 23:48:23 -0700747 boolean isStatic = (rcvc == null);
748 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700749 try {
jrose2cc9c832010-04-30 23:48:23 -0700750 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
751 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700752 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700753 else
jrose900bafd2010-10-30 21:08:23 -0700754 target = lookup.in(defc).unreflect(rmethod);
jrose55220c32009-10-21 23:19:48 -0700755 } catch (NoAccessException ex) {
756 noAccess = ex;
757 }
jrose2cc9c832010-04-30 23:48:23 -0700758 if (verbosity >= 3)
759 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
760 +(!isSpecial ? "" : " specialCaller="+specialCaller)
761 +( isStatic ? "" : " receiver="+rcvc)
762 +" => "+target
763 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700764 if (positive && noAccess != null) throw noAccess;
765 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
766 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700767 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700768 Class<?>[] paramsMaybeWithSelf = params;
769 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700770 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700771 }
jrose10f3b682010-01-07 16:16:45 -0800772 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700773 if (isStatic) {
774 assertEquals(typeMaybeWithSelf, target.type());
775 } else {
jrose2cc9c832010-04-30 23:48:23 -0700776 if (isSpecial)
777 assertEquals(specialCaller, target.type().parameterType(0));
778 else
779 assertEquals(defc, target.type().parameterType(0));
780 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
781 }
jrose55220c32009-10-21 23:19:48 -0700782 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
783 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700784 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700785 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700786 if (verbosity >= 1)
787 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700788 }
789
jrose2cc9c832010-04-30 23:48:23 -0700790 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
791 for (Object[] ac : accessCases(defc, name, true)) {
792 Class<?> specialCaller = rcvc;
793 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
794 }
795 }
796
797 @Test
jrose55220c32009-10-21 23:19:48 -0700798 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700799 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700800 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700801 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
802 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
803 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
804 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
805 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
806 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
807 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700808 }
809
jrose10f3b682010-01-07 16:16:45 -0800810 public static class HasFields {
811 boolean fZ = false;
812 byte fB = (byte)'B';
813 short fS = (short)'S';
814 char fC = 'C';
815 int fI = 'I';
816 long fJ = 'J';
817 float fF = 'F';
818 double fD = 'D';
819 static boolean sZ = true;
820 static byte sB = 1+(byte)'B';
821 static short sS = 1+(short)'S';
822 static char sC = 1+'C';
823 static int sI = 1+'I';
824 static long sJ = 1+'J';
825 static float sF = 1+'F';
826 static double sD = 1+'D';
827
828 Object fL = 'L';
829 String fR = "R";
830 static Object sL = 'M';
831 static String sR = "S";
832
833 static final Object[][] CASES;
834 static {
835 ArrayList<Object[]> cases = new ArrayList<Object[]>();
836 Object types[][] = {
837 {'L',Object.class}, {'R',String.class},
838 {'I',int.class}, {'J',long.class},
839 {'F',float.class}, {'D',double.class},
840 {'Z',boolean.class}, {'B',byte.class},
841 {'S',short.class}, {'C',char.class},
842 };
843 HasFields fields = new HasFields();
844 for (Object[] t : types) {
845 for (int kind = 0; kind <= 1; kind++) {
846 boolean isStatic = (kind != 0);
847 char btc = (Character)t[0];
848 String name = (isStatic ? "s" : "f") + btc;
849 Class<?> type = (Class<?>) t[1];
850 Object value;
851 Field field;
852 try {
853 field = HasFields.class.getDeclaredField(name);
854 } catch (Exception ex) {
855 throw new InternalError("no field HasFields."+name);
856 }
857 try {
858 value = field.get(fields);
859 } catch (Exception ex) {
860 throw new InternalError("cannot fetch field HasFields."+name);
861 }
862 if (type == float.class) {
863 float v = 'F';
864 if (isStatic) v++;
865 assert(value.equals(v));
866 }
867 assert(name.equals(field.getName()));
868 assert(type.equals(field.getType()));
869 assert(isStatic == (Modifier.isStatic(field.getModifiers())));
870 cases.add(new Object[]{ field, value });
871 }
872 }
873 CASES = cases.toArray(new Object[0][]);
874 }
875 }
876
jrosecf98d422010-06-08 23:08:56 -0700877 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC_FIELD = 3;
878 static boolean testModeMatches(int testMode, boolean isStatic) {
879 switch (testMode) {
880 case TEST_FIND_STATIC_FIELD: return isStatic;
881 case TEST_FIND_FIELD: return !isStatic;
882 default: return true; // unreflect matches both
883 }
884 }
885
jrose10f3b682010-01-07 16:16:45 -0800886 @Test
jrose55220c32009-10-21 23:19:48 -0700887 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700888 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700889 testGetter(TEST_UNREFLECT);
890 }
891 @Test
892 public void testFindGetter() throws Throwable {
893 startTest("findGetter");
894 testGetter(TEST_FIND_FIELD);
895 }
896 @Test
897 public void testFindStaticGetter() throws Throwable {
898 startTest("findStaticGetter");
899 testGetter(TEST_FIND_STATIC_FIELD);
900 }
901 public void testGetter(int testMode) throws Throwable {
902 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800903 for (Object[] c : HasFields.CASES) {
904 Field f = (Field)c[0];
905 Object value = c[1];
906 Class<?> type = f.getType();
jrosecf98d422010-06-08 23:08:56 -0700907 testGetter(lookup, f, type, value, testMode);
jrose10f3b682010-01-07 16:16:45 -0800908 }
909 }
jrosecf98d422010-06-08 23:08:56 -0700910 public void testGetter(MethodHandles.Lookup lookup,
911 Field f, Class<?> type, Object value, int testMode) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -0800912 boolean isStatic = Modifier.isStatic(f.getModifiers());
jrosecf98d422010-06-08 23:08:56 -0700913 Class<?> fclass = f.getDeclaringClass();
914 String fname = f.getName();
915 Class<?> ftype = f.getType();
916 if (!testModeMatches(testMode, isStatic)) return;
917 countTest(true);
jrose10f3b682010-01-07 16:16:45 -0800918 MethodType expType = MethodType.methodType(type, HasFields.class);
919 if (isStatic) expType = expType.dropParameterTypes(0, 1);
920 MethodHandle mh = lookup.unreflectGetter(f);
921 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -0700922 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -0800923 HasFields fields = new HasFields();
924 Object sawValue;
925 Class<?> rtype = type;
926 if (type != int.class) rtype = Object.class;
927 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(rtype));
928 Object expValue = value;
929 for (int i = 0; i <= 1; i++) {
930 if (isStatic) {
931 if (type == int.class)
jrose1c1bfac2010-11-22 22:41:31 -0800932 sawValue = (int) mh.invokeExact(); // do these exactly
jrose10f3b682010-01-07 16:16:45 -0800933 else
jrose2cc9c832010-04-30 23:48:23 -0700934 sawValue = mh.invokeExact();
jrose10f3b682010-01-07 16:16:45 -0800935 } else {
936 if (type == int.class)
jrose1c1bfac2010-11-22 22:41:31 -0800937 sawValue = (int) mh.invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800938 else
jrose2cc9c832010-04-30 23:48:23 -0700939 sawValue = mh.invokeExact((Object) fields);
jrose10f3b682010-01-07 16:16:45 -0800940 }
941 assertEquals(sawValue, expValue);
942 Object random = randomArg(type);
943 f.set(fields, random);
944 expValue = random;
945 }
946 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -0700947 }
948
jrose10f3b682010-01-07 16:16:45 -0800949
950 @Test
jrose55220c32009-10-21 23:19:48 -0700951 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -0700952 startTest("unreflectSetter");
953 testSetter(TEST_UNREFLECT);
954 }
955 @Test
956 public void testFindSetter() throws Throwable {
957 startTest("findSetter");
958 testSetter(TEST_FIND_FIELD);
959 }
960 @Test
961 public void testFindStaticSetter() throws Throwable {
962 startTest("findStaticSetter");
963 testSetter(TEST_FIND_STATIC_FIELD);
964 }
965 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700966 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
967 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -0800968 for (Object[] c : HasFields.CASES) {
969 Field f = (Field)c[0];
970 Object value = c[1];
971 Class<?> type = f.getType();
jrosecf98d422010-06-08 23:08:56 -0700972 testSetter(lookup, f, type, value, testMode);
jrose10f3b682010-01-07 16:16:45 -0800973 }
974 }
jrosecf98d422010-06-08 23:08:56 -0700975 public void testSetter(MethodHandles.Lookup lookup,
976 Field f, Class<?> type, Object value, int testMode) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -0800977 boolean isStatic = Modifier.isStatic(f.getModifiers());
jrosecf98d422010-06-08 23:08:56 -0700978 Class<?> fclass = f.getDeclaringClass();
979 String fname = f.getName();
980 Class<?> ftype = f.getType();
981 if (!testModeMatches(testMode, isStatic)) return;
982 countTest(true);
jrose10f3b682010-01-07 16:16:45 -0800983 MethodType expType = MethodType.methodType(void.class, HasFields.class, type);
984 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosecf98d422010-06-08 23:08:56 -0700985 MethodHandle mh;
986 if (testMode == TEST_UNREFLECT)
987 mh = lookup.unreflectSetter(f);
988 else if (testMode == TEST_FIND_FIELD)
989 mh = lookup.findSetter(fclass, fname, ftype);
990 else if (testMode == TEST_FIND_STATIC_FIELD)
991 mh = lookup.findStaticSetter(fclass, fname, ftype);
992 else throw new InternalError();
jrose10f3b682010-01-07 16:16:45 -0800993 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -0700994 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -0800995 HasFields fields = new HasFields();
996 Object sawValue;
997 Class<?> vtype = type;
998 if (type != int.class) vtype = Object.class;
999 int last = mh.type().parameterCount() - 1;
1000 mh = MethodHandles.convertArguments(mh, mh.type().generic().changeReturnType(void.class).changeParameterType(last, vtype));
1001 assertEquals(f.get(fields), value); // clean to start with
1002 for (int i = 0; i <= 1; i++) {
1003 Object putValue = randomArg(type);
1004 if (isStatic) {
1005 if (type == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001006 mh.invokeExact((int)putValue); // do these exactly
jrose10f3b682010-01-07 16:16:45 -08001007 else
jrose1c1bfac2010-11-22 22:41:31 -08001008 mh.invokeExact(putValue);
jrose10f3b682010-01-07 16:16:45 -08001009 } else {
1010 if (type == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001011 mh.invokeExact((Object) fields, (int)putValue);
jrose10f3b682010-01-07 16:16:45 -08001012 else
jrose1c1bfac2010-11-22 22:41:31 -08001013 mh.invokeExact((Object) fields, putValue);
jrose10f3b682010-01-07 16:16:45 -08001014 }
1015 assertEquals(f.get(fields), putValue);
1016 }
1017 f.set(fields, value); // put it back
jrose55220c32009-10-21 23:19:48 -07001018 }
1019
jrose10f3b682010-01-07 16:16:45 -08001020 @Test
jrose55220c32009-10-21 23:19:48 -07001021 public void testArrayElementGetter() throws Throwable {
1022 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001023 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001024 }
1025
jrose10f3b682010-01-07 16:16:45 -08001026 @Test
jrose55220c32009-10-21 23:19:48 -07001027 public void testArrayElementSetter() throws Throwable {
1028 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001029 testArrayElementGetterSetter(true);
1030 }
1031
1032 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
1033 testArrayElementGetterSetter(new Object[10], testSetter);
1034 testArrayElementGetterSetter(new String[10], testSetter);
1035 testArrayElementGetterSetter(new boolean[10], testSetter);
1036 testArrayElementGetterSetter(new byte[10], testSetter);
1037 testArrayElementGetterSetter(new char[10], testSetter);
1038 testArrayElementGetterSetter(new short[10], testSetter);
1039 testArrayElementGetterSetter(new int[10], testSetter);
1040 testArrayElementGetterSetter(new float[10], testSetter);
1041 testArrayElementGetterSetter(new long[10], testSetter);
1042 testArrayElementGetterSetter(new double[10], testSetter);
jrose10f3b682010-01-07 16:16:45 -08001043 }
1044
1045 public void testArrayElementGetterSetter(Object array, boolean testSetter) throws Throwable {
1046 countTest(true);
jrose2cc9c832010-04-30 23:48:23 -07001047 if (verbosity >= 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+Array.getLength(array)+"]");
jrose10f3b682010-01-07 16:16:45 -08001048 Class<?> arrayType = array.getClass();
1049 Class<?> elemType = arrayType.getComponentType();
1050 MethodType expType = !testSetter
1051 ? MethodType.methodType(elemType, arrayType, int.class)
1052 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1053 MethodHandle mh = !testSetter
1054 ? MethodHandles.arrayElementGetter(arrayType)
1055 : MethodHandles.arrayElementSetter(arrayType);
1056 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001057 if (elemType != int.class && elemType != boolean.class) {
1058 MethodType gtype;
1059 if (true) { // FIXME: remove this path (and remove <void> below in the mh.invokes)
1060 gtype = mh.type().changeParameterType(0, Object.class);
1061 if (testSetter)
1062 gtype = gtype.changeParameterType(2, Object.class);
1063 else
1064 gtype = gtype.changeReturnType(Object.class);
1065 } else
1066 // FIXME: This simpler path hits a bug in convertArguments => ToGeneric
1067 gtype = mh.type().generic().changeParameterType(1, int.class);
1068 mh = MethodHandles.convertArguments(mh, gtype);
1069 }
jrose10f3b682010-01-07 16:16:45 -08001070 Object sawValue, expValue;
1071 List<Object> model = array2list(array);
1072 int length = Array.getLength(array);
1073 for (int i = 0; i < length; i++) {
1074 // update array element
1075 Object random = randomArg(elemType);
1076 model.set(i, random);
1077 if (testSetter) {
1078 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001079 mh.invokeExact((int[]) array, i, (int)random);
jrose2cc9c832010-04-30 23:48:23 -07001080 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001081 mh.invokeExact((boolean[]) array, i, (boolean)random);
jrose10f3b682010-01-07 16:16:45 -08001082 else
jrose1c1bfac2010-11-22 22:41:31 -08001083 mh.invokeExact(array, i, random);
jrose10f3b682010-01-07 16:16:45 -08001084 assertEquals(model, array2list(array));
1085 } else {
1086 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001087 }
1088 if (verbosity >= 5) {
1089 List<Object> array2list = array2list(array);
1090 System.out.println("a["+i+"]="+random+" => "+array2list);
1091 if (!array2list.equals(model))
1092 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001093 }
1094 // observe array element
1095 sawValue = Array.get(array, i);
1096 if (!testSetter) {
1097 expValue = sawValue;
1098 if (elemType == int.class)
jrose1c1bfac2010-11-22 22:41:31 -08001099 sawValue = (int) mh.invokeExact((int[]) array, i);
jrose2cc9c832010-04-30 23:48:23 -07001100 else if (elemType == boolean.class)
jrose1c1bfac2010-11-22 22:41:31 -08001101 sawValue = (boolean) mh.invokeExact((boolean[]) array, i);
jrose10f3b682010-01-07 16:16:45 -08001102 else
jrose2cc9c832010-04-30 23:48:23 -07001103 sawValue = mh.invokeExact(array, i);
jrose10f3b682010-01-07 16:16:45 -08001104 assertEquals(sawValue, expValue);
1105 assertEquals(model, array2list(array));
1106 }
1107 }
1108 }
1109
1110 List<Object> array2list(Object array) {
1111 int length = Array.getLength(array);
1112 ArrayList<Object> model = new ArrayList<Object>(length);
1113 for (int i = 0; i < length; i++)
1114 model.add(Array.get(array, i));
1115 return model;
jrose55220c32009-10-21 23:19:48 -07001116 }
1117
1118 static class Callee {
1119 static Object id() { return called("id"); }
1120 static Object id(Object x) { return called("id", x); }
1121 static Object id(Object x, Object y) { return called("id", x, y); }
1122 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1123 static Object id(Object... vx) { return called("id", vx); }
1124 static MethodHandle ofType(int n) {
1125 return ofType(Object.class, n);
1126 }
1127 static MethodHandle ofType(Class<?> rtype, int n) {
1128 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001129 return ofType(MethodType.methodType(rtype, Object[].class));
1130 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001131 }
1132 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001133 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001134 }
1135 static MethodHandle ofType(MethodType type) {
1136 Class<?> rtype = type.returnType();
1137 String pfx = "";
1138 if (rtype != Object.class)
1139 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1140 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001141 try {
1142 return PRIVATE.findStatic(Callee.class, name, type);
1143 } catch (Exception ex) {
1144 throw new RuntimeException(ex);
1145 }
jrose55220c32009-10-21 23:19:48 -07001146 }
1147 }
1148
1149 @Test
1150 public void testConvertArguments() throws Throwable {
1151 if (CAN_SKIP_WORKING) return;
1152 startTest("convertArguments");
1153 testConvert(Callee.ofType(1), null, "id", int.class);
1154 testConvert(Callee.ofType(1), null, "id", String.class);
1155 testConvert(Callee.ofType(1), null, "id", Integer.class);
1156 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001157 testConvert(Callee.ofType(1), null, "id", char.class);
1158 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001159 }
1160
1161 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose900bafd2010-10-30 21:08:23 -07001162 testConvert(true, false, id, rtype, name, params);
1163 testConvert(true, true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001164 }
1165
jrose900bafd2010-10-30 21:08:23 -07001166 void testConvert(boolean positive, boolean useAsType,
1167 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001168 countTest(positive);
1169 MethodType idType = id.type();
1170 if (rtype == null) rtype = idType.returnType();
1171 for (int i = 0; i < params.length; i++) {
1172 if (params[i] == null) params[i] = idType.parameterType(i);
1173 }
1174 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001175 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001176 Object[] args = randomArgs(newType.parameterArray());
1177 Object[] convArgs = args.clone();
1178 for (int i = 0; i < args.length; i++) {
1179 Class<?> src = newType.parameterType(i);
1180 Class<?> dst = idType.parameterType(i);
1181 if (src != dst)
1182 convArgs[i] = castToWrapper(convArgs[i], dst);
1183 }
jrose900bafd2010-10-30 21:08:23 -07001184 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001185 {
1186 Class<?> dst = newType.returnType();
1187 Class<?> src = idType.returnType();
1188 if (src != dst)
1189 convResult = castToWrapper(convResult, dst);
1190 }
1191 MethodHandle target = null;
1192 RuntimeException error = null;
1193 try {
jrose900bafd2010-10-30 21:08:23 -07001194 if (useAsType)
jrose900bafd2010-10-30 21:08:23 -07001195 target = id.asType(newType);
jrosef108fc02011-02-11 01:26:24 -08001196 else
1197 target = MethodHandles.convertArguments(id, newType);
jrose55220c32009-10-21 23:19:48 -07001198 } catch (RuntimeException ex) {
1199 error = ex;
1200 }
jrose2cc9c832010-04-30 23:48:23 -07001201 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001202 System.out.println("convert "+id+ " to "+newType+" => "+target
1203 +(error == null ? "" : " !! "+error));
1204 if (positive && error != null) throw error;
1205 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1206 if (!positive) return; // negative test failed as expected
1207 assertEquals(newType, target.type());
1208 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001209 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001210 assertCalled(name, convArgs);
1211 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001212 if (verbosity >= 1)
1213 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001214 }
1215
1216 @Test
jrosef108fc02011-02-11 01:26:24 -08001217 public void testVarargsCollector() throws Throwable {
1218 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1219 MethodType.methodType(Object.class, String.class, Object[].class));
1220 vac0 = vac0.bindTo("vac");
1221 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
1222 testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1223 testConvert(true, true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1224 for (Class<?> at : new Class[] { Object.class, String.class, Integer.class }) {
1225 testConvert(true, true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1226 testConvert(true, true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
1227 }
1228 }
1229
1230 @Test
jrose10f3b682010-01-07 16:16:45 -08001231 public void testPermuteArguments() throws Throwable {
1232 if (CAN_SKIP_WORKING) return;
1233 startTest("permuteArguments");
1234 testPermuteArguments(4, Integer.class, 2, String.class, 0);
1235 //testPermuteArguments(6, Integer.class, 0, null, 30);
1236 //testPermuteArguments(4, Integer.class, 1, int.class, 6);
1237 }
1238 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001239 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001240 System.out.println("permuteArguments "+max+"*"+type1.getName()
1241 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1242 +(dilution > 0 ? " with dilution "+dilution : ""));
1243 int t2pos = t2c == 0 ? 0 : 1;
1244 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1245 Class<?>[] types = new Class<?>[inargs];
1246 Arrays.fill(types, type1);
1247 if (t2c != 0) {
1248 // Fill in a middle range with type2:
1249 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1250 }
1251 Object[] args = randomArgs(types);
1252 int numcases = 1;
1253 for (int outargs = 0; outargs <= max; outargs++) {
1254 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
1255 int[] reorder = new int[outargs];
1256 int casStep = dilution + 1;
1257 // Avoid some common factors:
1258 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1259 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1260 casStep++;
1261 for (int cas = 0; cas < numcases; cas += casStep) {
1262 for (int i = 0, c = cas; i < outargs; i++) {
1263 reorder[i] = c % inargs;
1264 c /= inargs;
1265 }
1266 testPermuteArguments(args, types, reorder);
1267 }
1268 numcases *= inargs;
1269 if (dilution > 10 && outargs >= 4) {
1270 // Do some special patterns, which we probably missed.
1271 // Replication of a single argument or argument pair.
1272 for (int i = 0; i < inargs; i++) {
1273 Arrays.fill(reorder, i);
1274 testPermuteArguments(args, types, reorder);
1275 for (int d = 1; d <= 2; d++) {
1276 if (i + d >= inargs) continue;
1277 for (int j = 1; j < outargs; j += 2)
1278 reorder[j] += 1;
1279 testPermuteArguments(args, types, reorder);
1280 testPermuteArguments(args, types, reverse(reorder));
1281 }
1282 }
1283 // Repetition of a sequence of 3 or more arguments.
1284 for (int i = 1; i < inargs; i++) {
1285 for (int len = 3; len <= inargs; len++) {
1286 for (int j = 0; j < outargs; j++)
1287 reorder[j] = (i + (j % len)) % inargs;
1288 testPermuteArguments(args, types, reorder);
1289 testPermuteArguments(args, types, reverse(reorder));
1290 }
1291 }
1292 }
1293 }
1294 }
1295 }
1296
1297 static int[] reverse(int[] reorder) {
1298 reorder = reorder.clone();
1299 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1300 int j = reorder.length - 1 - i;
1301 int tem = reorder[i];
1302 reorder[i] = reorder[j];
1303 reorder[j] = tem;
1304 }
1305 return reorder;
1306 }
1307
1308 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1309 countTest();
1310 if (args == null && types == null) {
1311 int max = 0;
1312 for (int j : reorder) {
1313 if (max < j) max = j;
1314 }
1315 args = randomArgs(max+1, Integer.class);
1316 }
1317 if (args == null) {
1318 args = randomArgs(types);
1319 }
1320 if (types == null) {
1321 types = new Class<?>[args.length];
1322 for (int i = 0; i < args.length; i++)
1323 types[i] = args[i].getClass();
1324 }
1325 int inargs = args.length, outargs = reorder.length;
1326 assert(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001327 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001328 System.out.println("permuteArguments "+Arrays.toString(reorder));
1329 Object[] permArgs = new Object[outargs];
1330 Class<?>[] permTypes = new Class<?>[outargs];
1331 for (int i = 0; i < outargs; i++) {
1332 permArgs[i] = args[reorder[i]];
1333 permTypes[i] = types[reorder[i]];
1334 }
jrose2cc9c832010-04-30 23:48:23 -07001335 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001336 System.out.println("in args: "+Arrays.asList(args));
1337 System.out.println("out args: "+Arrays.asList(permArgs));
1338 System.out.println("in types: "+Arrays.asList(types));
1339 System.out.println("out types: "+Arrays.asList(permTypes));
1340 }
1341 MethodType inType = MethodType.methodType(Object.class, types);
1342 MethodType outType = MethodType.methodType(Object.class, permTypes);
jroseadc650a2011-02-11 01:26:28 -08001343 MethodHandle target = MethodHandles.convertArguments(varargsList(outargs), outType);
jrose10f3b682010-01-07 16:16:45 -08001344 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose900bafd2010-10-30 21:08:23 -07001345 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001346 Object expected = Arrays.asList(permArgs);
1347 assertEquals(expected, result);
1348 }
1349
1350
1351 @Test
1352 public void testSpreadArguments() throws Throwable {
1353 if (CAN_SKIP_WORKING) return;
1354 startTest("spreadArguments");
1355 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001356 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001357 System.out.println("spreadArguments "+argType);
jrose2cc9c832010-04-30 23:48:23 -07001358 // FIXME: enable _adapter_spread_args and fix Fail_2
jrose10f3b682010-01-07 16:16:45 -08001359 for (int nargs = 0; nargs < 10; nargs++) {
1360 if (argType == int.class && nargs >= 6) continue; // FIXME Fail_1
1361 for (int pos = 0; pos < nargs; pos++) {
1362 if (argType == int.class && pos > 0) continue; // FIXME Fail_3
jrose2cc9c832010-04-30 23:48:23 -07001363 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001364 }
1365 }
1366 }
1367 }
1368 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1369 countTest();
jroseadc650a2011-02-11 01:26:28 -08001370 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001371 MethodHandle target2 = changeArgTypes(target, argType);
jrose2cc9c832010-04-30 23:48:23 -07001372 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001373 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1374 Object[] args = randomArgs(target2.type().parameterArray());
1375 // make sure the target does what we think it does:
1376 if (pos == 0 && nargs < 5) {
jrose900bafd2010-10-30 21:08:23 -07001377 Object[] check = (Object[]) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001378 assertArrayEquals(args, check);
1379 switch (nargs) {
1380 case 0:
jrose1c1bfac2010-11-22 22:41:31 -08001381 check = (Object[]) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001382 assertArrayEquals(args, check);
1383 break;
1384 case 1:
jrose1c1bfac2010-11-22 22:41:31 -08001385 check = (Object[]) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001386 assertArrayEquals(args, check);
1387 break;
1388 case 2:
jrose1c1bfac2010-11-22 22:41:31 -08001389 check = (Object[]) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001390 assertArrayEquals(args, check);
1391 break;
1392 }
1393 }
1394 List<Class<?>> newParams = new ArrayList<Class<?>>(target2.type().parameterList());
1395 { // modify newParams in place
1396 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
1397 spreadParams.clear(); spreadParams.add(Object[].class);
1398 }
1399 MethodType newType = MethodType.methodType(Object.class, newParams);
jroseadc650a2011-02-11 01:26:28 -08001400 MethodHandle result = target2.asSpreader(Object[].class, nargs-pos).asType(newType);
jrose10f3b682010-01-07 16:16:45 -08001401 Object[] returnValue;
1402 if (pos == 0) {
jrose1c1bfac2010-11-22 22:41:31 -08001403 // In the following line, the first cast implies
1404 // normal Object return value for the MH call (Object[])->Object,
1405 // while the second cast dynamically converts to an Object array.
1406 // Such a double cast is typical of MH.invokeExact.
1407 returnValue = (Object[]) (Object) result.invokeExact(args);
jrose10f3b682010-01-07 16:16:45 -08001408 } else {
1409 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
1410 args1[pos] = Arrays.copyOfRange(args, pos, args.length);
jrose900bafd2010-10-30 21:08:23 -07001411 returnValue = (Object[]) result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001412 }
1413 assertArrayEquals(args, returnValue);
1414 }
1415
1416 @Test
1417 public void testCollectArguments() throws Throwable {
1418 if (CAN_SKIP_WORKING) return;
1419 startTest("collectArguments");
1420 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001421 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001422 System.out.println("collectArguments "+argType);
1423 for (int nargs = 0; nargs < 10; nargs++) {
1424 for (int pos = 0; pos < nargs; pos++) {
1425 if (argType == int.class) continue; // FIXME Fail_4
1426 testCollectArguments(argType, pos, nargs);
1427 }
1428 }
1429 }
1430 }
1431 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1432 countTest();
1433 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001434 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001435 fake = changeArgTypes(fake, argType);
1436 MethodType newType = fake.type();
1437 Object[] args = randomArgs(newType.parameterArray());
1438 // here is what should happen:
1439 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1440 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1441 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001442 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001443 target = changeArgTypes(target, 0, pos, argType);
1444 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001445 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001446 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001447 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001448 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001449// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1450// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1451// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1452 assertArrayEquals(collectedArgs, returnValue);
1453 }
1454
1455 @Test
jrose55220c32009-10-21 23:19:48 -07001456 public void testInsertArguments() throws Throwable {
1457 if (CAN_SKIP_WORKING) return;
1458 startTest("insertArguments");
1459 for (int nargs = 0; nargs <= 4; nargs++) {
1460 for (int ins = 0; ins <= 4; ins++) {
1461 if (ins > MAX_ARG_INCREASE) continue; // FIXME Fail_6
1462 for (int pos = 0; pos <= nargs; pos++) {
1463 testInsertArguments(nargs, pos, ins);
1464 }
1465 }
1466 }
1467 }
1468
1469 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001470 countTest();
jroseadc650a2011-02-11 01:26:28 -08001471 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001472 Object[] args = randomArgs(target.type().parameterArray());
1473 List<Object> resList = Arrays.asList(args);
1474 List<Object> argsToPass = new ArrayList<Object>(resList);
1475 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001476 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001477 System.out.println("insert: "+argsToInsert+" into "+target);
jrose10f3b682010-01-07 16:16:45 -08001478 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
1479 (Object[]) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001480 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001481 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001482 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001483 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001484 System.out.println("result: "+res2List);
1485 //if (!resList.equals(res2List))
1486 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1487 assertEquals(resList, res2List);
1488 }
1489
jrose10f3b682010-01-07 16:16:45 -08001490 @Test
jroseadc650a2011-02-11 01:26:28 -08001491 public void testFilterReturnValue() throws Throwable {
1492 if (CAN_SKIP_WORKING) return;
1493 startTest("filterReturnValue");
1494 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1495 assertTrue(List.class.isAssignableFrom(classOfVCList));
1496 for (int nargs = 0; nargs <= 3; nargs++) {
1497 for (Class<?> rtype : new Class[] { Object.class,
1498 List.class,
1499 int.class,
1500 //byte.class, //FIXME: add this
1501 //long.class, //FIXME: add this
1502 CharSequence.class,
1503 String.class }) {
1504 testFilterReturnValue(nargs, rtype);
1505 }
1506 }
1507 }
1508
1509 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1510 countTest();
1511 MethodHandle target = varargsList(nargs, rtype);
1512 MethodHandle filter;
1513 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1514 filter = varargsList(1); // add another layer of list-ness
1515 else
1516 filter = MethodHandles.identity(rtype);
1517 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1518 Object[] argsToPass = randomArgs(nargs, Object.class);
1519 if (verbosity >= 3)
1520 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1521 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1522 if (verbosity >= 4)
1523 System.out.println("filtered target: "+target2);
1524 // Simulate expected effect of filter on return value:
1525 Object unfiltered = target.invokeWithArguments(argsToPass);
1526 Object expected = filter.invokeWithArguments(unfiltered);
1527 if (verbosity >= 4)
1528 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1529 if (verbosity >= 4)
1530 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1531 Object result = target2.invokeWithArguments(argsToPass);
1532 if (verbosity >= 3)
1533 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1534 if (!expected.equals(result))
1535 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1536 assertEquals(expected, result);
1537 }
1538
1539 @Test
jrose10f3b682010-01-07 16:16:45 -08001540 public void testFilterArguments() throws Throwable {
1541 if (CAN_SKIP_WORKING) return;
1542 startTest("filterArguments");
1543 for (int nargs = 1; nargs <= 6; nargs++) {
1544 for (int pos = 0; pos < nargs; pos++) {
1545 testFilterArguments(nargs, pos);
1546 }
1547 }
1548 }
1549
1550 void testFilterArguments(int nargs, int pos) throws Throwable {
1551 countTest();
jroseadc650a2011-02-11 01:26:28 -08001552 MethodHandle target = varargsList(nargs);
1553 MethodHandle filter = varargsList(1);
jrose10f3b682010-01-07 16:16:45 -08001554 filter = MethodHandles.convertArguments(filter, filter.type().generic());
1555 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001556 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001557 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001558 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001559 // Simulate expected effect of filter on arglist:
1560 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001561 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001562 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001563 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001564 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001565 System.out.println("result: "+result);
1566 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001567 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001568 assertEquals(expected, result);
1569 }
1570
1571 @Test
1572 public void testFoldArguments() throws Throwable {
1573 if (CAN_SKIP_WORKING) return;
1574 startTest("foldArguments");
1575 for (int nargs = 0; nargs <= 4; nargs++) {
1576 for (int fold = 0; fold <= nargs; fold++) {
1577 for (int pos = 0; pos <= nargs; pos++) {
1578 testFoldArguments(nargs, pos, fold);
1579 }
1580 }
1581 }
1582 }
1583
1584 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1585 if (pos != 0) return; // can fold only at pos=0 for now
1586 countTest();
jroseadc650a2011-02-11 01:26:28 -08001587 MethodHandle target = varargsList(1 + nargs);
1588 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001589 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001590 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001591 System.out.println("fold "+target+" with "+combine);
1592 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1593 // Simulate expected effect of combiner on arglist:
1594 List<Object> expected = new ArrayList<Object>(argsToPass);
1595 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001596 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001597 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001598 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001599 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001600 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001601 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001602 System.out.println("result: "+result);
1603 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001604 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001605 assertEquals(expected, result);
1606 }
1607
1608 @Test
1609 public void testDropArguments() throws Throwable {
1610 if (CAN_SKIP_WORKING) return;
1611 startTest("dropArguments");
1612 for (int nargs = 0; nargs <= 4; nargs++) {
1613 for (int drop = 1; drop <= 4; drop++) {
1614 for (int pos = 0; pos <= nargs; pos++) {
1615 testDropArguments(nargs, pos, drop);
1616 }
1617 }
1618 }
1619 }
1620
1621 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1622 countTest();
jroseadc650a2011-02-11 01:26:28 -08001623 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001624 Object[] args = randomArgs(target.type().parameterArray());
1625 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
1626 Collections.nCopies(drop, Object.class).toArray(new Class[0]));
1627 List<Object> resList = Arrays.asList(args);
1628 List<Object> argsToDrop = new ArrayList<Object>(resList);
1629 for (int i = drop; i > 0; i--) {
1630 argsToDrop.add(pos, "blort#"+i);
1631 }
jrose900bafd2010-10-30 21:08:23 -07001632 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001633 Object res2List = Arrays.asList((Object[])res2);
1634 //if (!resList.equals(res2List))
1635 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1636 assertEquals(resList, res2List);
1637 }
1638
1639 @Test
1640 public void testInvokers() throws Throwable {
1641 if (CAN_SKIP_WORKING) return;
1642 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1643 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
1644 Set<MethodType> done = new HashSet<MethodType>();
1645 for (int i = 0; i <= 6; i++) {
1646 MethodType gtype = MethodType.genericMethodType(i);
1647 for (Class<?> argType : new Class[]{Object.class, Integer.class, int.class}) {
1648 for (int j = -1; j < i; j++) {
1649 MethodType type = gtype;
1650 if (j < 0)
1651 type = type.changeReturnType(argType);
1652 else if (argType == void.class)
1653 continue;
1654 else
1655 type = type.changeParameterType(j, argType);
1656 if (argType.isPrimitive() && j != i-1) continue; // FIXME Fail_5
1657 if (done.add(type))
1658 testInvokers(type);
1659 MethodType vtype = type.changeReturnType(void.class);
1660 if (done.add(vtype))
1661 testInvokers(vtype);
1662 }
1663 }
1664 }
1665 }
1666
1667 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001668 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001669 System.out.println("test invokers for "+type);
1670 int nargs = type.parameterCount();
1671 boolean testRetCode = type.returnType() != void.class;
1672 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1673 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001674 assertTrue(target.isVarargsCollector());
1675 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001676 Object[] args = randomArgs(type.parameterArray());
1677 List<Object> targetPlusArgs = new ArrayList<Object>(Arrays.asList(args));
1678 targetPlusArgs.add(0, target);
1679 int code = (Integer) invokee(args);
1680 Object log = logEntry("invokee", args);
1681 assertEquals(log.hashCode(), code);
1682 assertCalled("invokee", args);
1683 MethodHandle inv;
1684 Object result;
1685 // exact invoker
1686 countTest();
1687 calledLog.clear();
1688 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07001689 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001690 if (testRetCode) assertEquals(code, result);
1691 assertCalled("invokee", args);
1692 // generic invoker
1693 countTest();
1694 inv = MethodHandles.genericInvoker(type);
1695 if (nargs <= 3) {
1696 calledLog.clear();
1697 switch (nargs) {
1698 case 0:
jrose2cc9c832010-04-30 23:48:23 -07001699 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08001700 break;
1701 case 1:
jrose2cc9c832010-04-30 23:48:23 -07001702 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08001703 break;
1704 case 2:
jrose2cc9c832010-04-30 23:48:23 -07001705 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001706 break;
1707 case 3:
jrose2cc9c832010-04-30 23:48:23 -07001708 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08001709 break;
1710 }
1711 if (testRetCode) assertEquals(code, result);
1712 assertCalled("invokee", args);
1713 }
1714 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001715 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08001716 if (testRetCode) assertEquals(code, result);
1717 assertCalled("invokee", args);
1718 // varargs invoker #0
1719 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001720 inv = MethodHandles.spreadInvoker(type, 0);
jrose2cc9c832010-04-30 23:48:23 -07001721 result = inv.invokeExact(target, args);
jrose10f3b682010-01-07 16:16:45 -08001722 if (testRetCode) assertEquals(code, result);
1723 assertCalled("invokee", args);
1724 if (nargs >= 1) {
1725 // varargs invoker #1
1726 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001727 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07001728 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08001729 if (testRetCode) assertEquals(code, result);
1730 assertCalled("invokee", args);
1731 }
1732 if (nargs >= 2) {
1733 // varargs invoker #2
1734 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001735 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07001736 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08001737 if (testRetCode) assertEquals(code, result);
1738 assertCalled("invokee", args);
1739 }
1740 if (nargs >= 3) {
1741 // varargs invoker #3
1742 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001743 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07001744 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08001745 if (testRetCode) assertEquals(code, result);
1746 assertCalled("invokee", args);
1747 }
1748 for (int k = 0; k <= nargs; k++) {
1749 // varargs invoker #0..N
1750 countTest();
1751 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08001752 inv = MethodHandles.spreadInvoker(type, k);
jrose10f3b682010-01-07 16:16:45 -08001753 List<Object> targetPlusVarArgs = new ArrayList<Object>(targetPlusArgs);
1754 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
1755 Object[] tail = tailList.toArray();
1756 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07001757 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08001758 if (testRetCode) assertEquals(code, result);
1759 assertCalled("invokee", args);
1760 }
jrose900bafd2010-10-30 21:08:23 -07001761
jrose10f3b682010-01-07 16:16:45 -08001762 // dynamic invoker
1763 countTest();
jroseb90d2e72010-12-16 15:59:27 -08001764 CallSite site = new MutableCallSite(type);
1765 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07001766
1767 // see if we get the result of the original target:
1768 try {
1769 result = inv.invokeWithArguments(args);
1770 assertTrue("should not reach here", false);
1771 } catch (IllegalStateException ex) {
1772 String msg = ex.getMessage();
1773 assertTrue(msg, msg.contains("site"));
1774 }
1775
1776 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08001777 site.setTarget(target);
1778 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07001779 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001780 if (testRetCode) assertEquals(code, result);
1781 assertCalled("invokee", args);
1782 }
1783
1784 static Object invokee(Object... args) {
1785 return called("invokee", args).hashCode();
1786 }
1787
jrose55220c32009-10-21 23:19:48 -07001788 private static final String MISSING_ARG = "missingArg";
1789 static Object targetIfEquals() {
1790 return called("targetIfEquals");
1791 }
1792 static Object fallbackIfNotEquals() {
1793 return called("fallbackIfNotEquals");
1794 }
1795 static Object targetIfEquals(Object x) {
1796 assertEquals(x, MISSING_ARG);
1797 return called("targetIfEquals", x);
1798 }
1799 static Object fallbackIfNotEquals(Object x) {
1800 assertFalse(x.toString(), x.equals(MISSING_ARG));
1801 return called("fallbackIfNotEquals", x);
1802 }
1803 static Object targetIfEquals(Object x, Object y) {
1804 assertEquals(x, y);
1805 return called("targetIfEquals", x, y);
1806 }
1807 static Object fallbackIfNotEquals(Object x, Object y) {
1808 assertFalse(x.toString(), x.equals(y));
1809 return called("fallbackIfNotEquals", x, y);
1810 }
1811 static Object targetIfEquals(Object x, Object y, Object z) {
1812 assertEquals(x, y);
1813 return called("targetIfEquals", x, y, z);
1814 }
1815 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
1816 assertFalse(x.toString(), x.equals(y));
1817 return called("fallbackIfNotEquals", x, y, z);
1818 }
1819
jrose10f3b682010-01-07 16:16:45 -08001820 @Test
1821 public void testGuardWithTest() throws Throwable {
1822 if (CAN_SKIP_WORKING) return;
1823 startTest("guardWithTest");
1824 for (int nargs = 0; nargs <= 3; nargs++) {
1825 if (nargs != 2) continue; // FIXME: test more later
1826 testGuardWithTest(nargs, Object.class);
1827 testGuardWithTest(nargs, String.class);
1828 }
1829 }
1830 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
1831 countTest();
1832 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
1833 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs));
1834 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs));
1835 while (test.type().parameterCount() < nargs)
1836 test = MethodHandles.dropArguments(test, test.type().parameterCount()-1, Object.class);
1837 while (test.type().parameterCount() > nargs)
1838 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
1839 if (argClass != Object.class) {
1840 test = changeArgTypes(test, argClass);
1841 target = changeArgTypes(target, argClass);
1842 fallback = changeArgTypes(fallback, argClass);
1843 }
1844 MethodHandle mh = MethodHandles.guardWithTest(test, target, fallback);
1845 assertEquals(target.type(), mh.type());
1846 Object[][] argLists = {
1847 { },
1848 { "foo" }, { MISSING_ARG },
1849 { "foo", "foo" }, { "foo", "bar" },
1850 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
1851 };
1852 for (Object[] argList : argLists) {
1853 if (argList.length != nargs) continue;
1854 boolean equals;
1855 switch (nargs) {
1856 case 0: equals = true; break;
1857 case 1: equals = MISSING_ARG.equals(argList[0]); break;
1858 default: equals = argList[0].equals(argList[1]); break;
1859 }
1860 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07001861 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001862 System.out.println(logEntry(willCall, argList));
jrose900bafd2010-10-30 21:08:23 -07001863 Object result = mh.invokeWithArguments(argList);
jrose10f3b682010-01-07 16:16:45 -08001864 assertCalled(willCall, argList);
1865 }
1866 }
1867
1868 @Test
1869 public void testCatchException() throws Throwable {
1870 if (CAN_SKIP_WORKING) return;
1871 startTest("catchException");
1872 for (int nargs = 2; nargs <= 6; nargs++) {
1873 for (int ti = 0; ti <= 1; ti++) {
1874 boolean throwIt = (ti != 0);
1875 testCatchException(int.class, new ClassCastException("testing"), throwIt, nargs);
1876 testCatchException(void.class, new java.io.IOException("testing"), throwIt, nargs);
1877 testCatchException(String.class, new LinkageError("testing"), throwIt, nargs);
1878 }
1879 }
1880 }
1881
1882 private static <T extends Throwable>
1883 Object throwOrReturn(Object normal, T exception) throws T {
1884 if (exception != null) throw exception;
1885 return normal;
1886 }
1887
1888 void testCatchException(Class<?> returnType, Throwable thrown, boolean throwIt, int nargs) throws Throwable {
1889 countTest();
jrose2cc9c832010-04-30 23:48:23 -07001890 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001891 System.out.println("catchException rt="+returnType+" throw="+throwIt+" nargs="+nargs);
1892 Class<? extends Throwable> exType = thrown.getClass();
1893 MethodHandle throwOrReturn
1894 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
1895 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb90d2e72010-12-16 15:59:27 -08001896 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jrose10f3b682010-01-07 16:16:45 -08001897 while (thrower.type().parameterCount() < nargs)
1898 thrower = MethodHandles.dropArguments(thrower, thrower.type().parameterCount(), Object.class);
jroseadc650a2011-02-11 01:26:28 -08001899 MethodHandle catcher = varargsList(1+nargs).asType(MethodType.genericMethodType(1+nargs));
jrose10f3b682010-01-07 16:16:45 -08001900 MethodHandle target = MethodHandles.catchException(thrower,
jroseb90d2e72010-12-16 15:59:27 -08001901 thrown.getClass(), catcher);
jrose10f3b682010-01-07 16:16:45 -08001902 assertEquals(thrower.type(), target.type());
1903 //System.out.println("catching with "+target+" : "+throwOrReturn);
1904 Object[] args = randomArgs(nargs, Object.class);
1905 args[1] = (throwIt ? thrown : null);
jrose900bafd2010-10-30 21:08:23 -07001906 Object returned = target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001907 //System.out.println("return from "+target+" : "+returned);
1908 if (!throwIt) {
1909 assertSame(args[0], returned);
1910 } else {
1911 List<Object> catchArgs = new ArrayList<Object>(Arrays.asList(args));
1912 catchArgs.add(0, thrown);
1913 assertEquals(catchArgs, returned);
1914 }
1915 }
1916
1917 @Test
1918 public void testThrowException() throws Throwable {
1919 if (CAN_SKIP_WORKING) return;
1920 startTest("throwException");
1921 testThrowException(int.class, new ClassCastException("testing"));
1922 testThrowException(void.class, new java.io.IOException("testing"));
1923 testThrowException(String.class, new LinkageError("testing"));
1924 }
1925
1926 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
1927 countTest();
1928 Class<? extends Throwable> exType = thrown.getClass();
1929 MethodHandle target = MethodHandles.throwException(returnType, exType);
1930 //System.out.println("throwing with "+target+" : "+thrown);
1931 MethodType expectedType = MethodType.methodType(returnType, exType);
1932 assertEquals(expectedType, target.type());
jrose2cc9c832010-04-30 23:48:23 -07001933 target = MethodHandles.convertArguments(target, target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001934 Throwable caught = null;
1935 try {
jrose2cc9c832010-04-30 23:48:23 -07001936 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08001937 fail("got "+res+" instead of throwing "+thrown);
1938 } catch (Throwable ex) {
1939 if (ex != thrown) {
1940 if (ex instanceof Error) throw (Error)ex;
1941 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
1942 }
1943 caught = ex;
1944 }
1945 assertSame(thrown, caught);
1946 }
1947
1948 @Test
1949 public void testCastFailure() throws Throwable {
1950 if (CAN_SKIP_WORKING) return;
1951 startTest("testCastFailure");
1952 testCastFailure("cast/argument", 11000);
1953 testCastFailure("unbox/argument", 11000);
1954 testCastFailure("cast/return", 11000);
1955 testCastFailure("unbox/return", 11000);
1956 }
1957
jrose900bafd2010-10-30 21:08:23 -07001958 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07001959 public MethodHandle asMethodHandle() {
1960 return VALUE.bindTo(this);
1961 }
jrose10f3b682010-01-07 16:16:45 -08001962 Object value(Object x) {
1963 trace("value", x);
1964 if (boo != null) return boo;
1965 return x;
1966 }
1967 Object boo;
1968 void boo(Object x) { boo = x; }
1969
1970 static void trace(String x, Object y) {
1971 if (verbosity > 8) System.out.println(x+"="+y);
1972 }
1973 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
1974 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
1975 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07001976 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
1977 static {
1978 try {
1979 VALUE = PRIVATE.findVirtual(
1980 Surprise.class, "value",
1981 MethodType.methodType(Object.class, Object.class));
1982 REF_IDENTITY = PRIVATE.findStatic(
1983 Surprise.class, "refIdentity",
1984 MethodType.methodType(Object.class, Object.class));
1985 BOX_IDENTITY = PRIVATE.findStatic(
1986 Surprise.class, "boxIdentity",
1987 MethodType.methodType(Integer.class, Integer.class));
1988 INT_IDENTITY = PRIVATE.findStatic(
1989 Surprise.class, "intIdentity",
1990 MethodType.methodType(int.class, int.class));
1991 } catch (Exception ex) {
1992 throw new RuntimeException(ex);
1993 }
1994 }
jrose10f3b682010-01-07 16:16:45 -08001995 }
1996
1997 void testCastFailure(String mode, int okCount) throws Throwable {
1998 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07001999 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002000 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002001 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002002 if (mode.endsWith("/return")) {
2003 if (mode.equals("unbox/return")) {
2004 // fail on return to ((Integer)surprise).intValue
2005 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(int.class, Object.class));
2006 identity = MethodHandles.convertArguments(identity, MethodType.methodType(int.class, Object.class));
2007 } else if (mode.equals("cast/return")) {
2008 // fail on return to (Integer)surprise
2009 surprise = MethodHandles.convertArguments(surprise, MethodType.methodType(Integer.class, Object.class));
2010 identity = MethodHandles.convertArguments(identity, MethodType.methodType(Integer.class, Object.class));
2011 }
2012 } else if (mode.endsWith("/argument")) {
2013 MethodHandle callee = null;
2014 if (mode.equals("unbox/argument")) {
2015 // fail on handing surprise to int argument
2016 callee = Surprise.INT_IDENTITY;
2017 } else if (mode.equals("cast/argument")) {
2018 // fail on handing surprise to Integer argument
2019 callee = Surprise.BOX_IDENTITY;
2020 }
2021 if (callee != null) {
2022 callee = MethodHandles.convertArguments(callee, MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002023 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2024 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002025 }
2026 }
jrosea1ebbe62010-09-08 18:40:23 -07002027 assertNotSame(mode, surprise, surprise0);
jrose10f3b682010-01-07 16:16:45 -08002028 identity = MethodHandles.convertArguments(identity, MethodType.genericMethodType(1));
2029 surprise = MethodHandles.convertArguments(surprise, MethodType.genericMethodType(1));
2030 Object x = 42;
2031 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002032 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002033 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002034 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002035 assertEquals(x, z);
2036 }
2037 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002038 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002039 assertEquals(x, y);
2040 try {
jrose2cc9c832010-04-30 23:48:23 -07002041 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002042 System.out.println("Failed to throw; got z="+z);
2043 assertTrue(false);
2044 } catch (Exception ex) {
jrose10f3b682010-01-07 16:16:45 -08002045 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002046 System.out.println("caught "+ex);
2047 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002048 ex.printStackTrace();
2049 assertTrue(ex instanceof ClassCastException
2050 // FIXME: accept only one of the two for any given unit test
2051 || ex instanceof WrongMethodTypeException
2052 );
2053 }
2054 }
2055
jrose45b7a332010-05-03 23:32:47 -07002056 static Example userMethod(Object o, String s, int i) {
2057 called("userMethod", o, s, i);
2058 return null;
2059 }
2060
2061 @Test
2062 public void testUserClassInSignature() throws Throwable {
2063 if (CAN_SKIP_WORKING) return;
2064 startTest("testUserClassInSignature");
2065 Lookup lookup = MethodHandles.lookup();
2066 String name; MethodType mt; MethodHandle mh;
2067 Object[] args;
2068
2069 // Try a static method.
2070 name = "userMethod";
2071 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2072 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2073 assertEquals(mt, mh.type());
2074 assertEquals(Example.class, mh.type().returnType());
2075 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002076 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002077 assertCalled(name, args);
2078
2079 // Try a virtual method.
2080 name = "v2";
2081 mt = MethodType.methodType(Object.class, Object.class, int.class);
2082 mh = lookup.findVirtual(Example.class, name, mt);
2083 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2084 assertTrue(mh.type().parameterList().contains(Example.class));
2085 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002086 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002087 assertCalled(name, args);
2088 }
jrosebe2db602010-09-08 18:40:34 -07002089
2090 static void runForRunnable() {
2091 called("runForRunnable");
2092 }
2093 private interface Fooable {
2094 Object foo(Fooable x, Object y);
2095 // this is for randomArg:
2096 public class Impl implements Fooable {
2097 public Object foo(Fooable x, Object y) {
2098 throw new RuntimeException("do not call");
2099 }
2100 final String name;
2101 public Impl() { name = "Fooable#"+nextArg(); }
2102 @Override public String toString() { return name; }
2103 }
2104 }
2105 static Object fooForFooable(Fooable x, Object y) {
2106 return called("fooForFooable", x, y);
2107 }
2108 private static class MyCheckedException extends Exception {
2109 }
2110 private interface WillThrow {
2111 void willThrow() throws MyCheckedException;
2112 }
2113
2114 @Test
2115 public void testAsInstance() throws Throwable {
2116 if (CAN_SKIP_WORKING) return;
2117 Lookup lookup = MethodHandles.lookup();
2118 {
2119 MethodType mt = MethodType.methodType(void.class);
2120 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
2121 Runnable proxy = MethodHandles.asInstance(mh, Runnable.class);
2122 proxy.run();
2123 assertCalled("runForRunnable");
2124 }
2125 {
2126 MethodType mt = MethodType.methodType(Object.class, Fooable.class, Object.class);
2127 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable", mt);
2128 Fooable proxy = MethodHandles.asInstance(mh, Fooable.class);
2129 Object[] args = randomArgs(mt.parameterArray());
2130 Object result = proxy.foo((Fooable) args[0], args[1]);
2131 assertCalled("fooForFooable", args);
2132 assertEquals(result, logEntry("fooForFooable", args));
2133 }
2134 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2135 new InternalError("ok"),
2136 new Throwable("fail"),
2137 new Exception("fail"),
2138 new MyCheckedException()
2139 }) {
2140 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2141 mh = MethodHandles.insertArguments(mh, 0, ex);
2142 WillThrow proxy = MethodHandles.asInstance(mh, WillThrow.class);
2143 try {
2144 proxy.willThrow();
2145 System.out.println("Failed to throw: "+ex);
2146 assertTrue(false);
2147 } catch (Throwable ex1) {
2148 if (verbosity > 2) {
2149 System.out.println("throw "+ex);
2150 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2151 }
2152 if (ex instanceof RuntimeException ||
2153 ex instanceof Error) {
2154 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2155 } else if (ex instanceof MyCheckedException) {
2156 assertSame("must pass declared exception out without wrapping", ex, ex1);
2157 } else {
2158 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
2159 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
2160 assertSame(ex, utex.getCause());
2161 }
2162 }
2163 }
2164 // Test error checking:
jrosebe2db602010-09-08 18:40:34 -07002165 for (Class<?> nonSAM : new Class[] { Object.class,
2166 String.class,
2167 CharSequence.class,
2168 Example.class }) {
2169 try {
jroseadc650a2011-02-11 01:26:28 -08002170 MethodHandles.asInstance(varargsArray(0), nonSAM);
jrosebe2db602010-09-08 18:40:34 -07002171 System.out.println("Failed to throw");
2172 assertTrue(false);
2173 } catch (IllegalArgumentException ex) {
2174 }
2175 }
2176 }
jrose55220c32009-10-21 23:19:48 -07002177}
2178// Local abbreviated copy of sun.dyn.util.ValueConversions
2179class ValueConversions {
2180 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2181 private static final Object[] NO_ARGS_ARRAY = {};
2182 private static Object[] makeArray(Object... args) { return args; }
2183 private static Object[] array() { return NO_ARGS_ARRAY; }
2184 private static Object[] array(Object a0)
2185 { return makeArray(a0); }
2186 private static Object[] array(Object a0, Object a1)
2187 { return makeArray(a0, a1); }
2188 private static Object[] array(Object a0, Object a1, Object a2)
2189 { return makeArray(a0, a1, a2); }
2190 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2191 { return makeArray(a0, a1, a2, a3); }
2192 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2193 Object a4)
2194 { return makeArray(a0, a1, a2, a3, a4); }
2195 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2196 Object a4, Object a5)
2197 { return makeArray(a0, a1, a2, a3, a4, a5); }
2198 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2199 Object a4, Object a5, Object a6)
2200 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2201 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2202 Object a4, Object a5, Object a6, Object a7)
2203 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2204 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2205 Object a4, Object a5, Object a6, Object a7,
2206 Object a8)
2207 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2208 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2209 Object a4, Object a5, Object a6, Object a7,
2210 Object a8, Object a9)
2211 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2212 static MethodHandle[] makeArrays() {
2213 ArrayList<MethodHandle> arrays = new ArrayList<MethodHandle>();
2214 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2215 for (;;) {
2216 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002217 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002218 String name = "array";
2219 MethodHandle array = null;
2220 try {
2221 array = lookup.findStatic(ValueConversions.class, name, type);
2222 } catch (NoAccessException ex) {
2223 }
2224 if (array == null) break;
2225 arrays.add(array);
2226 }
2227 assert(arrays.size() == 11); // current number of methods
2228 return arrays.toArray(new MethodHandle[0]);
2229 }
2230 static final MethodHandle[] ARRAYS = makeArrays();
2231
2232 /** Return a method handle that takes the indicated number of Object
2233 * arguments and returns an Object array of them, as if for varargs.
2234 */
2235 public static MethodHandle varargsArray(int nargs) {
2236 if (nargs < ARRAYS.length)
2237 return ARRAYS[nargs];
2238 // else need to spin bytecode or do something else fancy
jrose2cc9c832010-04-30 23:48:23 -07002239 throw new UnsupportedOperationException("NYI: cannot form a varargs array of length "+nargs);
jrose55220c32009-10-21 23:19:48 -07002240 }
jrose10f3b682010-01-07 16:16:45 -08002241
2242 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2243 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2244 private static List<Object> list() { return NO_ARGS_LIST; }
2245 private static List<Object> list(Object a0)
2246 { return makeList(a0); }
2247 private static List<Object> list(Object a0, Object a1)
2248 { return makeList(a0, a1); }
2249 private static List<Object> list(Object a0, Object a1, Object a2)
2250 { return makeList(a0, a1, a2); }
2251 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2252 { return makeList(a0, a1, a2, a3); }
2253 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2254 Object a4)
2255 { return makeList(a0, a1, a2, a3, a4); }
2256 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2257 Object a4, Object a5)
2258 { return makeList(a0, a1, a2, a3, a4, a5); }
2259 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2260 Object a4, Object a5, Object a6)
2261 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2262 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2263 Object a4, Object a5, Object a6, Object a7)
2264 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2265 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2266 Object a4, Object a5, Object a6, Object a7,
2267 Object a8)
2268 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2269 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2270 Object a4, Object a5, Object a6, Object a7,
2271 Object a8, Object a9)
2272 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2273 static MethodHandle[] makeLists() {
jroseadc650a2011-02-11 01:26:28 -08002274 ArrayList<MethodHandle> lists = new ArrayList<MethodHandle>();
jrose10f3b682010-01-07 16:16:45 -08002275 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2276 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002277 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002278 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2279 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002280 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002281 try {
jroseadc650a2011-02-11 01:26:28 -08002282 list = lookup.findStatic(ValueConversions.class, name, type);
jrose10f3b682010-01-07 16:16:45 -08002283 } catch (NoAccessException ex) {
2284 }
jroseadc650a2011-02-11 01:26:28 -08002285 if (list == null) break;
2286 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002287 }
jroseadc650a2011-02-11 01:26:28 -08002288 assert(lists.size() == 11); // current number of methods
2289 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002290 }
2291 static final MethodHandle[] LISTS = makeLists();
2292
2293 /** Return a method handle that takes the indicated number of Object
2294 * arguments and returns List.
2295 */
2296 public static MethodHandle varargsList(int nargs) {
2297 if (nargs < LISTS.length)
2298 return LISTS[nargs];
2299 // else need to spin bytecode or do something else fancy
2300 throw new UnsupportedOperationException("NYI");
2301 }
jrose55220c32009-10-21 23:19:48 -07002302}
2303// This guy tests access from outside the same package member, but inside
2304// the package itself.
2305class PackageSibling {
2306 static Lookup lookup() {
2307 return MethodHandles.lookup();
2308 }
2309}