1 /*
  2  * Copyright (c) 2022, 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 8276836
 27  * @summary Check that switch expression with no value does not crash the compiler.
 28  * @library /tools/lib /tools/javac/lib
 29  * @modules
 30  *      java.base/jdk.internal
 31  *      jdk.compiler/com.sun.tools.javac.api
 32  *      jdk.compiler/com.sun.tools.javac.file
 33  *      jdk.compiler/com.sun.tools.javac.main
 34  *      jdk.compiler/com.sun.tools.javac.util
 35  * @build toolbox.ToolBox toolbox.JavacTask
 36  * @build combo.ComboTestHelper
 37  * @compile SwitchExpressionNoValue.java
 38  * @run main/othervm SwitchExpressionNoValue
 39  */
 40 
 41 import combo.ComboInstance;
 42 import combo.ComboParameter;
 43 import combo.ComboTask;
 44 import combo.ComboTestHelper;
 45 import java.io.InputStream;
 46 import java.lang.reflect.InvocationTargetException;
 47 import java.nio.file.Path;
 48 import java.nio.file.Paths;
 49 import java.util.Iterator;
 50 import java.util.Objects;
 51 import javax.tools.Diagnostic;
 52 import toolbox.ToolBox;
 53 
 54 import javax.tools.JavaFileObject;
 55 
 56 public class SwitchExpressionNoValue extends ComboInstance<SwitchExpressionNoValue> {
 57     protected ToolBox tb;
 58 
 59     SwitchExpressionNoValue() {
 60         super();
 61         tb = new ToolBox();
 62     }
 63 
 64     public static void main(String... args) throws Exception {
 65         new ComboTestHelper<SwitchExpressionNoValue>()
 66                 .withDimension("SWITCH_EXPRESSION", (x, method) -> x.switchExpression = method, SwitchExpression.values())
 67                 .withDimension("EXPRESSION", (x, expression) -> x.expression = expression, Expression.values())
 68                 .withDimension("CONTEXT", (x, context) -> x.context = context, Context.values())
 69                 .withFilter(test -> test.context.expressionType == test.expression.expressionType &&
 70                                     test.context.expressionType == test.switchExpression.expressionType)
 71                 .run(SwitchExpressionNoValue::new);
 72     }
 73 
 74     private SwitchExpression switchExpression;
 75     private Expression expression;
 76     private Context context;
 77 
 78     private static final String MAIN_TEMPLATE =
 79             """
 80             public class Test {
 81                 public static void doTest() {
 82                     #{CONTEXT}
 83                 }
 84                 static int i;
 85                 static int[] arr = new int[0];
 86                 static void m(int i, Object o, int j) {}
 87             }
 88             """;
 89 
 90     @Override
 91     protected void doWork() throws Throwable {
 92         Path base = Paths.get(".");
 93 
 94         ComboTask task = newCompilationTask()
 95                 .withSourceFromTemplate(MAIN_TEMPLATE, pname -> switch (pname) {
 96                         case "SWITCH_EXPRESSION" -> switchExpression;
 97                         case "EXPRESSION" -> expression;
 98                         case "CONTEXT" -> context;
 99                         default -> throw new UnsupportedOperationException(pname);
100                     });
101 
102         task.generate(result -> {
103             try {
104                 if (result.hasErrors()) {
105                     throw new AssertionError(result.diagnosticsForKind(Diagnostic.Kind.ERROR));
106                 }
107                 Iterator<? extends JavaFileObject> filesIt = result.get().iterator();
108                 JavaFileObject file = filesIt.next();
109                 if (filesIt.hasNext()) {
110                     throw new IllegalStateException("More than one classfile returned!");
111                 }
112                 byte[] data;
113                 try (InputStream input = file.openInputStream()) {
114                     data = input.readAllBytes();
115                 }
116                 ClassLoader inMemoryLoader = new ClassLoader() {
117                     protected Class<?> findClass(String name) throws ClassNotFoundException {
118                         if ("Test".equals(name)) {
119                             return defineClass(name, data, 0, data.length);
120                         }
121                         return super.findClass(name);
122                     }
123                 };
124                 Class<?> test = Class.forName("Test", false, inMemoryLoader);
125                 try {
126                 java.lang.reflect.Method doTest = test.getDeclaredMethod("doTest");
127                     doTest.invoke(null);
128                     throw new AssertionError("No expected exception!");
129                 } catch (Throwable ex) {
130                     while (ex instanceof InvocationTargetException) {
131                         ex = ((InvocationTargetException) ex).getCause();
132                     }
133                     if (ex instanceof RuntimeException && "test".equals(ex.getMessage())) {
134                         //OK
135                     } else {
136                         throw new IllegalStateException(ex);
137                     }
138                 }
139             } catch (Throwable ex) {
140                 throw new IllegalStateException(ex);
141             }
142         });
143     }
144 
145     private void assertEquals(Object o1, Object o2) {
146         if (!Objects.equals(o1, o2)) {
147             throw new AssertionError();
148         }
149     }
150 
151     public enum SwitchExpression implements ComboParameter {
152         INT("switch (i) { case 0 -> throw new RuntimeException(\"test\"); default -> {if (true) throw new RuntimeException(\"test\"); else yield 0; } }", ExpressionType.INT),
153         BOOLEAN("switch (i) { case 0 -> throw new RuntimeException(\"test\"); default -> {if (true) throw new RuntimeException(\"test\"); else yield true; } }", ExpressionType.BOOLEAN)
154         ;
155         private final String expression;
156         private final ExpressionType expressionType;
157 
158         private SwitchExpression(String expression, ExpressionType expressionType) {
159             this.expression = expression;
160             this.expressionType = expressionType;
161         }
162 
163         @Override
164         public String expand(String optParameter) {
165             return expression;
166         }
167     }
168 
169     public enum Expression implements ComboParameter {
170         SIMPLE("#{SWITCH_EXPRESSION}", ExpressionType.INT),
171         BINARY_SIMPLE("3 + #{SWITCH_EXPRESSION}", ExpressionType.INT),
172         BINARY_LONGER1("3 + #{SWITCH_EXPRESSION} + #{SWITCH_EXPRESSION} + #{SWITCH_EXPRESSION}", ExpressionType.INT),
173         BINARY_LONGER2("3 + switch (0) { default -> 0; } + #{SWITCH_EXPRESSION} + #{SWITCH_EXPRESSION}", ExpressionType.INT),
174         BINARY_LONGER3("3 + #{SWITCH_EXPRESSION} + switch (0) { default -> 0; } + #{SWITCH_EXPRESSION}", ExpressionType.INT),
175         BINARY_BOOLEAN("\"\".isEmpty() && #{SWITCH_EXPRESSION}", ExpressionType.BOOLEAN),
176         ;
177         private final String expression;
178         private final ExpressionType expressionType;
179 
180         private Expression(String expression, ExpressionType expressionType) {
181             this.expression = expression;
182             this.expressionType = expressionType;
183         }
184 
185         @Override
186         public String expand(String optParameter) {
187             return expression;
188         }
189     }
190 
191     public enum Context implements ComboParameter {
192         ASSIGNMENT("i = #{EXPRESSION};", ExpressionType.INT),
193         COMPOUND_ASSIGNMENT("i += #{EXPRESSION};", ExpressionType.INT),
194         METHOD_INVOCATION("m(0, #{EXPRESSION}, 0);", ExpressionType.INT),
195         ARRAY_DEREF("arr[#{EXPRESSION}] = 0;", ExpressionType.INT),
196         IF("if (#{EXPRESSION});", ExpressionType.BOOLEAN),
197         WHILE("while (#{EXPRESSION});", ExpressionType.BOOLEAN)
198         ;
199         private final String code;
200         private final ExpressionType expressionType;
201         private Context(String code, ExpressionType expressionType) {
202             this.code = code;
203             this.expressionType = expressionType;
204         }
205         @Override
206         public String expand(String optParameter) {
207             return code;
208         }
209     }
210 
211     enum ExpressionType {
212         INT,
213         BOOLEAN;
214     }
215 }