1 /*
   2  * Copyright (c) 2015, 2016, 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  * @bug 8139885
  28  * @bug 8150635
  29  * @bug 8150956
  30  * @bug 8150957
  31  * @bug 8152667
  32  * @bug 8153637
  33  * @bug 8154751
  34  * @run testng/othervm -ea -esa test.java.lang.invoke.LoopCombinatorTest
  35  */
  36 
  37 package test.java.lang.invoke;
  38 
  39 import java.lang.invoke.MethodHandle;
  40 import java.lang.invoke.MethodHandles;
  41 import java.lang.invoke.MethodHandles.Lookup;
  42 import java.lang.invoke.MethodType;
  43 import java.util.*;
  44 
  45 import static java.lang.invoke.MethodType.methodType;
  46 
  47 import static org.testng.AssertJUnit.*;
  48 
  49 import org.testng.annotations.*;
  50 
  51 /**
  52  * Tests for the loop combinators introduced in JEP 274.
  53  */
  54 public class LoopCombinatorTest {
  55 
  56     static final Lookup LOOKUP = MethodHandles.lookup();
  57 
  58     @Test
  59     public static void testLoopFac() throws Throwable {
  60         MethodHandle[] counterClause = new MethodHandle[]{Fac.MH_zero, Fac.MH_inc};
  61         MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin};
  62         MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
  63         assertEquals(Fac.MT_fac, loop.type());
  64         assertEquals(120, loop.invoke(5));
  65     }
  66 
  67     @Test
  68     public static void testLoopFacNullInit() throws Throwable {
  69         // null initializer for counter, should initialize to 0
  70         MethodHandle[] counterClause = new MethodHandle[]{null, Fac.MH_inc};
  71         MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin};
  72         MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
  73         assertEquals(Fac.MT_fac, loop.type());
  74         assertEquals(120, loop.invoke(5));
  75     }
  76 
  77     @Test
  78     public static void testLoopNullInit() throws Throwable {
  79         // null initializer for counter, should initialize to 0, one-clause loop
  80         MethodHandle[] counterClause = new MethodHandle[]{null, Loop.MH_inc, Loop.MH_pred, Loop.MH_fin};
  81         MethodHandle loop = MethodHandles.loop(counterClause);
  82         assertEquals(Loop.MT_loop, loop.type());
  83         assertEquals(10, loop.invoke(10));
  84     }
  85 
  86     @Test
  87     public static void testLoopVoid1() throws Throwable {
  88         // construct a post-checked loop that only does one iteration and has a void body and void local state
  89         MethodHandle loop = MethodHandles.loop(new MethodHandle[]{Empty.MH_f, Empty.MH_f, Empty.MH_pred, null});
  90         assertEquals(MethodType.methodType(void.class), loop.type());
  91         loop.invoke();
  92     }
  93 
  94     @Test
  95     public static void testLoopVoid2() throws Throwable {
  96         // construct a post-checked loop that only does one iteration and has a void body and void local state,
  97         // initialized implicitly from the step type
  98         MethodHandle loop = MethodHandles.loop(new MethodHandle[]{null, Empty.MH_f, Empty.MH_pred, null});
  99         assertEquals(MethodType.methodType(void.class), loop.type());
 100         loop.invoke();
 101     }
 102 
 103     @Test
 104     public static void testLoopVoid3() throws Throwable {
 105         // construct a post-checked loop that only does one iteration and has a void body and void local state,
 106         // and that has a void finalizer
 107         MethodHandle loop = MethodHandles.loop(new MethodHandle[]{null, Empty.MH_f, Empty.MH_pred, Empty.MH_f});
 108         assertEquals(MethodType.methodType(void.class), loop.type());
 109         loop.invoke();
 110     }
 111 
 112     @Test
 113     public static void testLoopFacWithVoidState() throws Throwable {
 114         // like testLoopFac, but with additional void state that outputs a dot
 115         MethodHandle[] counterClause = new MethodHandle[]{Fac.MH_zero, Fac.MH_inc};
 116         MethodHandle[] accumulatorClause = new MethodHandle[]{Fac.MH_one, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin};
 117         MethodHandle[] dotClause = new MethodHandle[]{null, Fac.MH_dot};
 118         MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause, dotClause);
 119         assertEquals(Fac.MT_fac, loop.type());
 120         assertEquals(120, loop.invoke(5));
 121     }
 122 
 123     @Test
 124     public static void testLoopVoidInt() throws Throwable {
 125         // construct a post-checked loop that only does one iteration and has a void body and void local state,
 126         // and that returns a constant
 127         MethodHandle loop = MethodHandles.loop(new MethodHandle[]{null, Empty.MH_f, Empty.MH_pred, Empty.MH_c});
 128         assertEquals(MethodType.methodType(int.class), loop.type());
 129         assertEquals(23, loop.invoke());
 130     }
 131 
 132     @Test
 133     public static void testLoopWithVirtuals() throws Throwable {
 134         // construct a loop (to calculate factorial) that uses a mix of static and virtual methods
 135         MethodHandle[] counterClause = new MethodHandle[]{null, LoopWithVirtuals.permute(LoopWithVirtuals.MH_inc)};
 136         MethodHandle[] accumulatorClause = new MethodHandle[]{
 137                 // init function must indicate the loop arguments (there is no other means to determine them)
 138                 MethodHandles.dropArguments(LoopWithVirtuals.MH_one, 0, LoopWithVirtuals.class),
 139                 LoopWithVirtuals.permute(LoopWithVirtuals.MH_mult),
 140                 LoopWithVirtuals.permute(LoopWithVirtuals.MH_pred),
 141                 LoopWithVirtuals.permute(LoopWithVirtuals.MH_fin)
 142         };
 143         MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
 144         assertEquals(LoopWithVirtuals.MT_loop, loop.type());
 145         assertEquals(120, loop.invoke(new LoopWithVirtuals(), 5));
 146     }
 147 
 148     @DataProvider
 149     static Object[][] negativeTestData() {
 150         MethodHandle i0 = MethodHandles.constant(int.class, 0);
 151         MethodHandle ii = MethodHandles.dropArguments(i0, 0, int.class, int.class);
 152         MethodHandle id = MethodHandles.dropArguments(i0, 0, int.class, double.class);
 153         MethodHandle i3 = MethodHandles.dropArguments(i0, 0, int.class, int.class, int.class);
 154         List<MethodHandle> inits = Arrays.asList(ii, id, i3);
 155         List<Class<?>> ints = Arrays.asList(int.class, int.class, int.class);
 156         List<MethodHandle> finis = Arrays.asList(Fac.MH_fin, Fac.MH_inc, Counted.MH_step);
 157         List<MethodHandle> preds1 = Arrays.asList(null, null, null);
 158         List<MethodHandle> preds2 = Arrays.asList(null, Fac.MH_fin, null);
 159         MethodHandle eek = MethodHandles.dropArguments(i0, 0, int.class, int.class, double.class);
 160         List<MethodHandle> nesteps = Arrays.asList(Fac.MH_inc, eek, Fac.MH_dot);
 161         List<MethodHandle> nepreds = Arrays.asList(null, Fac.MH_pred, null);
 162         List<MethodHandle> nefinis = Arrays.asList(null, Fac.MH_fin, null);
 163         List<MethodHandle> lvsteps = Arrays.asList(LoopWithVirtuals.MH_inc, LoopWithVirtuals.MH_mult);
 164         List<MethodHandle> lvpreds = Arrays.asList(null, LoopWithVirtuals.MH_pred);
 165         List<MethodHandle> lvfinis = Arrays.asList(null, LoopWithVirtuals.MH_fin);
 166         return new Object[][] {
 167                 {null, "null or no clauses passed"},
 168                 {new MethodHandle[][]{}, "null or no clauses passed"},
 169                 {new MethodHandle[][]{{null, Fac.MH_inc}, {Fac.MH_one, null, Fac.MH_mult, Fac.MH_pred, Fac.MH_fin}},
 170                         "All loop clauses must be represented as MethodHandle arrays with at most 4 elements."},
 171                 {new MethodHandle[][]{{null, Fac.MH_inc}, null}, "null clauses are not allowed"},
 172                 {new MethodHandle[][]{{Fac.MH_zero, Fac.MH_dot}},
 173                         "clause 0: init and step return types must match: int != void"},
 174                 {new MethodHandle[][]{{ii}, {id}, {i3}},
 175                         "found non-effectively identical init parameter type lists: " + inits +
 176                                 " (common suffix: " + ints + ")"},
 177                 {new MethodHandle[][]{{null, Fac.MH_inc, null, Fac.MH_fin}, {null, Fac.MH_inc, null, Fac.MH_inc},
 178                         {null, Counted.MH_start, null, Counted.MH_step}},
 179                         "found non-identical finalizer return types: " + finis + " (return type: int)"},
 180                 {new MethodHandle[][]{{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, Fac.MH_mult, null, Fac.MH_fin},
 181                         {null, Fac.MH_dot}}, "no predicate found: " + preds1},
 182                 {new MethodHandle[][]{{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, Fac.MH_mult, Fac.MH_fin, Fac.MH_fin},
 183                         {null, Fac.MH_dot}}, "predicates must have boolean return type: " + preds2},
 184                 {new MethodHandle[][]{{Fac.MH_zero, Fac.MH_inc}, {Fac.MH_one, eek, Fac.MH_pred, Fac.MH_fin},
 185                         {null, Fac.MH_dot}},
 186                         "found non-effectively identical parameter type lists:\nstep: " + nesteps +
 187                                 "\npred: " + nepreds + "\nfini: " + nefinis + " (common parameter sequence: " + ints + ")"},
 188                 {new MethodHandle[][]{{null, LoopWithVirtuals.MH_inc},
 189                         {LoopWithVirtuals.MH_one, LoopWithVirtuals.MH_mult, LoopWithVirtuals.MH_pred, LoopWithVirtuals.MH_fin}},
 190                         "found non-effectively identical parameter type lists:\nstep: " + lvsteps +
 191                                 "\npred: " + lvpreds + "\nfini: " + lvfinis + " (common parameter sequence: " + ints + ")"}
 192         };
 193     }
 194 
 195     static final MethodHandle MH_loop;
 196 
 197     static {
 198         try {
 199             MH_loop = LOOKUP.findStatic(MethodHandles.class, "loop", methodType(MethodHandle.class, MethodHandle[][].class));
 200         } catch (NoSuchMethodException | IllegalAccessException e) {
 201             throw new ExceptionInInitializerError(e);
 202         }
 203     }
 204 
 205     @Test(dataProvider = "negativeTestData")
 206     public static void testLoopNegative(MethodHandle[][] clauses, String expectedMessage) throws Throwable {
 207         boolean caught = false;
 208         try {
 209             MH_loop.invokeWithArguments(clauses);
 210         } catch (IllegalArgumentException iae) {
 211             assertEquals(expectedMessage, iae.getMessage());
 212             caught = true;
 213         }
 214         assertTrue(caught);
 215     }
 216 
 217     @Test
 218     public static void testWhileLoop() throws Throwable {
 219         // int i = 0; while (i < limit) { ++i; } return i; => limit
 220         MethodHandle loop = MethodHandles.whileLoop(While.MH_zero, While.MH_pred, While.MH_step);
 221         assertEquals(While.MT_while, loop.type());
 222         assertEquals(23, loop.invoke(23));
 223     }
 224 
 225     @Test
 226     public static void testWhileLoopNoIteration() throws Throwable {
 227         // a while loop that never executes its body because the predicate evaluates to false immediately
 228         MethodHandle loop = MethodHandles.whileLoop(While.MH_initString, While.MH_predString, While.MH_stepString);
 229         assertEquals(While.MT_string, loop.type());
 230         assertEquals("a", loop.invoke());
 231     }
 232 
 233     @Test
 234     public static void testDoWhileLoop() throws Throwable {
 235         // int i = 0; do { ++i; } while (i < limit); return i; => limit
 236         MethodHandle loop = MethodHandles.doWhileLoop(While.MH_zero, While.MH_step, While.MH_pred);
 237         assertEquals(While.MT_while, loop.type());
 238         assertEquals(23, loop.invoke(23));
 239     }
 240 
 241     @Test
 242     public static void testDoWhileNullInit() throws Throwable {
 243         While w = new While();
 244         int v = 5;
 245         MethodHandle loop = MethodHandles.doWhileLoop(null, While.MH_voidBody.bindTo(w), While.MH_voidPred.bindTo(w));
 246         assertEquals(While.MT_void, loop.type());
 247         loop.invoke(v);
 248         assertEquals(v, w.i);
 249     }
 250 
 251     @Test
 252     public static void testWhileZip() throws Throwable {
 253         MethodHandle loop = MethodHandles.doWhileLoop(While.MH_zipInitZip, While.MH_zipStep, While.MH_zipPred);
 254         assertEquals(While.MT_zip, loop.type());
 255         List<String> a = Arrays.asList("a", "b", "c", "d");
 256         List<String> b = Arrays.asList("e", "f", "g", "h");
 257         List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
 258         assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
 259     }
 260 
 261     @Test
 262     public static void testWhileNullInit() throws Throwable {
 263         While w = new While();
 264         int v = 5;
 265         MethodHandle loop = MethodHandles.whileLoop(null, While.MH_voidPred.bindTo(w), While.MH_voidBody.bindTo(w));
 266         assertEquals(While.MT_void, loop.type());
 267         loop.invoke(v);
 268         assertEquals(v, w.i);
 269     }
 270 
 271     @Test
 272     public static void testWhileVoidInit() throws Throwable {
 273         While w = new While();
 274         int v = 5;
 275         MethodHandle loop = MethodHandles.whileLoop(While.MH_voidInit.bindTo(w), While.MH_voidPred.bindTo(w),
 276                 While.MH_voidBody.bindTo(w));
 277         assertEquals(While.MT_void, loop.type());
 278         loop.invoke(v);
 279         assertEquals(v, w.i);
 280     }
 281 
 282     @Test
 283     public static void testDoWhileVoidInit() throws Throwable {
 284         While w = new While();
 285         int v = 5;
 286         MethodHandle loop = MethodHandles.doWhileLoop(While.MH_voidInit.bindTo(w), While.MH_voidBody.bindTo(w),
 287                 While.MH_voidPred.bindTo(w));
 288         assertEquals(While.MT_void, loop.type());
 289         loop.invoke(v);
 290         assertEquals(v, w.i);
 291     }
 292 
 293     @Test
 294     public static void testCountedLoop() throws Throwable {
 295         // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; => a variation on a well known theme
 296         MethodHandle fit13 = MethodHandles.constant(int.class, 13);
 297         MethodHandle loop = MethodHandles.countedLoop(fit13, Counted.MH_start, Counted.MH_step);
 298         assertEquals(Counted.MT_counted, loop.type());
 299         assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
 300     }
 301 
 302     @Test
 303     public static void testCountedLoopVoidInit() throws Throwable {
 304         MethodHandle fit5 = MethodHandles.constant(int.class, 5);
 305         MethodHandle loop = MethodHandles.countedLoop(fit5, MethodHandles.zero(void.class), Counted.MH_printHello);
 306         assertEquals(Counted.MT_countedPrinting, loop.type());
 307         loop.invoke();
 308     }
 309 
 310     @Test
 311     public static void testCountedArrayLoop() throws Throwable {
 312         // int[] a = new int[]{0}; for (int i = 0; i < 13; ++i) { ++a[0]; } => a[0] == 13
 313         MethodHandle fit13 = MethodHandles.dropArguments(MethodHandles.constant(int.class, 13), 0, int[].class);
 314         MethodHandle loop = MethodHandles.countedLoop(fit13, null, Counted.MH_stepUpdateArray);
 315         assertEquals(Counted.MT_arrayCounted, loop.type());
 316         int[] a = new int[]{0};
 317         loop.invoke(a);
 318         assertEquals(13, a[0]);
 319     }
 320 
 321     @Test
 322     public static void testCountedPrintingLoop() throws Throwable {
 323         MethodHandle fit5 = MethodHandles.constant(int.class, 5);
 324         MethodHandle loop = MethodHandles.countedLoop(fit5, null, Counted.MH_printHello);
 325         assertEquals(Counted.MT_countedPrinting, loop.type());
 326         loop.invoke();
 327     }
 328 
 329     @Test
 330     public static void testCountedRangeLoop() throws Throwable {
 331         // String s = "Lambdaman!"; for (int i = -5; i < 8; ++i) { s = "na " + s; } return s; => a well known theme
 332         MethodHandle fitm5 = MethodHandles.dropArguments(Counted.MH_m5, 0, String.class);
 333         MethodHandle fit8 = MethodHandles.dropArguments(Counted.MH_8, 0, String.class);
 334         MethodHandle loop = MethodHandles.countedLoop(fitm5, fit8, Counted.MH_start, Counted.MH_step);
 335         assertEquals(Counted.MT_counted, loop.type());
 336         assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
 337     }
 338 
 339     @Test
 340     public static void testCountedLoopCounterInit() throws Throwable {
 341         // int x = 0; for (int i = 0; i < 5; ++i) { x += i; } return x; => 10
 342         // (only if counter's first value in body is 0)
 343         MethodHandle iter = MethodHandles.constant(int.class, 5);
 344         MethodHandle init = MethodHandles.constant(int.class, 0);
 345         MethodHandle body = Counted.MH_addCounter;
 346         MethodHandle loop = MethodHandles.countedLoop(iter, init, body);
 347         assertEquals(Counted.MT_counterInit, loop.type());
 348         assertEquals(10, loop.invoke());
 349     }
 350 
 351     @Test
 352     public static void testCountedLoopEmpty() throws Throwable {
 353         // for (int i = 0; i < 5; ++i) { /* empty */ }
 354         MethodHandle loop = MethodHandles.countedLoop(MethodHandles.constant(int.class, 5), null, null);
 355         assertEquals(methodType(void.class), loop.type());
 356         loop.invoke();
 357     }
 358 
 359     @Test
 360     public static void testCountedRangeLoopEmpty() throws Throwable {
 361         // for (int i = -5; i < 5; ++i) { /* empty */ }
 362         MethodHandle loop = MethodHandles.countedLoop(MethodHandles.constant(int.class, -5),
 363                 MethodHandles.constant(int.class, 5), null, null);
 364         assertEquals(methodType(void.class), loop.type());
 365         loop.invoke();
 366     }
 367 
 368     @Test
 369     public static void testIterateSum() throws Throwable {
 370         // Integer[] a = new Integer[]{1,2,3,4,5,6}; int sum = 0; for (int e : a) { sum += e; } return sum; => 21
 371         MethodHandle loop = MethodHandles.iteratedLoop(Iterate.MH_sumIterator, Iterate.MH_sumInit, Iterate.MH_sumStep);
 372         assertEquals(Iterate.MT_sum, loop.type());
 373         assertEquals(21, loop.invoke(new Integer[]{1, 2, 3, 4, 5, 6}));
 374     }
 375 
 376     @Test
 377     public static void testIterateReverse() throws Throwable {
 378         MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_reverseInit, Iterate.MH_reverseStep);
 379         assertEquals(Iterate.MT_reverse, loop.type());
 380         List<String> list = Arrays.asList("a", "b", "c", "d", "e");
 381         List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
 382         assertEquals(reversedList, (List<String>) loop.invoke(list));
 383     }
 384 
 385     @Test
 386     public static void testIterateLength() throws Throwable {
 387         MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_lengthInit, Iterate.MH_lengthStep);
 388         assertEquals(Iterate.MT_length, loop.type());
 389         List<Double> list = Arrays.asList(23.0, 148.0, 42.0);
 390         assertEquals(list.size(), (int) loop.invoke(list));
 391     }
 392 
 393     @Test
 394     public static void testIterateMap() throws Throwable {
 395         MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_mapInit, Iterate.MH_mapStep);
 396         assertEquals(Iterate.MT_map, loop.type());
 397         List<String> list = Arrays.asList("Hello", "world", "!");
 398         List<String> upList = Arrays.asList("HELLO", "WORLD", "!");
 399         assertEquals(upList, (List<String>) loop.invoke(list));
 400     }
 401 
 402     @Test
 403     public static void testIteratePrint() throws Throwable {
 404         MethodHandle loop = MethodHandles.iteratedLoop(null, null, Iterate.MH_printStep);
 405         assertEquals(Iterate.MT_print, loop.type());
 406         loop.invoke(Arrays.asList("hello", "world"));
 407     }
 408 
 409     @Test
 410     public static void testIterateNullBody() {
 411         boolean caught = false;
 412         try {
 413             MethodHandles.iteratedLoop(MethodHandles.empty(methodType(Iterator.class, int.class)),
 414                     MethodHandles.identity(int.class), null);
 415         } catch (IllegalArgumentException iae) {
 416             assertEquals("iterated loop body must not be null", iae.getMessage());
 417             caught = true;
 418         }
 419         assertTrue(caught);
 420     }
 421 
 422     @DataProvider
 423     static Object[][] wrongIteratorTypes() {
 424         return new Object[][]{{void.class}, {Object.class}, {Iterable.class}};
 425     }
 426 
 427     @Test(dataProvider = "wrongIteratorTypes")
 428     public static void testIterateVoidIterator(Class<?> it) {
 429         boolean caught = false;
 430         MethodType v = methodType(it);
 431         try {
 432             MethodHandles.iteratedLoop(MethodHandles.empty(v), null, MethodHandles.empty(v));
 433         } catch(IllegalArgumentException iae) {
 434             assertEquals("iteratedLoop first argument must have Iterator return type", iae.getMessage());
 435             caught = true;
 436         }
 437         assertTrue(caught);
 438     }
 439 
 440     @Test
 441     public static void testIterateVoidInit() throws Throwable {
 442         MethodHandle loop = MethodHandles.iteratedLoop(null, Iterate.MH_voidInit, Iterate.MH_printStep);
 443         assertEquals(Iterate.MT_print, loop.type());
 444         loop.invoke(Arrays.asList("hello", "world"));
 445     }
 446 
 447     @DataProvider
 448     static Object[][] iterateParameters() {
 449         MethodType i = methodType(int.class);
 450         MethodType sil_i = methodType(int.class, String.class, int.class, List.class);
 451         MethodType sl_v = methodType(void.class, String.class, List.class);
 452         MethodType l_it = methodType(Iterator.class, List.class);
 453         MethodType li_it = methodType(Iterator.class, List.class, int.class);
 454         MethodType l_i = methodType(int.class, List.class);
 455         MethodType _it = methodType(Iterator.class);
 456         MethodType si_i = methodType(int.class, String.class, int.class);
 457         MethodType s_i = methodType(int.class, String.class);
 458         return new Object[][]{
 459                 {null, null, sl_v},
 460                 {null, i, sil_i},
 461                 {null, l_i, sil_i},
 462                 {l_it, null, sl_v},
 463                 {l_it, i, sil_i},
 464                 {li_it, l_i, sil_i},
 465                 {l_it, null, sil_i},
 466                 {li_it, null, sl_v},
 467                 {_it, l_i, si_i},
 468                 {_it, l_i, s_i}
 469         };
 470     }
 471 
 472     @Test(dataProvider = "iterateParameters")
 473     public static void testIterateParameters(MethodType it, MethodType in, MethodType bo) throws Throwable {
 474         MethodHandle iterator = it == null ? null : MethodHandles.empty(it);
 475         MethodHandle init = in == null ? null : MethodHandles.empty(in);
 476         MethodHandle loop = MethodHandles.iteratedLoop(iterator, init, MethodHandles.empty(bo));
 477         MethodType lt = loop.type();
 478         if (it == null && in == null) {
 479             assertEquals(bo.dropParameterTypes(0, 1), lt);
 480         } else if (it == null) {
 481             if (in.parameterCount() == 0) {
 482                 assertEquals(bo.dropParameterTypes(0, in.returnType() == void.class ? 1 : 2), lt);
 483             } else {
 484                 assertEquals(methodType(bo.returnType(), in.parameterArray()), lt);
 485             }
 486         } else if (in == null) {
 487             assertEquals(methodType(bo.returnType(), it.parameterArray()), lt);
 488         } else if (it.parameterCount() > in.parameterCount()) {
 489             assertEquals(methodType(bo.returnType(), it.parameterArray()), lt);
 490         } else if (it.parameterCount() < in.parameterCount()) {
 491             assertEquals(methodType(bo.returnType(), in.parameterArray()), lt);
 492         } else {
 493             // both it, in present; with equal parameter list lengths
 494             assertEquals(it.parameterList(), lt.parameterList());
 495             assertEquals(in.parameterList(), lt.parameterList());
 496             assertEquals(bo.returnType(), lt.returnType());
 497         }
 498     }
 499 
 500     @Test
 501     public static void testIteratorSubclass() throws Throwable {
 502         MethodHandle loop = MethodHandles.iteratedLoop(MethodHandles.empty(methodType(BogusIterator.class, List.class)),
 503                 null, MethodHandles.empty(methodType(void.class, String.class)));
 504         assertEquals(methodType(void.class, List.class), loop.type());
 505     }
 506 
 507     static class BogusIterator implements Iterator {
 508         @Override
 509         public boolean hasNext() {
 510             return false;
 511         }
 512         @Override
 513         public Object next() {
 514             return null;
 515         }
 516     }
 517 
 518     static class Empty {
 519 
 520         static void f() { }
 521 
 522         static boolean pred() {
 523             return false;
 524         }
 525 
 526         static int c() {
 527             return 23;
 528         }
 529 
 530         static final Class<Empty> EMPTY = Empty.class;
 531 
 532         static final MethodType MT_f = methodType(void.class);
 533         static final MethodType MT_pred = methodType(boolean.class);
 534         static final MethodType MT_c = methodType(int.class);
 535 
 536         static final MethodHandle MH_f;
 537         static final MethodHandle MH_pred;
 538         static final MethodHandle MH_c;
 539 
 540         static {
 541             try {
 542                 MH_f = LOOKUP.findStatic(EMPTY, "f", MT_f);
 543                 MH_pred = LOOKUP.findStatic(EMPTY, "pred", MT_pred);
 544                 MH_c = LOOKUP.findStatic(EMPTY, "c", MT_c);
 545             } catch (Exception e) {
 546                 throw new ExceptionInInitializerError(e);
 547             }
 548         }
 549     }
 550 
 551     static class Fac {
 552 
 553         static int zero(int k) {
 554             return 0;
 555         }
 556 
 557         static int one(int k) {
 558             return 1;
 559         }
 560 
 561         static boolean pred(int i, int acc, int k) {
 562             return i < k;
 563         }
 564 
 565         static int inc(int i, int acc, int k) {
 566             return i + 1;
 567         }
 568 
 569         static int mult(int i, int acc, int k) {
 570             return i * acc;
 571         }
 572 
 573         static void dot(int i, int acc, int k) {
 574             System.out.print('.');
 575         }
 576 
 577         static int fin(int i, int acc, int k) {
 578             return acc;
 579         }
 580 
 581         static final Class<Fac> FAC = Fac.class;
 582 
 583         static final MethodType MT_init = methodType(int.class, int.class);
 584         static final MethodType MT_fn = methodType(int.class, int.class, int.class, int.class);
 585         static final MethodType MT_dot = methodType(void.class, int.class, int.class, int.class);
 586         static final MethodType MT_pred = methodType(boolean.class, int.class, int.class, int.class);
 587 
 588         static final MethodHandle MH_zero;
 589         static final MethodHandle MH_one;
 590         static final MethodHandle MH_pred;
 591         static final MethodHandle MH_inc;
 592         static final MethodHandle MH_mult;
 593         static final MethodHandle MH_dot;
 594         static final MethodHandle MH_fin;
 595 
 596         static final MethodType MT_fac = methodType(int.class, int.class);
 597 
 598         static {
 599             try {
 600                 MH_zero = LOOKUP.findStatic(FAC, "zero", MT_init);
 601                 MH_one = LOOKUP.findStatic(FAC, "one", MT_init);
 602                 MH_pred = LOOKUP.findStatic(FAC, "pred", MT_pred);
 603                 MH_inc = LOOKUP.findStatic(FAC, "inc", MT_fn);
 604                 MH_mult = LOOKUP.findStatic(FAC, "mult", MT_fn);
 605                 MH_dot = LOOKUP.findStatic(FAC, "dot", MT_dot);
 606                 MH_fin = LOOKUP.findStatic(FAC, "fin", MT_fn);
 607             } catch (Exception e) {
 608                 throw new ExceptionInInitializerError(e);
 609             }
 610         }
 611 
 612     }
 613 
 614     static class Loop {
 615 
 616         static int inc(int i, int k) {
 617             return i + 1;
 618         }
 619 
 620         static boolean pred(int i, int k) {
 621             return i < k;
 622         }
 623 
 624         static int fin(int i, int k) {
 625             return k;
 626         }
 627 
 628         static final Class<Loop> LOOP = Loop.class;
 629 
 630         static final MethodType MT_inc = methodType(int.class, int.class, int.class);
 631         static final MethodType MT_pred = methodType(boolean.class, int.class, int.class);
 632         static final MethodType MT_fin = methodType(int.class, int.class, int.class);
 633 
 634         static final MethodHandle MH_inc;
 635         static final MethodHandle MH_pred;
 636         static final MethodHandle MH_fin;
 637 
 638         static final MethodType MT_loop = methodType(int.class, int.class);
 639 
 640         static {
 641             try {
 642                 MH_inc = LOOKUP.findStatic(LOOP, "inc", MT_inc);
 643                 MH_pred = LOOKUP.findStatic(LOOP, "pred", MT_pred);
 644                 MH_fin = LOOKUP.findStatic(LOOP, "fin", MT_fin);
 645             } catch (Exception e) {
 646                 throw new ExceptionInInitializerError(e);
 647             }
 648         }
 649 
 650     }
 651 
 652     static class LoopWithVirtuals {
 653 
 654         static int one(int k) {
 655             return 1;
 656         }
 657 
 658         int inc(int i, int acc, int k) {
 659             return i + 1;
 660         }
 661 
 662         int mult(int i, int acc, int k) {
 663             return i * acc;
 664         }
 665 
 666         boolean pred(int i, int acc, int k) {
 667             return i < k;
 668         }
 669 
 670         int fin(int i, int acc, int k) {
 671             return acc;
 672         }
 673 
 674         static final Class<LoopWithVirtuals> LOOP_WITH_VIRTUALS = LoopWithVirtuals.class;
 675 
 676         static final MethodType MT_one = methodType(int.class, int.class);
 677         static final MethodType MT_inc = methodType(int.class, int.class, int.class, int.class);
 678         static final MethodType MT_mult = methodType(int.class, int.class, int.class, int.class);
 679         static final MethodType MT_pred = methodType(boolean.class, int.class, int.class, int.class);
 680         static final MethodType MT_fin = methodType(int.class, int.class, int.class, int.class);
 681 
 682         static final MethodHandle MH_one;
 683         static final MethodHandle MH_inc;
 684         static final MethodHandle MH_mult;
 685         static final MethodHandle MH_pred;
 686         static final MethodHandle MH_fin;
 687 
 688         static final MethodType MT_loop = methodType(int.class, LOOP_WITH_VIRTUALS, int.class);
 689 
 690         static {
 691             try {
 692                 MH_one = LOOKUP.findStatic(LOOP_WITH_VIRTUALS, "one", MT_one);
 693                 MH_inc = LOOKUP.findVirtual(LOOP_WITH_VIRTUALS, "inc", MT_inc);
 694                 MH_mult = LOOKUP.findVirtual(LOOP_WITH_VIRTUALS, "mult", MT_mult);
 695                 MH_pred = LOOKUP.findVirtual(LOOP_WITH_VIRTUALS, "pred", MT_pred);
 696                 MH_fin = LOOKUP.findVirtual(LOOP_WITH_VIRTUALS, "fin", MT_fin);
 697             } catch (Exception e) {
 698                 throw new ExceptionInInitializerError(e);
 699             }
 700         }
 701 
 702         static MethodHandle permute(MethodHandle h) {
 703             // The handles representing virtual methods need to be rearranged to match the required order of arguments
 704             // (loop-local state comes first, then loop arguments). As the receiver comes first in the signature but is
 705             // a loop argument, it must be moved to the appropriate position in the signature.
 706             return MethodHandles.permuteArguments(h,
 707                     methodType(h.type().returnType(), int.class, int.class, LOOP_WITH_VIRTUALS, int.class), 2, 0, 1, 3);
 708         }
 709 
 710     }
 711 
 712     static class While {
 713 
 714         static int zero(int limit) {
 715             return 0;
 716         }
 717 
 718         static boolean pred(int i, int limit) {
 719             return i < limit;
 720         }
 721 
 722         static int step(int i, int limit) {
 723             return i + 1;
 724         }
 725 
 726         static String initString() {
 727             return "a";
 728         }
 729 
 730         static boolean predString(String s) {
 731             return s.length() != 1;
 732         }
 733 
 734         static String stepString(String s) {
 735             return s + "a";
 736         }
 737 
 738         static List<String> zipInitZip(Iterator<String> a, Iterator<String> b) {
 739             return new ArrayList<>();
 740         }
 741 
 742         static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) {
 743             return a.hasNext() && b.hasNext();
 744         }
 745 
 746         static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
 747             zip.add(a.next());
 748             zip.add(b.next());
 749             return zip;
 750         }
 751 
 752         private int i = 0;
 753 
 754         void voidInit(int k) {
 755             // empty
 756         }
 757 
 758         void voidBody(int k) {
 759             ++i;
 760         }
 761 
 762         boolean voidPred(int k) {
 763             return i < k;
 764         }
 765 
 766         static final Class<While> WHILE = While.class;
 767 
 768         static final MethodType MT_zero = methodType(int.class, int.class);
 769         static final MethodType MT_pred = methodType(boolean.class, int.class, int.class);
 770         static final MethodType MT_fn = methodType(int.class, int.class, int.class);
 771         static final MethodType MT_initString = methodType(String.class);
 772         static final MethodType MT_predString = methodType(boolean.class, String.class);
 773         static final MethodType MT_stepString = methodType(String.class, String.class);
 774         static final MethodType MT_zipInitZip = methodType(List.class, Iterator.class, Iterator.class);
 775         static final MethodType MT_zipPred = methodType(boolean.class, List.class, Iterator.class, Iterator.class);
 776         static final MethodType MT_zipStep = methodType(List.class, List.class, Iterator.class, Iterator.class);
 777         static final MethodType MT_voidInit = methodType(void.class, int.class);
 778         static final MethodType MT_voidBody = methodType(void.class, int.class);
 779         static final MethodType MT_voidPred = methodType(boolean.class, int.class);
 780 
 781         static final MethodHandle MH_zero;
 782         static final MethodHandle MH_pred;
 783         static final MethodHandle MH_step;
 784         static final MethodHandle MH_initString;
 785         static final MethodHandle MH_predString;
 786         static final MethodHandle MH_stepString;
 787         static final MethodHandle MH_zipInitZip;
 788         static final MethodHandle MH_zipPred;
 789         static final MethodHandle MH_zipStep;
 790         static final MethodHandle MH_voidInit;
 791         static final MethodHandle MH_voidBody;
 792         static final MethodHandle MH_voidPred;
 793 
 794         static final MethodType MT_while = methodType(int.class, int.class);
 795         static final MethodType MT_string = methodType(String.class);
 796         static final MethodType MT_zip = methodType(List.class, Iterator.class, Iterator.class);
 797         static final MethodType MT_void = methodType(void.class, int.class);
 798 
 799         static {
 800             try {
 801                 MH_zero = LOOKUP.findStatic(WHILE, "zero", MT_zero);
 802                 MH_pred = LOOKUP.findStatic(WHILE, "pred", MT_pred);
 803                 MH_step = LOOKUP.findStatic(WHILE, "step", MT_fn);
 804                 MH_initString = LOOKUP.findStatic(WHILE, "initString", MT_initString);
 805                 MH_predString = LOOKUP.findStatic(WHILE, "predString", MT_predString);
 806                 MH_stepString = LOOKUP.findStatic(WHILE, "stepString", MT_stepString);
 807                 MH_zipInitZip = LOOKUP.findStatic(WHILE, "zipInitZip", MT_zipInitZip);
 808                 MH_zipPred = LOOKUP.findStatic(WHILE, "zipPred", MT_zipPred);
 809                 MH_zipStep = LOOKUP.findStatic(WHILE, "zipStep", MT_zipStep);
 810                 MH_voidInit = LOOKUP.findVirtual(WHILE, "voidInit", MT_voidInit);
 811                 MH_voidBody = LOOKUP.findVirtual(WHILE, "voidBody", MT_voidBody);
 812                 MH_voidPred = LOOKUP.findVirtual(WHILE, "voidPred", MT_voidPred);
 813             } catch (Exception e) {
 814                 throw new ExceptionInInitializerError(e);
 815             }
 816         }
 817 
 818     }
 819 
 820     static class Counted {
 821 
 822         static String start(String arg) {
 823             return arg;
 824         }
 825 
 826         static String step(int counter, String v, String arg) {
 827             return "na " + v;
 828         }
 829 
 830         static void stepUpdateArray(int counter, int[] a) {
 831             ++a[0];
 832         }
 833 
 834         static void printHello(int counter) {
 835             System.out.print("hello");
 836         }
 837 
 838         static int addCounter(int counter, int x) {
 839             return x + counter;
 840         }
 841 
 842         static final Class<Counted> COUNTED = Counted.class;
 843 
 844         static final MethodType MT_start = methodType(String.class, String.class);
 845         static final MethodType MT_step = methodType(String.class, int.class, String.class, String.class);
 846         static final MethodType MT_stepUpdateArray = methodType(void.class, int.class, int[].class);
 847         static final MethodType MT_printHello = methodType(void.class, int.class);
 848         static final MethodType MT_addCounter = methodType(int.class, int.class, int.class);
 849 
 850         static final MethodHandle MH_13;
 851         static final MethodHandle MH_m5;
 852         static final MethodHandle MH_8;
 853         static final MethodHandle MH_start;
 854         static final MethodHandle MH_step;
 855         static final MethodHandle MH_stepUpdateArray;
 856         static final MethodHandle MH_printHello;
 857         static final MethodHandle MH_addCounter;
 858 
 859         static final MethodType MT_counted = methodType(String.class, String.class);
 860         static final MethodType MT_arrayCounted = methodType(void.class, int[].class);
 861         static final MethodType MT_countedPrinting = methodType(void.class);
 862         static final MethodType MT_counterInit = methodType(int.class);
 863 
 864         static {
 865             try {
 866                 MH_13 = MethodHandles.constant(int.class, 13);
 867                 MH_m5 = MethodHandles.constant(int.class, -5);
 868                 MH_8 = MethodHandles.constant(int.class, 8);
 869                 MH_start = LOOKUP.findStatic(COUNTED, "start", MT_start);
 870                 MH_step = LOOKUP.findStatic(COUNTED, "step", MT_step);
 871                 MH_stepUpdateArray = LOOKUP.findStatic(COUNTED, "stepUpdateArray", MT_stepUpdateArray);
 872                 MH_printHello = LOOKUP.findStatic(COUNTED, "printHello", MT_printHello);
 873                 MH_addCounter = LOOKUP.findStatic(COUNTED, "addCounter", MT_addCounter);
 874             } catch (Exception e) {
 875                 throw new ExceptionInInitializerError(e);
 876             }
 877         }
 878 
 879     }
 880 
 881     static class Iterate {
 882 
 883         static Iterator<Integer> sumIterator(Integer[] a) {
 884             return Arrays.asList(a).iterator();
 885         }
 886 
 887         static int sumInit(Integer[] a) {
 888             return 0;
 889         }
 890 
 891         static int sumStep(int s, int e, Integer[] a) {
 892             return s + e;
 893         }
 894 
 895         static List<String> reverseInit(List<String> l) {
 896             return new ArrayList<>();
 897         }
 898 
 899         static List<String> reverseStep(String e, List<String> r, List<String> l) {
 900             r.add(0, e);
 901             return r;
 902         }
 903 
 904         static int lengthInit(List<Double> l) {
 905             return 0;
 906         }
 907 
 908         static int lengthStep(Object o, int len, List<Double> l) {
 909             return len + 1;
 910         }
 911 
 912         static List<String> mapInit(List<String> l) {
 913             return new ArrayList<>();
 914         }
 915 
 916         static List<String> mapStep(String e, List<String> r, List<String> l) {
 917             r.add(e.toUpperCase());
 918             return r;
 919         }
 920 
 921         static void printStep(String s, List<String> l) {
 922             System.out.print(s);
 923         }
 924 
 925         static void voidInit() {
 926             // empty
 927         }
 928 
 929         static final Class<Iterate> ITERATE = Iterate.class;
 930 
 931         static final MethodType MT_sumIterator = methodType(Iterator.class, Integer[].class);
 932 
 933         static final MethodType MT_sumInit = methodType(int.class, Integer[].class);
 934         static final MethodType MT_reverseInit = methodType(List.class, List.class);
 935         static final MethodType MT_lenghInit = methodType(int.class, List.class);
 936         static final MethodType MT_mapInit = methodType(List.class, List.class);
 937 
 938         static final MethodType MT_sumStep = methodType(int.class, int.class, int.class, Integer[].class);
 939         static final MethodType MT_reverseStep = methodType(List.class, String.class, List.class, List.class);
 940         static final MethodType MT_lengthStep = methodType(int.class, Object.class, int.class, List.class);
 941         static final MethodType MT_mapStep = methodType(List.class, String.class, List.class, List.class);
 942         static final MethodType MT_printStep = methodType(void.class, String.class, List.class);
 943 
 944         static final MethodType MT_voidInit = methodType(void.class);
 945 
 946         static final MethodHandle MH_sumIterator;
 947         static final MethodHandle MH_sumInit;
 948         static final MethodHandle MH_sumStep;
 949         static final MethodHandle MH_printStep;
 950 
 951         static final MethodHandle MH_reverseInit;
 952         static final MethodHandle MH_reverseStep;
 953 
 954         static final MethodHandle MH_lengthInit;
 955         static final MethodHandle MH_lengthStep;
 956 
 957         static final MethodHandle MH_mapInit;
 958         static final MethodHandle MH_mapStep;
 959 
 960         static final MethodHandle MH_voidInit;
 961 
 962         static final MethodType MT_sum = methodType(int.class, Integer[].class);
 963         static final MethodType MT_reverse = methodType(List.class, List.class);
 964         static final MethodType MT_length = methodType(int.class, List.class);
 965         static final MethodType MT_map = methodType(List.class, List.class);
 966         static final MethodType MT_print = methodType(void.class, List.class);
 967 
 968         static {
 969             try {
 970                 MH_sumIterator = LOOKUP.findStatic(ITERATE, "sumIterator", MT_sumIterator);
 971                 MH_sumInit = LOOKUP.findStatic(ITERATE, "sumInit", MT_sumInit);
 972                 MH_sumStep = LOOKUP.findStatic(ITERATE, "sumStep", MT_sumStep);
 973                 MH_reverseInit = LOOKUP.findStatic(ITERATE, "reverseInit", MT_reverseInit);
 974                 MH_reverseStep = LOOKUP.findStatic(ITERATE, "reverseStep", MT_reverseStep);
 975                 MH_lengthInit = LOOKUP.findStatic(ITERATE, "lengthInit", MT_lenghInit);
 976                 MH_lengthStep = LOOKUP.findStatic(ITERATE, "lengthStep", MT_lengthStep);
 977                 MH_mapInit = LOOKUP.findStatic(ITERATE, "mapInit", MT_mapInit);
 978                 MH_mapStep = LOOKUP.findStatic(ITERATE, "mapStep", MT_mapStep);
 979                 MH_printStep = LOOKUP.findStatic(ITERATE, "printStep", MT_printStep);
 980                 MH_voidInit = LOOKUP.findStatic(ITERATE, "voidInit", MT_voidInit);
 981             } catch (Exception e) {
 982                 throw new ExceptionInInitializerError(e);
 983             }
 984         }
 985 
 986     }
 987 
 988 }