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