1 /*
   2  * Copyright (c) 2011, 2012, 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  * @summary unit tests for method handles which permute their arguments
  28  * @run testng/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-VerifyDependencies -ea -esa -DPermuteArgsTest.MAX_ARITY=8 test.java.lang.invoke.PermuteArgsTest
  29  */
  30 /* Examples of manual runs:
  31  * java -DPermuteArgsTest.{DRY_RUN=true,MAX_ARITY=253} test.java.lang.invoke.PermuteArgsTest
  32  * java -DPermuteArgsTest.{VERBOSE=true,MAX_ARITY=5} test.java.lang.invoke.PermuteArgsTest
  33  * java test.java.lang.invoke.PermuteArgsTest list3I[2,0,1] listJLJ[2,0,1]
  34  */
  35 
  36 package test.java.lang.invoke;
  37 
  38 import org.testng.*;
  39 import org.testng.annotations.*;
  40 
  41 import java.util.*;
  42 import java.lang.reflect.*;
  43 
  44 import java.lang.invoke.*;
  45 import static java.lang.invoke.MethodHandles.*;
  46 import static java.lang.invoke.MethodType.*;
  47 
  48 public class PermuteArgsTest {
  49     private static final Class<?> CLASS = PermuteArgsTest.class;
  50     private static final int MAX_ARITY = Integer.getInteger(CLASS.getSimpleName()+".MAX_ARITY", 8);
  51     private static final boolean DRY_RUN = Boolean.getBoolean(CLASS.getSimpleName()+".DRY_RUN");
  52     private static final boolean VERBOSE = Boolean.getBoolean(CLASS.getSimpleName()+".VERBOSE") || DRY_RUN;
  53 
  54     static Object list2I(int x, int y) {
  55         return Arrays.asList(x, y);
  56     }
  57     static Object list3I(int x, int y, int z) {
  58         return Arrays.asList(x, y, z);
  59     }
  60     static Object list4I(int w, int x, int y, int z) {
  61         return Arrays.asList(w, x, y, z);
  62     }
  63     static Object list2J(long x, long y) {
  64         return Arrays.asList(x, y);
  65     }
  66     static Object list3J(long x, long y, long z) {
  67         return Arrays.asList(x, y, z);
  68     }
  69     static Object list4J(long w, long x, long y, long z) {
  70         return Arrays.asList(w, x, y, z);
  71     }
  72     static Object list2I2J(int w, int x, long y, long z) {
  73         return Arrays.asList(w, x, y, z);
  74     }
  75     static Object list2J2I(long w, long x, int y, int z) {
  76         return Arrays.asList(w, x, y, z);
  77     }
  78     static Object listLJJ(Object x, long y, long z) {
  79         return Arrays.asList(x, y, z);
  80     }
  81     static Object listJLJ(long x, Object y, long z) {
  82         return Arrays.asList(x, y, z);
  83     }
  84     static Object listJJL(long x, long y, Object z) {
  85         return Arrays.asList(x, y, z);
  86     }
  87     static Object listJLL(long x, Object y, Object z) {
  88         return Arrays.asList(x, y, z);
  89     }
  90     static Object listLJL(Object x, long y, Object z) {
  91         return Arrays.asList(x, y, z);
  92     }
  93     static Object listLLJ(Object x, Object y, long z) {
  94         return Arrays.asList(x, y, z);
  95     }
  96     static Object listJLLJ(long w, Object x, Object y, long z) {
  97         return Arrays.asList(w, x, y, z);
  98     }
  99     static Object listLJJL(Object w, long x, long y, Object z) {
 100         return Arrays.asList(w, x, y, z);
 101     }
 102     static Object listI_etc(int... va) {
 103         ArrayList<Object> res = new ArrayList<>();
 104         for (int x : va)  res.add(x);
 105         return res;
 106     }
 107     static Object listIJL_etc(int x, long y, Object z, Object... va) {
 108         ArrayList<Object> res = new ArrayList<>();
 109         res.addAll(Arrays.asList(x, y, z));
 110         res.addAll(Arrays.asList(va));
 111         return res;
 112     }
 113 
 114     public static void main(String argv[]) throws Throwable {
 115         if (argv.length > 0) {
 116             for (String arg : argv) {
 117                 // arg ::= name[n,...]
 118                 int k = arg.indexOf('[');
 119                 String mhName = arg.substring(0, k).trim();
 120                 String permString = arg.substring(k);
 121                 testOnePermutation(mhName, permString);
 122             }
 123             return;
 124         }
 125         new PermuteArgsTest().test();
 126     }
 127     static int testCases;
 128     @Test
 129     public void test() throws Throwable {
 130         testCases = 0;
 131         Lookup lookup = lookup();
 132         for (Method m : lookup.lookupClass().getDeclaredMethods()) {
 133             if (m.getName().startsWith("list") &&
 134                 Modifier.isStatic(m.getModifiers())) {
 135                 test(m.getName(), lookup.unreflect(m));
 136             }
 137         }
 138         System.out.println("ran a total of "+testCases+" test cases");
 139     }
 140 
 141     static int jump(int i, int min, int max) {
 142         if (i >= min && i <= max-1) {
 143             // jump faster
 144             int len = max-min;
 145             if (i < min + len/2)
 146                 i = min + len/2;
 147             else
 148                 i = max-1;
 149         }
 150         return i;
 151     }
 152 
 153     static void test(String name, MethodHandle mh) throws Throwable {
 154         if (VERBOSE)
 155             System.out.println("mh = "+name+" : "+mh+" { "
 156                                +Arrays.toString(junkArgs(mh.type().parameterArray())));
 157         int testCases0 = testCases;
 158         if (!mh.isVarargsCollector()) {
 159             // normal case
 160             testPermutations(mh);
 161         } else {
 162             // varargs case; add params up to MAX_ARITY
 163             MethodType mt = mh.type();
 164             int posArgs = mt.parameterCount() - 1;
 165             int arity0 = Math.max(3, posArgs);
 166             for (int arity = arity0; arity <= MAX_ARITY; arity++) {
 167                 MethodHandle mh1;
 168                 try {
 169                     mh1 = adjustArity(mh, arity);
 170                 } catch (IllegalArgumentException ex) {
 171                     System.out.println("*** mh = "+name+" : "+mh+"; arity = "+arity+" => "+ex);
 172                     ex.printStackTrace(System.out);
 173                     break;  // cannot get this arity for this type
 174                 }
 175                 test("("+arity+")"+name, mh1);
 176                 arity = jump(arity, arity0*2, MAX_ARITY);
 177             }
 178         }
 179         if (VERBOSE)
 180             System.out.println("ran "+(testCases - testCases0)+" test cases for "+name+" }");
 181     }
 182 
 183     static MethodHandle adjustArity(MethodHandle mh, int arity) {
 184         MethodType mt = mh.type();
 185         int posArgs = mt.parameterCount() - 1;
 186         Class<?> reptype = mt.parameterType(posArgs).getComponentType();
 187         MethodType mt1 = mt.dropParameterTypes(posArgs, posArgs+1);
 188         while (mt1.parameterCount() < arity) {
 189             Class<?> pt = reptype;
 190             if (pt == Object.class && posArgs > 0)
 191                 // repeat types cyclically if possible:
 192                 pt = mt1.parameterType(mt1.parameterCount() - posArgs);
 193             mt1 = mt1.appendParameterTypes(pt);
 194         }
 195         try {
 196             return mh.asType(mt1);
 197         } catch (WrongMethodTypeException | IllegalArgumentException ex) {
 198             throw new IllegalArgumentException("cannot convert to type "+mt1+" from "+mh, ex);
 199         }
 200     }
 201     static MethodHandle findTestMH(String name, int[] perm) throws ReflectiveOperationException {
 202         int arity = perm.length;
 203         Lookup lookup = lookup();
 204         for (Method m : lookup.lookupClass().getDeclaredMethods()) {
 205             if (m.getName().equals(name) &&
 206                 Modifier.isStatic(m.getModifiers())) {
 207                 MethodHandle mh = lookup.unreflect(m);
 208                 int mhArity = mh.type().parameterCount();
 209                 if (mh.isVarargsCollector()) {
 210                     if (mhArity-1 <= arity)
 211                         return adjustArity(mh, arity);
 212                 } else if (mhArity == arity) {
 213                     return mh;
 214                 }
 215             }
 216         }
 217         throw new RuntimeException("no such method for arity "+arity+": "+name);
 218     }
 219 
 220     static void testPermutations(MethodHandle mh) throws Throwable {
 221         HashSet<String> done = new HashSet<>();
 222         MethodType mt = mh.type();
 223         int[] perm = nullPerm(mt.parameterCount());
 224         final int MARGIN = (perm.length <= 10 ? 2 : 0);
 225         int testCases0 = testCases;
 226         for (int j = 0; j <= 1; j++) {
 227             int maxStart = perm.length-1;
 228             if (j != 0)  maxStart /= 2;
 229             for (int start = 0; start <= maxStart; start++) {
 230                 int maxOmit = (maxStart - start) / 2;
 231                 if (start != 0)  maxOmit = 2;
 232                 if (j != 0)  maxOmit = 1;
 233                 for (int omit = 0; omit <= maxOmit; omit++) {
 234                     int end = perm.length - omit;
 235                     if (end - start >= 2) {
 236                         //System.out.println("testPermutations"+Arrays.asList(start, end)+(j == 0 ? "" : " (reverse)"));
 237                         testPermutations(mh, perm, start, end, done);
 238                     }
 239                     omit = jump(omit, (start == 0 && j == 0 ? MARGIN : 0), maxOmit);
 240                 }
 241                 start = jump(start, (j == 0 ? MARGIN : 0), maxStart);
 242             }
 243             // do everything in reverse:
 244             reverse(perm, 0, perm.length);
 245         }
 246         switch (perm.length) {
 247         case 2: assert(testCases - testCases0 == 2); break;
 248         case 3: assert(testCases - testCases0 == 6); break;
 249         case 4: assert(testCases - testCases0 == 24); break;
 250         case 5: assert(testCases - testCases0 == 120); break;
 251         case 6: assert(testCases - testCases0 > 720/3); break;
 252         }
 253     }
 254 
 255     static void testPermutations(MethodHandle mh, int[] perm, int start, int end, Set<String> done) throws Throwable {
 256         if (end - start <= 1)  return;
 257         for (int j = 0; j <= 1; j++) {
 258             testRotations(mh, perm, start, end, done);
 259             if (end - start <= 2)  return;
 260             reverse(perm, start, end);
 261         }
 262         if (end - start <= 3)  return;
 263         int excess4 = (end - start) - 4;
 264         // composed rotations:
 265         int start2 = start + 1 + excess4/3;
 266         int end2   = end       - excess4/3;
 267         end2 = start2 + Math.min(start == 0 ? 4 : 3, end2 - start2);
 268         int skips = (perm.length+3)/5;
 269         for (int i = start; i < end; i++) {
 270             rotate(perm, start, end);
 271             if (skips > 1 && ((i-start) + (i-start)/7) % skips != 0)  continue;
 272             for (int j = 0; j <= 1; j++) {
 273                 testPermutations(mh, perm, start2, end2, done);
 274                 reverse(perm, start, end);
 275             }
 276         }
 277     }
 278 
 279     static void testRotations(MethodHandle mh, int[] perm, int start, int end, Set<String> done) throws Throwable {
 280         Object[] args = junkArgs(mh.type().parameterArray());
 281         for (int i = start; i < end; i++) {
 282             if (done.add(Arrays.toString(perm)))
 283                 testOnePermutation(mh, perm, args);
 284             rotate(perm, start, end);
 285         }
 286     }
 287 
 288     static void testOnePermutation(MethodHandle mh, int[] perm, Object[] args) throws Throwable {
 289         MethodType mt = mh.type();
 290         MethodType pmt = methodType(mt.returnType(), unpermuteArgs(perm, mt.parameterArray(), Class[].class));
 291         if (VERBOSE)
 292             System.out.println(Arrays.toString(perm));
 293         testCases += 1;
 294         if (DRY_RUN)
 295             return;
 296         Object res = permuteArguments(mh, pmt, perm).invokeWithArguments(unpermuteArgs(perm, args));
 297         String str = String.valueOf(res);
 298         if (!Arrays.toString(args).equals(str)) {
 299             System.out.println(Arrays.toString(perm)+" "+str+" *** WRONG ***");
 300         }
 301     }
 302 
 303     // For reproducing failures:
 304     static void testOnePermutation(String mhName, String permString) throws Throwable {
 305         String s = permString;
 306         s = s.replace('[', ' ').replace(']', ' ').replace(',', ' ');  // easier to trim spaces
 307         s = s.trim();
 308         int[] perm = new int[s.length()];
 309         int arity = 0;
 310         while (!s.isEmpty()) {
 311             int k = s.indexOf(' ');
 312             if (k < 0)  k = s.length();
 313             perm[arity++] = Integer.parseInt(s.substring(0, k));
 314             s = s.substring(k).trim();
 315         }
 316         perm = Arrays.copyOf(perm, arity);
 317         testOnePermutation(mhName, perm);
 318     }
 319     static void testOnePermutation(String mhName, int[] perm) throws Throwable {
 320         MethodHandle mh = findTestMH(mhName, perm);
 321         System.out.println("mh = "+mhName+" : "+mh+" { "
 322                            +Arrays.toString(junkArgs(mh.type().parameterArray())));
 323         Object[] args = junkArgs(mh.type().parameterArray());
 324         testOnePermutation(mh, perm, args);
 325         System.out.println("}");
 326     }
 327 
 328     static Object[] junkArgs(Class<?>[] ptypes) {
 329         Object[] args = new Object[ptypes.length];
 330         for (int i = 0; i < ptypes.length; i++) {
 331             Class<?> pt = ptypes[i];
 332             Object arg;
 333             if (pt == Void.class)       arg = null;
 334             else if (pt == int.class)   arg = i + 101;
 335             else if (pt == long.class)  arg = i + 10_000_000_001L;
 336             else                        arg = "#" + (i + 1);
 337             args[i] = arg;
 338         }
 339         return args;
 340     }
 341 
 342     static int[] nullPerm(int len) {
 343         int[] perm = new int[len];
 344         for (int i = 0; i < len; i++)
 345             perm[i] = i;
 346         return perm;
 347     }
 348     static void rotate(int[] perm) {
 349         rotate(perm, 0, perm.length);
 350     }
 351     static void rotate(int[] perm, int start, int end) {
 352         int x = perm[end-1];
 353         for (int j = start; j < end; j++) {
 354             int y = perm[j]; perm[j] = x; x = y;
 355         }
 356     }
 357     static void reverse(int[] perm) {
 358         reverse(perm, 0, perm.length);
 359     }
 360     static void reverse(int[] perm, int start, int end) {
 361         int mid = start + (end - start)/2;
 362         for (int j = start; j < mid; j++) {
 363             int k = (end-1) - j;
 364             int x = perm[j]; perm[j] = perm[k]; perm[k] = x;
 365         }
 366     }
 367     // Permute the args according to the inverse of perm.
 368     static Object[] unpermuteArgs(int[] perm, Object[] args) {
 369         return unpermuteArgs(perm, args, Object[].class);
 370     }
 371     static <T> T[] unpermuteArgs(int[] perm, T[] args, Class<T[]> Tclass) {
 372         T[] res = Arrays.copyOf(new Object[0], perm.length, Tclass);
 373         for (int i = 0; i < perm.length; i++)
 374             res[perm[i]] = args[i];
 375         return res;
 376     }
 377 }