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