1 /* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact 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. 24 */ 25 26 /* @test 27 * @run testng/othervm -ea -esa test.java.lang.invoke.T8139885 28 */ 29 30 package test.java.lang.invoke; 31 32 import java.io.StringWriter; 33 import java.lang.invoke.MethodHandle; 34 import java.lang.invoke.MethodHandles; 35 import java.lang.invoke.MethodHandles.Lookup; 36 import java.lang.invoke.MethodType; 37 import java.lang.invoke.WrongMethodTypeException; 38 import java.util.*; 39 40 import static java.lang.invoke.MethodType.methodType; 41 42 import static org.testng.AssertJUnit.*; 43 44 import org.testng.annotations.*; 45 46 /** 47 * Example-scale and negative tests for JEP 274 extensions. 48 */ 49 public class T8139885 { 50 51 static final Lookup LOOKUP = MethodHandles.lookup(); 52 53 // 54 // Tests. 55 // 56 57 @Test 58 public static void testLoopFac() throws Throwable { 59 MethodHandle[] counterClause = new MethodHandle[]{Fac.MH_zero, Fac.MH_inc}; 60 MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin}; 61 MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 62 assertEquals(Fac.MT_fac, loop.type()); 63 assertEquals(120, loop.invoke(5)); 64 } 65 66 @Test 67 public static void testLoopFacNullInit() throws Throwable { 68 // null initializer for counter, should initialize to 0 69 MethodHandle[] counterClause = new MethodHandle[]{null, Fac.MH_inc}; 70 MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin}; 71 MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 72 assertEquals(Fac.MT_fac, loop.type()); 73 assertEquals(120, loop.invoke(5)); 74 } 75 76 @Test 77 public static void testLoopVoid1() throws Throwable { 78 // construct a post-checked loop that only does one iteration and has a void body and void local state 79 MethodHandle loop = MethodHandles.loop(new MethodHandle[]{Empty.MH_f, Empty.MH_f, Empty.MH_pred, null}); 80 assertEquals(MethodType.methodType(void.class), loop.type()); 81 loop.invoke(); 82 } 83 84 @Test 85 public static void testLoopVoid2() throws Throwable { 86 // construct a post-checked loop that only does one iteration and has a void body and void local state, 87 // initialized implicitly from the step type 88 MethodHandle loop = MethodHandles.loop(new MethodHandle[]{null, Empty.MH_f, Empty.MH_pred, null}); 89 assertEquals(MethodType.methodType(void.class), loop.type()); 90 loop.invoke(); 91 } 92 93 @Test 94 public static void testLoopFacWithVoidState() throws Throwable { 95 // like testLoopFac, but with additional void state that outputs a dot 96 MethodHandle[] counterClause = new MethodHandle[]{Fac.MH_zero, Fac.MH_inc}; 97 MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin}; 98 MethodHandle[] dotClause = new MethodHandle[]{null, Fac.MH_dot}; 99 MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause, dotClause); 100 assertEquals(Fac.MT_fac, loop.type()); 101 assertEquals(120, loop.invoke(5)); 102 } 103 104 @Test 105 public static void testLoopNegative() throws Throwable { 106 MethodHandle mh_loop = 107 LOOKUP.findStatic(MethodHandles.class, "loop", methodType(MethodHandle.class, MethodHandle[][].class)); 108 MethodHandle i0 = MethodHandles.constant(int.class, 0); 109 MethodHandle ii = MethodHandles.dropArguments(i0, 0, int.class, int.class); 110 MethodHandle id = MethodHandles.dropArguments(i0, 0, int.class, double.class); 111 MethodHandle i3 = MethodHandles.dropArguments(i0, 0, int.class, int.class, int.class); 112 List<MethodHandle> inits = Arrays.asList(ii, id, i3); 113 List<Class<?>> ints = Arrays.asList(int.class, int.class, int.class); 114 List<MethodHandle> finis = Arrays.asList(Fac.MH_fin, Fac.MH_inc, Counted.MH_step); 115 List<MethodHandle> preds1 = Arrays.asList(null, null, null); 116 List<MethodHandle> preds2 = Arrays.asList(null, Fac.MH_fin, null); 117 MethodHandle eek = MethodHandles.dropArguments(i0, 0, int.class, int.class, double.class); 118 List<MethodHandle> nesteps = Arrays.asList(Fac.MH_inc, eek, Fac.MH_dot); 119 List<MethodHandle> nepreds = Arrays.asList(null, Fac.MH_pred, null); 120 List<MethodHandle> nefinis = Arrays.asList(null, Fac.MH_fin, null); 121 MethodHandle[][][] cases = { 122 null, 123 {}, 124 {{null, Fac.MH_inc}, {Fac.MH_one, null, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin}}, 125 {{null, Fac.MH_inc}, null}, 126 {{Fac.MH_zero, Fac.MH_dot}}, 127 {{ii}, {id}, {i3}}, 128 {{null, Fac.MH_inc, null, Fac.MH_fin}, {null, Fac.MH_inc, null, Fac.MH_inc}, 129 {null, Counted.MH_start, null, Counted.MH_step}}, 130 {{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, Fac.MH_mult, null, Fac.MH_fin}, {null, Fac.MH_dot}}, 131 {{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, Fac.MH_mult, Fac.MH_fin, Fac.MH_fin}, {null, Fac.MH_dot}}, 132 {{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, eek, Fac.MH_pred, Fac.MH_fin}, {null, Fac.MH_dot}} 133 }; 134 String[] messages = { 135 "null or no clauses passed", 136 "null or no clauses passed", 137 "All loop clauses must be represented as MethodHandle arrays with at most 4 elements.", 138 "null clauses are not allowed", 139 "clause 0: init and step return types must match: int != void", 140 "found non-effectively identical init parameter type lists: " + inits + " (common suffix: " + ints + ")", 141 "found non-identical finalizer return types: " + finis + " (return type: int)", 142 "no predicate found: " + preds1, 143 "predicates must have boolean return type: " + preds2, 144 "found non-effectively identical parameter type lists:\nstep: " + nesteps + "\npred: " + nepreds + 145 "\nfini: " + nefinis + " (common parameter sequence: " + ints + ")" 146 }; 147 for (int i = 0; i < cases.length; ++i) { 148 boolean caught = false; 149 try { 150 mh_loop.invokeWithArguments(cases[i]); 151 } catch (IllegalArgumentException iae) { 152 assertEquals(messages[i], iae.getMessage()); 153 caught = true; 154 } 155 assertTrue(caught); 156 } 157 } 158 159 @Test 160 public static void testWhileLoop() throws Throwable { 161 // int i = 0; while (i < limit) { ++i; } return i; => limit 162 MethodHandle loop = MethodHandles.whileLoop(While.MH_zero, While.MH_pred, While.MH_step); 163 assertEquals(While.MT_while, loop.type()); 164 assertEquals(23, loop.invoke(23)); 165 } 166 167 @Test 168 public static void testWhileLoopNoIteration() throws Throwable { 169 // a while loop that never executes its body because the predicate evaluates to false immediately 170 MethodHandle loop = MethodHandles.whileLoop(While.MH_initString, While.MH_predString, While.MH_stepString); 171 assertEquals(While.MT_string, loop.type()); 172 assertEquals("a", loop.invoke()); 173 } 174 175 @Test 176 public static void testDoWhileLoop() throws Throwable { 177 // int i = 0; do { ++i; } while (i < limit); return i; => limit 178 MethodHandle loop = MethodHandles.doWhileLoop(While.MH_zero, While.MH_step, While.MH_pred); 179 assertEquals(While.MT_while, loop.type()); 180 assertEquals(23, loop.invoke(23)); 181 } 182 183 @Test 184 public static void testWhileZip() throws Throwable { 185 MethodHandle loop = MethodHandles.doWhileLoop(While.MH_zipInitZip, While.MH_zipStep, While.MH_zipPred); 186 assertEquals(While.MT_zip, loop.type()); 187 List<String> a = Arrays.asList("a", "b", "c", "d"); 188 List<String> b = Arrays.asList("e", "f", "g", "h"); 189 List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 190 assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 191 } 192 193 @Test 194 public static void testCountedLoop() throws Throwable { 195 // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; => a variation on a well known theme 196 MethodHandle fit13 = MethodHandles.constant(int.class, 13); 197 MethodHandle loop = MethodHandles.countedLoop(fit13, Counted.MH_start, Counted.MH_step); 198 assertEquals(Counted.MT_counted, loop.type()); 199 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 200 } 201 202 @Test 203 public static void testCountedArrayLoop() throws Throwable { 204 // int[] a = new int[]{0}; for (int i = 0; i < 13; ++i) { ++a[0]; } => a[0] == 13 205 MethodHandle fit13 = MethodHandles.dropArguments(MethodHandles.constant(int.class, 13), 0, int[].class); 206 MethodHandle loop = MethodHandles.countedLoop(fit13, null, Counted.MH_stepUpdateArray); 207 assertEquals(Counted.MT_arrayCounted, loop.type()); 208 int[] a = new int[]{0}; 209 loop.invoke(a); 210 assertEquals(13, a[0]); 211 } 212 213 @Test 214 public static void testCountedPrintingLoop() throws Throwable { 215 MethodHandle fit5 = MethodHandles.constant(int.class, 5); 216 MethodHandle loop = MethodHandles.countedLoop(fit5, null, Counted.MH_printHello); 217 assertEquals(Counted.MT_countedPrinting, loop.type()); 218 loop.invoke(); 219 } 220 221 @Test 222 public static void testCountedRangeLoop() throws Throwable { 223 // String s = "Lambdaman!"; for (int i = -5; i < 8; ++i) { s = "na " + s; } return s; => a well known theme 224 MethodHandle fitm5 = MethodHandles.dropArguments(Counted.MH_m5, 0, String.class); 225 MethodHandle fit8 = MethodHandles.dropArguments(Counted.MH_8, 0, String.class); 226 MethodHandle loop = MethodHandles.countedLoop(fitm5, fit8, Counted.MH_start, Counted.MH_step); 227 assertEquals(Counted.MT_counted, loop.type()); 228 assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 229 } 230 231 @Test 232 public static void testIterateSum() throws Throwable { 233 // Integer[] a = new Integer[]{1,2,3,4,5,6}; int sum = 0; for (int e : a) { sum += e; } return sum; => 21 234 MethodHandle loop = MethodHandles.iteratedLoop(Iterate.MH_sumIterator, Iterate.MH_sumInit, Iterate.MH_sumStep); 235 assertEquals(Iterate.MT_sum, loop.type()); 236 assertEquals(21, loop.invoke(new Integer[]{1, 2, 3, 4, 5, 6})); 237 } 238 239 @Test 240 public static void testIterateReverse() throws Throwable { 241 MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_reverseInit, Iterate.MH_reverseStep); 242 assertEquals(Iterate.MT_reverse, loop.type()); 243 List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 244 List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 245 assertEquals(reversedList, (List<String>) loop.invoke(list)); 246 } 247 248 @Test 249 public static void testIterateLength() throws Throwable { 250 MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_lengthInit, Iterate.MH_lengthStep); 251 assertEquals(Iterate.MT_length, loop.type()); 252 List<Double> list = Arrays.asList(23.0, 148.0, 42.0); 253 assertEquals(list.size(), (int) loop.invoke(list)); 254 } 255 256 @Test 257 public static void testIterateMap() throws Throwable { 258 MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_mapInit, Iterate.MH_mapStep); 259 assertEquals(Iterate.MT_map, loop.type()); 260 List<String> list = Arrays.asList("Hello", "world", "!"); 261 List<String> upList = Arrays.asList("HELLO", "WORLD", "!"); 262 assertEquals(upList, (List<String>) loop.invoke(list)); 263 } 264 265 @Test 266 public static void testIteratePrint() throws Throwable { 267 MethodHandle loop = MethodHandles.iteratedLoop(null, null, Iterate.MH_printStep); 268 assertEquals(Iterate.MT_print, loop.type()); 269 loop.invoke(Arrays.asList("hello", "world")); 270 } 271 272 @Test 273 public static void testIterateNullBody() { 274 boolean caught = false; 275 try { 276 MethodHandles.iteratedLoop(MethodHandles.identity(int.class), MethodHandles.identity(int.class), null); 277 } catch (IllegalArgumentException iae) { 278 assertEquals("iterated loop body must not be null", iae.getMessage()); 279 caught = true; 280 } 281 assertTrue(caught); 282 } 283 284 @Test 285 public static void testTryFinally() throws Throwable { 286 MethodHandle hello = MethodHandles.tryFinally(TryFinally.MH_greet, TryFinally.MH_exclaim); 287 assertEquals(TryFinally.MT_hello, hello.type()); 288 assertEquals("Hello, world!", hello.invoke("world")); 289 } 290 291 @Test 292 public static void testTryFinallyVoid() throws Throwable { 293 MethodHandle tfVoid = MethodHandles.tryFinally(TryFinally.MH_print, TryFinally.MH_printMore); 294 assertEquals(TryFinally.MT_printHello, tfVoid.type()); 295 tfVoid.invoke("world"); 296 } 297 298 @Test 299 public static void testTryFinallySublist() throws Throwable { 300 MethodHandle helloMore = MethodHandles.tryFinally(TryFinally.MH_greetMore, TryFinally.MH_exclaimMore); 301 assertEquals(TryFinally.MT_moreHello, helloMore.type()); 302 assertEquals("Hello, world and universe (but world first)!", helloMore.invoke("world", "universe")); 303 } 304 305 @Test 306 public static void testTryFinallyNegative() { 307 MethodHandle intid = MethodHandles.identity(int.class); 308 MethodHandle intco = MethodHandles.constant(int.class, 0); 309 MethodHandle errTarget = MethodHandles.dropArguments(intco, 0, int.class, double.class, String.class, int.class); 310 MethodHandle errCleanup = MethodHandles.dropArguments(MethodHandles.constant(int.class, 0), 0, Throwable.class, 311 int.class, double.class, Object.class); 312 MethodHandle[][] cases = { 313 {intid, MethodHandles.identity(double.class)}, 314 {intid, MethodHandles.dropArguments(intid, 0, String.class)}, 315 {intid, MethodHandles.dropArguments(intid, 0, Throwable.class, double.class)}, 316 {errTarget, errCleanup} 317 }; 318 String[] messages = { 319 "target and return types must match: double != int", 320 "cleanup first argument and Throwable must match: (String,int)int != class java.lang.Throwable", 321 "cleanup second argument and target return type must match: (Throwable,double,int)int != int", 322 "cleanup parameters after (Throwable,result) and target parameter list prefix must match: " + 323 errCleanup.type() + " != " + errTarget.type() 324 }; 325 for (int i = 0; i < cases.length; ++i) { 326 boolean caught = false; 327 try { 328 MethodHandles.tryFinally(cases[i][0], cases[i][1]); 329 } catch (IllegalArgumentException iae) { 330 assertEquals(messages[i], iae.getMessage()); 331 caught = true; 332 } 333 assertTrue(caught); 334 } 335 } 336 337 @Test 338 public static void testFold0a() throws Throwable { 339 // equivalence to foldArguments(MethodHandle,MethodHandle) 340 MethodHandle fold = MethodHandles.foldArguments(Fold.MH_multer, 0, Fold.MH_adder); 341 assertEquals(Fold.MT_folded1, fold.type()); 342 assertEquals(720, (int) fold.invoke(3, 4, 5)); 343 } 344 345 @Test 346 public static void testFold1a() throws Throwable { 347 // test foldArguments for folding position 1 348 MethodHandle fold = MethodHandles.foldArguments(Fold.MH_multer, 1, Fold.MH_adder1); 349 assertEquals(Fold.MT_folded1, fold.type()); 350 assertEquals(540, (int) fold.invoke(3, 4, 5)); 351 } 352 353 @Test 354 public static void testFold0b() throws Throwable { 355 // test foldArguments equivalence with multiple types 356 MethodHandle fold = MethodHandles.foldArguments(Fold.MH_str, 0, Fold.MH_comb); 357 assertEquals(Fold.MT_folded2, fold.type()); 358 assertEquals(23, (int) fold.invoke("true", true, 23)); 359 } 360 361 @Test 362 public static void testFold1b() throws Throwable { 363 // test folgArguments for folding position 1, with multiple types 364 MethodHandle fold = MethodHandles.foldArguments(Fold.MH_str, 1, Fold.MH_comb2); 365 assertEquals(Fold.MT_folded3, fold.type()); 366 assertEquals(1, (int) fold.invoke(true, true, 1)); 367 assertEquals(-1, (int) fold.invoke(true, false, -1)); 368 } 369 370 @Test 371 public static void testFoldArgumentsExample() throws Throwable { 372 // test the JavaDoc foldArguments-with-pos example 373 StringWriter swr = new StringWriter(); 374 MethodHandle trace = LOOKUP.findVirtual(StringWriter.class, "write", methodType(void.class, String.class)).bindTo(swr); 375 MethodHandle cat = LOOKUP.findVirtual(String.class, "concat", methodType(String.class, String.class)); 376 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 377 MethodHandle catTrace = MethodHandles.foldArguments(cat, 1, trace); 378 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 379 assertEquals("jum", swr.toString()); 380 } 381 382 @Test 383 public static void testAsSpreader() throws Throwable { 384 MethodHandle spreader = SpreadCollect.MH_forSpreading.asSpreader(1, int[].class, 3); 385 assertEquals(SpreadCollect.MT_spreader, spreader.type()); 386 assertEquals("A456B", (String) spreader.invoke("A", new int[]{4, 5, 6}, "B")); 387 } 388 389 @Test 390 public static void testAsSpreaderExample() throws Throwable { 391 // test the JavaDoc asSpreader-with-pos example 392 MethodHandle compare = LOOKUP.findStatic(Objects.class, "compare", methodType(int.class, Object.class, Object.class, Comparator.class)); 393 MethodHandle compare2FromArray = compare.asSpreader(0, Object[].class, 2); 394 Object[] ints = new Object[]{3, 9, 7, 7}; 395 Comparator<Integer> cmp = (a, b) -> a - b; 396 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 0, 2), cmp) < 0); 397 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 1, 3), cmp) > 0); 398 assertTrue((int) compare2FromArray.invoke(Arrays.copyOfRange(ints, 2, 4), cmp) == 0); 399 } 400 401 @Test 402 public static void testAsSpreaderIllegalPos() throws Throwable { 403 int[] illegalPos = {-7, 3, 19}; 404 int caught = 0; 405 for (int p : illegalPos) { 406 try { 407 SpreadCollect.MH_forSpreading.asSpreader(p, Object[].class, 3); 408 } catch (IllegalArgumentException iae) { 409 assertEquals("bad spread position", iae.getMessage()); 410 ++caught; 411 } 412 } 413 assertEquals(illegalPos.length, caught); 414 } 415 416 @Test 417 public static void testAsSpreaderIllegalMethodType() throws Throwable { 418 MethodHandle h = MethodHandles.dropArguments(MethodHandles.constant(String.class, ""), 0, int.class, int.class); 419 boolean caught = false; 420 try { 421 MethodHandle s = h.asSpreader(String[].class, 1); 422 } catch (WrongMethodTypeException wmte) { 423 caught = true; 424 } 425 assertTrue(caught); 426 } 427 428 @Test 429 public static void testAsCollector() throws Throwable { 430 MethodHandle collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 1); 431 assertEquals(SpreadCollect.MT_collector1, collector.type()); 432 assertEquals("A4B", (String) collector.invoke("A", 4, "B")); 433 collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 2); 434 assertEquals(SpreadCollect.MT_collector2, collector.type()); 435 assertEquals("A45B", (String) collector.invoke("A", 4, 5, "B")); 436 collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 3); 437 assertEquals(SpreadCollect.MT_collector3, collector.type()); 438 assertEquals("A456B", (String) collector.invoke("A", 4, 5, 6, "B")); 439 } 440 441 @Test 442 public static void testAsCollectorInvokeWithArguments() throws Throwable { 443 MethodHandle collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 1); 444 assertEquals(SpreadCollect.MT_collector1, collector.type()); 445 assertEquals("A4B", (String) collector.invokeWithArguments("A", 4, "B")); 446 collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 2); 447 assertEquals(SpreadCollect.MT_collector2, collector.type()); 448 assertEquals("A45B", (String) collector.invokeWithArguments("A", 4, 5, "B")); 449 collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 3); 450 assertEquals(SpreadCollect.MT_collector3, collector.type()); 451 assertEquals("A456B", (String) collector.invokeWithArguments("A", 4, 5, 6, "B")); 452 } 453 454 @Test 455 public static void testAsCollectorLeading() throws Throwable { 456 MethodHandle collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 1); 457 assertEquals(SpreadCollect.MT_collectorLeading1, collector.type()); 458 assertEquals("7Q", (String) collector.invoke(7, "Q")); 459 collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 2); 460 assertEquals(SpreadCollect.MT_collectorLeading2, collector.type()); 461 assertEquals("78Q", (String) collector.invoke(7, 8, "Q")); 462 collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 3); 463 assertEquals(SpreadCollect.MT_collectorLeading3, collector.type()); 464 assertEquals("789Q", (String) collector.invoke(7, 8, 9, "Q")); 465 } 466 467 @Test 468 public static void testAsCollectorLeadingInvokeWithArguments() throws Throwable { 469 MethodHandle collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 1); 470 assertEquals(SpreadCollect.MT_collectorLeading1, collector.type()); 471 assertEquals("7Q", (String) collector.invokeWithArguments(7, "Q")); 472 collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 2); 473 assertEquals(SpreadCollect.MT_collectorLeading2, collector.type()); 474 assertEquals("78Q", (String) collector.invokeWithArguments(7, 8, "Q")); 475 collector = SpreadCollect.MH_forCollectingLeading.asCollector(0, int[].class, 3); 476 assertEquals(SpreadCollect.MT_collectorLeading3, collector.type()); 477 assertEquals("789Q", (String) collector.invokeWithArguments(7, 8, 9, "Q")); 478 } 479 480 @Test 481 public static void testAsCollectorNone() throws Throwable { 482 MethodHandle collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 0); 483 assertEquals(SpreadCollect.MT_collector0, collector.type()); 484 assertEquals("AB", (String) collector.invoke("A", "B")); 485 } 486 487 @Test 488 public static void testAsCollectorIllegalPos() throws Throwable { 489 int[] illegalPos = {-1, 17}; 490 int caught = 0; 491 for (int p : illegalPos) { 492 try { 493 SpreadCollect.MH_forCollecting.asCollector(p, int[].class, 0); 494 } catch (IllegalArgumentException iae) { 495 assertEquals("bad collect position", iae.getMessage()); 496 ++caught; 497 } 498 } 499 assertEquals(illegalPos.length, caught); 500 } 501 502 @Test 503 public static void testAsCollectorExample() throws Throwable { 504 // test the JavaDoc asCollector-with-pos example 505 StringWriter swr = new StringWriter(); 506 MethodHandle swWrite = LOOKUP. 507 findVirtual(StringWriter.class, "write", methodType(void.class, char[].class, int.class, int.class)). 508 bindTo(swr); 509 MethodHandle swWrite4 = swWrite.asCollector(0, char[].class, 4); 510 swWrite4.invoke('A', 'B', 'C', 'D', 1, 2); 511 assertEquals("BC", swr.toString()); 512 swWrite4.invoke('P', 'Q', 'R', 'S', 0, 4); 513 assertEquals("BCPQRS", swr.toString()); 514 swWrite4.invoke('W', 'X', 'Y', 'Z', 3, 1); 515 assertEquals("BCPQRSZ", swr.toString()); 516 } 517 518 @Test 519 public static void testFindSpecial() throws Throwable { 520 FindSpecial.C c = new FindSpecial.C(); 521 assertEquals("I1.m", c.m()); 522 MethodType t = MethodType.methodType(String.class); 523 MethodHandle ci1m = LOOKUP.findSpecial(FindSpecial.I1.class, "m", t, FindSpecial.C.class); 524 assertEquals("I1.m", (String) ci1m.invoke(c)); 525 } 526 527 @Test 528 public static void testFindSpecialAbstract() throws Throwable { 529 FindSpecial.C c = new FindSpecial.C(); 530 assertEquals("q", c.q()); 531 MethodType t = MethodType.methodType(String.class); 532 boolean caught = false; 533 try { 534 MethodHandle ci3q = LOOKUP.findSpecial(FindSpecial.I3.class, "q", t, FindSpecial.C.class); 535 } catch (Throwable thrown) { 536 if (!(thrown instanceof IllegalAccessException) || !FindSpecial.ABSTRACT_ERROR.equals(thrown.getMessage())) { 537 throw new AssertionError(thrown.getMessage(), thrown); 538 } 539 caught = true; 540 } 541 assertTrue(caught); 542 } 543 544 @Test 545 public static void testFindClassCNFE() throws Throwable { 546 boolean caught = false; 547 try { 548 LOOKUP.findClass("does.not.Exist"); 549 } catch (ClassNotFoundException cnfe) { 550 caught = true; 551 } 552 assertTrue(caught); 553 } 554 555 // 556 // Methods used to assemble tests. 557 // 558 559 static class Empty { 560 561 static void f() { } 562 563 static boolean pred() { 564 return false; 565 } 566 567 static final Class<Empty> EMPTY = Empty.class; 568 569 static final MethodType MT_f = methodType(void.class); 570 static final MethodType MT_pred = methodType(boolean.class); 571 572 static final MethodHandle MH_f; 573 static final MethodHandle MH_pred; 574 575 static { 576 try { 577 MH_f = LOOKUP.findStatic(EMPTY, "f", MT_f); 578 MH_pred = LOOKUP.findStatic(EMPTY, "pred", MT_pred); 579 } catch (Exception e) { 580 throw new ExceptionInInitializerError(e); 581 } 582 } 583 } 584 585 static class Fac { 586 587 static int zero(int k) { 588 return 0; 589 } 590 591 static int one(int k) { 592 return 1; 593 } 594 595 static boolean pred(int i, int acc, int k) { 596 return i < k; 597 } 598 599 static int inc(int i, int acc, int k) { 600 return i + 1; 601 } 602 603 static int mult(int i, int acc, int k) { 604 return i * acc; 605 } 606 607 static void dot(int i, int acc, int k) { 608 System.out.print('.'); 609 } 610 611 static int fin(int i, int acc, int k) { 612 return acc; 613 } 614 615 static final Class<Fac> FAC = Fac.class; 616 617 static final MethodType MT_init = methodType(int.class, int.class); 618 static final MethodType MT_fn = methodType(int.class, int.class, int.class, int.class); 619 static final MethodType MT_dot = methodType(void.class, int.class, int.class, int.class); 620 static final MethodType MT_pred = methodType(boolean.class, int.class, int.class, int.class); 621 622 static final MethodHandle MH_zero; 623 static final MethodHandle MH_one; 624 static final MethodHandle MH_pred; 625 static final MethodHandle MH_inc; 626 static final MethodHandle MH_mult; 627 static final MethodHandle MH_dot; 628 static final MethodHandle MH_fin; 629 630 static final MethodType MT_fac = methodType(int.class, int.class); 631 632 static { 633 try { 634 MH_zero = LOOKUP.findStatic(FAC, "zero", MT_init); 635 MH_one = LOOKUP.findStatic(FAC, "one", MT_init); 636 MH_pred = LOOKUP.findStatic(FAC, "pred", MT_pred); 637 MH_inc = LOOKUP.findStatic(FAC, "inc", MT_fn); 638 MH_mult = LOOKUP.findStatic(FAC, "mult", MT_fn); 639 MH_dot = LOOKUP.findStatic(FAC, "dot", MT_dot); 640 MH_fin = LOOKUP.findStatic(FAC, "fin", MT_fn); 641 } catch (Exception e) { 642 throw new ExceptionInInitializerError(e); 643 } 644 } 645 646 } 647 648 static class While { 649 650 static int zero(int limit) { 651 return 0; 652 } 653 654 static boolean pred(int i, int limit) { 655 return i < limit; 656 } 657 658 static int step(int i, int limit) { 659 return i + 1; 660 } 661 662 static String initString() { 663 return "a"; 664 } 665 666 static boolean predString(String s) { 667 return s.length() != 1; 668 } 669 670 static String stepString(String s) { 671 return s + "a"; 672 } 673 674 static List<String> zipInitZip(Iterator<String> a, Iterator<String> b) { 675 return new ArrayList<>(); 676 } 677 678 static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { 679 return a.hasNext() && b.hasNext(); 680 } 681 682 static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 683 zip.add(a.next()); 684 zip.add(b.next()); 685 return zip; 686 } 687 688 static final Class<While> WHILE = While.class; 689 690 static final MethodType MT_zero = methodType(int.class, int.class); 691 static final MethodType MT_pred = methodType(boolean.class, int.class, int.class); 692 static final MethodType MT_fn = methodType(int.class, int.class, int.class); 693 static final MethodType MT_initString = methodType(String.class); 694 static final MethodType MT_predString = methodType(boolean.class, String.class); 695 static final MethodType MT_stepString = methodType(String.class, String.class); 696 static final MethodType MT_zipInitZip = methodType(List.class, Iterator.class, Iterator.class); 697 static final MethodType MT_zipPred = methodType(boolean.class, List.class, Iterator.class, Iterator.class); 698 static final MethodType MT_zipStep = methodType(List.class, List.class, Iterator.class, Iterator.class); 699 700 static final MethodHandle MH_zero; 701 static final MethodHandle MH_pred; 702 static final MethodHandle MH_step; 703 static final MethodHandle MH_initString; 704 static final MethodHandle MH_predString; 705 static final MethodHandle MH_stepString; 706 static final MethodHandle MH_zipInitZip; 707 static final MethodHandle MH_zipPred; 708 static final MethodHandle MH_zipStep; 709 710 static final MethodType MT_while = methodType(int.class, int.class); 711 static final MethodType MT_string = methodType(String.class); 712 static final MethodType MT_zip = methodType(List.class, Iterator.class, Iterator.class); 713 714 static { 715 try { 716 MH_zero = LOOKUP.findStatic(WHILE, "zero", MT_zero); 717 MH_pred = LOOKUP.findStatic(WHILE, "pred", MT_pred); 718 MH_step = LOOKUP.findStatic(WHILE, "step", MT_fn); 719 MH_initString = LOOKUP.findStatic(WHILE, "initString", MT_initString); 720 MH_predString = LOOKUP.findStatic(WHILE, "predString", MT_predString); 721 MH_stepString = LOOKUP.findStatic(WHILE, "stepString", MT_stepString); 722 MH_zipInitZip = LOOKUP.findStatic(WHILE, "zipInitZip", MT_zipInitZip); 723 MH_zipPred = LOOKUP.findStatic(WHILE, "zipPred", MT_zipPred); 724 MH_zipStep = LOOKUP.findStatic(WHILE, "zipStep", MT_zipStep); 725 } catch (Exception e) { 726 throw new ExceptionInInitializerError(e); 727 } 728 } 729 730 } 731 732 static class Counted { 733 734 static String start(String arg) { 735 return arg; 736 } 737 738 static String step(int counter, String v, String arg) { 739 return "na " + v; 740 } 741 742 static void stepUpdateArray(int counter, int[] a) { 743 ++a[0]; 744 } 745 746 static void printHello(int counter) { 747 System.out.print("hello"); 748 } 749 750 static final Class<Counted> COUNTED = Counted.class; 751 752 static final MethodType MT_start = methodType(String.class, String.class); 753 static final MethodType MT_step = methodType(String.class, int.class, String.class, String.class); 754 static final MethodType MT_stepUpdateArray = methodType(void.class, int.class, int[].class); 755 static final MethodType MT_printHello = methodType(void.class, int.class); 756 757 static final MethodHandle MH_13; 758 static final MethodHandle MH_m5; 759 static final MethodHandle MH_8; 760 static final MethodHandle MH_start; 761 static final MethodHandle MH_step; 762 static final MethodHandle MH_stepUpdateArray; 763 static final MethodHandle MH_printHello; 764 765 static final MethodType MT_counted = methodType(String.class, String.class); 766 static final MethodType MT_arrayCounted = methodType(void.class, int[].class); 767 static final MethodType MT_countedPrinting = methodType(void.class); 768 769 static { 770 try { 771 MH_13 = MethodHandles.constant(int.class, 13); 772 MH_m5 = MethodHandles.constant(int.class, -5); 773 MH_8 = MethodHandles.constant(int.class, 8); 774 MH_start = LOOKUP.findStatic(COUNTED, "start", MT_start); 775 MH_step = LOOKUP.findStatic(COUNTED, "step", MT_step); 776 MH_stepUpdateArray = LOOKUP.findStatic(COUNTED, "stepUpdateArray", MT_stepUpdateArray); 777 MH_printHello = LOOKUP.findStatic(COUNTED, "printHello", MT_printHello); 778 } catch (Exception e) { 779 throw new ExceptionInInitializerError(e); 780 } 781 } 782 783 } 784 785 static class Iterate { 786 787 static Iterator<Integer> sumIterator(Integer[] a) { 788 return Arrays.asList(a).iterator(); 789 } 790 791 static int sumInit(Integer[] a) { 792 return 0; 793 } 794 795 static int sumStep(int s, int e, Integer[] a) { 796 return s + e; 797 } 798 799 static List<String> reverseInit(List<String> l) { 800 return new ArrayList<>(); 801 } 802 803 static List<String> reverseStep(String e, List<String> r, List<String> l) { 804 r.add(0, e); 805 return r; 806 } 807 808 static int lengthInit(List<Double> l) { 809 return 0; 810 } 811 812 static int lengthStep(Object o, int len, List<Double> l) { 813 return len + 1; 814 } 815 816 static List<String> mapInit(List<String> l) { 817 return new ArrayList<>(); 818 } 819 820 static List<String> mapStep(String e, List<String> r, List<String> l) { 821 r.add(e.toUpperCase()); 822 return r; 823 } 824 825 static void printStep(String s, List<String> l) { 826 System.out.print(s); 827 } 828 829 static final Class<Iterate> ITERATE = Iterate.class; 830 831 static final MethodType MT_sumIterator = methodType(Iterator.class, Integer[].class); 832 833 static final MethodType MT_sumInit = methodType(int.class, Integer[].class); 834 static final MethodType MT_reverseInit = methodType(List.class, List.class); 835 static final MethodType MT_lenghInit = methodType(int.class, List.class); 836 static final MethodType MT_mapInit = methodType(List.class, List.class); 837 838 static final MethodType MT_sumStep = methodType(int.class, int.class, int.class, Integer[].class); 839 static final MethodType MT_reverseStep = methodType(List.class, String.class, List.class, List.class); 840 static final MethodType MT_lengthStep = methodType(int.class, Object.class, int.class, List.class); 841 static final MethodType MT_mapStep = methodType(List.class, String.class, List.class, List.class); 842 static final MethodType MT_printStep = methodType(void.class, String.class, List.class); 843 844 static final MethodHandle MH_sumIterator; 845 static final MethodHandle MH_sumInit; 846 static final MethodHandle MH_sumStep; 847 static final MethodHandle MH_printStep; 848 849 static final MethodHandle MH_reverseInit; 850 static final MethodHandle MH_reverseStep; 851 852 static final MethodHandle MH_lengthInit; 853 static final MethodHandle MH_lengthStep; 854 855 static final MethodHandle MH_mapInit; 856 static final MethodHandle MH_mapStep; 857 858 static final MethodType MT_sum = methodType(int.class, Integer[].class); 859 static final MethodType MT_reverse = methodType(List.class, List.class); 860 static final MethodType MT_length = methodType(int.class, List.class); 861 static final MethodType MT_map = methodType(List.class, List.class); 862 static final MethodType MT_print = methodType(void.class, List.class); 863 864 static { 865 try { 866 MH_sumIterator = LOOKUP.findStatic(ITERATE, "sumIterator", MT_sumIterator); 867 MH_sumInit = LOOKUP.findStatic(ITERATE, "sumInit", MT_sumInit); 868 MH_sumStep = LOOKUP.findStatic(ITERATE, "sumStep", MT_sumStep); 869 MH_reverseInit = LOOKUP.findStatic(ITERATE, "reverseInit", MT_reverseInit); 870 MH_reverseStep = LOOKUP.findStatic(ITERATE, "reverseStep", MT_reverseStep); 871 MH_lengthInit = LOOKUP.findStatic(ITERATE, "lengthInit", MT_lenghInit); 872 MH_lengthStep = LOOKUP.findStatic(ITERATE, "lengthStep", MT_lengthStep); 873 MH_mapInit = LOOKUP.findStatic(ITERATE, "mapInit", MT_mapInit); 874 MH_mapStep = LOOKUP.findStatic(ITERATE, "mapStep", MT_mapStep); 875 MH_printStep = LOOKUP.findStatic(ITERATE, "printStep", MT_printStep); 876 } catch (Exception e) { 877 throw new ExceptionInInitializerError(e); 878 } 879 } 880 881 } 882 883 static class TryFinally { 884 885 static String greet(String whom) { 886 return "Hello, " + whom; 887 } 888 889 static String exclaim(Throwable t, String r, String whom) { 890 return r + "!"; 891 } 892 893 static void print(String what) { 894 System.out.print("Hello, " + what); 895 } 896 897 static void printMore(Throwable t, String what) { 898 System.out.println("!"); 899 } 900 901 static String greetMore(String first, String second) { 902 return "Hello, " + first + " and " + second; 903 } 904 905 static String exclaimMore(Throwable t, String r, String first) { 906 return r + " (but " + first + " first)!"; 907 } 908 909 static final Class<TryFinally> TRY_FINALLY = TryFinally.class; 910 911 static final MethodType MT_greet = methodType(String.class, String.class); 912 static final MethodType MT_exclaim = methodType(String.class, Throwable.class, String.class, String.class); 913 static final MethodType MT_print = methodType(void.class, String.class); 914 static final MethodType MT_printMore = methodType(void.class, Throwable.class, String.class); 915 static final MethodType MT_greetMore = methodType(String.class, String.class, String.class); 916 static final MethodType MT_exclaimMore = methodType(String.class, Throwable.class, String.class, String.class); 917 918 static final MethodHandle MH_greet; 919 static final MethodHandle MH_exclaim; 920 static final MethodHandle MH_print; 921 static final MethodHandle MH_printMore; 922 static final MethodHandle MH_greetMore; 923 static final MethodHandle MH_exclaimMore; 924 925 static final MethodType MT_hello = methodType(String.class, String.class); 926 static final MethodType MT_printHello = methodType(void.class, String.class); 927 static final MethodType MT_moreHello = methodType(String.class, String.class, String.class); 928 929 static { 930 try { 931 MH_greet = LOOKUP.findStatic(TRY_FINALLY, "greet", MT_greet); 932 MH_exclaim = LOOKUP.findStatic(TRY_FINALLY, "exclaim", MT_exclaim); 933 MH_print = LOOKUP.findStatic(TRY_FINALLY, "print", MT_print); 934 MH_printMore = LOOKUP.findStatic(TRY_FINALLY, "printMore", MT_printMore); 935 MH_greetMore = LOOKUP.findStatic(TRY_FINALLY, "greetMore", MT_greetMore); 936 MH_exclaimMore = LOOKUP.findStatic(TRY_FINALLY, "exclaimMore", MT_exclaimMore); 937 } catch (Exception e) { 938 throw new ExceptionInInitializerError(e); 939 } 940 } 941 942 } 943 944 static class Fold { 945 946 static int adder(int a, int b, int c) { 947 return a + b + c; 948 } 949 950 static int adder1(int a, int b) { 951 return a + b; 952 } 953 954 static int multer(int x, int q, int r, int s) { 955 return x * q * r * s; 956 } 957 958 static int str(boolean b1, String s, boolean b2, int x) { 959 return b1 && s.equals(String.valueOf(b2)) ? x : -x; 960 } 961 962 static boolean comb(String s, boolean b2) { 963 return !s.equals(b2); 964 } 965 966 static String comb2(boolean b2, int x) { 967 int ib = b2 ? 1 : 0; 968 return ib == x ? "true" : "false"; 969 } 970 971 static final Class<Fold> FOLD = Fold.class; 972 973 static final MethodType MT_adder = methodType(int.class, int.class, int.class, int.class); 974 static final MethodType MT_adder1 = methodType(int.class, int.class, int.class); 975 static final MethodType MT_multer = methodType(int.class, int.class, int.class, int.class, int.class); 976 static final MethodType MT_str = methodType(int.class, boolean.class, String.class, boolean.class, int.class); 977 static final MethodType MT_comb = methodType(boolean.class, String.class, boolean.class); 978 static final MethodType MT_comb2 = methodType(String.class, boolean.class, int.class); 979 980 static final MethodHandle MH_adder; 981 static final MethodHandle MH_adder1; 982 static final MethodHandle MH_multer; 983 static final MethodHandle MH_str; 984 static final MethodHandle MH_comb; 985 static final MethodHandle MH_comb2; 986 987 static final MethodType MT_folded1 = methodType(int.class, int.class, int.class, int.class); 988 static final MethodType MT_folded2 = methodType(int.class, String.class, boolean.class, int.class); 989 static final MethodType MT_folded3 = methodType(int.class, boolean.class, boolean.class, int.class); 990 991 static { 992 try { 993 MH_adder = LOOKUP.findStatic(FOLD, "adder", MT_adder); 994 MH_adder1 = LOOKUP.findStatic(FOLD, "adder1", MT_adder1); 995 MH_multer = LOOKUP.findStatic(FOLD, "multer", MT_multer); 996 MH_str = LOOKUP.findStatic(FOLD, "str", MT_str); 997 MH_comb = LOOKUP.findStatic(FOLD, "comb", MT_comb); 998 MH_comb2 = LOOKUP.findStatic(FOLD, "comb2", MT_comb2); 999 } catch (Exception e) { 1000 throw new ExceptionInInitializerError(e); 1001 } 1002 } 1003 } 1004 1005 static class SpreadCollect { 1006 1007 static String forSpreading(String s1, int i1, int i2, int i3, String s2) { 1008 return s1 + i1 + i2 + i3 + s2; 1009 } 1010 1011 static String forCollecting(String s1, int[] is, String s2) { 1012 StringBuilder sb = new StringBuilder(s1); 1013 for (int i : is) { 1014 sb.append(i); 1015 } 1016 return sb.append(s2).toString(); 1017 } 1018 1019 static String forCollectingLeading(int[] is, String s) { 1020 return forCollecting("", is, s); 1021 } 1022 1023 static final Class<SpreadCollect> SPREAD_COLLECT = SpreadCollect.class; 1024 1025 static final MethodType MT_forSpreading = methodType(String.class, String.class, int.class, int.class, int.class, String.class); 1026 static final MethodType MT_forCollecting = methodType(String.class, String.class, int[].class, String.class); 1027 static final MethodType MT_forCollectingLeading = methodType(String.class, int[].class, String.class); 1028 1029 static final MethodHandle MH_forSpreading; 1030 static final MethodHandle MH_forCollecting; 1031 static final MethodHandle MH_forCollectingLeading; 1032 1033 static final MethodType MT_spreader = methodType(String.class, String.class, int[].class, String.class); 1034 static final MethodType MT_collector0 = methodType(String.class, String.class, String.class); 1035 static final MethodType MT_collector1 = methodType(String.class, String.class, int.class, String.class); 1036 static final MethodType MT_collector2 = methodType(String.class, String.class, int.class, int.class, String.class); 1037 static final MethodType MT_collector3 = methodType(String.class, String.class, int.class, int.class, int.class, String.class); 1038 static final MethodType MT_collectorLeading1 = methodType(String.class, int.class, String.class); 1039 static final MethodType MT_collectorLeading2 = methodType(String.class, int.class, int.class, String.class); 1040 static final MethodType MT_collectorLeading3 = methodType(String.class, int.class, int.class, int.class, String.class); 1041 1042 static final String NONE_ERROR = "zero array length in MethodHandle.asCollector"; 1043 1044 static { 1045 try { 1046 MH_forSpreading = LOOKUP.findStatic(SPREAD_COLLECT, "forSpreading", MT_forSpreading); 1047 MH_forCollecting = LOOKUP.findStatic(SPREAD_COLLECT, "forCollecting", MT_forCollecting); 1048 MH_forCollectingLeading = LOOKUP.findStatic(SPREAD_COLLECT, "forCollectingLeading", MT_forCollectingLeading); 1049 } catch (Exception e) { 1050 throw new ExceptionInInitializerError(e); 1051 } 1052 } 1053 1054 } 1055 1056 static class FindSpecial { 1057 1058 interface I1 { 1059 default String m() { 1060 return "I1.m"; 1061 } 1062 } 1063 1064 interface I2 { 1065 default String m() { 1066 return "I2.m"; 1067 } 1068 } 1069 1070 interface I3 { 1071 String q(); 1072 } 1073 1074 static class C implements I1, I2, I3 { 1075 public String m() { 1076 return I1.super.m(); 1077 } 1078 public String q() { 1079 return "q"; 1080 } 1081 } 1082 1083 static final String ABSTRACT_ERROR = "no such method: test.java.lang.invoke.T8139885$FindSpecial$I3.q()String/invokeSpecial"; 1084 1085 } 1086 1087 // 1088 // Auxiliary methods. 1089 // 1090 1091 static MethodHandle[] mha(MethodHandle... mhs) { 1092 return mhs; 1093 } 1094 1095 }