1/*
2 * Copyright (c) 2013, 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.
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/*
25 * @test
26 * @bug     8011738
27 * @author  sogoel
28 * @summary Code translation test for Lambda expressions, method references
29 * @modules jdk.jdeps/com.sun.tools.classfile
30 * @run main ByteCodeTest
31 */
32
33import com.sun.tools.classfile.Attribute;
34import com.sun.tools.classfile.BootstrapMethods_attribute;
35import com.sun.tools.classfile.ClassFile;
36import com.sun.tools.classfile.ConstantPool;
37import com.sun.tools.classfile.ConstantPoolException;
38import com.sun.tools.classfile.ConstantPool.*;
39
40import java.io.BufferedWriter;
41import java.io.File;
42import java.io.FileWriter;
43import java.io.IOException;
44import java.io.PrintWriter;
45import java.util.ArrayList;
46import java.util.Collections;
47import java.util.HashMap;
48import java.util.HashSet;
49import java.util.List;
50import java.util.Map;
51
52public class ByteCodeTest {
53
54    static boolean IS_DEBUG = false;
55    public static void main(String[] args) {
56        File classFile = null;
57        int err = 0;
58        boolean verifyResult = false;
59        for(TestCases tc : TestCases.values()) {
60            classFile = getCompiledFile(tc.name(), tc.srcCode);
61            if(classFile == null) { // either testFile or classFile was not created
62               err++;
63            } else {
64                verifyResult = verifyClassFileAttributes(classFile, tc);
65                if(!verifyResult)
66                    System.out.println("Bootstrap class file attributes did not match for " + tc.name());
67            }
68        }
69        if(err > 0)
70            throw new RuntimeException("Found " + err + " found");
71        else
72            System.out.println("Test passed");
73    }
74
75    private static boolean verifyClassFileAttributes(File classFile, TestCases tc) {
76        ClassFile c = null;
77        try {
78            c = ClassFile.read(classFile);
79        } catch (IOException | ConstantPoolException e) {
80            e.printStackTrace();
81        }
82        ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constant_pool.size());
83        Map<Integer, String> hm = cpv.getBSMMap();
84
85        List<String> expectedValList = tc.getExpectedArgValues();
86        expectedValList.add(tc.bsmSpecifier.specifier);
87        if(!(hm.values().containsAll(new HashSet<String>(expectedValList)))) {
88            System.out.println("Values do not match");
89            return false;
90        }
91        return true;
92    }
93
94    private static File getCompiledFile(String fname, String srcString) {
95        File testFile = null, classFile = null;
96        boolean isTestFileCreated = true;
97
98        try {
99            testFile = writeTestFile(fname+".java", srcString);
100        } catch(IOException ioe) {
101            isTestFileCreated = false;
102            System.err.println("fail to write" + ioe);
103        }
104
105        if(isTestFileCreated) {
106            try {
107                classFile = compile(testFile);
108            } catch (Error err) {
109                System.err.println("fail compile. Source:\n" + srcString);
110                throw err;
111            }
112        }
113        return classFile;
114    }
115
116    static File writeTestFile(String fname, String source) throws IOException {
117        File f = new File(fname);
118          PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
119          out.println(source);
120          out.close();
121          return f;
122    }
123
124    static File compile(File f) {
125        int rc = com.sun.tools.javac.Main.compile(new String[] {
126                "-g", f.getPath() });
127        if (rc != 0)
128                throw new Error("compilation failed. rc=" + rc);
129            String path = f.getPath();
130            return new File(path.substring(0, path.length() - 5) + ".class");
131    }
132
133    static void debugln(String str) {
134        if(IS_DEBUG)
135            System.out.println(str);
136    }
137
138    enum BSMSpecifier {
139        SPECIFIER1("REF_invokeStatic java/lang/invoke/LambdaMetafactory metaFactory " +
140                "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;" +
141                "Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)" +
142                "Ljava/lang/invoke/CallSite;"),
143        SPECIFIER2("REF_invokeStatic java/lang/invoke/LambdaMetafactory altMetaFactory " +
144                        "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;" +
145                        "[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;");
146
147        String specifier;
148        private BSMSpecifier(String specifier) {
149            this.specifier = specifier;
150        }
151    }
152
153    enum TestCases {
154        // Single line lambda expression
155        TC1("class TC1 {\n" +
156            "    public static void main(String[] args) {\n" +
157            "        Object o = (Runnable) () -> { System.out.println(\"hi\");};\n" +
158            "    }\n"+
159            "}", BSMSpecifier.SPECIFIER1) {
160
161            @Override
162            List<String> getExpectedArgValues() {
163                List<String> valList = new ArrayList<>();
164                valList.add("REF_invokeInterface java/lang/Runnable run ()V");
165                valList.add("REF_invokeStatic TC1 lambda$0 ()V");
166                valList.add("()V");
167                return valList;
168            }
169        },
170
171        // Lambda expression in a for loop
172        TC2("import java.util.*;\n" +
173            "public class TC2 {\n" +
174            "    void TC2_test() {\n" +
175            "        List<String> list = new ArrayList<>();\n" +
176            "        list.add(\"A\");\n" +
177            "        list.add(\"B\");\n" +
178            "        list.stream().forEach( s -> { System.out.println(s); } );\n" +
179            "    }\n" +
180            "    public static void main(String[] args) {\n" +
181            "        new TC2().TC2_test();\n" +
182            "    }\n" +
183            "}", BSMSpecifier.SPECIFIER1) {
184
185            @Override
186            List<String> getExpectedArgValues() {
187                List<String> valList = new ArrayList<>();
188                valList.add("REF_invokeInterface java/util/function/Consumer accept (Ljava/lang/Object;)V");
189                valList.add("REF_invokeStatic TC2 lambda$0 (Ljava/lang/String;)V");
190                valList.add("(Ljava/lang/String;)V");
191                return valList;
192            }
193        },
194
195        // Lambda initializer
196        TC3("class TC3 {\n" +
197            "    interface SAM {\n" +
198            "        void m(int i);\n" +
199            "    }\n" +
200            "    SAM lambda_03 = (int pos) -> { };\n" +
201            "}", BSMSpecifier.SPECIFIER1) {
202
203            @Override
204            List<String> getExpectedArgValues() {
205                List<String> valList = new ArrayList<>();
206                valList.add("REF_invokeInterface TC3$SAM m (I)V");
207                valList.add("REF_invokeStatic TC3 lambda$0 (I)V");
208                valList.add("(I)V");
209                return valList;
210            }
211        },
212
213        // Array initializer
214        TC4("class TC4 {\n" +
215            "    interface Block<T> {\n" +
216            "        void m(T t);\n" +
217            "     }\n" +
218            "     void test1() {\n" +
219            "         Block<?>[] arr1 =  { t -> { }, t -> { } };\n" +
220            "     }\n" +
221            "}", BSMSpecifier.SPECIFIER1) {
222
223            @Override
224            List<String> getExpectedArgValues() {
225                List<String> valList = new ArrayList<>();
226                valList.add("REF_invokeInterface TC4$Block m (Ljava/lang/Object;)V");
227                valList.add("REF_invokeStatic TC4 lambda$0 (Ljava/lang/Object;)V");
228                valList.add("(Ljava/lang/Object;)V");
229                valList.add("REF_invokeStatic TC4 lambda$1 (Ljava/lang/Object;)V");
230                return valList;
231            }
232        },
233
234        //Lambda expression as a method arg
235        TC5("class TC5 {\n"+
236            "    interface MapFun<T,R> {  R m( T n); }\n" +
237            "    void meth( MapFun<String,Integer> mf ) {\n" +
238            "        assert( mf.m(\"four\") == 4);\n" +
239            "    }\n"+
240            "    void test(Integer i) {\n" +
241            "        meth(s -> { Integer len = s.length(); return len; } );\n" +
242            "    }\n"+
243            "}", BSMSpecifier.SPECIFIER1) {
244
245            @Override
246            List<String> getExpectedArgValues() {
247                List<String> valList = new ArrayList<>();
248                valList.add("REF_invokeInterface TC5$MapFun m (Ljava/lang/Object;)Ljava/lang/Object;");
249                valList.add("REF_invokeStatic TC5 lambda$0 (Ljava/lang/String;)Ljava/lang/Integer;");
250                valList.add("(Ljava/lang/String;)Ljava/lang/Integer;");
251                return valList;
252            }
253        },
254
255        //Inner class of Lambda expression
256        TC6("class TC6 {\n" +
257            "    interface MapFun<T, R> {  R m( T n); }\n" +
258            "    MapFun<Class<?>,String> cs;\n" +
259            "    void test() {\n" +
260            "        cs = c -> {\n" +
261            "                 class innerClass   {\n" +
262            "                    Class<?> icc;\n" +
263            "                    innerClass(Class<?> _c) { icc = _c; }\n" +
264            "                    String getString() { return icc.toString(); }\n" +
265            "                  }\n" +
266            "             return new innerClass(c).getString();\n"+
267            "             };\n" +
268            "    }\n" +
269            "}\n", BSMSpecifier.SPECIFIER1) {
270
271            @Override
272            List<String> getExpectedArgValues() {
273                List<String> valList = new ArrayList<>();
274                valList.add("REF_invokeInterface TC6$MapFun m (Ljava/lang/Object;)Ljava/lang/Object;");
275                valList.add("REF_invokeSpecial TC6 lambda$0 (Ljava/lang/Class;)Ljava/lang/String;");
276                valList.add("(Ljava/lang/Class;)Ljava/lang/String;");
277                return valList;
278            }
279        },
280
281        // Method reference
282        TC7("class TC7 {\n" +
283            "    static interface SAM {\n" +
284            "       void m(Integer i);\n" +
285            "    }\n" +
286            "    void m(Integer i) {}\n" +
287            "       SAM s = this::m;\n" +
288            "}\n", BSMSpecifier.SPECIFIER1) {
289
290            @Override
291            List<String> getExpectedArgValues() {
292                List<String> valList = new ArrayList<>();
293                valList.add("REF_invokeInterface TC7$SAM m (Ljava/lang/Integer;)V");
294                valList.add("REF_invokeVirtual TC7 m (Ljava/lang/Integer;)V");
295                valList.add("(Ljava/lang/Integer;)V");
296                return valList;
297            }
298        },
299
300        // Constructor reference
301        TC8("public class TC8 {\n" +
302            "    static interface A {Fee<String> m();}\n" +
303            "    static class Fee<T> {\n" +
304            "        private T t;\n" +
305            "        public Fee() {}\n" +
306            "    }\n" +
307            "    public static void main(String[] args) {\n" +
308            "        A a = Fee<String>::new; \n" +
309            "    }\n" +
310            "}\n", BSMSpecifier.SPECIFIER1) {
311
312            @Override
313            List<String> getExpectedArgValues() {
314                List<String> valList = new ArrayList<>();
315                valList.add("REF_invokeInterface TC8$A m ()LTC8$Fee;");
316                valList.add("REF_newInvokeSpecial TC8$Fee <init> ()V");
317                valList.add("()LTC8$Fee;");
318                return valList;
319            }
320        },
321
322        // Recursive lambda expression
323        TC9("class TC9 {\n" +
324            "    interface Recursive<T, R> { T apply(R n); };\n" +
325            "    Recursive<Integer,Integer> factorial;\n" +
326            "    void test(Integer j) {\n" +
327            "        factorial = i -> { return i == 0 ? 1 : i * factorial.apply( i - 1 ); };\n" +
328            "    }\n" +
329            "}\n", BSMSpecifier.SPECIFIER1) {
330
331            @Override
332            List<String> getExpectedArgValues() {
333                List<String> valList = new ArrayList<>();
334                valList.add("REF_invokeInterface TC9$Recursive apply (Ljava/lang/Object;)Ljava/lang/Object;");
335                valList.add("REF_invokeSpecial TC9 lambda$0 (Ljava/lang/Integer;)Ljava/lang/Integer;");
336                valList.add("(Ljava/lang/Integer;)Ljava/lang/Integer;");
337                return valList;
338            }
339        },
340
341        //Serializable Lambda
342        TC10("import java.io.Serializable;\n" +
343              "class TC10 {\n" +
344              "    interface Foo { int m(); }\n" +
345              "    public static void main(String[] args) {\n" +
346              "        Foo f1 = (Foo & Serializable)() -> 3;\n" +
347              "    }\n" +
348              "}\n", BSMSpecifier.SPECIFIER2) {
349
350            @Override
351            List<String> getExpectedArgValues() {
352                List<String> valList = new ArrayList<>();
353                valList.add("REF_invokeStatic java/lang/invoke/LambdaMetafactory altMetaFactory (Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;");
354                valList.add("REF_invokeInterface TC10$Foo m ()I");
355                valList.add("REF_invokeStatic TC10 lambda$main$3231c38a$0 ()I");
356                valList.add("()I");
357                valList.add("1");
358                return valList;
359            }
360        };
361
362        String srcCode;
363        BSMSpecifier bsmSpecifier;
364
365        TestCases(String src, BSMSpecifier bsmSpecifier) {
366            this.srcCode = src;
367            // By default, all test cases will have bootstrap method specifier as Lambda.MetaFactory
368            // For serializable lambda test cases, bootstrap method specifier changed to altMetaFactory
369            this.bsmSpecifier = bsmSpecifier;
370        }
371
372        List<String> getExpectedArgValues() {
373            return null;
374        }
375
376        void setSrcCode(String src) {
377            srcCode = src;
378        }
379    }
380
381    static class ConstantPoolVisitor implements ConstantPool.Visitor<String, Integer> {
382        final List<String> slist;
383        final ClassFile cf;
384        final ConstantPool cfpool;
385        final Map<Integer, String> bsmMap;
386
387
388        public ConstantPoolVisitor(ClassFile cf, int size) {
389            slist = new ArrayList<>(size);
390            for (int i = 0 ; i < size; i++) {
391                slist.add(null);
392            }
393            this.cf = cf;
394            this.cfpool = cf.constant_pool;
395            bsmMap = readBSM();
396        }
397
398        public Map<Integer, String> getBSMMap() {
399            return Collections.unmodifiableMap(bsmMap);
400        }
401
402        public String visit(CPInfo c, int index) {
403            return c.accept(this, index);
404        }
405
406        private Map<Integer, String> readBSM() {
407            BootstrapMethods_attribute bsmAttr =
408                    (BootstrapMethods_attribute) cf.getAttribute(Attribute.BootstrapMethods);
409            if (bsmAttr != null) {
410                Map<Integer, String> out =
411                        new HashMap<>(bsmAttr.bootstrap_method_specifiers.length);
412                for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsms :
413                        bsmAttr.bootstrap_method_specifiers) {
414                    int index = bsms.bootstrap_method_ref;
415                    try {
416                        String value = slist.get(index);
417                        if (value == null) {
418                            value = visit(cfpool.get(index), index);
419                            debugln("[SG]: index " + index);
420                            debugln("[SG]: value " + value);
421                            slist.set(index, value);
422                            out.put(index, value);
423                        }
424                        for (int idx : bsms.bootstrap_arguments) {
425                            value = slist.get(idx);
426                            if (value == null) {
427                                value = visit(cfpool.get(idx), idx);
428                                debugln("[SG]: idx " + idx);
429                                debugln("[SG]: value " + value);
430                                slist.set(idx, value);
431                                out.put(idx, value);
432                            }
433                        }
434                    } catch (InvalidIndex ex) {
435                        ex.printStackTrace();
436                    }
437                }
438                return out;
439            }
440            return new HashMap<>(0);
441        }
442
443        @Override
444        public String visitClass(CONSTANT_Class_info c, Integer p) {
445
446            String value = slist.get(p);
447            if (value == null) {
448                try {
449                    value = visit(cfpool.get(c.name_index), c.name_index);
450                    slist.set(p, value);
451                } catch (ConstantPoolException ex) {
452                    ex.printStackTrace();
453                }
454            }
455            return value;
456        }
457
458        @Override
459        public String visitDouble(CONSTANT_Double_info c, Integer p) {
460
461            String value = slist.get(p);
462            if (value == null) {
463                value = Double.toString(c.value);
464                slist.set(p, value);
465            }
466            return value;
467        }
468
469        @Override
470        public String visitFieldref(CONSTANT_Fieldref_info c, Integer p) {
471
472        String value = slist.get(p);
473            if (value == null) {
474                try {
475                    value = visit(cfpool.get(c.class_index), c.class_index);
476                    value = value.concat(" " + visit(cfpool.get(c.name_and_type_index),
477                                         c.name_and_type_index));
478                    slist.set(p, value);
479                } catch (ConstantPoolException ex) {
480                    ex.printStackTrace();
481                }
482            }
483            return value;
484        }
485
486        @Override
487        public String visitFloat(CONSTANT_Float_info c, Integer p) {
488
489            String value = slist.get(p);
490            if (value == null) {
491                value = Float.toString(c.value);
492                slist.set(p, value);
493            }
494            return value;
495        }
496
497        @Override
498        public String visitInteger(CONSTANT_Integer_info cnstnt, Integer p) {
499
500            String value = slist.get(p);
501            if (value == null) {
502                value = Integer.toString(cnstnt.value);
503                slist.set(p, value);
504            }
505            return value;
506        }
507
508        @Override
509        public String visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info c,
510                                              Integer p) {
511
512            String value = slist.get(p);
513            if (value == null) {
514                try {
515                    value = visit(cfpool.get(c.class_index), c.class_index);
516                    value = value.concat(" " +
517                                         visit(cfpool.get(c.name_and_type_index),
518                                         c.name_and_type_index));
519                    slist.set(p, value);
520                } catch (ConstantPoolException ex) {
521                    ex.printStackTrace();
522                }
523            }
524            return value;
525        }
526
527        @Override
528        public String visitInvokeDynamic(CONSTANT_InvokeDynamic_info c, Integer p) {
529
530            String value = slist.get(p);
531            if (value == null) {
532                try {
533                    value = bsmMap.get(c.bootstrap_method_attr_index) + " "
534                            + visit(cfpool.get(c.name_and_type_index), c.name_and_type_index);
535                    slist.set(p, value);
536                } catch (ConstantPoolException ex) {
537                    ex.printStackTrace();
538                }
539            }
540            return value;
541        }
542
543        @Override
544        public String visitLong(CONSTANT_Long_info c, Integer p) {
545
546            String value = slist.get(p);
547            if (value == null) {
548                value = Long.toString(c.value);
549                slist.set(p, value);
550            }
551            return value;
552        }
553
554        @Override
555        public String visitNameAndType(CONSTANT_NameAndType_info c, Integer p) {
556
557            String value = slist.get(p);
558            if (value == null) {
559                try {
560                    value = visit(cfpool.get(c.name_index), c.name_index);
561                    value = value.concat(" " +
562                            visit(cfpool.get(c.type_index), c.type_index));
563                    slist.set(p, value);
564                } catch (InvalidIndex ex) {
565                    ex.printStackTrace();
566                }
567            }
568            return value;
569        }
570
571        @Override
572        public String visitMethodref(CONSTANT_Methodref_info c, Integer p) {
573
574            String value = slist.get(p);
575            if (value == null) {
576                try {
577                    value = visit(cfpool.get(c.class_index), c.class_index);
578                    value = value.concat(" " +
579                                         visit(cfpool.get(c.name_and_type_index),
580                                         c.name_and_type_index));
581                    slist.set(p, value);
582                } catch (ConstantPoolException ex) {
583                    ex.printStackTrace();
584                }
585            }
586            return value;
587        }
588
589        @Override
590        public String visitMethodHandle(CONSTANT_MethodHandle_info c, Integer p) {
591
592        String value = slist.get(p);
593            if (value == null) {
594                try {
595                    value = c.reference_kind.name();
596                    value = value.concat(" "
597                            + visit(cfpool.get(c.reference_index), c.reference_index));
598                    slist.set(p, value);
599                } catch (ConstantPoolException ex) {
600                    ex.printStackTrace();
601                }
602            }
603            return value;
604        }
605
606        @Override
607        public String visitMethodType(CONSTANT_MethodType_info c, Integer p) {
608
609            String value = slist.get(p);
610            if (value == null) {
611                try {
612                    value = visit(cfpool.get(c.descriptor_index), c.descriptor_index);
613                    slist.set(p, value);
614                } catch (ConstantPoolException ex) {
615                    ex.printStackTrace();
616                }
617            }
618            return value;
619        }
620
621        @Override
622        public String visitModule(CONSTANT_Module_info c, Integer p) {
623
624            String value = slist.get(p);
625            if (value == null) {
626                try {
627                    value = visit(cfpool.get(c.name_index), c.name_index);
628                    slist.set(p, value);
629                } catch (ConstantPoolException ex) {
630                    ex.printStackTrace();
631                }
632            }
633            return value;
634        }
635
636        @Override
637        public String visitPackage(CONSTANT_Package_info c, Integer p) {
638
639            String value = slist.get(p);
640            if (value == null) {
641                try {
642                    value = visit(cfpool.get(c.name_index), c.name_index);
643                    slist.set(p, value);
644                } catch (ConstantPoolException ex) {
645                    ex.printStackTrace();
646                }
647            }
648            return value;
649        }
650
651        @Override
652        public String visitString(CONSTANT_String_info c, Integer p) {
653
654            try {
655                String value = slist.get(p);
656                if (value == null) {
657                    value = c.getString();
658                    slist.set(p, value);
659                }
660                return value;
661            } catch (ConstantPoolException ex) {
662                throw new RuntimeException("Fatal error", ex);
663            }
664        }
665
666        @Override
667        public String  visitUtf8(CONSTANT_Utf8_info cnstnt, Integer p) {
668
669            String value = slist.get(p);
670            if (value == null) {
671                value = cnstnt.value;
672                slist.set(p, value);
673            }
674            return value;
675        }
676    }
677}
678
679