blob: ef1cedb92b9cd500e7cdf8c91119037bbc3be473 [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
jroseada69fa2011-03-23 23:02:31 -070027 * @summary unit tests for java.lang.invoke.MethodHandles
jrose9633f5f2011-04-07 22:07:06 -070028 * @compile -source 7 -target 7 MethodHandlesTest.java
29 * @run junit/othervm test.java.lang.invoke.MethodHandlesTest
jrose55220c32009-10-21 23:19:48 -070030 */
31
jroseada69fa2011-03-23 23:02:31 -070032package test.java.lang.invoke;
jrose55220c32009-10-21 23:19:48 -070033
jroseada69fa2011-03-23 23:02:31 -070034import java.lang.invoke.*;
35import java.lang.invoke.MethodHandles.Lookup;
jrose55220c32009-10-21 23:19:48 -070036import java.lang.reflect.*;
37import java.util.*;
38import org.junit.*;
39import static org.junit.Assert.*;
jrose55220c32009-10-21 23:19:48 -070040
41
42/**
43 *
44 * @author jrose
45 */
46public class MethodHandlesTest {
jroseb4be0262011-07-16 15:44:33 -070047 static final Class<?> THIS_CLASS = MethodHandlesTest.class;
jrose55220c32009-10-21 23:19:48 -070048 // How much output?
jrose2cc9c832010-04-30 23:48:23 -070049 static int verbosity = 0;
jrosecf98d422010-06-08 23:08:56 -070050 static {
jroseb4be0262011-07-16 15:44:33 -070051 String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".verbosity");
52 if (vstr == null)
53 vstr = System.getProperty(THIS_CLASS.getName()+".verbosity");
jrosecf98d422010-06-08 23:08:56 -070054 if (vstr != null) verbosity = Integer.parseInt(vstr);
55 }
jrose55220c32009-10-21 23:19:48 -070056
57 // Set this true during development if you want to fast-forward to
58 // a particular new, non-working test. Tests which are known to
59 // work (or have recently worked) test this flag and return on true.
60 static boolean CAN_SKIP_WORKING = false;
61 //static { CAN_SKIP_WORKING = true; }
62
jroseb4be0262011-07-16 15:44:33 -070063 // Set 'true' to do about 15x fewer tests, especially those redundant with RicochetTest.
64 // This might be useful with -Xcomp stress tests that compile all method handles.
65 static boolean CAN_TEST_LIGHTLY = Boolean.getBoolean(THIS_CLASS.getName()+".CAN_TEST_LIGHTLY");
jrose55220c32009-10-21 23:19:48 -070066
jrose55220c32009-10-21 23:19:48 -070067 @Test
68 public void testFirst() throws Throwable {
69 verbosity += 9; try {
70 // left blank for debugging
jrose2cc9c832010-04-30 23:48:23 -070071 } finally { printCounts(); verbosity -= 9; }
jrose55220c32009-10-21 23:19:48 -070072 }
73
jrose10f3b682010-01-07 16:16:45 -080074 // current failures
jroseb4be0262011-07-16 15:44:33 -070075 @Test //@Ignore("failure in call to makeRawRetypeOnly in ToGeneric")
jrose10f3b682010-01-07 16:16:45 -080076 public void testFail_1() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070077 // AMH.<init>: IllegalArgumentException: bad adapter (conversion=0xfffab300): adapter pushes too many parameters
jrose10f3b682010-01-07 16:16:45 -080078 testSpreadArguments(int.class, 0, 6);
79 }
jroseb4be0262011-07-16 15:44:33 -070080 @Test //@Ignore("failure in JVM when expanding the stack using asm stub for _adapter_spread_args")
jrose10f3b682010-01-07 16:16:45 -080081 public void testFail_2() throws Throwable {
82 // if CONV_OP_IMPLEMENTED_MASK includes OP_SPREAD_ARGS, this crashes:
83 testSpreadArguments(Object.class, 0, 2);
84 }
jroseb4be0262011-07-16 15:44:33 -070085 @Test //@Ignore("IllArgEx failure in call to ToGeneric.make")
jrose10f3b682010-01-07 16:16:45 -080086 public void testFail_3() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070087 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080088 testSpreadArguments(int.class, 1, 2);
89 }
jroseb4be0262011-07-16 15:44:33 -070090 @Test //@Ignore("IllArgEx failure in call to ToGeneric.make")
jrose10f3b682010-01-07 16:16:45 -080091 public void testFail_4() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070092 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080093 testCollectArguments(int.class, 1, 2);
94 }
jroseb4be0262011-07-16 15:44:33 -070095 @Test //@Ignore("cannot collect leading primitive types")
jrose10f3b682010-01-07 16:16:45 -080096 public void testFail_5() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -070097 // ToGeneric.<init>: UnsupportedOperationException: NYI: primitive parameters must follow references; entryType = (int,java.lang.Object)java.lang.Object
jrose10f3b682010-01-07 16:16:45 -080098 testInvokers(MethodType.genericMethodType(2).changeParameterType(0, int.class));
99 }
jroseb4be0262011-07-16 15:44:33 -0700100 @Test //@Ignore("should not insert arguments beyond MethodHandlePushLimit")
jrose10f3b682010-01-07 16:16:45 -0800101 public void testFail_6() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700102 // ValueConversions.varargsArray: UnsupportedOperationException: NYI: cannot form a varargs array of length 13
103 testInsertArguments(0, 0, MAX_ARG_INCREASE+10);
jrose10f3b682010-01-07 16:16:45 -0800104 }
jroseb4be0262011-07-16 15:44:33 -0700105 @Test //@Ignore("permuteArguments has trouble with double slots")
jrose9b82ad62011-05-26 17:37:36 -0700106 public void testFail_7() throws Throwable {
107 testPermuteArguments(new Object[]{10, 200L},
108 new Class<?>[]{Integer.class, long.class},
109 new int[]{1,0});
110 testPermuteArguments(new Object[]{10, 200L, 5000L},
111 new Class<?>[]{Integer.class, long.class, long.class},
112 new int[]{2,0,1}); //rot
113 testPermuteArguments(new Object[]{10, 200L, 5000L},
114 new Class<?>[]{Integer.class, long.class, long.class},
115 new int[]{1,2,0}); //rot
116 testPermuteArguments(new Object[]{10, 200L, 5000L},
117 new Class<?>[]{Integer.class, long.class, long.class},
118 new int[]{2,1,0}); //swap
119 testPermuteArguments(new Object[]{10, 200L, 5000L},
120 new Class<?>[]{Integer.class, long.class, long.class},
121 new int[]{0,1,2,2}); //dup
122 testPermuteArguments(new Object[]{10, 200L, 5000L},
123 new Class<?>[]{Integer.class, long.class, long.class},
124 new int[]{2,0,1,2});
125 testPermuteArguments(new Object[]{10, 200L, 5000L},
126 new Class<?>[]{Integer.class, long.class, long.class},
127 new int[]{2,2,0,1});
jroseb4be0262011-07-16 15:44:33 -0700128 //testPermuteArguments(4, Integer.class, 2, long.class, 6);
jrose9b82ad62011-05-26 17:37:36 -0700129 }
jrose55220c32009-10-21 23:19:48 -0700130 static final int MAX_ARG_INCREASE = 3;
131
132 public MethodHandlesTest() {
133 }
134
jrose55220c32009-10-21 23:19:48 -0700135 String testName;
jrosecf98d422010-06-08 23:08:56 -0700136 static int allPosTests, allNegTests;
jrose55220c32009-10-21 23:19:48 -0700137 int posTests, negTests;
138 @After
139 public void printCounts() {
jrose2cc9c832010-04-30 23:48:23 -0700140 if (verbosity >= 2 && (posTests | negTests) != 0) {
jrose55220c32009-10-21 23:19:48 -0700141 System.out.println();
142 if (posTests != 0) System.out.println("=== "+testName+": "+posTests+" positive test cases run");
143 if (negTests != 0) System.out.println("=== "+testName+": "+negTests+" negative test cases run");
jrosecf98d422010-06-08 23:08:56 -0700144 allPosTests += posTests;
145 allNegTests += negTests;
jrose2cc9c832010-04-30 23:48:23 -0700146 posTests = negTests = 0;
jrose55220c32009-10-21 23:19:48 -0700147 }
148 }
149 void countTest(boolean positive) {
150 if (positive) ++posTests;
151 else ++negTests;
152 }
153 void countTest() { countTest(true); }
154 void startTest(String name) {
155 if (testName != null) printCounts();
jrose2cc9c832010-04-30 23:48:23 -0700156 if (verbosity >= 1)
jrose55220c32009-10-21 23:19:48 -0700157 System.out.println(name);
158 posTests = negTests = 0;
159 testName = name;
160 }
161
162 @BeforeClass
163 public static void setUpClass() throws Exception {
164 calledLog.clear();
165 calledLog.add(null);
jrose2cc9c832010-04-30 23:48:23 -0700166 nextArgVal = INITIAL_ARG_VAL;
jrose55220c32009-10-21 23:19:48 -0700167 }
168
169 @AfterClass
170 public static void tearDownClass() throws Exception {
jrosecf98d422010-06-08 23:08:56 -0700171 int posTests = allPosTests, negTests = allNegTests;
jroseb4be0262011-07-16 15:44:33 -0700172 if (verbosity >= 0 && (posTests | negTests) != 0) {
jrosecf98d422010-06-08 23:08:56 -0700173 System.out.println();
174 if (posTests != 0) System.out.println("=== "+posTests+" total positive test cases");
175 if (negTests != 0) System.out.println("=== "+negTests+" total negative test cases");
176 }
jrose55220c32009-10-21 23:19:48 -0700177 }
178
jrose49494522012-01-18 17:34:29 -0800179 static List<Object> calledLog = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -0700180 static Object logEntry(String name, Object... args) {
181 return Arrays.asList(name, Arrays.asList(args));
182 }
183 static Object called(String name, Object... args) {
184 Object entry = logEntry(name, args);
185 calledLog.add(entry);
186 return entry;
187 }
188 static void assertCalled(String name, Object... args) {
189 Object expected = logEntry(name, args);
190 Object actual = calledLog.get(calledLog.size() - 1);
jrose2cc9c832010-04-30 23:48:23 -0700191 if (expected.equals(actual) && verbosity < 9) return;
jrose55220c32009-10-21 23:19:48 -0700192 System.out.println("assertCalled "+name+":");
193 System.out.println("expected: "+expected);
194 System.out.println("actual: "+actual);
195 System.out.println("ex. types: "+getClasses(expected));
196 System.out.println("act. types: "+getClasses(actual));
jrose55220c32009-10-21 23:19:48 -0700197 assertEquals("previous method call", expected, actual);
198 }
199 static void printCalled(MethodHandle target, String name, Object... args) {
jrose2cc9c832010-04-30 23:48:23 -0700200 if (verbosity >= 3)
201 System.out.println("calling MH="+target+" to "+name+Arrays.toString(args));
jrose55220c32009-10-21 23:19:48 -0700202 }
203
204 static Object castToWrapper(Object value, Class<?> dst) {
205 Object wrap = null;
206 if (value instanceof Number)
207 wrap = castToWrapperOrNull(((Number)value).longValue(), dst);
208 if (value instanceof Character)
209 wrap = castToWrapperOrNull((char)(Character)value, dst);
210 if (wrap != null) return wrap;
211 return dst.cast(value);
212 }
213
jrose49494522012-01-18 17:34:29 -0800214 @SuppressWarnings("cast") // primitive cast to (long) is part of the pattern
jrose55220c32009-10-21 23:19:48 -0700215 static Object castToWrapperOrNull(long value, Class<?> dst) {
216 if (dst == int.class || dst == Integer.class)
217 return (int)(value);
218 if (dst == long.class || dst == Long.class)
219 return (long)(value);
220 if (dst == char.class || dst == Character.class)
221 return (char)(value);
222 if (dst == short.class || dst == Short.class)
223 return (short)(value);
224 if (dst == float.class || dst == Float.class)
225 return (float)(value);
226 if (dst == double.class || dst == Double.class)
227 return (double)(value);
jrose10f3b682010-01-07 16:16:45 -0800228 if (dst == byte.class || dst == Byte.class)
229 return (byte)(value);
230 if (dst == boolean.class || dst == boolean.class)
231 return ((value % 29) & 1) == 0;
jrose55220c32009-10-21 23:19:48 -0700232 return null;
233 }
234
jrose2cc9c832010-04-30 23:48:23 -0700235 static final int ONE_MILLION = (1000*1000), // first int value
236 TEN_BILLION = (10*1000*1000*1000), // scale factor to reach upper 32 bits
237 INITIAL_ARG_VAL = ONE_MILLION << 1; // <<1 makes space for sign bit;
238 static long nextArgVal;
239 static long nextArg(boolean moreBits) {
240 long val = nextArgVal++;
241 long sign = -(val & 1); // alternate signs
242 val >>= 1;
243 if (moreBits)
244 // Guarantee some bits in the high word.
245 // In any case keep the decimal representation simple-looking,
246 // with lots of zeroes, so as not to make the printed decimal
247 // strings unnecessarily noisy.
248 val += (val % ONE_MILLION) * TEN_BILLION;
249 return val ^ sign;
250 }
251 static int nextArg() {
252 // Produce a 32-bit result something like ONE_MILLION+(smallint).
253 // Example: 1_000_042.
254 return (int) nextArg(false);
255 }
256 static long nextArg(Class<?> kind) {
257 if (kind == long.class || kind == Long.class ||
258 kind == double.class || kind == Double.class)
259 // produce a 64-bit result something like
260 // ((TEN_BILLION+1) * (ONE_MILLION+(smallint)))
261 // Example: 10_000_420_001_000_042.
262 return nextArg(true);
263 return (long) nextArg();
264 }
265
jrose55220c32009-10-21 23:19:48 -0700266 static Object randomArg(Class<?> param) {
jrose2cc9c832010-04-30 23:48:23 -0700267 Object wrap = castToWrapperOrNull(nextArg(param), param);
jrose55220c32009-10-21 23:19:48 -0700268 if (wrap != null) {
jrose55220c32009-10-21 23:19:48 -0700269 return wrap;
270 }
jroseada69fa2011-03-23 23:02:31 -0700271// import sun.invoke.util.Wrapper;
jrose55220c32009-10-21 23:19:48 -0700272// Wrapper wrap = Wrapper.forBasicType(dst);
273// if (wrap == Wrapper.OBJECT && Wrapper.isWrapperType(dst))
274// wrap = Wrapper.forWrapperType(dst);
275// if (wrap != Wrapper.OBJECT)
276// return wrap.wrap(nextArg++);
jrosebe2db602010-09-08 18:40:34 -0700277 if (param.isInterface()) {
278 for (Class<?> c : param.getClasses()) {
279 if (param.isAssignableFrom(c) && !c.isInterface())
280 { param = c; break; }
281 }
282 }
jrose485df122012-07-12 00:11:35 -0700283 if (param.isInterface() && param.isAssignableFrom(List.class))
284 return Arrays.asList("#"+nextArg());
jrose55220c32009-10-21 23:19:48 -0700285 if (param.isInterface() || param.isAssignableFrom(String.class))
jrose2cc9c832010-04-30 23:48:23 -0700286 return "#"+nextArg();
jrose55220c32009-10-21 23:19:48 -0700287 else
288 try {
289 return param.newInstance();
jrose49494522012-01-18 17:34:29 -0800290 } catch (InstantiationException | IllegalAccessException ex) {
jrose55220c32009-10-21 23:19:48 -0700291 }
292 return null; // random class not Object, String, Integer, etc.
293 }
294 static Object[] randomArgs(Class<?>... params) {
295 Object[] args = new Object[params.length];
296 for (int i = 0; i < args.length; i++)
297 args[i] = randomArg(params[i]);
298 return args;
299 }
300 static Object[] randomArgs(int nargs, Class<?> param) {
301 Object[] args = new Object[nargs];
302 for (int i = 0; i < args.length; i++)
303 args[i] = randomArg(param);
304 return args;
305 }
306
jrose49494522012-01-18 17:34:29 -0800307 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700308 static <T, E extends T> T[] array(Class<T[]> atype, E... a) {
309 return Arrays.copyOf(a, a.length, atype);
310 }
jrose49494522012-01-18 17:34:29 -0800311 @SafeVarargs @SuppressWarnings("varargs")
jrose55220c32009-10-21 23:19:48 -0700312 static <T> T[] cat(T[] a, T... b) {
313 int alen = a.length, blen = b.length;
314 if (blen == 0) return a;
315 T[] c = Arrays.copyOf(a, alen + blen);
316 System.arraycopy(b, 0, c, alen, blen);
317 return c;
318 }
319 static Integer[] boxAll(int... vx) {
320 Integer[] res = new Integer[vx.length];
321 for (int i = 0; i < res.length; i++) {
322 res[i] = vx[i];
323 }
324 return res;
325 }
326 static Object getClasses(Object x) {
327 if (x == null) return x;
328 if (x instanceof String) return x; // keep the name
329 if (x instanceof List) {
330 // recursively report classes of the list elements
331 Object[] xa = ((List)x).toArray();
332 for (int i = 0; i < xa.length; i++)
333 xa[i] = getClasses(xa[i]);
334 return Arrays.asList(xa);
335 }
336 return x.getClass().getSimpleName();
337 }
338
jroseadc650a2011-02-11 01:26:28 -0800339 /** Return lambda(arg...[arity]) { new Object[]{ arg... } } */
340 static MethodHandle varargsList(int arity) {
341 return ValueConversions.varargsList(arity);
342 }
343 /** Return lambda(arg...[arity]) { Arrays.asList(arg...) } */
344 static MethodHandle varargsArray(int arity) {
345 return ValueConversions.varargsArray(arity);
346 }
jrose320b7692011-05-12 19:27:49 -0700347 static MethodHandle varargsArray(Class<?> arrayType, int arity) {
348 return ValueConversions.varargsArray(arrayType, arity);
349 }
jroseadc650a2011-02-11 01:26:28 -0800350 /** Variation of varargsList, but with the given rtype. */
351 static MethodHandle varargsList(int arity, Class<?> rtype) {
352 MethodHandle list = varargsList(arity);
353 MethodType listType = list.type().changeReturnType(rtype);
354 if (List.class.isAssignableFrom(rtype) || rtype == void.class || rtype == Object.class) {
355 // OK
356 } else if (rtype.isAssignableFrom(String.class)) {
357 if (LIST_TO_STRING == null)
358 try {
359 LIST_TO_STRING = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToString",
360 MethodType.methodType(String.class, List.class));
jrose49494522012-01-18 17:34:29 -0800361 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800362 list = MethodHandles.filterReturnValue(list, LIST_TO_STRING);
363 } else if (rtype.isPrimitive()) {
364 if (LIST_TO_INT == null)
365 try {
366 LIST_TO_INT = PRIVATE.findStatic(PRIVATE.lookupClass(), "listToInt",
367 MethodType.methodType(int.class, List.class));
jrose49494522012-01-18 17:34:29 -0800368 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseadc650a2011-02-11 01:26:28 -0800369 list = MethodHandles.filterReturnValue(list, LIST_TO_INT);
370 list = MethodHandles.explicitCastArguments(list, listType);
371 } else {
372 throw new RuntimeException("varargsList: "+rtype);
373 }
374 return list.asType(listType);
375 }
376 private static MethodHandle LIST_TO_STRING, LIST_TO_INT;
jrose49494522012-01-18 17:34:29 -0800377 private static String listToString(List<?> x) { return x.toString(); }
378 private static int listToInt(List<?> x) { return x.toString().hashCode(); }
jroseadc650a2011-02-11 01:26:28 -0800379
jrose55220c32009-10-21 23:19:48 -0700380 static MethodHandle changeArgTypes(MethodHandle target, Class<?> argType) {
381 return changeArgTypes(target, 0, 999, argType);
382 }
383 static MethodHandle changeArgTypes(MethodHandle target,
384 int beg, int end, Class<?> argType) {
385 MethodType targetType = target.type();
386 end = Math.min(end, targetType.parameterCount());
jrose49494522012-01-18 17:34:29 -0800387 ArrayList<Class<?>> argTypes = new ArrayList<>(targetType.parameterList());
jrose55220c32009-10-21 23:19:48 -0700388 Collections.fill(argTypes.subList(beg, end), argType);
jrose10f3b682010-01-07 16:16:45 -0800389 MethodType ttype2 = MethodType.methodType(targetType.returnType(), argTypes);
jrose9b82ad62011-05-26 17:37:36 -0700390 return target.asType(ttype2);
jrose55220c32009-10-21 23:19:48 -0700391 }
jroseb4be0262011-07-16 15:44:33 -0700392 static MethodHandle addTrailingArgs(MethodHandle target, int nargs, Class<?> argClass) {
393 int targetLen = target.type().parameterCount();
394 int extra = (nargs - targetLen);
395 if (extra <= 0) return target;
396 List<Class<?>> fakeArgs = Collections.<Class<?>>nCopies(extra, argClass);
397 return MethodHandles.dropArguments(target, targetLen, fakeArgs);
398 }
jrose55220c32009-10-21 23:19:48 -0700399
400 // This lookup is good for all members in and under MethodHandlesTest.
401 static final Lookup PRIVATE = MethodHandles.lookup();
402 // This lookup is good for package-private members but not private ones.
403 static final Lookup PACKAGE = PackageSibling.lookup();
404 // This lookup is good only for public members.
jrose10f3b682010-01-07 16:16:45 -0800405 static final Lookup PUBLIC = MethodHandles.publicLookup();
jrose55220c32009-10-21 23:19:48 -0700406
407 // Subject methods...
408 static class Example implements IntExample {
409 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700410 public Example() { name = "Example#"+nextArg(); }
jrose55220c32009-10-21 23:19:48 -0700411 protected Example(String name) { this.name = name; }
jrose49494522012-01-18 17:34:29 -0800412 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700413 protected Example(int x) { this(); called("protected <init>", this, x); }
414 @Override public String toString() { return name; }
415
416 public void v0() { called("v0", this); }
417 void pkg_v0() { called("pkg_v0", this); }
418 private void pri_v0() { called("pri_v0", this); }
419 public static void s0() { called("s0"); }
420 static void pkg_s0() { called("pkg_s0"); }
421 private static void pri_s0() { called("pri_s0"); }
422
423 public Object v1(Object x) { return called("v1", this, x); }
424 public Object v2(Object x, Object y) { return called("v2", this, x, y); }
425 public Object v2(Object x, int y) { return called("v2", this, x, y); }
426 public Object v2(int x, Object y) { return called("v2", this, x, y); }
427 public Object v2(int x, int y) { return called("v2", this, x, y); }
428 public static Object s1(Object x) { return called("s1", x); }
429 public static Object s2(int x) { return called("s2", x); }
430 public static Object s3(long x) { return called("s3", x); }
431 public static Object s4(int x, int y) { return called("s4", x, y); }
432 public static Object s5(long x, int y) { return called("s5", x, y); }
433 public static Object s6(int x, long y) { return called("s6", x, y); }
434 public static Object s7(float x, double y) { return called("s7", x, y); }
jrose2cc9c832010-04-30 23:48:23 -0700435
jroseb4be0262011-07-16 15:44:33 -0700436 // for testing findConstructor:
437 public Example(String x, int y) { this.name = x+y; called("Example.<init>", x, y); }
438 public Example(int x, String y) { this.name = x+y; called("Example.<init>", x, y); }
439
jrose2cc9c832010-04-30 23:48:23 -0700440 static final Lookup EXAMPLE = MethodHandles.lookup(); // for testing findSpecial
jrose55220c32009-10-21 23:19:48 -0700441 }
jrose2cc9c832010-04-30 23:48:23 -0700442 static final Lookup EXAMPLE = Example.EXAMPLE;
jrose55220c32009-10-21 23:19:48 -0700443 public static class PubExample extends Example {
jrose2cc9c832010-04-30 23:48:23 -0700444 public PubExample() { super("PubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700445 }
446 static class SubExample extends Example {
447 @Override public void v0() { called("Sub/v0", this); }
448 @Override void pkg_v0() { called("Sub/pkg_v0", this); }
jrose49494522012-01-18 17:34:29 -0800449 @SuppressWarnings("LeakingThisInConstructor")
jrose55220c32009-10-21 23:19:48 -0700450 private SubExample(int x) { called("<init>", this, x); }
jrose2cc9c832010-04-30 23:48:23 -0700451 public SubExample() { super("SubExample#"+nextArg()); }
jrose55220c32009-10-21 23:19:48 -0700452 }
453 public static interface IntExample {
454 public void v0();
jrosebe2db602010-09-08 18:40:34 -0700455 public static class Impl implements IntExample {
jrose55220c32009-10-21 23:19:48 -0700456 public void v0() { called("Int/v0", this); }
457 final String name;
jrose2cc9c832010-04-30 23:48:23 -0700458 public Impl() { name = "Impl#"+nextArg(); }
459 @Override public String toString() { return name; }
jrose55220c32009-10-21 23:19:48 -0700460 }
461 }
jrose485df122012-07-12 00:11:35 -0700462 static interface SubIntExample extends IntExample { }
jrose55220c32009-10-21 23:19:48 -0700463
464 static final Object[][][] ACCESS_CASES = {
jrose2cc9c832010-04-30 23:48:23 -0700465 { { false, PUBLIC }, { false, PACKAGE }, { false, PRIVATE }, { false, EXAMPLE } }, //[0]: all false
466 { { false, PUBLIC }, { false, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[1]: only PRIVATE
467 { { false, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[2]: PUBLIC false
468 { { true, PUBLIC }, { true, PACKAGE }, { true, PRIVATE }, { true, EXAMPLE } }, //[3]: all true
jrose55220c32009-10-21 23:19:48 -0700469 };
470
jrose2cc9c832010-04-30 23:48:23 -0700471 static Object[][] accessCases(Class<?> defc, String name, boolean isSpecial) {
472 Object[][] cases;
473 if (name.contains("pri_") || isSpecial) {
474 cases = ACCESS_CASES[1]; // PRIVATE only
475 } else if (name.contains("pkg_") || !Modifier.isPublic(defc.getModifiers())) {
476 cases = ACCESS_CASES[2]; // not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800477 } else {
478 assertTrue(name.indexOf('_') < 0);
479 boolean pubc = Modifier.isPublic(defc.getModifiers());
480 if (pubc)
jrose2cc9c832010-04-30 23:48:23 -0700481 cases = ACCESS_CASES[3]; // all access levels
482 else
483 cases = ACCESS_CASES[2]; // PACKAGE but not PUBLIC
jrose10f3b682010-01-07 16:16:45 -0800484 }
jrose2cc9c832010-04-30 23:48:23 -0700485 if (defc != Example.class && cases[cases.length-1][1] == EXAMPLE)
486 cases = Arrays.copyOfRange(cases, 0, cases.length-1);
487 return cases;
488 }
489 static Object[][] accessCases(Class<?> defc, String name) {
490 return accessCases(defc, name, false);
jrose55220c32009-10-21 23:19:48 -0700491 }
492
493 @Test
494 public void testFindStatic() throws Throwable {
495 if (CAN_SKIP_WORKING) return;
496 startTest("findStatic");
497 testFindStatic(PubExample.class, void.class, "s0");
498 testFindStatic(Example.class, void.class, "s0");
499 testFindStatic(Example.class, void.class, "pkg_s0");
500 testFindStatic(Example.class, void.class, "pri_s0");
501
502 testFindStatic(Example.class, Object.class, "s1", Object.class);
503 testFindStatic(Example.class, Object.class, "s2", int.class);
504 testFindStatic(Example.class, Object.class, "s3", long.class);
505 testFindStatic(Example.class, Object.class, "s4", int.class, int.class);
506 testFindStatic(Example.class, Object.class, "s5", long.class, int.class);
507 testFindStatic(Example.class, Object.class, "s6", int.class, long.class);
508 testFindStatic(Example.class, Object.class, "s7", float.class, double.class);
509
510 testFindStatic(false, PRIVATE, Example.class, void.class, "bogus");
511 }
512
513 void testFindStatic(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
514 for (Object[] ac : accessCases(defc, name)) {
515 testFindStatic((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
516 }
517 }
518 void testFindStatic(Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
519 testFindStatic(true, lookup, defc, ret, name, params);
520 }
521 void testFindStatic(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
522 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800523 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700524 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700525 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700526 try {
jrose2cc9c832010-04-30 23:48:23 -0700527 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700528 target = lookup.in(defc).findStatic(defc, name, type);
jrosef15905c2011-02-11 01:26:32 -0800529 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700530 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800531 if (name.contains("bogus"))
532 assertTrue(noAccess instanceof NoSuchMethodException);
533 else
534 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700535 }
jrose2cc9c832010-04-30 23:48:23 -0700536 if (verbosity >= 3)
537 System.out.println("findStatic "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700538 +(noAccess == null ? "" : " !! "+noAccess));
539 if (positive && noAccess != null) throw noAccess;
540 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
541 if (!positive) return; // negative test failed as expected
542 assertEquals(type, target.type());
jrose900bafd2010-10-30 21:08:23 -0700543 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700544 Object[] args = randomArgs(params);
545 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700546 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700547 assertCalled(name, args);
jrose2cc9c832010-04-30 23:48:23 -0700548 if (verbosity >= 1)
549 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700550 }
551
jrose73016262011-05-17 19:48:19 -0700552 static final boolean DEBUG_METHOD_HANDLE_NAMES = Boolean.getBoolean("java.lang.invoke.MethodHandle.DEBUG_NAMES");
553
jrose900bafd2010-10-30 21:08:23 -0700554 // rough check of name string
jrose73016262011-05-17 19:48:19 -0700555 static void assertNameStringContains(MethodHandle x, String s) {
556 if (!DEBUG_METHOD_HANDLE_NAMES) {
557 // ignore s
558 assertEquals("MethodHandle"+x.type(), x.toString());
559 return;
560 }
jrose900bafd2010-10-30 21:08:23 -0700561 if (x.toString().contains(s)) return;
562 assertEquals(s, x);
563 }
564
jrose55220c32009-10-21 23:19:48 -0700565 @Test
566 public void testFindVirtual() throws Throwable {
567 if (CAN_SKIP_WORKING) return;
568 startTest("findVirtual");
569 testFindVirtual(Example.class, void.class, "v0");
570 testFindVirtual(Example.class, void.class, "pkg_v0");
571 testFindVirtual(Example.class, void.class, "pri_v0");
572 testFindVirtual(Example.class, Object.class, "v1", Object.class);
573 testFindVirtual(Example.class, Object.class, "v2", Object.class, Object.class);
574 testFindVirtual(Example.class, Object.class, "v2", Object.class, int.class);
575 testFindVirtual(Example.class, Object.class, "v2", int.class, Object.class);
576 testFindVirtual(Example.class, Object.class, "v2", int.class, int.class);
577 testFindVirtual(false, PRIVATE, Example.class, Example.class, void.class, "bogus");
578 // test dispatch
579 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/v0");
580 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/v0");
581 testFindVirtual(SubExample.class, IntExample.class, void.class, "Sub/v0");
582 testFindVirtual(SubExample.class, SubExample.class, void.class, "Sub/pkg_v0");
583 testFindVirtual(SubExample.class, Example.class, void.class, "Sub/pkg_v0");
584 testFindVirtual(Example.class, IntExample.class, void.class, "v0");
585 testFindVirtual(IntExample.Impl.class, IntExample.class, void.class, "Int/v0");
586 }
587
588 void testFindVirtual(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
589 Class<?> rcvc = defc;
590 testFindVirtual(rcvc, defc, ret, name, params);
591 }
592 void testFindVirtual(Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
593 for (Object[] ac : accessCases(defc, name)) {
594 testFindVirtual((Boolean)ac[0], (Lookup)ac[1], rcvc, defc, ret, name, params);
595 }
596 }
597 void testFindVirtual(Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
598 testFindVirtual(true, lookup, rcvc, defc, ret, name, params);
599 }
600 void testFindVirtual(boolean positive, Lookup lookup, Class<?> rcvc, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
601 countTest(positive);
602 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800603 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700604 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700605 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700606 try {
jrose2cc9c832010-04-30 23:48:23 -0700607 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700608 target = lookup.in(defc).findVirtual(defc, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800609 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700610 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800611 if (name.contains("bogus"))
612 assertTrue(noAccess instanceof NoSuchMethodException);
613 else
614 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700615 }
jrose2cc9c832010-04-30 23:48:23 -0700616 if (verbosity >= 3)
617 System.out.println("findVirtual "+lookup+": "+defc.getName()+"."+name+"/"+type+" => "+target
jrose55220c32009-10-21 23:19:48 -0700618 +(noAccess == null ? "" : " !! "+noAccess));
619 if (positive && noAccess != null) throw noAccess;
620 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
621 if (!positive) return; // negative test failed as expected
622 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)defc), params);
jrose10f3b682010-01-07 16:16:45 -0800623 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700624 assertEquals(typeWithSelf, target.type());
jrose900bafd2010-10-30 21:08:23 -0700625 assertNameStringContains(target, methodName);
jrose55220c32009-10-21 23:19:48 -0700626 Object[] argsWithSelf = randomArgs(paramsWithSelf);
627 if (rcvc != defc) argsWithSelf[0] = randomArg(rcvc);
628 printCalled(target, name, argsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700629 target.invokeWithArguments(argsWithSelf);
jrose55220c32009-10-21 23:19:48 -0700630 assertCalled(name, argsWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700631 if (verbosity >= 1)
632 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700633 }
634
635 @Test
636 public void testFindSpecial() throws Throwable {
637 if (CAN_SKIP_WORKING) return;
638 startTest("findSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700639 testFindSpecial(SubExample.class, Example.class, void.class, "v0");
640 testFindSpecial(SubExample.class, Example.class, void.class, "pkg_v0");
641 // Do some negative testing:
jrosef15905c2011-02-11 01:26:32 -0800642 testFindSpecial(false, EXAMPLE, SubExample.class, Example.class, void.class, "bogus");
643 testFindSpecial(false, PRIVATE, SubExample.class, Example.class, void.class, "bogus");
jrose2cc9c832010-04-30 23:48:23 -0700644 for (Lookup lookup : new Lookup[]{ PRIVATE, EXAMPLE, PACKAGE, PUBLIC }) {
645 testFindSpecial(false, lookup, Object.class, Example.class, void.class, "v0");
646 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "<init>", int.class);
647 testFindSpecial(false, lookup, SubExample.class, Example.class, void.class, "s0");
jrose2cc9c832010-04-30 23:48:23 -0700648 }
jrose55220c32009-10-21 23:19:48 -0700649 }
650
jrose2cc9c832010-04-30 23:48:23 -0700651 void testFindSpecial(Class<?> specialCaller,
652 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
653 testFindSpecial(true, EXAMPLE, specialCaller, defc, ret, name, params);
654 testFindSpecial(true, PRIVATE, specialCaller, defc, ret, name, params);
655 testFindSpecial(false, PACKAGE, specialCaller, defc, ret, name, params);
656 testFindSpecial(false, PUBLIC, specialCaller, defc, ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700657 }
jrose2cc9c832010-04-30 23:48:23 -0700658 void testFindSpecial(boolean positive, Lookup lookup, Class<?> specialCaller,
659 Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700660 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800661 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700662 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700663 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700664 try {
jrose2cc9c832010-04-30 23:48:23 -0700665 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700666 if (verbosity >= 5) System.out.println(" lookup => "+lookup.in(specialCaller));
667 target = lookup.in(specialCaller).findSpecial(defc, name, type, specialCaller);
jrosef15905c2011-02-11 01:26:32 -0800668 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700669 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800670 if (name.contains("bogus"))
671 assertTrue(noAccess instanceof NoSuchMethodException);
672 else
673 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700674 }
jrose2cc9c832010-04-30 23:48:23 -0700675 if (verbosity >= 3)
676 System.out.println("findSpecial from "+specialCaller.getName()+" to "+defc.getName()+"."+name+"/"+type+" => "+target
677 +(target == null ? "" : target.type())
678 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700679 if (positive && noAccess != null) throw noAccess;
680 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
681 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700682 assertEquals(specialCaller, target.type().parameterType(0));
683 assertEquals(type, target.type().dropParameterTypes(0,1));
684 Class<?>[] paramsWithSelf = cat(array(Class[].class, (Class)specialCaller), params);
jrose10f3b682010-01-07 16:16:45 -0800685 MethodType typeWithSelf = MethodType.methodType(ret, paramsWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700686 assertNameStringContains(target, name);
jrose55220c32009-10-21 23:19:48 -0700687 Object[] args = randomArgs(paramsWithSelf);
688 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700689 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700690 assertCalled(name, args);
jrose55220c32009-10-21 23:19:48 -0700691 }
692
693 @Test
jroseb4be0262011-07-16 15:44:33 -0700694 public void testFindConstructor() throws Throwable {
695 if (CAN_SKIP_WORKING) return;
696 startTest("findConstructor");
697 testFindConstructor(true, EXAMPLE, Example.class);
698 testFindConstructor(true, EXAMPLE, Example.class, int.class);
699 testFindConstructor(true, EXAMPLE, Example.class, String.class);
700 }
701 void testFindConstructor(boolean positive, Lookup lookup,
702 Class<?> defc, Class<?>... params) throws Throwable {
703 countTest(positive);
704 MethodType type = MethodType.methodType(void.class, params);
705 MethodHandle target = null;
706 Exception noAccess = null;
707 try {
708 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" <init>"+type);
709 target = lookup.findConstructor(defc, type);
710 } catch (ReflectiveOperationException ex) {
711 noAccess = ex;
712 assertTrue(noAccess instanceof IllegalAccessException);
713 }
714 if (verbosity >= 3)
715 System.out.println("findConstructor "+defc.getName()+".<init>/"+type+" => "+target
716 +(target == null ? "" : target.type())
717 +(noAccess == null ? "" : " !! "+noAccess));
718 if (positive && noAccess != null) throw noAccess;
719 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
720 if (!positive) return; // negative test failed as expected
721 assertEquals(type.changeReturnType(defc), target.type());
722 Object[] args = randomArgs(params);
723 printCalled(target, defc.getSimpleName(), args);
724 Object obj = target.invokeWithArguments(args);
725 if (!(defc == Example.class && params.length < 2))
726 assertCalled(defc.getSimpleName()+".<init>", args);
727 assertTrue("instance of "+defc.getName(), defc.isInstance(obj));
728 }
729
730 @Test
jrose55220c32009-10-21 23:19:48 -0700731 public void testBind() throws Throwable {
732 if (CAN_SKIP_WORKING) return;
733 startTest("bind");
734 testBind(Example.class, void.class, "v0");
735 testBind(Example.class, void.class, "pkg_v0");
736 testBind(Example.class, void.class, "pri_v0");
737 testBind(Example.class, Object.class, "v1", Object.class);
738 testBind(Example.class, Object.class, "v2", Object.class, Object.class);
739 testBind(Example.class, Object.class, "v2", Object.class, int.class);
740 testBind(Example.class, Object.class, "v2", int.class, Object.class);
741 testBind(Example.class, Object.class, "v2", int.class, int.class);
742 testBind(false, PRIVATE, Example.class, void.class, "bogus");
743 testBind(SubExample.class, void.class, "Sub/v0");
744 testBind(SubExample.class, void.class, "Sub/pkg_v0");
745 testBind(IntExample.Impl.class, void.class, "Int/v0");
746 }
747
748 void testBind(Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
749 for (Object[] ac : accessCases(defc, name)) {
750 testBind((Boolean)ac[0], (Lookup)ac[1], defc, ret, name, params);
751 }
752 }
753
754 void testBind(boolean positive, Lookup lookup, Class<?> defc, Class<?> ret, String name, Class<?>... params) throws Throwable {
755 countTest(positive);
756 String methodName = name.substring(1 + name.indexOf('/')); // foo/bar => foo
jrose10f3b682010-01-07 16:16:45 -0800757 MethodType type = MethodType.methodType(ret, params);
jrose55220c32009-10-21 23:19:48 -0700758 Object receiver = randomArg(defc);
759 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700760 Exception noAccess = null;
jrose55220c32009-10-21 23:19:48 -0700761 try {
jrose2cc9c832010-04-30 23:48:23 -0700762 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
jrose900bafd2010-10-30 21:08:23 -0700763 target = lookup.in(defc).bind(receiver, methodName, type);
jrosef15905c2011-02-11 01:26:32 -0800764 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700765 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800766 if (name.contains("bogus"))
767 assertTrue(noAccess instanceof NoSuchMethodException);
768 else
769 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700770 }
jrose2cc9c832010-04-30 23:48:23 -0700771 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -0700772 System.out.println("bind "+receiver+"."+name+"/"+type+" => "+target
773 +(noAccess == null ? "" : " !! "+noAccess));
774 if (positive && noAccess != null) throw noAccess;
775 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
776 if (!positive) return; // negative test failed as expected
777 assertEquals(type, target.type());
778 Object[] args = randomArgs(params);
779 printCalled(target, name, args);
jrose900bafd2010-10-30 21:08:23 -0700780 target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -0700781 Object[] argsWithReceiver = cat(array(Object[].class, receiver), args);
782 assertCalled(name, argsWithReceiver);
jrose2cc9c832010-04-30 23:48:23 -0700783 if (verbosity >= 1)
784 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700785 }
786
787 @Test
788 public void testUnreflect() throws Throwable {
789 if (CAN_SKIP_WORKING) return;
790 startTest("unreflect");
791 testUnreflect(Example.class, true, void.class, "s0");
792 testUnreflect(Example.class, true, void.class, "pkg_s0");
793 testUnreflect(Example.class, true, void.class, "pri_s0");
794
795 testUnreflect(Example.class, true, Object.class, "s1", Object.class);
796 testUnreflect(Example.class, true, Object.class, "s2", int.class);
jrose2cc9c832010-04-30 23:48:23 -0700797 testUnreflect(Example.class, true, Object.class, "s3", long.class);
798 testUnreflect(Example.class, true, Object.class, "s4", int.class, int.class);
799 testUnreflect(Example.class, true, Object.class, "s5", long.class, int.class);
800 testUnreflect(Example.class, true, Object.class, "s6", int.class, long.class);
jrose55220c32009-10-21 23:19:48 -0700801
802 testUnreflect(Example.class, false, void.class, "v0");
803 testUnreflect(Example.class, false, void.class, "pkg_v0");
804 testUnreflect(Example.class, false, void.class, "pri_v0");
805 testUnreflect(Example.class, false, Object.class, "v1", Object.class);
806 testUnreflect(Example.class, false, Object.class, "v2", Object.class, Object.class);
807 testUnreflect(Example.class, false, Object.class, "v2", Object.class, int.class);
808 testUnreflect(Example.class, false, Object.class, "v2", int.class, Object.class);
809 testUnreflect(Example.class, false, Object.class, "v2", int.class, int.class);
810 }
811
812 void testUnreflect(Class<?> defc, boolean isStatic, Class<?> ret, String name, Class<?>... params) throws Throwable {
813 for (Object[] ac : accessCases(defc, name)) {
jrose2cc9c832010-04-30 23:48:23 -0700814 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, (isStatic ? null : defc), ret, name, params);
jrose55220c32009-10-21 23:19:48 -0700815 }
816 }
jrose2cc9c832010-04-30 23:48:23 -0700817 void testUnreflect(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
818 for (Object[] ac : accessCases(defc, name)) {
819 testUnreflectMaybeSpecial(null, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
820 }
821 }
822 void testUnreflectMaybeSpecial(Class<?> specialCaller,
823 boolean positive, Lookup lookup,
824 Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700825 countTest(positive);
jrose10f3b682010-01-07 16:16:45 -0800826 MethodType type = MethodType.methodType(ret, params);
jrosef15905c2011-02-11 01:26:32 -0800827 Method rmethod = defc.getDeclaredMethod(name, params);
jrose55220c32009-10-21 23:19:48 -0700828 MethodHandle target = null;
jrosea1ebbe62010-09-08 18:40:23 -0700829 Exception noAccess = null;
jrose2cc9c832010-04-30 23:48:23 -0700830 boolean isStatic = (rcvc == null);
831 boolean isSpecial = (specialCaller != null);
jrose55220c32009-10-21 23:19:48 -0700832 try {
jrose2cc9c832010-04-30 23:48:23 -0700833 if (verbosity >= 4) System.out.println("lookup via "+lookup+" of "+defc+" "+name+type);
834 if (isSpecial)
jrose900bafd2010-10-30 21:08:23 -0700835 target = lookup.in(specialCaller).unreflectSpecial(rmethod, specialCaller);
jrose2cc9c832010-04-30 23:48:23 -0700836 else
jrose900bafd2010-10-30 21:08:23 -0700837 target = lookup.in(defc).unreflect(rmethod);
jrosef15905c2011-02-11 01:26:32 -0800838 } catch (ReflectiveOperationException ex) {
jrose55220c32009-10-21 23:19:48 -0700839 noAccess = ex;
jrosef15905c2011-02-11 01:26:32 -0800840 if (name.contains("bogus"))
841 assertTrue(noAccess instanceof NoSuchMethodException);
842 else
843 assertTrue(noAccess instanceof IllegalAccessException);
jrose55220c32009-10-21 23:19:48 -0700844 }
jrose2cc9c832010-04-30 23:48:23 -0700845 if (verbosity >= 3)
846 System.out.println("unreflect"+(isSpecial?"Special":"")+" "+defc.getName()+"."+name+"/"+type
847 +(!isSpecial ? "" : " specialCaller="+specialCaller)
848 +( isStatic ? "" : " receiver="+rcvc)
849 +" => "+target
850 +(noAccess == null ? "" : " !! "+noAccess));
jrose55220c32009-10-21 23:19:48 -0700851 if (positive && noAccess != null) throw noAccess;
852 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
853 if (!positive) return; // negative test failed as expected
jrose2cc9c832010-04-30 23:48:23 -0700854 assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
jrose55220c32009-10-21 23:19:48 -0700855 Class<?>[] paramsMaybeWithSelf = params;
856 if (!isStatic) {
jrose2cc9c832010-04-30 23:48:23 -0700857 paramsMaybeWithSelf = cat(array(Class[].class, (Class)rcvc), params);
jrose55220c32009-10-21 23:19:48 -0700858 }
jrose10f3b682010-01-07 16:16:45 -0800859 MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700860 if (isStatic) {
861 assertEquals(typeMaybeWithSelf, target.type());
862 } else {
jrose2cc9c832010-04-30 23:48:23 -0700863 if (isSpecial)
864 assertEquals(specialCaller, target.type().parameterType(0));
865 else
866 assertEquals(defc, target.type().parameterType(0));
867 assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
868 }
jrose55220c32009-10-21 23:19:48 -0700869 Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
870 printCalled(target, name, argsMaybeWithSelf);
jrose900bafd2010-10-30 21:08:23 -0700871 target.invokeWithArguments(argsMaybeWithSelf);
jrose55220c32009-10-21 23:19:48 -0700872 assertCalled(name, argsMaybeWithSelf);
jrose2cc9c832010-04-30 23:48:23 -0700873 if (verbosity >= 1)
874 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -0700875 }
876
jrose2cc9c832010-04-30 23:48:23 -0700877 void testUnreflectSpecial(Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
878 for (Object[] ac : accessCases(defc, name, true)) {
879 Class<?> specialCaller = rcvc;
880 testUnreflectMaybeSpecial(specialCaller, (Boolean)ac[0], (Lookup)ac[1], defc, rcvc, ret, name, params);
881 }
882 }
883
884 @Test
jrose55220c32009-10-21 23:19:48 -0700885 public void testUnreflectSpecial() throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -0700886 if (CAN_SKIP_WORKING) return;
jrose55220c32009-10-21 23:19:48 -0700887 startTest("unreflectSpecial");
jrose2cc9c832010-04-30 23:48:23 -0700888 testUnreflectSpecial(Example.class, Example.class, void.class, "v0");
889 testUnreflectSpecial(Example.class, SubExample.class, void.class, "v0");
890 testUnreflectSpecial(Example.class, Example.class, void.class, "pkg_v0");
891 testUnreflectSpecial(Example.class, SubExample.class, void.class, "pkg_v0");
892 testUnreflectSpecial(Example.class, Example.class, Object.class, "v2", int.class, int.class);
893 testUnreflectSpecial(Example.class, SubExample.class, Object.class, "v2", int.class, int.class);
894 testUnreflectMaybeSpecial(Example.class, false, PRIVATE, Example.class, Example.class, void.class, "s0");
jrose55220c32009-10-21 23:19:48 -0700895 }
896
jrose10f3b682010-01-07 16:16:45 -0800897 public static class HasFields {
898 boolean fZ = false;
899 byte fB = (byte)'B';
900 short fS = (short)'S';
901 char fC = 'C';
902 int fI = 'I';
903 long fJ = 'J';
904 float fF = 'F';
905 double fD = 'D';
906 static boolean sZ = true;
907 static byte sB = 1+(byte)'B';
908 static short sS = 1+(short)'S';
909 static char sC = 1+'C';
910 static int sI = 1+'I';
911 static long sJ = 1+'J';
912 static float sF = 1+'F';
913 static double sD = 1+'D';
914
915 Object fL = 'L';
916 String fR = "R";
917 static Object sL = 'M';
918 static String sR = "S";
919
920 static final Object[][] CASES;
921 static {
jrose49494522012-01-18 17:34:29 -0800922 ArrayList<Object[]> cases = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -0800923 Object types[][] = {
924 {'L',Object.class}, {'R',String.class},
925 {'I',int.class}, {'J',long.class},
926 {'F',float.class}, {'D',double.class},
927 {'Z',boolean.class}, {'B',byte.class},
928 {'S',short.class}, {'C',char.class},
929 };
930 HasFields fields = new HasFields();
931 for (Object[] t : types) {
932 for (int kind = 0; kind <= 1; kind++) {
933 boolean isStatic = (kind != 0);
934 char btc = (Character)t[0];
935 String name = (isStatic ? "s" : "f") + btc;
936 Class<?> type = (Class<?>) t[1];
937 Object value;
938 Field field;
jrose320b7692011-05-12 19:27:49 -0700939 try {
jrose10f3b682010-01-07 16:16:45 -0800940 field = HasFields.class.getDeclaredField(name);
jrose49494522012-01-18 17:34:29 -0800941 } catch (NoSuchFieldException | SecurityException ex) {
jrose10f3b682010-01-07 16:16:45 -0800942 throw new InternalError("no field HasFields."+name);
943 }
944 try {
945 value = field.get(fields);
jrose49494522012-01-18 17:34:29 -0800946 } catch (IllegalArgumentException | IllegalAccessException ex) {
jrose10f3b682010-01-07 16:16:45 -0800947 throw new InternalError("cannot fetch field HasFields."+name);
948 }
949 if (type == float.class) {
950 float v = 'F';
951 if (isStatic) v++;
jrosef15905c2011-02-11 01:26:32 -0800952 assertTrue(value.equals(v));
jrose10f3b682010-01-07 16:16:45 -0800953 }
jrosef15905c2011-02-11 01:26:32 -0800954 assertTrue(name.equals(field.getName()));
955 assertTrue(type.equals(field.getType()));
956 assertTrue(isStatic == (Modifier.isStatic(field.getModifiers())));
jrose10f3b682010-01-07 16:16:45 -0800957 cases.add(new Object[]{ field, value });
958 }
959 }
jrosef15905c2011-02-11 01:26:32 -0800960 cases.add(new Object[]{ new Object[]{ false, HasFields.class, "bogus_fD", double.class }, Error.class });
961 cases.add(new Object[]{ new Object[]{ true, HasFields.class, "bogus_sL", Object.class }, Error.class });
jrose10f3b682010-01-07 16:16:45 -0800962 CASES = cases.toArray(new Object[0][]);
963 }
964 }
965
jrose485df122012-07-12 00:11:35 -0700966 static final int TEST_UNREFLECT = 1, TEST_FIND_FIELD = 2, TEST_FIND_STATIC = 3, TEST_SETTER = 0x10, TEST_NPE = 0x20;
jrosecf98d422010-06-08 23:08:56 -0700967 static boolean testModeMatches(int testMode, boolean isStatic) {
968 switch (testMode) {
jrosef15905c2011-02-11 01:26:32 -0800969 case TEST_FIND_STATIC: return isStatic;
jrosecf98d422010-06-08 23:08:56 -0700970 case TEST_FIND_FIELD: return !isStatic;
jrosef15905c2011-02-11 01:26:32 -0800971 case TEST_UNREFLECT: return true; // unreflect matches both
jrosecf98d422010-06-08 23:08:56 -0700972 }
jrosef15905c2011-02-11 01:26:32 -0800973 throw new InternalError("testMode="+testMode);
jrosecf98d422010-06-08 23:08:56 -0700974 }
975
jrose10f3b682010-01-07 16:16:45 -0800976 @Test
jrose55220c32009-10-21 23:19:48 -0700977 public void testUnreflectGetter() throws Throwable {
jrose55220c32009-10-21 23:19:48 -0700978 startTest("unreflectGetter");
jrosecf98d422010-06-08 23:08:56 -0700979 testGetter(TEST_UNREFLECT);
980 }
981 @Test
982 public void testFindGetter() throws Throwable {
983 startTest("findGetter");
984 testGetter(TEST_FIND_FIELD);
985 }
986 @Test
987 public void testFindStaticGetter() throws Throwable {
988 startTest("findStaticGetter");
jrosef15905c2011-02-11 01:26:32 -0800989 testGetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -0700990 }
991 public void testGetter(int testMode) throws Throwable {
992 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
jrose10f3b682010-01-07 16:16:45 -0800993 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -0800994 boolean positive = (c[1] != Error.class);
995 testGetter(positive, lookup, c[0], c[1], testMode);
jrose485df122012-07-12 00:11:35 -0700996 if (positive)
997 testGetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
jrosef15905c2011-02-11 01:26:32 -0800998 }
999 testGetter(true, lookup,
1000 new Object[]{ true, System.class, "out", java.io.PrintStream.class },
1001 System.out, testMode);
1002 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1003 testGetter(false, lookup,
1004 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1005 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001006 }
1007 }
jrosef15905c2011-02-11 01:26:32 -08001008 public void testGetter(boolean positive, MethodHandles.Lookup lookup,
1009 Object fieldRef, Object value, int testMode) throws Throwable {
1010 testAccessor(positive, lookup, fieldRef, value, testMode);
1011 }
1012
jrose485df122012-07-12 00:11:35 -07001013 public void testAccessor(boolean positive0, MethodHandles.Lookup lookup,
jrosef15905c2011-02-11 01:26:32 -08001014 Object fieldRef, Object value, int testMode0) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07001015 if (verbosity >= 4)
jrose485df122012-07-12 00:11:35 -07001016 System.out.println("testAccessor"+Arrays.deepToString(new Object[]{positive0, lookup, fieldRef, value, testMode0}));
jrosef15905c2011-02-11 01:26:32 -08001017 boolean isGetter = ((testMode0 & TEST_SETTER) == 0);
jrose485df122012-07-12 00:11:35 -07001018 boolean testNPE = ((testMode0 & TEST_NPE) != 0);
1019 int testMode = testMode0 & ~(TEST_SETTER | TEST_NPE);
1020 boolean positive = positive0 && !testNPE;
jrosef15905c2011-02-11 01:26:32 -08001021 boolean isStatic;
1022 Class<?> fclass;
1023 String fname;
1024 Class<?> ftype;
1025 Field f = (fieldRef instanceof Field ? (Field)fieldRef : null);
1026 if (f != null) {
1027 isStatic = Modifier.isStatic(f.getModifiers());
1028 fclass = f.getDeclaringClass();
1029 fname = f.getName();
1030 ftype = f.getType();
1031 } else {
1032 Object[] scnt = (Object[]) fieldRef;
1033 isStatic = (Boolean) scnt[0];
1034 fclass = (Class<?>) scnt[1];
1035 fname = (String) scnt[2];
1036 ftype = (Class<?>) scnt[3];
1037 try {
1038 f = fclass.getDeclaredField(fname);
1039 } catch (ReflectiveOperationException ex) {
1040 f = null;
1041 }
1042 }
jrosecf98d422010-06-08 23:08:56 -07001043 if (!testModeMatches(testMode, isStatic)) return;
jrosef15905c2011-02-11 01:26:32 -08001044 if (f == null && testMode == TEST_UNREFLECT) return;
jrose485df122012-07-12 00:11:35 -07001045 if (testNPE && isStatic) return;
jrosef15905c2011-02-11 01:26:32 -08001046 countTest(positive);
1047 MethodType expType;
1048 if (isGetter)
1049 expType = MethodType.methodType(ftype, HasFields.class);
1050 else
1051 expType = MethodType.methodType(void.class, HasFields.class, ftype);
jrose10f3b682010-01-07 16:16:45 -08001052 if (isStatic) expType = expType.dropParameterTypes(0, 1);
jrosef15905c2011-02-11 01:26:32 -08001053 Exception noAccess = null;
1054 MethodHandle mh;
1055 try {
jrose485df122012-07-12 00:11:35 -07001056 switch (testMode0 & ~TEST_NPE) {
jrosef15905c2011-02-11 01:26:32 -08001057 case TEST_UNREFLECT: mh = lookup.unreflectGetter(f); break;
1058 case TEST_FIND_FIELD: mh = lookup.findGetter(fclass, fname, ftype); break;
1059 case TEST_FIND_STATIC: mh = lookup.findStaticGetter(fclass, fname, ftype); break;
1060 case TEST_SETTER|
1061 TEST_UNREFLECT: mh = lookup.unreflectSetter(f); break;
1062 case TEST_SETTER|
1063 TEST_FIND_FIELD: mh = lookup.findSetter(fclass, fname, ftype); break;
1064 case TEST_SETTER|
1065 TEST_FIND_STATIC: mh = lookup.findStaticSetter(fclass, fname, ftype); break;
1066 default:
1067 throw new InternalError("testMode="+testMode);
1068 }
1069 } catch (ReflectiveOperationException ex) {
1070 mh = null;
1071 noAccess = ex;
1072 if (fname.contains("bogus"))
1073 assertTrue(noAccess instanceof NoSuchFieldException);
1074 else
1075 assertTrue(noAccess instanceof IllegalAccessException);
1076 }
1077 if (verbosity >= 3)
1078 System.out.println("find"+(isStatic?"Static":"")+(isGetter?"Getter":"Setter")+" "+fclass.getName()+"."+fname+"/"+ftype
1079 +" => "+mh
1080 +(noAccess == null ? "" : " !! "+noAccess));
jrose485df122012-07-12 00:11:35 -07001081 if (positive && !testNPE && noAccess != null) throw new RuntimeException(noAccess);
1082 assertEquals(positive0 ? "positive test" : "negative test erroneously passed", positive0, mh != null);
1083 if (!positive && !testNPE) return; // negative access test failed as expected
jrosef15905c2011-02-11 01:26:32 -08001084 assertEquals((isStatic ? 0 : 1)+(isGetter ? 0 : 1), mh.type().parameterCount());
1085
1086
jrose10f3b682010-01-07 16:16:45 -08001087 assertSame(mh.type(), expType);
jrose900bafd2010-10-30 21:08:23 -07001088 assertNameStringContains(mh, fname);
jrose10f3b682010-01-07 16:16:45 -08001089 HasFields fields = new HasFields();
jrose485df122012-07-12 00:11:35 -07001090 HasFields fieldsForMH = fields;
1091 if (testNPE) fieldsForMH = null; // perturb MH argument to elicit expected error
jrose10f3b682010-01-07 16:16:45 -08001092 Object sawValue;
jrosef15905c2011-02-11 01:26:32 -08001093 Class<?> vtype = ftype;
1094 if (ftype != int.class) vtype = Object.class;
1095 if (isGetter) {
jrose9b82ad62011-05-26 17:37:36 -07001096 mh = mh.asType(mh.type().generic()
1097 .changeReturnType(vtype));
jrosef15905c2011-02-11 01:26:32 -08001098 } else {
1099 int last = mh.type().parameterCount() - 1;
jrose9b82ad62011-05-26 17:37:36 -07001100 mh = mh.asType(mh.type().generic()
1101 .changeReturnType(void.class)
1102 .changeParameterType(last, vtype));
jrose10f3b682010-01-07 16:16:45 -08001103 }
jrosef15905c2011-02-11 01:26:32 -08001104 if (f != null && f.getDeclaringClass() == HasFields.class) {
1105 assertEquals(f.get(fields), value); // clean to start with
1106 }
jrose485df122012-07-12 00:11:35 -07001107 Throwable caughtEx = null;
jrosef15905c2011-02-11 01:26:32 -08001108 if (isGetter) {
1109 Object expValue = value;
1110 for (int i = 0; i <= 1; i++) {
1111 if (isStatic) {
1112 if (ftype == int.class)
1113 sawValue = (int) mh.invokeExact(); // do these exactly
1114 else
1115 sawValue = mh.invokeExact();
1116 } else {
jrose485df122012-07-12 00:11:35 -07001117 sawValue = null; // make DA rules happy under try/catch
1118 try {
1119 if (ftype == int.class)
1120 sawValue = (int) mh.invokeExact((Object) fieldsForMH);
1121 else
1122 sawValue = mh.invokeExact((Object) fieldsForMH);
1123 } catch (RuntimeException ex) {
1124 if (ex instanceof NullPointerException && testNPE) {
1125 caughtEx = ex;
1126 break;
1127 }
1128 }
jrosef15905c2011-02-11 01:26:32 -08001129 }
1130 assertEquals(sawValue, expValue);
1131 if (f != null && f.getDeclaringClass() == HasFields.class
1132 && !Modifier.isFinal(f.getModifiers())) {
1133 Object random = randomArg(ftype);
1134 f.set(fields, random);
1135 expValue = random;
1136 } else {
1137 break;
1138 }
1139 }
1140 } else {
1141 for (int i = 0; i <= 1; i++) {
1142 Object putValue = randomArg(ftype);
1143 if (isStatic) {
1144 if (ftype == int.class)
1145 mh.invokeExact((int)putValue); // do these exactly
1146 else
1147 mh.invokeExact(putValue);
1148 } else {
jrose485df122012-07-12 00:11:35 -07001149 try {
1150 if (ftype == int.class)
1151 mh.invokeExact((Object) fieldsForMH, (int)putValue);
1152 else
1153 mh.invokeExact((Object) fieldsForMH, putValue);
1154 } catch (RuntimeException ex) {
1155 if (ex instanceof NullPointerException && testNPE) {
1156 caughtEx = ex;
1157 break;
1158 }
1159 }
jrosef15905c2011-02-11 01:26:32 -08001160 }
1161 if (f != null && f.getDeclaringClass() == HasFields.class) {
1162 assertEquals(f.get(fields), putValue);
1163 }
1164 }
1165 }
1166 if (f != null && f.getDeclaringClass() == HasFields.class) {
1167 f.set(fields, value); // put it back
1168 }
jrose485df122012-07-12 00:11:35 -07001169 if (testNPE) {
1170 if (caughtEx == null || !(caughtEx instanceof NullPointerException))
1171 throw new RuntimeException("failed to catch NPE exception"+(caughtEx == null ? " (caughtEx=null)" : ""), caughtEx);
1172 caughtEx = null; // nullify expected exception
1173 }
1174 if (caughtEx != null) {
1175 throw new RuntimeException("unexpected exception", caughtEx);
1176 }
jrose55220c32009-10-21 23:19:48 -07001177 }
1178
jrose10f3b682010-01-07 16:16:45 -08001179
1180 @Test
jrose55220c32009-10-21 23:19:48 -07001181 public void testUnreflectSetter() throws Throwable {
jrosecf98d422010-06-08 23:08:56 -07001182 startTest("unreflectSetter");
1183 testSetter(TEST_UNREFLECT);
1184 }
1185 @Test
1186 public void testFindSetter() throws Throwable {
1187 startTest("findSetter");
1188 testSetter(TEST_FIND_FIELD);
1189 }
1190 @Test
1191 public void testFindStaticSetter() throws Throwable {
1192 startTest("findStaticSetter");
jrosef15905c2011-02-11 01:26:32 -08001193 testSetter(TEST_FIND_STATIC);
jrosecf98d422010-06-08 23:08:56 -07001194 }
1195 public void testSetter(int testMode) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001196 Lookup lookup = PRIVATE; // FIXME: test more lookups than this one
1197 startTest("unreflectSetter");
jrose10f3b682010-01-07 16:16:45 -08001198 for (Object[] c : HasFields.CASES) {
jrosef15905c2011-02-11 01:26:32 -08001199 boolean positive = (c[1] != Error.class);
1200 testSetter(positive, lookup, c[0], c[1], testMode);
jrose485df122012-07-12 00:11:35 -07001201 if (positive)
1202 testSetter(positive, lookup, c[0], c[1], testMode | TEST_NPE);
jrosef15905c2011-02-11 01:26:32 -08001203 }
1204 for (int isStaticN = 0; isStaticN <= 1; isStaticN++) {
1205 testSetter(false, lookup,
1206 new Object[]{ (isStaticN != 0), System.class, "bogus", char.class },
1207 null, testMode);
jrose10f3b682010-01-07 16:16:45 -08001208 }
1209 }
jrosef15905c2011-02-11 01:26:32 -08001210 public void testSetter(boolean positive, MethodHandles.Lookup lookup,
1211 Object fieldRef, Object value, int testMode) throws Throwable {
1212 testAccessor(positive, lookup, fieldRef, value, testMode | TEST_SETTER);
jrose55220c32009-10-21 23:19:48 -07001213 }
1214
jrose10f3b682010-01-07 16:16:45 -08001215 @Test
jrose55220c32009-10-21 23:19:48 -07001216 public void testArrayElementGetter() throws Throwable {
1217 startTest("arrayElementGetter");
jrose2cc9c832010-04-30 23:48:23 -07001218 testArrayElementGetterSetter(false);
jrose55220c32009-10-21 23:19:48 -07001219 }
1220
jrose10f3b682010-01-07 16:16:45 -08001221 @Test
jrose55220c32009-10-21 23:19:48 -07001222 public void testArrayElementSetter() throws Throwable {
1223 startTest("arrayElementSetter");
jrose2cc9c832010-04-30 23:48:23 -07001224 testArrayElementGetterSetter(true);
1225 }
1226
jrose485df122012-07-12 00:11:35 -07001227 private static final int TEST_ARRAY_NONE = 0, TEST_ARRAY_NPE = 1, TEST_ARRAY_OOB = 2, TEST_ARRAY_ASE = 3;
1228
jrose2cc9c832010-04-30 23:48:23 -07001229 public void testArrayElementGetterSetter(boolean testSetter) throws Throwable {
jrose485df122012-07-12 00:11:35 -07001230 testArrayElementGetterSetter(testSetter, TEST_ARRAY_NONE);
jrose10f3b682010-01-07 16:16:45 -08001231 }
1232
jrose485df122012-07-12 00:11:35 -07001233 @Test
1234 public void testArrayElementErrors() throws Throwable {
1235 startTest("arrayElementErrors");
1236 testArrayElementGetterSetter(false, TEST_ARRAY_NPE);
1237 testArrayElementGetterSetter(true, TEST_ARRAY_NPE);
1238 testArrayElementGetterSetter(false, TEST_ARRAY_OOB);
1239 testArrayElementGetterSetter(true, TEST_ARRAY_OOB);
1240 testArrayElementGetterSetter(new Object[10], true, TEST_ARRAY_ASE);
1241 testArrayElementGetterSetter(new Example[10], true, TEST_ARRAY_ASE);
1242 testArrayElementGetterSetter(new IntExample[10], true, TEST_ARRAY_ASE);
1243 }
1244
1245 public void testArrayElementGetterSetter(boolean testSetter, int negTest) throws Throwable {
1246 testArrayElementGetterSetter(new String[10], testSetter, negTest);
1247 testArrayElementGetterSetter(new Iterable<?>[10], testSetter, negTest);
1248 testArrayElementGetterSetter(new Example[10], testSetter, negTest);
1249 testArrayElementGetterSetter(new IntExample[10], testSetter, negTest);
1250 testArrayElementGetterSetter(new Object[10], testSetter, negTest);
1251 testArrayElementGetterSetter(new boolean[10], testSetter, negTest);
1252 testArrayElementGetterSetter(new byte[10], testSetter, negTest);
1253 testArrayElementGetterSetter(new char[10], testSetter, negTest);
1254 testArrayElementGetterSetter(new short[10], testSetter, negTest);
1255 testArrayElementGetterSetter(new int[10], testSetter, negTest);
1256 testArrayElementGetterSetter(new float[10], testSetter, negTest);
1257 testArrayElementGetterSetter(new long[10], testSetter, negTest);
1258 testArrayElementGetterSetter(new double[10], testSetter, negTest);
1259 }
1260
1261 public void testArrayElementGetterSetter(Object array, boolean testSetter, int negTest) throws Throwable {
1262 boolean positive = (negTest == TEST_ARRAY_NONE);
1263 int length = java.lang.reflect.Array.getLength(array);
jrose10f3b682010-01-07 16:16:45 -08001264 Class<?> arrayType = array.getClass();
1265 Class<?> elemType = arrayType.getComponentType();
jrose485df122012-07-12 00:11:35 -07001266 Object arrayToMH = array;
1267 // this stanza allows negative tests to make argument perturbations:
1268 switch (negTest) {
1269 case TEST_ARRAY_NPE:
1270 arrayToMH = null;
1271 break;
1272 case TEST_ARRAY_OOB:
1273 assert(length > 0);
1274 arrayToMH = java.lang.reflect.Array.newInstance(elemType, 0);
1275 break;
1276 case TEST_ARRAY_ASE:
1277 assert(testSetter && !elemType.isPrimitive());
1278 if (elemType == Object.class)
1279 arrayToMH = new StringBuffer[length]; // very random subclass of Object!
1280 else if (elemType == Example.class)
1281 arrayToMH = new SubExample[length];
1282 else if (elemType == IntExample.class)
1283 arrayToMH = new SubIntExample[length];
1284 else
1285 return; // can't make an ArrayStoreException test
1286 assert(arrayType.isInstance(arrayToMH))
1287 : Arrays.asList(arrayType, arrayToMH.getClass(), testSetter, negTest);
1288 break;
1289 }
1290 countTest(positive);
1291 if (verbosity > 2) System.out.println("array type = "+array.getClass().getComponentType().getName()+"["+length+"]"+(positive ? "" : " negative test #"+negTest+" using "+Arrays.deepToString(new Object[]{arrayToMH})));
jrose10f3b682010-01-07 16:16:45 -08001292 MethodType expType = !testSetter
1293 ? MethodType.methodType(elemType, arrayType, int.class)
1294 : MethodType.methodType(void.class, arrayType, int.class, elemType);
1295 MethodHandle mh = !testSetter
1296 ? MethodHandles.arrayElementGetter(arrayType)
1297 : MethodHandles.arrayElementSetter(arrayType);
1298 assertSame(mh.type(), expType);
jrose2cc9c832010-04-30 23:48:23 -07001299 if (elemType != int.class && elemType != boolean.class) {
jrose485df122012-07-12 00:11:35 -07001300 MethodType gtype = mh.type().generic().changeParameterType(1, int.class);
jrose320b7692011-05-12 19:27:49 -07001301 if (testSetter) gtype = gtype.changeReturnType(void.class);
jrose9b82ad62011-05-26 17:37:36 -07001302 mh = mh.asType(gtype);
jrose2cc9c832010-04-30 23:48:23 -07001303 }
jrose10f3b682010-01-07 16:16:45 -08001304 Object sawValue, expValue;
1305 List<Object> model = array2list(array);
jrose485df122012-07-12 00:11:35 -07001306 Throwable caughtEx = null;
jrose10f3b682010-01-07 16:16:45 -08001307 for (int i = 0; i < length; i++) {
1308 // update array element
1309 Object random = randomArg(elemType);
1310 model.set(i, random);
1311 if (testSetter) {
jrose485df122012-07-12 00:11:35 -07001312 try {
1313 if (elemType == int.class)
1314 mh.invokeExact((int[]) arrayToMH, i, (int)random);
1315 else if (elemType == boolean.class)
1316 mh.invokeExact((boolean[]) arrayToMH, i, (boolean)random);
1317 else
1318 mh.invokeExact(arrayToMH, i, random);
1319 } catch (RuntimeException ex) {
1320 caughtEx = ex;
1321 break;
1322 }
jrose10f3b682010-01-07 16:16:45 -08001323 assertEquals(model, array2list(array));
1324 } else {
1325 Array.set(array, i, random);
jrose2cc9c832010-04-30 23:48:23 -07001326 }
1327 if (verbosity >= 5) {
1328 List<Object> array2list = array2list(array);
1329 System.out.println("a["+i+"]="+random+" => "+array2list);
1330 if (!array2list.equals(model))
1331 System.out.println("*** != "+model);
jrose10f3b682010-01-07 16:16:45 -08001332 }
1333 // observe array element
1334 sawValue = Array.get(array, i);
1335 if (!testSetter) {
1336 expValue = sawValue;
jrose485df122012-07-12 00:11:35 -07001337 try {
1338 if (elemType == int.class)
1339 sawValue = (int) mh.invokeExact((int[]) arrayToMH, i);
1340 else if (elemType == boolean.class)
1341 sawValue = (boolean) mh.invokeExact((boolean[]) arrayToMH, i);
1342 else
1343 sawValue = mh.invokeExact(arrayToMH, i);
1344 } catch (RuntimeException ex) {
1345 caughtEx = ex;
1346 break;
1347 }
jrose10f3b682010-01-07 16:16:45 -08001348 assertEquals(sawValue, expValue);
1349 assertEquals(model, array2list(array));
1350 }
1351 }
jrose485df122012-07-12 00:11:35 -07001352 if (!positive) {
1353 if (caughtEx == null)
1354 throw new RuntimeException("failed to catch exception for negTest="+negTest);
1355 // test the kind of exception
1356 Class<?> reqType = null;
1357 switch (negTest) {
1358 case TEST_ARRAY_ASE: reqType = ArrayStoreException.class; break;
1359 case TEST_ARRAY_OOB: reqType = ArrayIndexOutOfBoundsException.class; break;
1360 case TEST_ARRAY_NPE: reqType = NullPointerException.class; break;
1361 default: assert(false);
1362 }
1363 if (reqType.isInstance(caughtEx)) {
1364 caughtEx = null; // nullify expected exception
1365 }
1366 }
1367 if (caughtEx != null) {
1368 throw new RuntimeException("unexpected exception", caughtEx);
1369 }
jrose10f3b682010-01-07 16:16:45 -08001370 }
1371
1372 List<Object> array2list(Object array) {
1373 int length = Array.getLength(array);
jrose49494522012-01-18 17:34:29 -08001374 ArrayList<Object> model = new ArrayList<>(length);
jrose10f3b682010-01-07 16:16:45 -08001375 for (int i = 0; i < length; i++)
1376 model.add(Array.get(array, i));
1377 return model;
jrose55220c32009-10-21 23:19:48 -07001378 }
1379
1380 static class Callee {
1381 static Object id() { return called("id"); }
1382 static Object id(Object x) { return called("id", x); }
1383 static Object id(Object x, Object y) { return called("id", x, y); }
1384 static Object id(Object x, Object y, Object z) { return called("id", x, y, z); }
1385 static Object id(Object... vx) { return called("id", vx); }
1386 static MethodHandle ofType(int n) {
1387 return ofType(Object.class, n);
1388 }
1389 static MethodHandle ofType(Class<?> rtype, int n) {
1390 if (n == -1)
jrose10f3b682010-01-07 16:16:45 -08001391 return ofType(MethodType.methodType(rtype, Object[].class));
1392 return ofType(MethodType.genericMethodType(n).changeReturnType(rtype));
jrose55220c32009-10-21 23:19:48 -07001393 }
1394 static MethodHandle ofType(Class<?> rtype, Class<?>... ptypes) {
jrose10f3b682010-01-07 16:16:45 -08001395 return ofType(MethodType.methodType(rtype, ptypes));
jrose55220c32009-10-21 23:19:48 -07001396 }
1397 static MethodHandle ofType(MethodType type) {
1398 Class<?> rtype = type.returnType();
1399 String pfx = "";
1400 if (rtype != Object.class)
1401 pfx = rtype.getSimpleName().substring(0, 1).toLowerCase();
1402 String name = pfx+"id";
jrosea1ebbe62010-09-08 18:40:23 -07001403 try {
1404 return PRIVATE.findStatic(Callee.class, name, type);
jrose49494522012-01-18 17:34:29 -08001405 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07001406 throw new RuntimeException(ex);
1407 }
jrose55220c32009-10-21 23:19:48 -07001408 }
1409 }
1410
1411 @Test
1412 public void testConvertArguments() throws Throwable {
1413 if (CAN_SKIP_WORKING) return;
1414 startTest("convertArguments");
1415 testConvert(Callee.ofType(1), null, "id", int.class);
1416 testConvert(Callee.ofType(1), null, "id", String.class);
1417 testConvert(Callee.ofType(1), null, "id", Integer.class);
1418 testConvert(Callee.ofType(1), null, "id", short.class);
jrose2cc9c832010-04-30 23:48:23 -07001419 testConvert(Callee.ofType(1), null, "id", char.class);
1420 testConvert(Callee.ofType(1), null, "id", byte.class);
jrose55220c32009-10-21 23:19:48 -07001421 }
1422
1423 void testConvert(MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose9b82ad62011-05-26 17:37:36 -07001424 testConvert(true, id, rtype, name, params);
jrose55220c32009-10-21 23:19:48 -07001425 }
1426
jrose9b82ad62011-05-26 17:37:36 -07001427 void testConvert(boolean positive,
jrose900bafd2010-10-30 21:08:23 -07001428 MethodHandle id, Class<?> rtype, String name, Class<?>... params) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001429 countTest(positive);
1430 MethodType idType = id.type();
1431 if (rtype == null) rtype = idType.returnType();
1432 for (int i = 0; i < params.length; i++) {
1433 if (params[i] == null) params[i] = idType.parameterType(i);
1434 }
1435 // simulate the pairwise conversion
jrose10f3b682010-01-07 16:16:45 -08001436 MethodType newType = MethodType.methodType(rtype, params);
jrose55220c32009-10-21 23:19:48 -07001437 Object[] args = randomArgs(newType.parameterArray());
1438 Object[] convArgs = args.clone();
1439 for (int i = 0; i < args.length; i++) {
1440 Class<?> src = newType.parameterType(i);
1441 Class<?> dst = idType.parameterType(i);
1442 if (src != dst)
1443 convArgs[i] = castToWrapper(convArgs[i], dst);
1444 }
jrose900bafd2010-10-30 21:08:23 -07001445 Object convResult = id.invokeWithArguments(convArgs);
jrose55220c32009-10-21 23:19:48 -07001446 {
1447 Class<?> dst = newType.returnType();
1448 Class<?> src = idType.returnType();
1449 if (src != dst)
1450 convResult = castToWrapper(convResult, dst);
1451 }
1452 MethodHandle target = null;
1453 RuntimeException error = null;
1454 try {
jrose9b82ad62011-05-26 17:37:36 -07001455 target = id.asType(newType);
jrose55220c32009-10-21 23:19:48 -07001456 } catch (RuntimeException ex) {
1457 error = ex;
1458 }
jrose2cc9c832010-04-30 23:48:23 -07001459 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001460 System.out.println("convert "+id+ " to "+newType+" => "+target
1461 +(error == null ? "" : " !! "+error));
1462 if (positive && error != null) throw error;
1463 assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
1464 if (!positive) return; // negative test failed as expected
1465 assertEquals(newType, target.type());
1466 printCalled(target, id.toString(), args);
jrose900bafd2010-10-30 21:08:23 -07001467 Object result = target.invokeWithArguments(args);
jrose55220c32009-10-21 23:19:48 -07001468 assertCalled(name, convArgs);
1469 assertEquals(convResult, result);
jrose2cc9c832010-04-30 23:48:23 -07001470 if (verbosity >= 1)
1471 System.out.print(':');
jrose55220c32009-10-21 23:19:48 -07001472 }
1473
1474 @Test
jrosef108fc02011-02-11 01:26:24 -08001475 public void testVarargsCollector() throws Throwable {
1476 MethodHandle vac0 = PRIVATE.findStatic(MethodHandlesTest.class, "called",
1477 MethodType.methodType(Object.class, String.class, Object[].class));
1478 vac0 = vac0.bindTo("vac");
1479 MethodHandle vac = vac0.asVarargsCollector(Object[].class);
jrose9b82ad62011-05-26 17:37:36 -07001480 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
1481 testConvert(true, vac.asType(MethodType.genericMethodType(0)), null, "vac");
jrose49494522012-01-18 17:34:29 -08001482 for (Class<?> at : new Class<?>[] { Object.class, String.class, Integer.class }) {
jrose9b82ad62011-05-26 17:37:36 -07001483 testConvert(true, vac.asType(MethodType.genericMethodType(1)), null, "vac", at);
1484 testConvert(true, vac.asType(MethodType.genericMethodType(2)), null, "vac", at, at);
jrosef108fc02011-02-11 01:26:24 -08001485 }
1486 }
1487
1488 @Test
jrose10f3b682010-01-07 16:16:45 -08001489 public void testPermuteArguments() throws Throwable {
1490 if (CAN_SKIP_WORKING) return;
1491 startTest("permuteArguments");
jroseb4be0262011-07-16 15:44:33 -07001492 testPermuteArguments(4, Integer.class, 2, long.class, 6);
1493 if (CAN_TEST_LIGHTLY) return;
jrose10f3b682010-01-07 16:16:45 -08001494 testPermuteArguments(4, Integer.class, 2, String.class, 0);
jrose9b82ad62011-05-26 17:37:36 -07001495 testPermuteArguments(6, Integer.class, 0, null, 30);
jrose10f3b682010-01-07 16:16:45 -08001496 }
1497 public void testPermuteArguments(int max, Class<?> type1, int t2c, Class<?> type2, int dilution) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001498 if (verbosity >= 2)
jrose10f3b682010-01-07 16:16:45 -08001499 System.out.println("permuteArguments "+max+"*"+type1.getName()
1500 +(t2c==0?"":"/"+t2c+"*"+type2.getName())
1501 +(dilution > 0 ? " with dilution "+dilution : ""));
1502 int t2pos = t2c == 0 ? 0 : 1;
1503 for (int inargs = t2pos+1; inargs <= max; inargs++) {
1504 Class<?>[] types = new Class<?>[inargs];
1505 Arrays.fill(types, type1);
1506 if (t2c != 0) {
1507 // Fill in a middle range with type2:
1508 Arrays.fill(types, t2pos, Math.min(t2pos+t2c, inargs), type2);
1509 }
1510 Object[] args = randomArgs(types);
1511 int numcases = 1;
1512 for (int outargs = 0; outargs <= max; outargs++) {
1513 if (outargs - inargs >= MAX_ARG_INCREASE) continue;
jrose10f3b682010-01-07 16:16:45 -08001514 int casStep = dilution + 1;
1515 // Avoid some common factors:
1516 while ((casStep > 2 && casStep % 2 == 0 && inargs % 2 == 0) ||
1517 (casStep > 3 && casStep % 3 == 0 && inargs % 3 == 0))
1518 casStep++;
jrose320b7692011-05-12 19:27:49 -07001519 testPermuteArguments(args, types, outargs, numcases, casStep);
jrose10f3b682010-01-07 16:16:45 -08001520 numcases *= inargs;
jroseb4be0262011-07-16 15:44:33 -07001521 if (CAN_TEST_LIGHTLY && outargs < max-2) continue;
jrose10f3b682010-01-07 16:16:45 -08001522 if (dilution > 10 && outargs >= 4) {
jroseb4be0262011-07-16 15:44:33 -07001523 if (CAN_TEST_LIGHTLY) continue;
jrose320b7692011-05-12 19:27:49 -07001524 int[] reorder = new int[outargs];
jrose10f3b682010-01-07 16:16:45 -08001525 // Do some special patterns, which we probably missed.
1526 // Replication of a single argument or argument pair.
1527 for (int i = 0; i < inargs; i++) {
1528 Arrays.fill(reorder, i);
1529 testPermuteArguments(args, types, reorder);
1530 for (int d = 1; d <= 2; d++) {
1531 if (i + d >= inargs) continue;
1532 for (int j = 1; j < outargs; j += 2)
1533 reorder[j] += 1;
1534 testPermuteArguments(args, types, reorder);
1535 testPermuteArguments(args, types, reverse(reorder));
1536 }
1537 }
1538 // Repetition of a sequence of 3 or more arguments.
1539 for (int i = 1; i < inargs; i++) {
1540 for (int len = 3; len <= inargs; len++) {
1541 for (int j = 0; j < outargs; j++)
1542 reorder[j] = (i + (j % len)) % inargs;
1543 testPermuteArguments(args, types, reorder);
1544 testPermuteArguments(args, types, reverse(reorder));
1545 }
1546 }
1547 }
1548 }
1549 }
1550 }
1551
jrose320b7692011-05-12 19:27:49 -07001552 public void testPermuteArguments(Object[] args, Class<?>[] types,
1553 int outargs, int numcases, int casStep) throws Throwable {
1554 int inargs = args.length;
1555 int[] reorder = new int[outargs];
1556 for (int cas = 0; cas < numcases; cas += casStep) {
1557 for (int i = 0, c = cas; i < outargs; i++) {
1558 reorder[i] = c % inargs;
1559 c /= inargs;
1560 }
jroseb4be0262011-07-16 15:44:33 -07001561 if (CAN_TEST_LIGHTLY && outargs >= 3 && (reorder[0] == reorder[1] || reorder[1] == reorder[2])) continue;
jrose320b7692011-05-12 19:27:49 -07001562 testPermuteArguments(args, types, reorder);
1563 }
1564 }
1565
jrose10f3b682010-01-07 16:16:45 -08001566 static int[] reverse(int[] reorder) {
1567 reorder = reorder.clone();
1568 for (int i = 0, imax = reorder.length / 2; i < imax; i++) {
1569 int j = reorder.length - 1 - i;
1570 int tem = reorder[i];
1571 reorder[i] = reorder[j];
1572 reorder[j] = tem;
1573 }
1574 return reorder;
1575 }
1576
1577 void testPermuteArguments(Object[] args, Class<?>[] types, int[] reorder) throws Throwable {
1578 countTest();
1579 if (args == null && types == null) {
1580 int max = 0;
1581 for (int j : reorder) {
1582 if (max < j) max = j;
1583 }
1584 args = randomArgs(max+1, Integer.class);
1585 }
1586 if (args == null) {
1587 args = randomArgs(types);
1588 }
1589 if (types == null) {
1590 types = new Class<?>[args.length];
1591 for (int i = 0; i < args.length; i++)
1592 types[i] = args[i].getClass();
1593 }
1594 int inargs = args.length, outargs = reorder.length;
jrosef15905c2011-02-11 01:26:32 -08001595 assertTrue(inargs == types.length);
jrose2cc9c832010-04-30 23:48:23 -07001596 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001597 System.out.println("permuteArguments "+Arrays.toString(reorder));
1598 Object[] permArgs = new Object[outargs];
1599 Class<?>[] permTypes = new Class<?>[outargs];
1600 for (int i = 0; i < outargs; i++) {
1601 permArgs[i] = args[reorder[i]];
1602 permTypes[i] = types[reorder[i]];
1603 }
jrose2cc9c832010-04-30 23:48:23 -07001604 if (verbosity >= 4) {
jrose10f3b682010-01-07 16:16:45 -08001605 System.out.println("in args: "+Arrays.asList(args));
1606 System.out.println("out args: "+Arrays.asList(permArgs));
1607 System.out.println("in types: "+Arrays.asList(types));
1608 System.out.println("out types: "+Arrays.asList(permTypes));
1609 }
1610 MethodType inType = MethodType.methodType(Object.class, types);
1611 MethodType outType = MethodType.methodType(Object.class, permTypes);
jrose9b82ad62011-05-26 17:37:36 -07001612 MethodHandle target = varargsList(outargs).asType(outType);
jrose10f3b682010-01-07 16:16:45 -08001613 MethodHandle newTarget = MethodHandles.permuteArguments(target, inType, reorder);
jrose9b82ad62011-05-26 17:37:36 -07001614 if (verbosity >= 5) System.out.println("newTarget = "+newTarget);
jrose900bafd2010-10-30 21:08:23 -07001615 Object result = newTarget.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001616 Object expected = Arrays.asList(permArgs);
jrose320b7692011-05-12 19:27:49 -07001617 if (!expected.equals(result)) {
1618 System.out.println("*** failed permuteArguments "+Arrays.toString(reorder)+" types="+Arrays.asList(types));
1619 System.out.println("in args: "+Arrays.asList(args));
1620 System.out.println("out args: "+expected);
1621 System.out.println("bad args: "+result);
1622 }
jrose10f3b682010-01-07 16:16:45 -08001623 assertEquals(expected, result);
1624 }
1625
1626
1627 @Test
1628 public void testSpreadArguments() throws Throwable {
1629 if (CAN_SKIP_WORKING) return;
1630 startTest("spreadArguments");
jrose49494522012-01-18 17:34:29 -08001631 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001632 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001633 System.out.println("spreadArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001634 for (int nargs = 0; nargs < 50; nargs++) {
1635 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1636 for (int pos = 0; pos <= nargs; pos++) {
1637 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1638 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1639 continue;
1640 testSpreadArguments(argType, pos, nargs);
jrose10f3b682010-01-07 16:16:45 -08001641 }
1642 }
1643 }
1644 }
1645 public void testSpreadArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1646 countTest();
jrose320b7692011-05-12 19:27:49 -07001647 Class<?> arrayType = java.lang.reflect.Array.newInstance(argType, 0).getClass();
1648 MethodHandle target2 = varargsArray(arrayType, nargs);
1649 MethodHandle target = target2.asType(target2.type().generic());
jrose2cc9c832010-04-30 23:48:23 -07001650 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001651 System.out.println("spread into "+target2+" ["+pos+".."+nargs+"]");
1652 Object[] args = randomArgs(target2.type().parameterArray());
1653 // make sure the target does what we think it does:
jrose320b7692011-05-12 19:27:49 -07001654 if (pos == 0 && nargs < 5 && !argType.isPrimitive()) {
jrose49494522012-01-18 17:34:29 -08001655 Object[] check = (Object[]) target.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001656 assertArrayEquals(args, check);
1657 switch (nargs) {
1658 case 0:
jrose320b7692011-05-12 19:27:49 -07001659 check = (Object[]) (Object) target.invokeExact();
jrose10f3b682010-01-07 16:16:45 -08001660 assertArrayEquals(args, check);
1661 break;
1662 case 1:
jrose320b7692011-05-12 19:27:49 -07001663 check = (Object[]) (Object) target.invokeExact(args[0]);
jrose10f3b682010-01-07 16:16:45 -08001664 assertArrayEquals(args, check);
1665 break;
1666 case 2:
jrose320b7692011-05-12 19:27:49 -07001667 check = (Object[]) (Object) target.invokeExact(args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08001668 assertArrayEquals(args, check);
1669 break;
1670 }
1671 }
jrose49494522012-01-18 17:34:29 -08001672 List<Class<?>> newParams = new ArrayList<>(target2.type().parameterList());
jrose10f3b682010-01-07 16:16:45 -08001673 { // modify newParams in place
1674 List<Class<?>> spreadParams = newParams.subList(pos, nargs);
jrose320b7692011-05-12 19:27:49 -07001675 spreadParams.clear(); spreadParams.add(arrayType);
jrose10f3b682010-01-07 16:16:45 -08001676 }
jrose320b7692011-05-12 19:27:49 -07001677 MethodType newType = MethodType.methodType(arrayType, newParams);
1678 MethodHandle result = target2.asSpreader(arrayType, nargs-pos);
1679 assert(result.type() == newType) : Arrays.asList(result, newType);
1680 result = result.asType(newType.generic());
1681 Object returnValue;
jrose10f3b682010-01-07 16:16:45 -08001682 if (pos == 0) {
jrose320b7692011-05-12 19:27:49 -07001683 Object args2 = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1684 returnValue = result.invokeExact(args2);
jrose10f3b682010-01-07 16:16:45 -08001685 } else {
1686 Object[] args1 = Arrays.copyOfRange(args, 0, pos+1);
jrose320b7692011-05-12 19:27:49 -07001687 args1[pos] = ValueConversions.changeArrayType(arrayType, Arrays.copyOfRange(args, pos, args.length));
1688 returnValue = result.invokeWithArguments(args1);
jrose10f3b682010-01-07 16:16:45 -08001689 }
jrose320b7692011-05-12 19:27:49 -07001690 String argstr = Arrays.toString(args);
1691 if (!argType.isPrimitive()) {
1692 Object[] rv = (Object[]) returnValue;
1693 String rvs = Arrays.toString(rv);
1694 if (!Arrays.equals(args, rv)) {
1695 System.out.println("method: "+result);
1696 System.out.println("expected: "+argstr);
1697 System.out.println("returned: "+rvs);
1698 assertArrayEquals(args, rv);
1699 }
1700 } else if (argType == int.class) {
1701 String rvs = Arrays.toString((int[]) returnValue);
1702 if (!argstr.equals(rvs)) {
1703 System.out.println("method: "+result);
1704 System.out.println("expected: "+argstr);
1705 System.out.println("returned: "+rvs);
1706 assertEquals(argstr, rvs);
1707 }
1708 } else if (argType == long.class) {
1709 String rvs = Arrays.toString((long[]) returnValue);
1710 if (!argstr.equals(rvs)) {
1711 System.out.println("method: "+result);
1712 System.out.println("expected: "+argstr);
1713 System.out.println("returned: "+rvs);
1714 assertEquals(argstr, rvs);
1715 }
1716 } else {
1717 // cannot test...
1718 }
jrose10f3b682010-01-07 16:16:45 -08001719 }
1720
1721 @Test
1722 public void testCollectArguments() throws Throwable {
1723 if (CAN_SKIP_WORKING) return;
1724 startTest("collectArguments");
jrose49494522012-01-18 17:34:29 -08001725 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose2cc9c832010-04-30 23:48:23 -07001726 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001727 System.out.println("collectArguments "+argType);
jroseb4be0262011-07-16 15:44:33 -07001728 for (int nargs = 0; nargs < 50; nargs++) {
1729 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1730 for (int pos = 0; pos <= nargs; pos++) {
1731 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
1732 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1733 continue;
jrose10f3b682010-01-07 16:16:45 -08001734 testCollectArguments(argType, pos, nargs);
1735 }
1736 }
1737 }
1738 }
1739 public void testCollectArguments(Class<?> argType, int pos, int nargs) throws Throwable {
1740 countTest();
1741 // fake up a MH with the same type as the desired adapter:
jroseadc650a2011-02-11 01:26:28 -08001742 MethodHandle fake = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001743 fake = changeArgTypes(fake, argType);
1744 MethodType newType = fake.type();
1745 Object[] args = randomArgs(newType.parameterArray());
1746 // here is what should happen:
1747 Object[] collectedArgs = Arrays.copyOfRange(args, 0, pos+1);
1748 collectedArgs[pos] = Arrays.copyOfRange(args, pos, args.length);
1749 // here is the MH which will witness the collected argument tail:
jroseadc650a2011-02-11 01:26:28 -08001750 MethodHandle target = varargsArray(pos+1);
jrose10f3b682010-01-07 16:16:45 -08001751 target = changeArgTypes(target, 0, pos, argType);
1752 target = changeArgTypes(target, pos, pos+1, Object[].class);
jrose2cc9c832010-04-30 23:48:23 -07001753 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001754 System.out.println("collect from "+Arrays.asList(args)+" ["+pos+".."+nargs+"]");
jroseadc650a2011-02-11 01:26:28 -08001755 MethodHandle result = target.asCollector(Object[].class, nargs-pos).asType(newType);
jrose900bafd2010-10-30 21:08:23 -07001756 Object[] returnValue = (Object[]) result.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08001757// assertTrue(returnValue.length == pos+1 && returnValue[pos] instanceof Object[]);
1758// returnValue[pos] = Arrays.asList((Object[]) returnValue[pos]);
1759// collectedArgs[pos] = Arrays.asList((Object[]) collectedArgs[pos]);
1760 assertArrayEquals(collectedArgs, returnValue);
1761 }
1762
1763 @Test
jrose55220c32009-10-21 23:19:48 -07001764 public void testInsertArguments() throws Throwable {
1765 if (CAN_SKIP_WORKING) return;
1766 startTest("insertArguments");
jroseb4be0262011-07-16 15:44:33 -07001767 for (int nargs = 0; nargs < 50; nargs++) {
1768 if (CAN_TEST_LIGHTLY && nargs > 7) break;
1769 for (int ins = 0; ins <= nargs; ins++) {
1770 if (nargs > 10 && ins > 4 && ins < nargs-4 && ins % 10 != 3)
1771 continue;
jrose55220c32009-10-21 23:19:48 -07001772 for (int pos = 0; pos <= nargs; pos++) {
jroseb4be0262011-07-16 15:44:33 -07001773 if (nargs > 10 && pos > 4 && pos < nargs-4 && pos % 10 != 3)
1774 continue;
1775 if (CAN_TEST_LIGHTLY && pos > 2 && pos < nargs-2) continue;
jrose55220c32009-10-21 23:19:48 -07001776 testInsertArguments(nargs, pos, ins);
1777 }
1778 }
1779 }
1780 }
1781
1782 void testInsertArguments(int nargs, int pos, int ins) throws Throwable {
jrose55220c32009-10-21 23:19:48 -07001783 countTest();
jroseadc650a2011-02-11 01:26:28 -08001784 MethodHandle target = varargsArray(nargs + ins);
jrose55220c32009-10-21 23:19:48 -07001785 Object[] args = randomArgs(target.type().parameterArray());
1786 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08001787 List<Object> argsToPass = new ArrayList<>(resList);
jrose55220c32009-10-21 23:19:48 -07001788 List<Object> argsToInsert = argsToPass.subList(pos, pos + ins);
jrose2cc9c832010-04-30 23:48:23 -07001789 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001790 System.out.println("insert: "+argsToInsert+" into "+target);
jrose49494522012-01-18 17:34:29 -08001791 @SuppressWarnings("cast") // cast to spread Object... is helpful
jrose10f3b682010-01-07 16:16:45 -08001792 MethodHandle target2 = MethodHandles.insertArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08001793 (Object[]/*...*/) argsToInsert.toArray());
jrose55220c32009-10-21 23:19:48 -07001794 argsToInsert.clear(); // remove from argsToInsert
jrose900bafd2010-10-30 21:08:23 -07001795 Object res2 = target2.invokeWithArguments(argsToPass);
jrose55220c32009-10-21 23:19:48 -07001796 Object res2List = Arrays.asList((Object[])res2);
jrose2cc9c832010-04-30 23:48:23 -07001797 if (verbosity >= 3)
jrose55220c32009-10-21 23:19:48 -07001798 System.out.println("result: "+res2List);
1799 //if (!resList.equals(res2List))
1800 // System.out.println("*** fail at n/p/i = "+nargs+"/"+pos+"/"+ins+": "+resList+" => "+res2List);
1801 assertEquals(resList, res2List);
1802 }
1803
jrose10f3b682010-01-07 16:16:45 -08001804 @Test
jroseadc650a2011-02-11 01:26:28 -08001805 public void testFilterReturnValue() throws Throwable {
1806 if (CAN_SKIP_WORKING) return;
1807 startTest("filterReturnValue");
1808 Class<?> classOfVCList = varargsList(1).invokeWithArguments(0).getClass();
1809 assertTrue(List.class.isAssignableFrom(classOfVCList));
1810 for (int nargs = 0; nargs <= 3; nargs++) {
jrose49494522012-01-18 17:34:29 -08001811 for (Class<?> rtype : new Class<?>[] { Object.class,
jroseadc650a2011-02-11 01:26:28 -08001812 List.class,
1813 int.class,
jroseb4be0262011-07-16 15:44:33 -07001814 byte.class,
1815 long.class,
jroseadc650a2011-02-11 01:26:28 -08001816 CharSequence.class,
1817 String.class }) {
1818 testFilterReturnValue(nargs, rtype);
1819 }
1820 }
1821 }
1822
1823 void testFilterReturnValue(int nargs, Class<?> rtype) throws Throwable {
1824 countTest();
1825 MethodHandle target = varargsList(nargs, rtype);
1826 MethodHandle filter;
1827 if (List.class.isAssignableFrom(rtype) || rtype.isAssignableFrom(List.class))
1828 filter = varargsList(1); // add another layer of list-ness
1829 else
1830 filter = MethodHandles.identity(rtype);
1831 filter = filter.asType(MethodType.methodType(target.type().returnType(), rtype));
1832 Object[] argsToPass = randomArgs(nargs, Object.class);
1833 if (verbosity >= 3)
1834 System.out.println("filter "+target+" to "+rtype.getSimpleName()+" with "+filter);
1835 MethodHandle target2 = MethodHandles.filterReturnValue(target, filter);
1836 if (verbosity >= 4)
1837 System.out.println("filtered target: "+target2);
1838 // Simulate expected effect of filter on return value:
1839 Object unfiltered = target.invokeWithArguments(argsToPass);
1840 Object expected = filter.invokeWithArguments(unfiltered);
1841 if (verbosity >= 4)
1842 System.out.println("unfiltered: "+unfiltered+" : "+unfiltered.getClass().getSimpleName());
1843 if (verbosity >= 4)
1844 System.out.println("expected: "+expected+" : "+expected.getClass().getSimpleName());
1845 Object result = target2.invokeWithArguments(argsToPass);
1846 if (verbosity >= 3)
1847 System.out.println("result: "+result+" : "+result.getClass().getSimpleName());
1848 if (!expected.equals(result))
1849 System.out.println("*** fail at n/rt = "+nargs+"/"+rtype.getSimpleName()+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
1850 assertEquals(expected, result);
1851 }
1852
1853 @Test
jrose10f3b682010-01-07 16:16:45 -08001854 public void testFilterArguments() throws Throwable {
1855 if (CAN_SKIP_WORKING) return;
1856 startTest("filterArguments");
1857 for (int nargs = 1; nargs <= 6; nargs++) {
1858 for (int pos = 0; pos < nargs; pos++) {
1859 testFilterArguments(nargs, pos);
1860 }
1861 }
1862 }
1863
1864 void testFilterArguments(int nargs, int pos) throws Throwable {
1865 countTest();
jroseadc650a2011-02-11 01:26:28 -08001866 MethodHandle target = varargsList(nargs);
1867 MethodHandle filter = varargsList(1);
jrose9b82ad62011-05-26 17:37:36 -07001868 filter = filter.asType(filter.type().generic());
jrose10f3b682010-01-07 16:16:45 -08001869 Object[] argsToPass = randomArgs(nargs, Object.class);
jrose2cc9c832010-04-30 23:48:23 -07001870 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001871 System.out.println("filter "+target+" at "+pos+" with "+filter);
jrose900bafd2010-10-30 21:08:23 -07001872 MethodHandle target2 = MethodHandles.filterArguments(target, pos, filter);
jrose10f3b682010-01-07 16:16:45 -08001873 // Simulate expected effect of filter on arglist:
1874 Object[] filteredArgs = argsToPass.clone();
jrose2cc9c832010-04-30 23:48:23 -07001875 filteredArgs[pos] = filter.invokeExact(filteredArgs[pos]);
jrose10f3b682010-01-07 16:16:45 -08001876 List<Object> expected = Arrays.asList(filteredArgs);
jrose900bafd2010-10-30 21:08:23 -07001877 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001878 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001879 System.out.println("result: "+result);
1880 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001881 System.out.println("*** fail at n/p = "+nargs+"/"+pos+": "+Arrays.asList(argsToPass)+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001882 assertEquals(expected, result);
1883 }
1884
1885 @Test
1886 public void testFoldArguments() throws Throwable {
1887 if (CAN_SKIP_WORKING) return;
1888 startTest("foldArguments");
1889 for (int nargs = 0; nargs <= 4; nargs++) {
1890 for (int fold = 0; fold <= nargs; fold++) {
1891 for (int pos = 0; pos <= nargs; pos++) {
1892 testFoldArguments(nargs, pos, fold);
1893 }
1894 }
1895 }
1896 }
1897
1898 void testFoldArguments(int nargs, int pos, int fold) throws Throwable {
1899 if (pos != 0) return; // can fold only at pos=0 for now
1900 countTest();
jroseadc650a2011-02-11 01:26:28 -08001901 MethodHandle target = varargsList(1 + nargs);
1902 MethodHandle combine = varargsList(fold).asType(MethodType.genericMethodType(fold));
jrose10f3b682010-01-07 16:16:45 -08001903 List<Object> argsToPass = Arrays.asList(randomArgs(nargs, Object.class));
jrose2cc9c832010-04-30 23:48:23 -07001904 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001905 System.out.println("fold "+target+" with "+combine);
1906 MethodHandle target2 = MethodHandles.foldArguments(target, combine);
1907 // Simulate expected effect of combiner on arglist:
jrose49494522012-01-18 17:34:29 -08001908 List<Object> expected = new ArrayList<>(argsToPass);
jrose10f3b682010-01-07 16:16:45 -08001909 List<Object> argsToFold = expected.subList(pos, pos + fold);
jrose2cc9c832010-04-30 23:48:23 -07001910 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001911 System.out.println("fold: "+argsToFold+" into "+target2);
jrose900bafd2010-10-30 21:08:23 -07001912 Object foldedArgs = combine.invokeWithArguments(argsToFold);
jrose10f3b682010-01-07 16:16:45 -08001913 argsToFold.add(0, foldedArgs);
jrose900bafd2010-10-30 21:08:23 -07001914 Object result = target2.invokeWithArguments(argsToPass);
jrose2cc9c832010-04-30 23:48:23 -07001915 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001916 System.out.println("result: "+result);
1917 if (!expected.equals(result))
jroseadc650a2011-02-11 01:26:28 -08001918 System.out.println("*** fail at n/p/f = "+nargs+"/"+pos+"/"+fold+": "+argsToPass+" => "+result+" != "+expected);
jrose10f3b682010-01-07 16:16:45 -08001919 assertEquals(expected, result);
1920 }
1921
1922 @Test
1923 public void testDropArguments() throws Throwable {
1924 if (CAN_SKIP_WORKING) return;
1925 startTest("dropArguments");
1926 for (int nargs = 0; nargs <= 4; nargs++) {
1927 for (int drop = 1; drop <= 4; drop++) {
1928 for (int pos = 0; pos <= nargs; pos++) {
1929 testDropArguments(nargs, pos, drop);
1930 }
1931 }
1932 }
1933 }
1934
1935 void testDropArguments(int nargs, int pos, int drop) throws Throwable {
1936 countTest();
jroseadc650a2011-02-11 01:26:28 -08001937 MethodHandle target = varargsArray(nargs);
jrose10f3b682010-01-07 16:16:45 -08001938 Object[] args = randomArgs(target.type().parameterArray());
1939 MethodHandle target2 = MethodHandles.dropArguments(target, pos,
jrose49494522012-01-18 17:34:29 -08001940 Collections.nCopies(drop, Object.class).toArray(new Class<?>[0]));
jrose10f3b682010-01-07 16:16:45 -08001941 List<Object> resList = Arrays.asList(args);
jrose49494522012-01-18 17:34:29 -08001942 List<Object> argsToDrop = new ArrayList<>(resList);
jrose10f3b682010-01-07 16:16:45 -08001943 for (int i = drop; i > 0; i--) {
1944 argsToDrop.add(pos, "blort#"+i);
1945 }
jrose900bafd2010-10-30 21:08:23 -07001946 Object res2 = target2.invokeWithArguments(argsToDrop);
jrose10f3b682010-01-07 16:16:45 -08001947 Object res2List = Arrays.asList((Object[])res2);
1948 //if (!resList.equals(res2List))
1949 // System.out.println("*** fail at n/p/d = "+nargs+"/"+pos+"/"+drop+": "+argsToDrop+" => "+res2List);
1950 assertEquals(resList, res2List);
1951 }
1952
1953 @Test
1954 public void testInvokers() throws Throwable {
1955 if (CAN_SKIP_WORKING) return;
1956 startTest("exactInvoker, genericInvoker, varargsInvoker, dynamicInvoker");
1957 // exactInvoker, genericInvoker, varargsInvoker[0..N], dynamicInvoker
jrose49494522012-01-18 17:34:29 -08001958 Set<MethodType> done = new HashSet<>();
jrose10f3b682010-01-07 16:16:45 -08001959 for (int i = 0; i <= 6; i++) {
jroseb4be0262011-07-16 15:44:33 -07001960 if (CAN_TEST_LIGHTLY && i > 3) break;
jrose10f3b682010-01-07 16:16:45 -08001961 MethodType gtype = MethodType.genericMethodType(i);
jrose49494522012-01-18 17:34:29 -08001962 for (Class<?> argType : new Class<?>[]{Object.class, Integer.class, int.class}) {
jrose10f3b682010-01-07 16:16:45 -08001963 for (int j = -1; j < i; j++) {
1964 MethodType type = gtype;
1965 if (j < 0)
1966 type = type.changeReturnType(argType);
1967 else if (argType == void.class)
1968 continue;
1969 else
1970 type = type.changeParameterType(j, argType);
jrose10f3b682010-01-07 16:16:45 -08001971 if (done.add(type))
1972 testInvokers(type);
1973 MethodType vtype = type.changeReturnType(void.class);
1974 if (done.add(vtype))
1975 testInvokers(vtype);
1976 }
1977 }
1978 }
1979 }
1980
1981 public void testInvokers(MethodType type) throws Throwable {
jrose2cc9c832010-04-30 23:48:23 -07001982 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08001983 System.out.println("test invokers for "+type);
1984 int nargs = type.parameterCount();
1985 boolean testRetCode = type.returnType() != void.class;
1986 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "invokee",
1987 MethodType.genericMethodType(0, true));
jroseadc650a2011-02-11 01:26:28 -08001988 assertTrue(target.isVarargsCollector());
1989 target = target.asType(type);
jrose10f3b682010-01-07 16:16:45 -08001990 Object[] args = randomArgs(type.parameterArray());
jrose49494522012-01-18 17:34:29 -08001991 List<Object> targetPlusArgs = new ArrayList<>(Arrays.asList(args));
jrose10f3b682010-01-07 16:16:45 -08001992 targetPlusArgs.add(0, target);
1993 int code = (Integer) invokee(args);
1994 Object log = logEntry("invokee", args);
1995 assertEquals(log.hashCode(), code);
1996 assertCalled("invokee", args);
1997 MethodHandle inv;
1998 Object result;
1999 // exact invoker
2000 countTest();
2001 calledLog.clear();
2002 inv = MethodHandles.exactInvoker(type);
jrose900bafd2010-10-30 21:08:23 -07002003 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002004 if (testRetCode) assertEquals(code, result);
2005 assertCalled("invokee", args);
2006 // generic invoker
2007 countTest();
jrose79e0a6c2011-05-12 19:27:33 -07002008 inv = MethodHandles.invoker(type);
jrose9b82ad62011-05-26 17:37:36 -07002009 if (nargs <= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002010 calledLog.clear();
2011 switch (nargs) {
2012 case 0:
jrose2cc9c832010-04-30 23:48:23 -07002013 result = inv.invokeExact(target);
jrose10f3b682010-01-07 16:16:45 -08002014 break;
2015 case 1:
jrose2cc9c832010-04-30 23:48:23 -07002016 result = inv.invokeExact(target, args[0]);
jrose10f3b682010-01-07 16:16:45 -08002017 break;
2018 case 2:
jrose2cc9c832010-04-30 23:48:23 -07002019 result = inv.invokeExact(target, args[0], args[1]);
jrose10f3b682010-01-07 16:16:45 -08002020 break;
2021 case 3:
jrose2cc9c832010-04-30 23:48:23 -07002022 result = inv.invokeExact(target, args[0], args[1], args[2]);
jrose10f3b682010-01-07 16:16:45 -08002023 break;
2024 }
2025 if (testRetCode) assertEquals(code, result);
2026 assertCalled("invokee", args);
2027 }
2028 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07002029 result = inv.invokeWithArguments(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002030 if (testRetCode) assertEquals(code, result);
2031 assertCalled("invokee", args);
2032 // varargs invoker #0
2033 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002034 inv = MethodHandles.spreadInvoker(type, 0);
jrose9b82ad62011-05-26 17:37:36 -07002035 if (type.returnType() == Object.class) {
2036 result = inv.invokeExact(target, args);
2037 } else if (type.returnType() == void.class) {
2038 result = null; inv.invokeExact(target, args);
2039 } else {
2040 result = inv.invokeWithArguments(target, (Object) args);
2041 }
jrose10f3b682010-01-07 16:16:45 -08002042 if (testRetCode) assertEquals(code, result);
2043 assertCalled("invokee", args);
jrose9b82ad62011-05-26 17:37:36 -07002044 if (nargs >= 1 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002045 // varargs invoker #1
2046 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002047 inv = MethodHandles.spreadInvoker(type, 1);
jrose2cc9c832010-04-30 23:48:23 -07002048 result = inv.invokeExact(target, args[0], Arrays.copyOfRange(args, 1, nargs));
jrose10f3b682010-01-07 16:16:45 -08002049 if (testRetCode) assertEquals(code, result);
2050 assertCalled("invokee", args);
2051 }
jrose9b82ad62011-05-26 17:37:36 -07002052 if (nargs >= 2 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002053 // varargs invoker #2
2054 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002055 inv = MethodHandles.spreadInvoker(type, 2);
jrose2cc9c832010-04-30 23:48:23 -07002056 result = inv.invokeExact(target, args[0], args[1], Arrays.copyOfRange(args, 2, nargs));
jrose10f3b682010-01-07 16:16:45 -08002057 if (testRetCode) assertEquals(code, result);
2058 assertCalled("invokee", args);
2059 }
jrose9b82ad62011-05-26 17:37:36 -07002060 if (nargs >= 3 && type == type.generic()) {
jrose10f3b682010-01-07 16:16:45 -08002061 // varargs invoker #3
2062 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002063 inv = MethodHandles.spreadInvoker(type, 3);
jrose2cc9c832010-04-30 23:48:23 -07002064 result = inv.invokeExact(target, args[0], args[1], args[2], Arrays.copyOfRange(args, 3, nargs));
jrose10f3b682010-01-07 16:16:45 -08002065 if (testRetCode) assertEquals(code, result);
2066 assertCalled("invokee", args);
2067 }
2068 for (int k = 0; k <= nargs; k++) {
2069 // varargs invoker #0..N
jroseb4be0262011-07-16 15:44:33 -07002070 if (CAN_TEST_LIGHTLY && (k > 1 || k < nargs - 1)) continue;
jrose10f3b682010-01-07 16:16:45 -08002071 countTest();
2072 calledLog.clear();
jrosef108fc02011-02-11 01:26:24 -08002073 inv = MethodHandles.spreadInvoker(type, k);
jrose9b82ad62011-05-26 17:37:36 -07002074 MethodType expType = (type.dropParameterTypes(k, nargs)
2075 .appendParameterTypes(Object[].class)
2076 .insertParameterTypes(0, MethodHandle.class));
2077 assertEquals(expType, inv.type());
jrose49494522012-01-18 17:34:29 -08002078 List<Object> targetPlusVarArgs = new ArrayList<>(targetPlusArgs);
jrose10f3b682010-01-07 16:16:45 -08002079 List<Object> tailList = targetPlusVarArgs.subList(1+k, 1+nargs);
2080 Object[] tail = tailList.toArray();
2081 tailList.clear(); tailList.add(tail);
jrose900bafd2010-10-30 21:08:23 -07002082 result = inv.invokeWithArguments(targetPlusVarArgs);
jrose10f3b682010-01-07 16:16:45 -08002083 if (testRetCode) assertEquals(code, result);
2084 assertCalled("invokee", args);
2085 }
jrose900bafd2010-10-30 21:08:23 -07002086
jrose10f3b682010-01-07 16:16:45 -08002087 // dynamic invoker
2088 countTest();
jroseb90d2e72010-12-16 15:59:27 -08002089 CallSite site = new MutableCallSite(type);
2090 inv = site.dynamicInvoker();
jrose900bafd2010-10-30 21:08:23 -07002091
2092 // see if we get the result of the original target:
2093 try {
2094 result = inv.invokeWithArguments(args);
2095 assertTrue("should not reach here", false);
2096 } catch (IllegalStateException ex) {
2097 String msg = ex.getMessage();
2098 assertTrue(msg, msg.contains("site"));
2099 }
2100
2101 // set new target after invoker is created, to make sure we track target
jrose10f3b682010-01-07 16:16:45 -08002102 site.setTarget(target);
2103 calledLog.clear();
jrose900bafd2010-10-30 21:08:23 -07002104 result = inv.invokeWithArguments(args);
jrose10f3b682010-01-07 16:16:45 -08002105 if (testRetCode) assertEquals(code, result);
2106 assertCalled("invokee", args);
2107 }
2108
2109 static Object invokee(Object... args) {
2110 return called("invokee", args).hashCode();
2111 }
2112
jrose55220c32009-10-21 23:19:48 -07002113 private static final String MISSING_ARG = "missingArg";
jroseb4be0262011-07-16 15:44:33 -07002114 private static final String MISSING_ARG_2 = "missingArg#2";
jrose55220c32009-10-21 23:19:48 -07002115 static Object targetIfEquals() {
2116 return called("targetIfEquals");
2117 }
2118 static Object fallbackIfNotEquals() {
2119 return called("fallbackIfNotEquals");
2120 }
2121 static Object targetIfEquals(Object x) {
2122 assertEquals(x, MISSING_ARG);
2123 return called("targetIfEquals", x);
2124 }
2125 static Object fallbackIfNotEquals(Object x) {
2126 assertFalse(x.toString(), x.equals(MISSING_ARG));
2127 return called("fallbackIfNotEquals", x);
2128 }
2129 static Object targetIfEquals(Object x, Object y) {
2130 assertEquals(x, y);
2131 return called("targetIfEquals", x, y);
2132 }
2133 static Object fallbackIfNotEquals(Object x, Object y) {
2134 assertFalse(x.toString(), x.equals(y));
2135 return called("fallbackIfNotEquals", x, y);
2136 }
2137 static Object targetIfEquals(Object x, Object y, Object z) {
2138 assertEquals(x, y);
2139 return called("targetIfEquals", x, y, z);
2140 }
2141 static Object fallbackIfNotEquals(Object x, Object y, Object z) {
2142 assertFalse(x.toString(), x.equals(y));
2143 return called("fallbackIfNotEquals", x, y, z);
2144 }
2145
jrose10f3b682010-01-07 16:16:45 -08002146 @Test
2147 public void testGuardWithTest() throws Throwable {
2148 if (CAN_SKIP_WORKING) return;
2149 startTest("guardWithTest");
jroseb4be0262011-07-16 15:44:33 -07002150 for (int nargs = 0; nargs <= 50; nargs++) {
2151 if (CAN_TEST_LIGHTLY && nargs > 7) break;
jrose10f3b682010-01-07 16:16:45 -08002152 testGuardWithTest(nargs, Object.class);
2153 testGuardWithTest(nargs, String.class);
2154 }
2155 }
2156 void testGuardWithTest(int nargs, Class<?> argClass) throws Throwable {
jroseb4be0262011-07-16 15:44:33 -07002157 testGuardWithTest(nargs, 0, argClass);
2158 if (nargs <= 5 || nargs % 10 == 3) {
2159 for (int testDrops = 1; testDrops <= nargs; testDrops++)
2160 testGuardWithTest(nargs, testDrops, argClass);
2161 }
2162 }
2163 void testGuardWithTest(int nargs, int testDrops, Class<?> argClass) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002164 countTest();
jroseb4be0262011-07-16 15:44:33 -07002165 int nargs1 = Math.min(3, nargs);
jrose10f3b682010-01-07 16:16:45 -08002166 MethodHandle test = PRIVATE.findVirtual(Object.class, "equals", MethodType.methodType(boolean.class, Object.class));
jroseb4be0262011-07-16 15:44:33 -07002167 MethodHandle target = PRIVATE.findStatic(MethodHandlesTest.class, "targetIfEquals", MethodType.genericMethodType(nargs1));
2168 MethodHandle fallback = PRIVATE.findStatic(MethodHandlesTest.class, "fallbackIfNotEquals", MethodType.genericMethodType(nargs1));
jrose10f3b682010-01-07 16:16:45 -08002169 while (test.type().parameterCount() > nargs)
jroseb4be0262011-07-16 15:44:33 -07002170 // 0: test = constant(MISSING_ARG.equals(MISSING_ARG))
2171 // 1: test = lambda (_) MISSING_ARG.equals(_)
jrose10f3b682010-01-07 16:16:45 -08002172 test = MethodHandles.insertArguments(test, 0, MISSING_ARG);
2173 if (argClass != Object.class) {
2174 test = changeArgTypes(test, argClass);
2175 target = changeArgTypes(target, argClass);
2176 fallback = changeArgTypes(fallback, argClass);
2177 }
jroseb4be0262011-07-16 15:44:33 -07002178 int testArgs = nargs - testDrops;
2179 assert(testArgs >= 0);
2180 test = addTrailingArgs(test, Math.min(testArgs, nargs), argClass);
2181 target = addTrailingArgs(target, nargs, argClass);
2182 fallback = addTrailingArgs(fallback, nargs, argClass);
jrose10f3b682010-01-07 16:16:45 -08002183 Object[][] argLists = {
2184 { },
2185 { "foo" }, { MISSING_ARG },
2186 { "foo", "foo" }, { "foo", "bar" },
2187 { "foo", "foo", "baz" }, { "foo", "bar", "baz" }
2188 };
2189 for (Object[] argList : argLists) {
jroseb4be0262011-07-16 15:44:33 -07002190 Object[] argList1 = argList;
2191 if (argList.length != nargs) {
2192 if (argList.length != nargs1) continue;
2193 argList1 = Arrays.copyOf(argList, nargs);
2194 Arrays.fill(argList1, nargs1, nargs, MISSING_ARG_2);
2195 }
2196 MethodHandle test1 = test;
2197 if (test1.type().parameterCount() > testArgs) {
2198 int pc = test1.type().parameterCount();
2199 test1 = MethodHandles.insertArguments(test, testArgs, Arrays.copyOfRange(argList1, testArgs, pc));
2200 }
2201 MethodHandle mh = MethodHandles.guardWithTest(test1, target, fallback);
2202 assertEquals(target.type(), mh.type());
jrose10f3b682010-01-07 16:16:45 -08002203 boolean equals;
2204 switch (nargs) {
2205 case 0: equals = true; break;
2206 case 1: equals = MISSING_ARG.equals(argList[0]); break;
2207 default: equals = argList[0].equals(argList[1]); break;
2208 }
2209 String willCall = (equals ? "targetIfEquals" : "fallbackIfNotEquals");
jrose2cc9c832010-04-30 23:48:23 -07002210 if (verbosity >= 3)
jrose10f3b682010-01-07 16:16:45 -08002211 System.out.println(logEntry(willCall, argList));
jroseb4be0262011-07-16 15:44:33 -07002212 Object result = mh.invokeWithArguments(argList1);
jrose10f3b682010-01-07 16:16:45 -08002213 assertCalled(willCall, argList);
2214 }
2215 }
2216
2217 @Test
2218 public void testCatchException() throws Throwable {
2219 if (CAN_SKIP_WORKING) return;
2220 startTest("catchException");
jroseb4be0262011-07-16 15:44:33 -07002221 for (int nargs = 0; nargs < 40; nargs++) {
2222 if (CAN_TEST_LIGHTLY && nargs > 7) break;
2223 for (int throwMode = 0; throwMode < THROW_MODE_LIMIT; throwMode++) {
2224 testCatchException(int.class, new ClassCastException("testing"), throwMode, nargs);
2225 if (CAN_TEST_LIGHTLY && nargs > 3) continue;
2226 testCatchException(void.class, new java.io.IOException("testing"), throwMode, nargs);
2227 testCatchException(String.class, new LinkageError("testing"), throwMode, nargs);
jrose10f3b682010-01-07 16:16:45 -08002228 }
2229 }
2230 }
2231
jroseb4be0262011-07-16 15:44:33 -07002232 static final int THROW_NOTHING = 0, THROW_CAUGHT = 1, THROW_UNCAUGHT = 2, THROW_THROUGH_ADAPTER = 3, THROW_MODE_LIMIT = 4;
2233
2234 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs) throws Throwable {
2235 testCatchException(returnType, thrown, throwMode, nargs, 0);
2236 if (nargs <= 5 || nargs % 10 == 3) {
2237 for (int catchDrops = 1; catchDrops <= nargs; catchDrops++)
2238 testCatchException(returnType, thrown, throwMode, nargs, catchDrops);
2239 }
2240 }
2241
jrose10f3b682010-01-07 16:16:45 -08002242 private static <T extends Throwable>
2243 Object throwOrReturn(Object normal, T exception) throws T {
jroseb4be0262011-07-16 15:44:33 -07002244 if (exception != null) {
2245 called("throwOrReturn/throw", normal, exception);
2246 throw exception;
2247 }
2248 called("throwOrReturn/normal", normal, exception);
jrose10f3b682010-01-07 16:16:45 -08002249 return normal;
2250 }
jroseb4be0262011-07-16 15:44:33 -07002251 private int fakeIdentityCount;
2252 private Object fakeIdentity(Object x) {
2253 System.out.println("should throw through this!");
2254 fakeIdentityCount++;
2255 return x;
2256 }
jrose10f3b682010-01-07 16:16:45 -08002257
jroseb4be0262011-07-16 15:44:33 -07002258 void testCatchException(Class<?> returnType, Throwable thrown, int throwMode, int nargs, int catchDrops) throws Throwable {
jrose10f3b682010-01-07 16:16:45 -08002259 countTest();
jrose2cc9c832010-04-30 23:48:23 -07002260 if (verbosity >= 3)
jroseb4be0262011-07-16 15:44:33 -07002261 System.out.println("catchException rt="+returnType+" throw="+throwMode+" nargs="+nargs+" drops="+catchDrops);
jrose10f3b682010-01-07 16:16:45 -08002262 Class<? extends Throwable> exType = thrown.getClass();
jroseb4be0262011-07-16 15:44:33 -07002263 if (throwMode > THROW_CAUGHT) thrown = new UnsupportedOperationException("do not catch this");
jrose10f3b682010-01-07 16:16:45 -08002264 MethodHandle throwOrReturn
2265 = PRIVATE.findStatic(MethodHandlesTest.class, "throwOrReturn",
2266 MethodType.methodType(Object.class, Object.class, Throwable.class));
jroseb4be0262011-07-16 15:44:33 -07002267 if (throwMode == THROW_THROUGH_ADAPTER) {
2268 MethodHandle fakeIdentity
2269 = PRIVATE.findVirtual(MethodHandlesTest.class, "fakeIdentity",
2270 MethodType.methodType(Object.class, Object.class)).bindTo(this);
2271 for (int i = 0; i < 10; i++)
2272 throwOrReturn = MethodHandles.filterReturnValue(throwOrReturn, fakeIdentity);
2273 }
2274 int nargs1 = Math.max(2, nargs);
jroseb90d2e72010-12-16 15:59:27 -08002275 MethodHandle thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
jroseb4be0262011-07-16 15:44:33 -07002276 thrower = addTrailingArgs(thrower, nargs, Object.class);
2277 int catchArgc = 1 + nargs - catchDrops;
2278 MethodHandle catcher = varargsList(catchArgc).asType(MethodType.genericMethodType(catchArgc));
jrose10f3b682010-01-07 16:16:45 -08002279 Object[] args = randomArgs(nargs, Object.class);
jroseb4be0262011-07-16 15:44:33 -07002280 Object arg0 = MISSING_ARG;
2281 Object arg1 = (throwMode == THROW_NOTHING) ? (Throwable) null : thrown;
2282 if (nargs > 0) arg0 = args[0];
2283 if (nargs > 1) args[1] = arg1;
2284 assertEquals(nargs1, thrower.type().parameterCount());
2285 if (nargs < nargs1) {
2286 Object[] appendArgs = { arg0, arg1 };
2287 appendArgs = Arrays.copyOfRange(appendArgs, nargs, nargs1);
2288 thrower = MethodHandles.insertArguments(thrower, nargs, appendArgs);
2289 }
2290 assertEquals(nargs, thrower.type().parameterCount());
2291 MethodHandle target = MethodHandles.catchException(thrower, exType, catcher);
2292 assertEquals(thrower.type(), target.type());
2293 assertEquals(nargs, target.type().parameterCount());
2294 //System.out.println("catching with "+target+" : "+throwOrReturn);
2295 Object returned;
2296 try {
2297 returned = target.invokeWithArguments(args);
2298 } catch (Throwable ex) {
2299 assertSame("must get the out-of-band exception", thrown, ex);
2300 if (throwMode <= THROW_CAUGHT)
2301 assertEquals(THROW_UNCAUGHT, throwMode);
2302 returned = ex;
2303 }
2304 assertCalled("throwOrReturn/"+(throwMode == THROW_NOTHING ? "normal" : "throw"), arg0, arg1);
jrose10f3b682010-01-07 16:16:45 -08002305 //System.out.println("return from "+target+" : "+returned);
jroseb4be0262011-07-16 15:44:33 -07002306 if (throwMode == THROW_NOTHING) {
2307 assertSame(arg0, returned);
2308 } else if (throwMode == THROW_CAUGHT) {
jrose49494522012-01-18 17:34:29 -08002309 List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
jroseb4be0262011-07-16 15:44:33 -07002310 // catcher receives an initial subsequence of target arguments:
2311 catchArgs.subList(nargs - catchDrops, nargs).clear();
2312 // catcher also receives the exception, prepended:
jrose10f3b682010-01-07 16:16:45 -08002313 catchArgs.add(0, thrown);
2314 assertEquals(catchArgs, returned);
2315 }
jroseb4be0262011-07-16 15:44:33 -07002316 assertEquals(0, fakeIdentityCount);
jrose10f3b682010-01-07 16:16:45 -08002317 }
2318
2319 @Test
2320 public void testThrowException() throws Throwable {
2321 if (CAN_SKIP_WORKING) return;
2322 startTest("throwException");
2323 testThrowException(int.class, new ClassCastException("testing"));
2324 testThrowException(void.class, new java.io.IOException("testing"));
2325 testThrowException(String.class, new LinkageError("testing"));
2326 }
2327
2328 void testThrowException(Class<?> returnType, Throwable thrown) throws Throwable {
2329 countTest();
2330 Class<? extends Throwable> exType = thrown.getClass();
2331 MethodHandle target = MethodHandles.throwException(returnType, exType);
2332 //System.out.println("throwing with "+target+" : "+thrown);
2333 MethodType expectedType = MethodType.methodType(returnType, exType);
2334 assertEquals(expectedType, target.type());
jrose9b82ad62011-05-26 17:37:36 -07002335 target = target.asType(target.type().generic());
jrose10f3b682010-01-07 16:16:45 -08002336 Throwable caught = null;
2337 try {
jrose2cc9c832010-04-30 23:48:23 -07002338 Object res = target.invokeExact((Object) thrown);
jrose10f3b682010-01-07 16:16:45 -08002339 fail("got "+res+" instead of throwing "+thrown);
2340 } catch (Throwable ex) {
2341 if (ex != thrown) {
2342 if (ex instanceof Error) throw (Error)ex;
2343 if (ex instanceof RuntimeException) throw (RuntimeException)ex;
2344 }
2345 caught = ex;
2346 }
2347 assertSame(thrown, caught);
2348 }
2349
2350 @Test
jroseb4be0262011-07-16 15:44:33 -07002351 public void testInterfaceCast() throws Throwable {
2352 for (Class<?> ctype : new Class<?>[]{ Object.class, String.class, CharSequence.class, Number.class, Iterable.class}) {
2353 testInterfaceCast(ctype, false, false);
2354 testInterfaceCast(ctype, true, false);
2355 testInterfaceCast(ctype, false, true);
2356 testInterfaceCast(ctype, true, true);
2357 }
2358 }
2359 public void testInterfaceCast(Class<?> ctype, boolean doret, boolean docast) throws Throwable {
2360 String str = "normal return value";
2361 MethodHandle mh = MethodHandles.identity(String.class);
2362 MethodType mt = mh.type();
2363 if (doret) mt = mt.changeReturnType(ctype);
2364 else mt = mt.changeParameterType(0, ctype);
2365 if (docast) mh = MethodHandles.explicitCastArguments(mh, mt);
2366 else mh = mh.asType(mt);
2367 // this bit is needed to make the interface types disappear for invokeWithArguments:
2368 mh = MethodHandles.explicitCastArguments(mh, mt.generic());
2369 boolean expectFail = !ctype.isInstance(str);
2370 if (ctype.isInterface()) {
2371 // special rules: interfaces slide by more frequently
2372 if (docast || !doret) expectFail = false;
2373 }
2374 Object res;
2375 try {
2376 res = mh.invokeWithArguments(str);
2377 } catch (Exception ex) {
2378 res = ex;
2379 }
2380 boolean sawFail = !(res instanceof String);
2381 if (sawFail != expectFail) {
2382 System.out.println("*** testInterfaceCast: "+mh+" was "+mt+" => "+res+(docast ? " (explicitCastArguments)" : ""));
2383 }
2384 if (!sawFail) {
2385 assertFalse(res.toString(), expectFail);
2386 assertEquals(str, res);
2387 } else {
2388 assertTrue(res.toString(), expectFail);
2389 }
2390 }
2391
2392 @Test
jrose10f3b682010-01-07 16:16:45 -08002393 public void testCastFailure() throws Throwable {
2394 if (CAN_SKIP_WORKING) return;
2395 startTest("testCastFailure");
2396 testCastFailure("cast/argument", 11000);
2397 testCastFailure("unbox/argument", 11000);
2398 testCastFailure("cast/return", 11000);
2399 testCastFailure("unbox/return", 11000);
2400 }
2401
jrose900bafd2010-10-30 21:08:23 -07002402 static class Surprise {
jrosea1ebbe62010-09-08 18:40:23 -07002403 public MethodHandle asMethodHandle() {
2404 return VALUE.bindTo(this);
2405 }
jrose10f3b682010-01-07 16:16:45 -08002406 Object value(Object x) {
2407 trace("value", x);
2408 if (boo != null) return boo;
2409 return x;
2410 }
2411 Object boo;
2412 void boo(Object x) { boo = x; }
2413
2414 static void trace(String x, Object y) {
2415 if (verbosity > 8) System.out.println(x+"="+y);
2416 }
2417 static Object refIdentity(Object x) { trace("ref.x", x); return x; }
2418 static Integer boxIdentity(Integer x) { trace("box.x", x); return x; }
2419 static int intIdentity(int x) { trace("int.x", x); return x; }
jrosea1ebbe62010-09-08 18:40:23 -07002420 static MethodHandle VALUE, REF_IDENTITY, BOX_IDENTITY, INT_IDENTITY;
2421 static {
2422 try {
2423 VALUE = PRIVATE.findVirtual(
2424 Surprise.class, "value",
2425 MethodType.methodType(Object.class, Object.class));
2426 REF_IDENTITY = PRIVATE.findStatic(
2427 Surprise.class, "refIdentity",
2428 MethodType.methodType(Object.class, Object.class));
2429 BOX_IDENTITY = PRIVATE.findStatic(
2430 Surprise.class, "boxIdentity",
2431 MethodType.methodType(Integer.class, Integer.class));
2432 INT_IDENTITY = PRIVATE.findStatic(
2433 Surprise.class, "intIdentity",
2434 MethodType.methodType(int.class, int.class));
jrose49494522012-01-18 17:34:29 -08002435 } catch (NoSuchMethodException | IllegalAccessException ex) {
jrosea1ebbe62010-09-08 18:40:23 -07002436 throw new RuntimeException(ex);
2437 }
2438 }
jrose10f3b682010-01-07 16:16:45 -08002439 }
2440
jrose49494522012-01-18 17:34:29 -08002441 @SuppressWarnings("ConvertToStringSwitch")
jrose10f3b682010-01-07 16:16:45 -08002442 void testCastFailure(String mode, int okCount) throws Throwable {
2443 countTest(false);
jrose2cc9c832010-04-30 23:48:23 -07002444 if (verbosity > 2) System.out.println("mode="+mode);
jrose10f3b682010-01-07 16:16:45 -08002445 Surprise boo = new Surprise();
jrosea1ebbe62010-09-08 18:40:23 -07002446 MethodHandle identity = Surprise.REF_IDENTITY, surprise0 = boo.asMethodHandle(), surprise = surprise0;
jrose10f3b682010-01-07 16:16:45 -08002447 if (mode.endsWith("/return")) {
2448 if (mode.equals("unbox/return")) {
2449 // fail on return to ((Integer)surprise).intValue
jrose9b82ad62011-05-26 17:37:36 -07002450 surprise = surprise.asType(MethodType.methodType(int.class, Object.class));
2451 identity = identity.asType(MethodType.methodType(int.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002452 } else if (mode.equals("cast/return")) {
2453 // fail on return to (Integer)surprise
jrose9b82ad62011-05-26 17:37:36 -07002454 surprise = surprise.asType(MethodType.methodType(Integer.class, Object.class));
2455 identity = identity.asType(MethodType.methodType(Integer.class, Object.class));
jrose10f3b682010-01-07 16:16:45 -08002456 }
2457 } else if (mode.endsWith("/argument")) {
2458 MethodHandle callee = null;
2459 if (mode.equals("unbox/argument")) {
2460 // fail on handing surprise to int argument
2461 callee = Surprise.INT_IDENTITY;
2462 } else if (mode.equals("cast/argument")) {
2463 // fail on handing surprise to Integer argument
2464 callee = Surprise.BOX_IDENTITY;
2465 }
2466 if (callee != null) {
jrose9b82ad62011-05-26 17:37:36 -07002467 callee = callee.asType(MethodType.genericMethodType(1));
jrose900bafd2010-10-30 21:08:23 -07002468 surprise = MethodHandles.filterArguments(callee, 0, surprise);
2469 identity = MethodHandles.filterArguments(callee, 0, identity);
jrose10f3b682010-01-07 16:16:45 -08002470 }
2471 }
jrosea1ebbe62010-09-08 18:40:23 -07002472 assertNotSame(mode, surprise, surprise0);
jrose9b82ad62011-05-26 17:37:36 -07002473 identity = identity.asType(MethodType.genericMethodType(1));
2474 surprise = surprise.asType(MethodType.genericMethodType(1));
jrose10f3b682010-01-07 16:16:45 -08002475 Object x = 42;
2476 for (int i = 0; i < okCount; i++) {
jrose2cc9c832010-04-30 23:48:23 -07002477 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002478 assertEquals(x, y);
jrose2cc9c832010-04-30 23:48:23 -07002479 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002480 assertEquals(x, z);
2481 }
2482 boo.boo("Boo!");
jrose2cc9c832010-04-30 23:48:23 -07002483 Object y = identity.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002484 assertEquals(x, y);
2485 try {
jrose2cc9c832010-04-30 23:48:23 -07002486 Object z = surprise.invokeExact(x);
jrose10f3b682010-01-07 16:16:45 -08002487 System.out.println("Failed to throw; got z="+z);
2488 assertTrue(false);
jrose320b7692011-05-12 19:27:49 -07002489 } catch (ClassCastException ex) {
jrose10f3b682010-01-07 16:16:45 -08002490 if (verbosity > 2)
jrose2cc9c832010-04-30 23:48:23 -07002491 System.out.println("caught "+ex);
2492 if (verbosity > 3)
jrose10f3b682010-01-07 16:16:45 -08002493 ex.printStackTrace();
jrose320b7692011-05-12 19:27:49 -07002494 assertTrue(true); // all is well
jrose10f3b682010-01-07 16:16:45 -08002495 }
2496 }
2497
jrose45b7a332010-05-03 23:32:47 -07002498 static Example userMethod(Object o, String s, int i) {
2499 called("userMethod", o, s, i);
2500 return null;
2501 }
2502
2503 @Test
2504 public void testUserClassInSignature() throws Throwable {
2505 if (CAN_SKIP_WORKING) return;
2506 startTest("testUserClassInSignature");
2507 Lookup lookup = MethodHandles.lookup();
2508 String name; MethodType mt; MethodHandle mh;
2509 Object[] args;
2510
2511 // Try a static method.
2512 name = "userMethod";
2513 mt = MethodType.methodType(Example.class, Object.class, String.class, int.class);
2514 mh = lookup.findStatic(lookup.lookupClass(), name, mt);
2515 assertEquals(mt, mh.type());
2516 assertEquals(Example.class, mh.type().returnType());
2517 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002518 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002519 assertCalled(name, args);
2520
2521 // Try a virtual method.
2522 name = "v2";
2523 mt = MethodType.methodType(Object.class, Object.class, int.class);
2524 mh = lookup.findVirtual(Example.class, name, mt);
2525 assertEquals(mt, mh.type().dropParameterTypes(0,1));
2526 assertTrue(mh.type().parameterList().contains(Example.class));
2527 args = randomArgs(mh.type().parameterArray());
jrose900bafd2010-10-30 21:08:23 -07002528 mh.invokeWithArguments(args);
jrose45b7a332010-05-03 23:32:47 -07002529 assertCalled(name, args);
2530 }
jrosebe2db602010-09-08 18:40:34 -07002531
2532 static void runForRunnable() {
2533 called("runForRunnable");
2534 }
jroseaf751942011-06-14 22:47:12 -07002535 public interface Fooable {
jroseb4be0262011-07-16 15:44:33 -07002536 // overloads:
jrose49494522012-01-18 17:34:29 -08002537 Object foo(Object x, String y);
2538 List<?> foo(String x, int y);
2539 Object foo(String x);
jrosebe2db602010-09-08 18:40:34 -07002540 }
jroseb4be0262011-07-16 15:44:33 -07002541 static Object fooForFooable(String x, Object... y) {
2542 return called("fooForFooable/"+x, y);
jrosebe2db602010-09-08 18:40:34 -07002543 }
jrose49494522012-01-18 17:34:29 -08002544 @SuppressWarnings("serial") // not really a public API, just a test case
jroseaf751942011-06-14 22:47:12 -07002545 public static class MyCheckedException extends Exception {
jrosebe2db602010-09-08 18:40:34 -07002546 }
jroseaf751942011-06-14 22:47:12 -07002547 public interface WillThrow {
jrosebe2db602010-09-08 18:40:34 -07002548 void willThrow() throws MyCheckedException;
2549 }
jroseb4be0262011-07-16 15:44:33 -07002550 /*non-public*/ interface PrivateRunnable {
2551 public void run();
2552 }
jrosebe2db602010-09-08 18:40:34 -07002553
2554 @Test
jroseb4be0262011-07-16 15:44:33 -07002555 public void testAsInterfaceInstance() throws Throwable {
jrosebe2db602010-09-08 18:40:34 -07002556 if (CAN_SKIP_WORKING) return;
jroseb4be0262011-07-16 15:44:33 -07002557 startTest("testAsInterfaceInstance");
jrosebe2db602010-09-08 18:40:34 -07002558 Lookup lookup = MethodHandles.lookup();
jroseb4be0262011-07-16 15:44:33 -07002559 // test typical case: Runnable.run
jrosebe2db602010-09-08 18:40:34 -07002560 {
jroseb4be0262011-07-16 15:44:33 -07002561 countTest();
2562 if (verbosity >= 2) System.out.println("Runnable");
jrosebe2db602010-09-08 18:40:34 -07002563 MethodType mt = MethodType.methodType(void.class);
2564 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
jrose9b82ad62011-05-26 17:37:36 -07002565 Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002566 proxy.run();
2567 assertCalled("runForRunnable");
2568 }
jroseb4be0262011-07-16 15:44:33 -07002569 // well known single-name overloaded interface: Appendable.append
jrosebe2db602010-09-08 18:40:34 -07002570 {
jroseb4be0262011-07-16 15:44:33 -07002571 countTest();
2572 if (verbosity >= 2) System.out.println("Appendable");
jrose49494522012-01-18 17:34:29 -08002573 ArrayList<List<?>> appendResults = new ArrayList<>();
jroseb4be0262011-07-16 15:44:33 -07002574 MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
2575 append = append.asType(MethodType.methodType(void.class, List.class)); // specialize the type
2576 MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
2577 MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
2578 Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
2579 proxy.append("one");
2580 proxy.append("two", 3, 4);
2581 proxy.append('5');
2582 assertEquals(Arrays.asList(Arrays.asList("one"),
2583 Arrays.asList("two", 3, 4),
2584 Arrays.asList('5')),
2585 appendResults);
2586 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
2587 appendResults.clear();
2588 Formatter formatter = new Formatter(proxy);
2589 String fmt = "foo str=%s char='%c' num=%d";
2590 Object[] fmtArgs = { "str!", 'C', 42 };
2591 String expect = String.format(fmt, fmtArgs);
2592 formatter.format(fmt, fmtArgs);
2593 String actual = "";
2594 if (verbosity >= 3) System.out.println("appendResults="+appendResults);
jrose49494522012-01-18 17:34:29 -08002595 for (List<?> l : appendResults) {
jroseb4be0262011-07-16 15:44:33 -07002596 Object x = l.get(0);
2597 switch (l.size()) {
2598 case 1: actual += x; continue;
jrose49494522012-01-18 17:34:29 -08002599 case 3: actual += ((String)x).substring((int)(Object)l.get(1), (int)(Object)l.get(2)); continue;
jroseb4be0262011-07-16 15:44:33 -07002600 }
2601 actual += l;
2602 }
2603 if (verbosity >= 3) System.out.println("expect="+expect);
2604 if (verbosity >= 3) System.out.println("actual="+actual);
2605 assertEquals(expect, actual);
jrosebe2db602010-09-08 18:40:34 -07002606 }
jroseb4be0262011-07-16 15:44:33 -07002607 // test case of an single name which is overloaded: Fooable.foo(...)
2608 {
2609 if (verbosity >= 2) System.out.println("Fooable");
2610 MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable",
2611 MethodType.methodType(Object.class, String.class, Object[].class));
2612 Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
2613 for (Method m : Fooable.class.getDeclaredMethods()) {
2614 countTest();
2615 assertSame("foo", m.getName());
2616 if (verbosity > 3)
2617 System.out.println("calling "+m);
2618 MethodHandle invoker = lookup.unreflect(m);
2619 MethodType mt = invoker.type();
2620 Class<?>[] types = mt.parameterArray();
2621 types[0] = int.class; // placeholder
2622 Object[] args = randomArgs(types);
2623 args[0] = proxy;
2624 if (verbosity > 3)
2625 System.out.println("calling "+m+" on "+Arrays.asList(args));
2626 Object result = invoker.invokeWithArguments(args);
2627 if (verbosity > 4)
2628 System.out.println("result = "+result);
2629 String name = "fooForFooable/"+args[1];
2630 Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
2631 assertCalled(name, argTail);
2632 assertEquals(result, logEntry(name, argTail));
2633 }
2634 }
2635 // test processing of thrown exceptions:
jrosebe2db602010-09-08 18:40:34 -07002636 for (Throwable ex : new Throwable[] { new NullPointerException("ok"),
2637 new InternalError("ok"),
2638 new Throwable("fail"),
2639 new Exception("fail"),
2640 new MyCheckedException()
2641 }) {
2642 MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
2643 mh = MethodHandles.insertArguments(mh, 0, ex);
jrose9b82ad62011-05-26 17:37:36 -07002644 WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
jrosebe2db602010-09-08 18:40:34 -07002645 try {
jroseb4be0262011-07-16 15:44:33 -07002646 countTest();
jrosebe2db602010-09-08 18:40:34 -07002647 proxy.willThrow();
2648 System.out.println("Failed to throw: "+ex);
2649 assertTrue(false);
2650 } catch (Throwable ex1) {
jroseb4be0262011-07-16 15:44:33 -07002651 if (verbosity > 3) {
jrosebe2db602010-09-08 18:40:34 -07002652 System.out.println("throw "+ex);
2653 System.out.println("catch "+(ex == ex1 ? "UNWRAPPED" : ex1));
2654 }
2655 if (ex instanceof RuntimeException ||
2656 ex instanceof Error) {
2657 assertSame("must pass unchecked exception out without wrapping", ex, ex1);
2658 } else if (ex instanceof MyCheckedException) {
2659 assertSame("must pass declared exception out without wrapping", ex, ex1);
2660 } else {
2661 assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
jroseaf751942011-06-14 22:47:12 -07002662 if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
2663 ex1.printStackTrace();
2664 }
2665 assertSame(ex, ex1.getCause());
jrosebe2db602010-09-08 18:40:34 -07002666 UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
jrosebe2db602010-09-08 18:40:34 -07002667 }
2668 }
2669 }
jroseb4be0262011-07-16 15:44:33 -07002670 // Test error checking on bad interfaces:
jrose49494522012-01-18 17:34:29 -08002671 for (Class<?> nonSMI : new Class<?>[] { Object.class,
jrosebe2db602010-09-08 18:40:34 -07002672 String.class,
2673 CharSequence.class,
jroseb4be0262011-07-16 15:44:33 -07002674 java.io.Serializable.class,
2675 PrivateRunnable.class,
jrosebe2db602010-09-08 18:40:34 -07002676 Example.class }) {
jroseb4be0262011-07-16 15:44:33 -07002677 if (verbosity > 2) System.out.println(nonSMI.getName());
jrosebe2db602010-09-08 18:40:34 -07002678 try {
jroseb4be0262011-07-16 15:44:33 -07002679 countTest(false);
2680 MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
2681 assertTrue("Failed to throw on "+nonSMI.getName(), false);
jrosebe2db602010-09-08 18:40:34 -07002682 } catch (IllegalArgumentException ex) {
jroseb4be0262011-07-16 15:44:33 -07002683 if (verbosity > 2) System.out.println(nonSMI.getSimpleName()+": "+ex);
2684 // Object: java.lang.IllegalArgumentException:
2685 // not a public interface: java.lang.Object
2686 // String: java.lang.IllegalArgumentException:
2687 // not a public interface: java.lang.String
2688 // CharSequence: java.lang.IllegalArgumentException:
2689 // not a single-method interface: java.lang.CharSequence
2690 // Serializable: java.lang.IllegalArgumentException:
2691 // not a single-method interface: java.io.Serializable
2692 // PrivateRunnable: java.lang.IllegalArgumentException:
2693 // not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
2694 // Example: java.lang.IllegalArgumentException:
2695 // not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
2696 }
2697 }
2698 // Test error checking on interfaces with the wrong method type:
jrose49494522012-01-18 17:34:29 -08002699 for (Class<?> intfc : new Class<?>[] { Runnable.class /*arity 0*/,
jroseb4be0262011-07-16 15:44:33 -07002700 Fooable.class /*arity 1 & 2*/ }) {
2701 int badArity = 1; // known to be incompatible
2702 if (verbosity > 2) System.out.println(intfc.getName());
2703 try {
2704 countTest(false);
2705 MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
2706 assertTrue("Failed to throw on "+intfc.getName(), false);
2707 } catch (WrongMethodTypeException ex) {
2708 if (verbosity > 2) System.out.println(intfc.getSimpleName()+": "+ex);
2709 // Runnable: java.lang.invoke.WrongMethodTypeException:
2710 // cannot convert MethodHandle(Object)Object[] to ()void
2711 // Fooable: java.lang.invoke.WrongMethodTypeException:
2712 // cannot convert MethodHandle(Object)Object[] to (Object,String)Object
jrosebe2db602010-09-08 18:40:34 -07002713 }
2714 }
2715 }
jrose43b8c122011-07-16 15:40:13 -07002716
2717 @Test
2718 public void testRunnableProxy() throws Throwable {
2719 if (CAN_SKIP_WORKING) return;
2720 startTest("testRunnableProxy");
2721 MethodHandles.Lookup lookup = MethodHandles.lookup();
2722 MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
2723 Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
2724 testRunnableProxy(r);
2725 assertCalled("runForRunnable");
2726 }
2727 private static void testRunnableProxy(Runnable r) {
2728 //7058630: JSR 292 method handle proxy violates contract for Object methods
2729 r.run();
2730 Object o = r;
2731 r = null;
2732 boolean eq = (o == o);
2733 int hc = System.identityHashCode(o);
2734 String st = o.getClass().getName() + "@" + Integer.toHexString(hc);
2735 Object expect = Arrays.asList(st, eq, hc);
2736 if (verbosity >= 2) System.out.println("expect st/eq/hc = "+expect);
2737 Object actual = Arrays.asList(o.toString(), o.equals(o), o.hashCode());
2738 if (verbosity >= 2) System.out.println("actual st/eq/hc = "+actual);
2739 assertEquals(expect, actual);
2740 }
jrose55220c32009-10-21 23:19:48 -07002741}
jroseada69fa2011-03-23 23:02:31 -07002742// Local abbreviated copy of sun.invoke.util.ValueConversions
jrose55220c32009-10-21 23:19:48 -07002743class ValueConversions {
2744 private static final Lookup IMPL_LOOKUP = MethodHandles.lookup();
2745 private static final Object[] NO_ARGS_ARRAY = {};
2746 private static Object[] makeArray(Object... args) { return args; }
2747 private static Object[] array() { return NO_ARGS_ARRAY; }
2748 private static Object[] array(Object a0)
2749 { return makeArray(a0); }
2750 private static Object[] array(Object a0, Object a1)
2751 { return makeArray(a0, a1); }
2752 private static Object[] array(Object a0, Object a1, Object a2)
2753 { return makeArray(a0, a1, a2); }
2754 private static Object[] array(Object a0, Object a1, Object a2, Object a3)
2755 { return makeArray(a0, a1, a2, a3); }
2756 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2757 Object a4)
2758 { return makeArray(a0, a1, a2, a3, a4); }
2759 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2760 Object a4, Object a5)
2761 { return makeArray(a0, a1, a2, a3, a4, a5); }
2762 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2763 Object a4, Object a5, Object a6)
2764 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
2765 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2766 Object a4, Object a5, Object a6, Object a7)
2767 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
2768 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2769 Object a4, Object a5, Object a6, Object a7,
2770 Object a8)
2771 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2772 private static Object[] array(Object a0, Object a1, Object a2, Object a3,
2773 Object a4, Object a5, Object a6, Object a7,
2774 Object a8, Object a9)
2775 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2776 static MethodHandle[] makeArrays() {
jrose49494522012-01-18 17:34:29 -08002777 ArrayList<MethodHandle> arrays = new ArrayList<>();
jrose55220c32009-10-21 23:19:48 -07002778 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2779 for (;;) {
2780 int nargs = arrays.size();
jrose10f3b682010-01-07 16:16:45 -08002781 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(Object[].class);
jrose55220c32009-10-21 23:19:48 -07002782 String name = "array";
2783 MethodHandle array = null;
2784 try {
2785 array = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002786 } catch (ReflectiveOperationException ex) {
2787 // break from loop!
jrose55220c32009-10-21 23:19:48 -07002788 }
2789 if (array == null) break;
2790 arrays.add(array);
2791 }
jrosef15905c2011-02-11 01:26:32 -08002792 assertTrue(arrays.size() == 11); // current number of methods
jrose55220c32009-10-21 23:19:48 -07002793 return arrays.toArray(new MethodHandle[0]);
2794 }
2795 static final MethodHandle[] ARRAYS = makeArrays();
2796
2797 /** Return a method handle that takes the indicated number of Object
2798 * arguments and returns an Object array of them, as if for varargs.
2799 */
2800 public static MethodHandle varargsArray(int nargs) {
2801 if (nargs < ARRAYS.length)
2802 return ARRAYS[nargs];
jroseaf751942011-06-14 22:47:12 -07002803 return MethodHandles.identity(Object[].class).asCollector(Object[].class, nargs);
jrose55220c32009-10-21 23:19:48 -07002804 }
jrose320b7692011-05-12 19:27:49 -07002805 public static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
2806 Class<?> elemType = arrayType.getComponentType();
2807 MethodType vaType = MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType));
2808 MethodHandle mh = varargsArray(nargs);
2809 if (arrayType != Object[].class)
2810 mh = MethodHandles.filterReturnValue(mh, CHANGE_ARRAY_TYPE.bindTo(arrayType));
2811 return mh.asType(vaType);
2812 }
2813 static Object changeArrayType(Class<?> arrayType, Object[] a) {
2814 Class<?> elemType = arrayType.getComponentType();
2815 if (!elemType.isPrimitive())
2816 return Arrays.copyOf(a, a.length, arrayType.asSubclass(Object[].class));
2817 Object b = java.lang.reflect.Array.newInstance(elemType, a.length);
2818 for (int i = 0; i < a.length; i++)
2819 java.lang.reflect.Array.set(b, i, a[i]);
2820 return b;
2821 }
2822 private static final MethodHandle CHANGE_ARRAY_TYPE;
2823 static {
2824 try {
2825 CHANGE_ARRAY_TYPE = IMPL_LOOKUP.findStatic(ValueConversions.class, "changeArrayType",
2826 MethodType.methodType(Object.class, Class.class, Object[].class));
2827 } catch (NoSuchMethodException | IllegalAccessException ex) {
2828 Error err = new InternalError("uncaught exception");
2829 err.initCause(ex);
2830 throw err;
2831 }
2832 }
jrose10f3b682010-01-07 16:16:45 -08002833
2834 private static final List<Object> NO_ARGS_LIST = Arrays.asList(NO_ARGS_ARRAY);
2835 private static List<Object> makeList(Object... args) { return Arrays.asList(args); }
2836 private static List<Object> list() { return NO_ARGS_LIST; }
2837 private static List<Object> list(Object a0)
2838 { return makeList(a0); }
2839 private static List<Object> list(Object a0, Object a1)
2840 { return makeList(a0, a1); }
2841 private static List<Object> list(Object a0, Object a1, Object a2)
2842 { return makeList(a0, a1, a2); }
2843 private static List<Object> list(Object a0, Object a1, Object a2, Object a3)
2844 { return makeList(a0, a1, a2, a3); }
2845 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2846 Object a4)
2847 { return makeList(a0, a1, a2, a3, a4); }
2848 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2849 Object a4, Object a5)
2850 { return makeList(a0, a1, a2, a3, a4, a5); }
2851 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2852 Object a4, Object a5, Object a6)
2853 { return makeList(a0, a1, a2, a3, a4, a5, a6); }
2854 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2855 Object a4, Object a5, Object a6, Object a7)
2856 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7); }
2857 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2858 Object a4, Object a5, Object a6, Object a7,
2859 Object a8)
2860 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
2861 private static List<Object> list(Object a0, Object a1, Object a2, Object a3,
2862 Object a4, Object a5, Object a6, Object a7,
2863 Object a8, Object a9)
2864 { return makeList(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
2865 static MethodHandle[] makeLists() {
jrose49494522012-01-18 17:34:29 -08002866 ArrayList<MethodHandle> lists = new ArrayList<>();
jrose10f3b682010-01-07 16:16:45 -08002867 MethodHandles.Lookup lookup = IMPL_LOOKUP;
2868 for (;;) {
jroseadc650a2011-02-11 01:26:28 -08002869 int nargs = lists.size();
jrose10f3b682010-01-07 16:16:45 -08002870 MethodType type = MethodType.genericMethodType(nargs).changeReturnType(List.class);
2871 String name = "list";
jroseadc650a2011-02-11 01:26:28 -08002872 MethodHandle list = null;
jrose10f3b682010-01-07 16:16:45 -08002873 try {
jroseadc650a2011-02-11 01:26:28 -08002874 list = lookup.findStatic(ValueConversions.class, name, type);
jrosef15905c2011-02-11 01:26:32 -08002875 } catch (ReflectiveOperationException ex) {
2876 // break from loop!
jrose10f3b682010-01-07 16:16:45 -08002877 }
jroseadc650a2011-02-11 01:26:28 -08002878 if (list == null) break;
2879 lists.add(list);
jrose10f3b682010-01-07 16:16:45 -08002880 }
jrosef15905c2011-02-11 01:26:32 -08002881 assertTrue(lists.size() == 11); // current number of methods
jroseadc650a2011-02-11 01:26:28 -08002882 return lists.toArray(new MethodHandle[0]);
jrose10f3b682010-01-07 16:16:45 -08002883 }
2884 static final MethodHandle[] LISTS = makeLists();
jroseaf751942011-06-14 22:47:12 -07002885 static final MethodHandle AS_LIST;
2886 static {
2887 try {
2888 AS_LIST = IMPL_LOOKUP.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
jrose49494522012-01-18 17:34:29 -08002889 } catch (NoSuchMethodException | IllegalAccessException ex) { throw new RuntimeException(ex); }
jroseaf751942011-06-14 22:47:12 -07002890 }
jrose10f3b682010-01-07 16:16:45 -08002891
2892 /** Return a method handle that takes the indicated number of Object
2893 * arguments and returns List.
2894 */
2895 public static MethodHandle varargsList(int nargs) {
2896 if (nargs < LISTS.length)
2897 return LISTS[nargs];
jroseaf751942011-06-14 22:47:12 -07002898 return AS_LIST.asCollector(Object[].class, nargs);
jrose10f3b682010-01-07 16:16:45 -08002899 }
jrose55220c32009-10-21 23:19:48 -07002900}
2901// This guy tests access from outside the same package member, but inside
2902// the package itself.
2903class PackageSibling {
2904 static Lookup lookup() {
2905 return MethodHandles.lookup();
2906 }
2907}