jlahoda closed pull request #822: Hint to convert ordinary switch to a rule 
switch
URL: https://github.com/apache/incubator-netbeans/pull/822
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/java/java.hints.test/apichanges.xml 
b/java/java.hints.test/apichanges.xml
index 44ff369155..b460a6aac4 100644
--- a/java/java.hints.test/apichanges.xml
+++ b/java/java.hints.test/apichanges.xml
@@ -83,6 +83,18 @@ is the proper place.
     <!-- ACTUAL CHANGES BEGIN HERE: -->
 
     <changes>
+        <change id="HintTest-options">
+            <api name="JavaHintsTest"/>
+            <summary>Added HintTest.options method</summary>
+            <version major="1" minor="23"/>
+            <date day="6" month="9" year="2018"/>
+            <author login="jlahoda"/>
+            <compatibility addition="yes" binary="compatible" deletion="no" 
deprecation="no" modification="no" semantic="compatible" source="compatible"/>
+            <description>
+                A method <code>HintTestoptions</code> was added that allows to 
specify additional compiler options.
+            </description>
+            <class name="HintTest" 
package="org.netbeans.modules.java.hints.test.api"/>
+        </change>
         <change id="HintTest-fixNotPresent">
             <api name="JavaHintsTest"/>
             <summary>Assertion for missing fixes</summary>
diff --git a/java/java.hints.test/nbproject/project.properties 
b/java/java.hints.test/nbproject/project.properties
index 59117174aa..c16a76c3ce 100644
--- a/java/java.hints.test/nbproject/project.properties
+++ b/java/java.hints.test/nbproject/project.properties
@@ -17,7 +17,7 @@
 is.autoload=true
 javac.source=1.8
 javac.compilerargs=-Xlint -Xlint:-serial
-spec.version.base=1.22.0
+spec.version.base=1.23.0
 javadoc.arch=${basedir}/arch.xml
 javadoc.apichanges=${basedir}/apichanges.xml
 requires.nb.javac=true
diff --git 
a/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
 
b/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
index 98c80cea70..1fb4ade3a8 100644
--- 
a/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
+++ 
b/java/java.hints.test/src/org/netbeans/modules/java/hints/test/api/HintTest.java
@@ -114,6 +114,7 @@
 import org.netbeans.spi.java.hints.Hint.Kind;
 import org.netbeans.spi.java.hints.HintContext;
 import org.netbeans.spi.java.hints.JavaFix;
+import org.netbeans.spi.java.queries.CompilerOptionsQueryImplementation;
 import org.netbeans.spi.java.queries.SourceForBinaryQueryImplementation;
 import org.netbeans.spi.java.queries.SourceLevelQueryImplementation;
 import org.openide.LifecycleManager;
@@ -177,6 +178,7 @@
     private final HintsSettings hintSettings;
     private final List<FileObject> checkCompilable = new 
ArrayList<FileObject>();
     private String sourceLevel = "1.5";
+    private List<String> extraOptions = new ArrayList<>();
     private Character caretMarker;
     private FileObject testFile;
     private int caret = -1;
@@ -211,6 +213,7 @@ private HintTest() throws Exception {
                           new TestProxyClassPathProvider(),
                           new TestSourceForBinaryQuery(),
                           new TestSourceLevelQueryImplementation(),
+                          new TestCompilerOptionsQueryImplementation(),
                           JavaDataLoader.findObject(JavaDataLoader.class, 
true)),
             Lookups.metaInfServices(HintTest.class.getClassLoader()),
             Lookups.singleton(HintTest.class.getClassLoader())
@@ -387,6 +390,17 @@ public HintTest sourceLevel(String sourceLevel) {
         return this;
     }
 
+    /**Sets additional command line options for all Java files used in this 
test.
+     *
+     * @param options the additional command line options to use while parsing 
Java files
+     * @return itself
+     * @since 1.23
+     */
+    public HintTest options(String... options) {
+        extraOptions.addAll(Arrays.asList(options));
+        return this;
+    }
+
     /**Sets a preference that will be visible to the hint.
      *
      * @param preferencesKey a key for the preferences
@@ -711,6 +725,28 @@ public String getSourceLevel(FileObject javaFile) {
 
     }
 
+    private class TestCompilerOptionsQueryImplementation implements 
CompilerOptionsQueryImplementation {
+
+        @Override
+        public Result getOptions(FileObject file) {
+            return new Result() {
+                @Override
+                public List<? extends String> getArguments() {
+                    return extraOptions;
+                }
+
+                @Override
+                public void addChangeListener(ChangeListener listener) {
+                }
+
+                @Override
+                public void removeChangeListener(ChangeListener listener) {
+                }
+            };
+        }
+
+    }
+
 
     private static class DeadlockTask implements Task<CompilationController> {
 
@@ -1085,7 +1121,7 @@ private void assertSameOutput(String result, String 
golden) throws Exception {
                         rt = s1.token();
                         if (!wh) {
                             if 
(!rt.text().toString().equals(gt.text().toString())) {
-                                failNotSame(result, golden, s1.offset());
+                                failNotSame(result, golden, s1.offset(), 
s2.offset());
                             }
                         } else if (!isWH(rt)) {
                             s1.movePrevious();
@@ -1093,14 +1129,14 @@ private void assertSameOutput(String result, String 
golden) throws Exception {
                         }
                     } while (isWH(rt) && s1.moveNext());
                 } else if (!wh) {
-                    failNotSame(result, golden, s2.offset());
+                    failNotSame(result, golden, s1.offset(), s2.offset());
                 }
             }
             
             s1.movePrevious();
             s2.movePrevious();
             if (s1.moveNext() != s2.moveNext()) {
-                failNotSame(result, golden, s2.offset());
+                failNotSame(result, golden, s1.offset(), s2.offset());
             }
         }
         
@@ -1108,8 +1144,8 @@ private boolean isWH(Token t) {
             return t.id() == JavaTokenId.WHITESPACE;
         }
         
-        private void failNotSame(String result, String golden, int point) {
-            String fakeGolden = result.substring(0, point) + 
golden.substring(point);
+        private void failNotSame(String result, String golden, int 
resultPoint, int goldenPoint) {
+            String fakeGolden = result.substring(0, resultPoint) + 
golden.substring(goldenPoint);
             assertEquals("The output code does not match the expected code.", 
fakeGolden, result);
         }
         
diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/TreeShims.java 
b/java/java.hints/src/org/netbeans/modules/java/hints/TreeShims.java
new file mode 100644
index 0000000000..267a3ef2f4
--- /dev/null
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/TreeShims.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.java.hints;
+
+import com.sun.source.tree.CaseTree;
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.Tree;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.List;
+
+public class TreeShims {
+
+    public static List<? extends ExpressionTree> getExpressions(CaseTree node) 
{
+        try {
+            Method getExpressions = 
CaseTree.class.getDeclaredMethod("getExpressions");
+            return (List<? extends ExpressionTree>) 
getExpressions.invoke(node);
+        } catch (NoSuchMethodException ex) {
+            return Collections.singletonList(node.getExpression());
+        } catch (IllegalAccessException | IllegalArgumentException | 
InvocationTargetException ex) {
+            throw TreeShims.<RuntimeException>throwAny(ex);
+        }
+    }
+
+    public static Tree getBody(CaseTree node) {
+        try {
+            Method getBody = CaseTree.class.getDeclaredMethod("getBody");
+            return (Tree) getBody.invoke(node);
+        } catch (NoSuchMethodException ex) {
+            return null;
+        } catch (IllegalAccessException | IllegalArgumentException | 
InvocationTargetException ex) {
+            throw TreeShims.<RuntimeException>throwAny(ex);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T extends Throwable> RuntimeException throwAny(Throwable 
t) throws T {
+        throw (T) t;
+    }
+}
diff --git 
a/java/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitch.java
 
b/java/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitch.java
new file mode 100644
index 0000000000..4f8955dd39
--- /dev/null
+++ 
b/java/java.hints/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitch.java
@@ -0,0 +1,271 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.java.hints.jdk;
+
+import com.sun.source.tree.AssignmentTree;
+import com.sun.source.tree.BlockTree;
+import com.sun.source.tree.BreakTree;
+import com.sun.source.tree.CaseTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.ContinueTree;
+import com.sun.source.tree.ExpressionStatementTree;
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.IdentifierTree;
+import com.sun.source.tree.IfTree;
+import com.sun.source.tree.LambdaExpressionTree;
+import com.sun.source.tree.ReturnTree;
+import com.sun.source.tree.StatementTree;
+import com.sun.source.tree.SwitchTree;
+import com.sun.source.tree.ThrowTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.Tree.Kind;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreePathScanner;
+import com.sun.source.util.TreeScanner;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.VariableElement;
+import org.netbeans.api.java.queries.CompilerOptionsQuery;
+import org.netbeans.api.java.source.CompilationInfo;
+import org.netbeans.api.java.source.TreeMaker;
+import org.netbeans.api.java.source.WorkingCopy;
+import org.netbeans.modules.java.hints.TreeShims;
+import org.netbeans.spi.editor.hints.ErrorDescription;
+import org.netbeans.spi.java.hints.ErrorDescriptionFactory;
+import org.netbeans.spi.java.hints.Hint;
+import org.netbeans.spi.java.hints.HintContext;
+import org.netbeans.spi.java.hints.JavaFix;
+import org.netbeans.spi.java.hints.TriggerTreeKind;
+import org.openide.util.NbBundle.Messages;
+
+@Hint(displayName = 
"#DN_org.netbeans.modules.java.hints.jdk.ConvertSwitchToRuleSwitch",
+      description = 
"#DESC_org.netbeans.modules.java.hints.jdk.ConvertSwitchToRuleSwitch", 
category="rules15",
+      minSourceVersion = "12")
+@Messages({
+    "DN_org.netbeans.modules.java.hints.jdk.ConvertSwitchToRuleSwitch=Convert 
switch to rule switch",
+    
"DESC_org.netbeans.modules.java.hints.jdk.ConvertSwitchToRuleSwitch=Converts 
switch to rule switch",
+})
+public class ConvertSwitchToRuleSwitch {
+    
+    @TriggerTreeKind(Tree.Kind.SWITCH)
+    @Messages("ERR_ConverSwitchToRuleSwitch=Convert switch to rule switch")
+    public static ErrorDescription switch2RuleSwitch(HintContext ctx) {
+        if 
(!CompilerOptionsQuery.getOptions(ctx.getInfo().getFileObject()).getArguments().contains("--enable-preview"))
+            return null;
+        SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
+        boolean completesNormally = false;
+        boolean wasDefault = false;
+        boolean wasEmpty = false;
+        for (CaseTree ct : st.getCases()) {
+            if (ct.getStatements() == null) //TODO: test
+                return null;
+            if (completesNormally) {
+                if (!wasEmpty) //fall-through from a non-empty case
+                    return null;
+                if (wasDefault) //fall-through from default to a case
+                    return null;
+                if (!wasDefault && ct.getExpression() == null) //fall-through 
from a case to default
+                    return null;
+            }
+            completesNormally = completesNormally(ctx.getInfo(), new 
TreePath(ctx.getPath(), ct));
+            wasDefault = ct.getExpression() == null;
+            wasEmpty = ct.getStatements().isEmpty();
+        }
+        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), 
Bundle.ERR_ConverSwitchToRuleSwitch(), new FixImpl(ctx.getInfo(), 
ctx.getPath()).toEditorFix());
+    }
+    private static boolean completesNormally(CompilationInfo info, TreePath 
tp) {
+        class Scanner extends TreePathScanner<Void, Void> {
+            private boolean completesNormally = true;
+            private Set<Tree> seenTrees = new HashSet<>();
+            @Override
+            public Void visitReturn(ReturnTree node, Void p) {
+                completesNormally = false;
+                return null;
+            }
+            @Override
+            public Void visitBreak(BreakTree node, Void p) {
+                completesNormally &= 
seenTrees.contains(info.getTreeUtilities().getBreakContinueTarget(getCurrentPath()));
+                return null;
+            }
+            @Override
+            public Void visitContinue(ContinueTree node, Void p) {
+                completesNormally &= 
seenTrees.contains(info.getTreeUtilities().getBreakContinueTarget(getCurrentPath()));
+                return null;
+            }
+            @Override
+            public Void visitThrow(ThrowTree node, Void p) {
+                completesNormally = false;
+                return null;
+            }
+            @Override
+            public Void visitIf(IfTree node, Void p) {
+                boolean origCompletesNormally = completesNormally;
+                scan(node.getThenStatement(), p);
+                boolean afterThen = completesNormally;
+                completesNormally = origCompletesNormally;
+                scan(node.getElseStatement(), p);
+                completesNormally |= afterThen;
+                return null;
+            }
+            @Override
+            public Void visitSwitch(SwitchTree node, Void p) {
+                //exhaustiveness: (TODO)
+                boolean hasDefault = node.getCases().stream().anyMatch(c -> 
c.getExpression() == null);
+                if (node.getCases().size() > 0) {
+                    scan(node.getCases().get(node.getCases().size() - 1), p);
+                }
+                completesNormally |= !hasDefault;
+                return null;
+            }
+            //TODO: loops
+            @Override
+            public Void scan(Tree tree, Void p) {
+                seenTrees.add(tree);
+                return super.scan(tree, p);
+            }
+            @Override
+            public Void visitLambdaExpression(LambdaExpressionTree node, Void 
p) {
+                return null;
+            }
+            @Override
+            public Void visitClass(ClassTree node, Void p) {
+                return null;
+            }
+        }
+
+        Scanner scanner = new Scanner();
+
+        scanner.scan(tp, null);
+        return scanner.completesNormally;
+    }
+
+    private static final class FixImpl extends JavaFix {
+
+        public FixImpl(CompilationInfo info, TreePath switchStatement) {
+            super(info, switchStatement);
+        }
+
+        @Override
+        @Messages("FIX_ConvertToRuleSwitch=Convert to rule switch")
+        protected String getText() {
+            return Bundle.FIX_ConvertToRuleSwitch();
+        }
+
+        @Override
+        protected void performRewrite(TransformationContext ctx) {
+            WorkingCopy wc = ctx.getWorkingCopy();
+            TreePath tp = ctx.getPath();
+            TreeMaker make = wc.getTreeMaker();
+            SwitchTree st = (SwitchTree) tp.getLeaf();
+            List<CaseTree> newCases = new ArrayList<>();
+            List<ExpressionTree> patterns = new ArrayList<>();
+            Set<VariableElement> variablesDeclaredInOtherCases = new 
HashSet<>();
+
+            for (Iterator<? extends CaseTree> it = st.getCases().iterator(); 
it.hasNext();) {
+                CaseTree ct = it.next();
+                TreePath casePath = new TreePath(tp, ct);
+                patterns.addAll(TreeShims.getExpressions(ct));
+                List<StatementTree> statements = new 
ArrayList<>(ct.getStatements());
+                if (statements.isEmpty()) {
+                    if (it.hasNext()) {
+                        continue;
+                    }
+                    //last case, no break
+                } else if (statements.get(statements.size() - 1).getKind() == 
Kind.BREAK &&
+                    
ctx.getWorkingCopy().getTreeUtilities().getBreakContinueTarget(new TreePath(new 
TreePath(tp, ct), statements.get(statements.size() - 1))) == st) {
+                    statements.remove(statements.size() - 1);
+                } else {
+                    new TreePathScanner<Void, Void>() {
+                        @Override
+                        public Void visitBlock(BlockTree node, Void p) {
+                            if (!node.getStatements().isEmpty() &&
+                                    
node.getStatements().get(node.getStatements().size() - 1).getKind() == 
Kind.BREAK &&
+                                    
ctx.getWorkingCopy().getTreeUtilities().getBreakContinueTarget(new 
TreePath(getCurrentPath(), node.getStatements().get(node.getStatements().size() 
- 1))) == st) {
+                                wc.rewrite(node, 
make.removeBlockStatement(node, 
node.getStatements().get(node.getStatements().size() - 1)));
+                                //TODO: optimize ifs?
+                            }
+                            return super.visitBlock(node, p);
+                        }
+                    }.scan(new TreePath(new TreePath(tp, ct), 
statements.get(statements.size() - 1)), null);
+                }
+                Set<Element> seenVariables = new HashSet<>();
+                int idx = 0;
+                for (StatementTree statement : new ArrayList<>(statements)) {
+                    TreePath statementPath = new TreePath(casePath, statement);
+                    if (statement.getKind() == Kind.EXPRESSION_STATEMENT) {
+                        ExpressionTree expr = ((ExpressionStatementTree) 
statement).getExpression();
+                        if (expr.getKind() == Kind.ASSIGNMENT) {
+                            AssignmentTree at = (AssignmentTree) expr;
+                            Element var = wc.getTrees().getElement(new 
TreePath(new TreePath(statementPath, at), at.getVariable()));
+                            if (variablesDeclaredInOtherCases.contains(var)) {
+                                seenVariables.add(var);
+                                //XXX: take type from the original variable
+                                wc.rewrite(statement,
+                                           
make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), 
var.getSimpleName(), make.Type(var.asType()), at.getExpression()));
+                            }
+                        }
+                    }
+                    Set<Element> thisStatementSeenVariables = new HashSet<>();
+                    new TreePathScanner<Void, Void>() {
+                        @Override
+                        public Void visitIdentifier(IdentifierTree node, Void 
p) {
+                            Element el = 
wc.getTrees().getElement(getCurrentPath());
+                            if (variablesDeclaredInOtherCases.contains(el) && 
seenVariables.add(el)) {
+                                thisStatementSeenVariables.add(el);
+                            }
+                            return super.visitIdentifier(node, p);
+                        }
+                    }.scan(statementPath, null);
+
+                    if (!thisStatementSeenVariables.isEmpty()) {
+                        for (Element el : thisStatementSeenVariables) {
+                            VariableElement var = (VariableElement) el;
+                            statements.add(idx++, 
make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), 
var.getSimpleName(), make.Type(var.asType()), null));
+                        }
+                    }
+                    idx++;
+                }
+                Tree body = make.Block(statements, false);
+                if (statements.size() == 1) {
+                    if (statements.get(0).getKind() == 
Kind.EXPRESSION_STATEMENT ||
+                            statements.get(0).getKind() == Kind.THROW ||
+                            statements.get(0).getKind() == Kind.BLOCK) {
+                        body = statements.get(0);
+                    }
+                }
+                newCases.add(make.Case(patterns, body));
+                patterns = new ArrayList<>();
+                for (StatementTree statement : ct.getStatements()) {
+                    if (statement.getKind() == Kind.VARIABLE) {
+                        variablesDeclaredInOtherCases.add((VariableElement) 
wc.getTrees().getElement(new TreePath(casePath, statement)));
+                    }
+                }
+            }
+
+            wc.rewrite(st, make.Switch(st.getExpression(), newCases));
+        }
+        
+    }
+}
diff --git 
a/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitchTest.java
 
b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitchTest.java
new file mode 100644
index 0000000000..f204ad8202
--- /dev/null
+++ 
b/java/java.hints/test/unit/src/org/netbeans/modules/java/hints/jdk/ConvertSwitchToRuleSwitchTest.java
@@ -0,0 +1,471 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.java.hints.jdk;
+
+import com.sun.tools.javac.tree.JCTree;
+import javax.lang.model.SourceVersion;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import org.netbeans.junit.NbTestCase;
+import org.netbeans.modules.java.hints.test.api.HintTest;
+
+/**
+ *
+ * @author lahvac
+ */
+public class ConvertSwitchToRuleSwitchTest extends NbTestCase {
+    
+    public ConvertSwitchToRuleSwitchTest(String name) {
+        super(name);
+    }
+    
+    public void testSwitch2RuleSwitch() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 1: result = \"1\"; break;\n" +
+                       "             case 2: if (true) result = \"2\"; 
break;\n" +
+                       "             case 3: System.err.println(3); result = 
\"3\"; break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 1 -> result = \"1\";\n" +
+                              "             case 2 -> { if (true) result = 
\"2\"; }\n" +
+                              "             case 3 -> { System.err.println(3); 
result = \"3\"; }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+    
+    public void testLastNotBreak() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 1: if (p == 1) { result = \"1\"; 
break; } else { result = \"2\"; break; }\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 1 -> { if (p == 1) { result = 
\"1\"; } else { result = \"2\"; } }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+    
+    public void testMultipleCases() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "             case 1: result = \"1\"; break;\n" +
+                       "             case 2: result = \"2\"; break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0, 1 -> result = \"1\";\n" +
+                              "             case 2 -> result = \"2\";\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+    
+    public void testFallThrough() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0: System.err.println(0);\n" +
+                       "             case 1: result = \"1\"; break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+    
+    public void testMissingLastBreak() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "             case 1: result = \"1\"; break;\n" +
+                       "             case 2: result = \"2\";\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0, 1 -> result = \"1\";\n" +
+                              "             case 2 -> result = \"2\";\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+
+    public void testDefault() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0: result = \"1\"; break;\n" +
+                       "             default: result = \"d\"; break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0 -> result = \"1\";\n" +
+                              "             default -> result = \"d\";\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+
+    public void testVariables1() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "                 int i = 0;\n" +
+                       "                 int j = 0;\n" +
+                       "                 break;\n" +
+                       "             default:\n" +
+                       "                 i = 0;\n" +
+                       "                 System.err.println(i);\n" +
+                       "                 System.err.println(j = 15);\n" +
+                       "                 break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0 -> {\n" +
+                              "                 int i = 0;\n" +
+                              "                 int j = 0;\n" +
+                              "             }\n" +
+                              "             default -> {\n" +
+                              "                 int i = 0;\n" +
+                              "                 System.err.println(i);\n" +
+                              "                 int j;\n" +
+                              "                 System.err.println(j = 15);\n" 
+
+                              "             }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+
+    public void testFallThroughDefault1() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             default:\n" +
+                       "             case 0:\n" +
+                       "                 break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+
+    public void testFallThroughDefault2() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "             default:\n" +
+                       "                 break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+
+    public void testTrailingEmptyCase() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "                 int i = 0;\n" +
+                       "                 int j = 0;\n" +
+                       "                 break;\n" +
+                       "             default:\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + 
Bundle.ERR_ConverSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0 -> {\n" +
+                              "                 int i = 0;\n" +
+                              "                 int j = 0;\n" +
+                              "             }\n" +
+                              "             default -> { }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}\n");
+    }
+
+    public void testNeedsPreview() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0:\n" +
+                       "                 int i = 0;\n" +
+                       "                 int j = 0;\n" +
+                       "                 break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+
+    public void testBreakInside1() throws Exception {
+        HintTest.create()
+                .input("package test;" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0: while (true) break;\n" +
+                       "             case 1: INNER: while (true) break 
INNER;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+
+    public void testBreakInside2() throws Exception {
+        HintTest.create()
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0: while (true) break;\n" +
+                       "                     break;\n" +
+                       "             case 1: INNER: while (true) break 
INNER;\n" +
+                       "                     break;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("4:9-4:15:verifier:Convert switch to rule switch")
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;\n" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         switch (p) {\n" +
+                              "             case 0 -> {\n" +
+                              "                 while (true) break;\n" +
+                              "             }\n" +
+                              "             case 1 -> {\n" +
+                              "                 INNER: while (true) break 
INNER;\n" +
+                              "             }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}");
+    }
+
+    public void testContinueInside1() throws Exception {
+        HintTest.create()
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         switch (p) {\n" +
+                       "             case 0: while (p++ < 12) continue;\n" +
+                       "             case 1: INNER: while (p++ < 12) continue 
INNER;\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .assertWarnings();
+    }
+
+    public void testContinueInside2() throws Exception {
+        HintTest.create()
+                .input("package test;\n" +
+                       "public class Test {\n" +
+                       "     private void test(int p) {\n" +
+                       "         String result;\n" +
+                       "         OUTER: while (p-- > 0) {\n" +
+                       "             switch (p) {\n" +
+                       "                 case 0: while (p++ < 12) continue 
OUTER;\n" +
+                       "                         break;\n" +
+                       "                 case 1: INNER: while (p++ < 12) 
continue OUTER;\n" +
+                       "                         break;\n" +
+                       "             }\n" +
+                       "         }\n" +
+                       "     }\n" +
+                       "}\n")
+                .sourceLevel(SourceVersion.latest().name())
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("5:13-5:19:verifier:Convert switch to rule 
switch")
+                .applyFix()
+                .assertCompilable()
+                .assertOutput("package test;\n" +
+                              "public class Test {\n" +
+                              "     private void test(int p) {\n" +
+                              "         String result;\n" +
+                              "         OUTER: while (p-- > 0) {\n" +
+                              "             switch (p) {\n" +
+                              "                 case 0 -> {\n" +
+                              "                     while (p++ < 12) continue 
OUTER;\n" +
+                              "                 }\n" +
+                              "                 case 1 -> {\n" +
+                              "                     INNER: while (p++ < 12) 
continue OUTER;\n" +
+                              "                 }\n" +
+                              "             }\n" +
+                              "         }\n" +
+                              "     }\n" +
+                              "}");
+    }
+
+    public static Test suite() {
+        TestSuite suite = new TestSuite();
+        try {
+            Class.forName("com.sun.source.tree.CaseTree$CaseKind", false, 
JCTree.class.getClassLoader());
+            suite.addTestSuite(ConvertSwitchToRuleSwitchTest.class);
+        } catch (ClassNotFoundException ex) {
+            //OK
+            suite.addTest(new ConvertSwitchToRuleSwitchTest("noop"));
+        }
+        return suite;
+    }
+
+    public void noop() {}
+}
diff --git a/java/java.source.base/apichanges.xml 
b/java/java.source.base/apichanges.xml
index 8115cfd11a..d1c2be7b4f 100644
--- a/java/java.source.base/apichanges.xml
+++ b/java/java.source.base/apichanges.xml
@@ -25,6 +25,19 @@
     <apidef name="javasource_base">Java Source API</apidef>
 </apidefs>
 <changes>
+    <change id="TreeMaker.Case">
+        <api name="javasource_base"/>
+        <summary>Adding case-related overload to TreeMaker</summary>
+        <version major="1" minor="2.39"/>
+        <date day="6" month="9" year="2018"/>
+        <author login="jlahoda"/>
+        <compatibility addition="yes" binary="compatible" source="compatible"/>
+        <description>
+            Added TreeMaker.CaseMultipleLabels(List&lt;? extends 
ExpressionTree&gt; patterns, List&lt;? extends StatementTree&gt; statements) and
+            TreeMaker.Case(List&lt;? extends ExpressionTree&gt; patterns, Tree 
body) overloads.
+        </description>
+        <class name="TreeUtilities" package="org.netbeans.api.java.source"/>
+    </change>
     <change id="BuildArtifactMapper.isCompileOnSaveSupported">
         <api name="javasource_base"/>
         <summary>Check the var type variable in given tree path.</summary>
diff --git a/java/java.source.base/nbproject/project.properties 
b/java/java.source.base/nbproject/project.properties
index 084b11b0d1..76919d6377 100644
--- a/java/java.source.base/nbproject/project.properties
+++ b/java/java.source.base/nbproject/project.properties
@@ -23,7 +23,7 @@ javadoc.name=Java Source Base
 javadoc.title=Java Source Base
 javadoc.arch=${basedir}/arch.xml
 javadoc.apichanges=${basedir}/apichanges.xml
-spec.version.base=2.38.0
+spec.version.base=2.39.0
 
test.qa-functional.cp.extra=${refactoring.java.dir}/modules/ext/nb-javac-api.jar
 test.unit.run.cp.extra=${o.n.core.dir}/core/core.jar:\
     ${o.n.core.dir}/lib/boot.jar:\
diff --git 
a/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java 
b/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
index 6d52e93f0e..174a820c44 100644
--- a/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
+++ b/java/java.source.base/src/org/netbeans/api/java/source/TreeMaker.java
@@ -241,6 +241,30 @@ public CaseTree Case(ExpressionTree expression, List<? 
extends StatementTree> st
         return delegate.Case(expression, statements);
     }
     
+    /**
+     * Creates a new CaseTree.
+     *
+     * @param patterns the labels for this case statement.
+     * @param statements the list of statements.
+     * @see com.sun.source.tree.CaseTree
+     * @since 2.39
+     */
+    public CaseTree CaseMultipleLabels(List<? extends ExpressionTree> 
patterns, List<? extends StatementTree> statements) {
+        return delegate.Case(patterns, statements);
+    }
+    
+    /**
+     * Creates a new CaseTree for a rule case (case &lt;constants&gt; -> 
&lt;body&gt;).
+     *
+     * @param patterns the labels for this case statement.
+     * @param body the case's body
+     * @see com.sun.source.tree.CaseTree
+     * @since 2.39
+     */
+    public CaseTree Case(List<? extends ExpressionTree> patterns, Tree body) {
+        return delegate.Case(patterns, body);
+    }
+    
     /**
      * Creates a new CatchTree.
      *
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/TreeShims.java 
b/java/java.source.base/src/org/netbeans/modules/java/source/TreeShims.java
new file mode 100644
index 0000000000..bbf8900d5f
--- /dev/null
+++ b/java/java.source.base/src/org/netbeans/modules/java/source/TreeShims.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.netbeans.modules.java.source;
+
+import com.sun.source.tree.CaseTree;
+import com.sun.source.tree.ExpressionTree;
+import com.sun.source.tree.Tree;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.List;
+
+public class TreeShims {
+
+    public static List<? extends ExpressionTree> getExpressions(CaseTree node) 
{
+        try {
+            Method getExpressions = 
CaseTree.class.getDeclaredMethod("getExpressions");
+            return (List<? extends ExpressionTree>) 
getExpressions.invoke(node);
+        } catch (NoSuchMethodException ex) {
+            return Collections.singletonList(node.getExpression());
+        } catch (IllegalAccessException | IllegalArgumentException | 
InvocationTargetException ex) {
+            throw TreeShims.<RuntimeException>throwAny(ex);
+        }
+    }
+
+    public static Tree getBody(CaseTree node) {
+        try {
+            Method getBody = CaseTree.class.getDeclaredMethod("getBody");
+            return (Tree) getBody.invoke(node);
+        } catch (NoSuchMethodException ex) {
+            return null;
+        } catch (IllegalAccessException | IllegalArgumentException | 
InvocationTargetException ex) {
+            throw TreeShims.<RuntimeException>throwAny(ex);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static <T extends Throwable> RuntimeException throwAny(Throwable 
t) throws T {
+        throw (T) t;
+    }
+}
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/builder/TreeFactory.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/builder/TreeFactory.java
index 5fcb34f3ef..8157cecbe5 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/builder/TreeFactory.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/builder/TreeFactory.java
@@ -194,14 +194,75 @@ public BlockTree Block(List<? extends StatementTree> 
statements, boolean isStati
     
     public BreakTree Break(CharSequence label) {
         Name n = label != null ? names.fromString(label.toString()) : null;
-        return make.at(NOPOS).Break(n);
+        try {
+            return make.at(NOPOS).Break(n);
+        } catch (NoSuchMethodError err) {
+            try {
+                return (BreakTree) make.getClass().getMethod("Break", 
JCExpression.class).invoke(make.at(NOPOS), label != null ? Identifier(label) : 
null);
+            } catch (Throwable t) {
+                err.addSuppressed(t);
+                throw throwAny(err);
+            }
+        }
+    }
+    
+    public BreakTree Break(ExpressionTree value) {
+        try {
+            return (BreakTree) make.getClass().getMethod("Break", 
JCExpression.class).invoke(make.at(NOPOS), (JCExpression) value);
+        } catch (Throwable t) {
+            throw throwAny(t);
+        }
     }
     
     public CaseTree Case(ExpressionTree expression, List<? extends 
StatementTree> statements) {
         ListBuffer<JCStatement> lb = new ListBuffer<JCStatement>();
         for (StatementTree t : statements)
             lb.append((JCStatement)t);
-        return make.at(NOPOS).Case((JCExpression)expression, lb.toList());
+        try {
+            return make.at(NOPOS).Case((JCExpression)expression, lb.toList());
+        } catch (NoSuchMethodError err) {
+            try {
+                Class<Enum> caseKind = (Class<Enum>) 
Class.forName("com.sun.source.tree.CaseTree$CaseKind", false, 
JCTree.class.getClassLoader());
+                com.sun.tools.javac.util.List<? extends Object> pats = 
expression != null ? com.sun.tools.javac.util.List.of((JCExpression)expression) 
: com.sun.tools.javac.util.List.nil();
+                return (CaseTree) make.getClass().getMethod("Case", caseKind, 
com.sun.tools.javac.util.List.class, com.sun.tools.javac.util.List.class, 
JCTree.class).invoke(make.at(NOPOS), Enum.valueOf(caseKind, "STATEMENT"), pats, 
lb.toList(), null);
+            } catch (Throwable t) {
+                err.addSuppressed(t);
+                throw throwAny(err);
+            }
+        }
+    }
+    
+    public CaseTree Case(List<? extends ExpressionTree> expressions, List<? 
extends StatementTree> statements) {
+        switch (expressions.size()) {
+            case 0: return Case((ExpressionTree) null, statements);
+            case 1: return Case(expressions.get(0), statements);
+        }
+        ListBuffer<JCStatement> lb = new ListBuffer<JCStatement>();
+        for (StatementTree t : statements)
+            lb.append((JCStatement)t);
+        ListBuffer<JCExpression> exprs = new ListBuffer<>();
+        for (ExpressionTree t : expressions)
+            exprs.append((JCExpression)t);
+        try {
+            Class<Enum> caseKind = (Class<Enum>) 
Class.forName("com.sun.source.tree.CaseTree$CaseKind", false, 
JCTree.class.getClassLoader());
+            return (CaseTree) make.getClass().getMethod("Case", caseKind, 
com.sun.tools.javac.util.List.class, com.sun.tools.javac.util.List.class, 
JCTree.class).invoke(make.at(NOPOS), Enum.valueOf(caseKind, "STATEMENT"), 
exprs.toList(), lb.toList(), null);
+        } catch (Throwable t) {
+            throw throwAny(t);
+        }
+    }
+    
+    public CaseTree Case(List<? extends ExpressionTree> expressions, Tree 
body) {
+        ListBuffer<JCStatement> lb = new ListBuffer<>();
+        lb.append(body instanceof ExpressionTree ? (JCStatement) 
Break((ExpressionTree) body) : (JCStatement) body);
+        ListBuffer<JCExpression> exprs = new ListBuffer<>();
+        for (ExpressionTree t : expressions)
+            exprs.append((JCExpression)t);
+        try {
+            Class<Enum> caseKind = (Class<Enum>) 
Class.forName("com.sun.source.tree.CaseTree$CaseKind", false, 
JCTree.class.getClassLoader());
+            return (CaseTree) make.getClass().getMethod("Case", caseKind, 
com.sun.tools.javac.util.List.class, com.sun.tools.javac.util.List.class, 
JCTree.class).invoke(make.at(NOPOS), Enum.valueOf(caseKind, "RULE"), 
exprs.toList(), lb.toList(), body);
+        } catch (Throwable t) {
+            throw throwAny(t);
+        }
     }
     
     public CatchTree Catch(VariableTree parameter, BlockTree block) {
@@ -1845,4 +1906,9 @@ public ReferenceTree Reference(ExpressionTree qualExpr, 
CharSequence member, Lis
         }
         return docMake.at(NOPOS).newReferenceTree("", (JCExpression) qualExpr, 
member != null ? (Name) names.fromString(member.toString()) : null, 
paramTypesList);
     }
+    
+    @SuppressWarnings("unchecked")
+    private <T extends Throwable> RuntimeException throwAny(Throwable t) 
throws T {
+        throw (T) t;
+    }
 }
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java
index 1a499eb768..0efb0f5c4a 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/parsing/JavacParser.java
@@ -1044,6 +1044,8 @@ private static JavacTaskImpl createJavacTask(
                 xmoduleSeen = true;
             } else if (option.equals("-parameters") || 
option.startsWith("-Xlint")) {     //NOI18N
                 res.add(option);
+            } else if (option.equals("--enable-preview")) {     //NOI18N
+                res.add(option);
             } else if ((
                     option.startsWith("--add-modules") ||   //NOI18N
                     option.startsWith("--limit-modules") || //NOI18N
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java
index 6abd4a5578..667dbd6798 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/pretty/VeryPretty.java
@@ -1273,17 +1273,29 @@ public void visitSwitch(JCSwitch tree) {
     public void visitCase(JCCase tree) {
         int old = cs.indentCasesFromSwitch() ? indent() : out.leftMargin;
         toLeftMargin();
-       if (tree.pat == null) {
+        java.util.List<JCExpression> patterns = 
CasualDiff.getCasePatterns(tree);
+       if (patterns.isEmpty()) {
            print("default");
        } else {
            print("case ");
-           printNoParenExpr(tree.pat);
+            String sep = "";
+            for (JCExpression pat : patterns) {
+                print(sep);
+                printNoParenExpr(pat);
+                sep = ", "; //TODO: space or not should be a configuration 
setting
+            }
        }
-       print(':');
-       newline();
-       indent();
-       printStats(tree.stats);
-       undent(old);
+        Object caseKind = CasualDiff.getCaseKind(tree);
+        if (caseKind == null || !String.valueOf(caseKind).equals("RULE")) {
+            print(':');
+            newline();
+            indent();
+            printStats(tree.stats);
+            undent(old);
+        } else {
+            print(" -> "); //TODO: configure spaces!
+            printStat(tree.stats.head);
+        }
     }
 
     @Override
@@ -1425,9 +1437,10 @@ public void visitExec(JCExpressionStatement tree) {
     @Override
     public void visitBreak(JCBreak tree) {
        print("break");
-       if (tree.label != null) {
+        //TODO: value breaks
+       if (tree.getLabel() != null) {
            needSpace();
-           print(tree.label);
+           print(tree.getLabel());
        }
        print(';');
     }
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java
index a37dfc3518..9d3a5b29e2 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/CasualDiff.java
@@ -1876,20 +1876,61 @@ protected int diffSwitch(JCSwitch oldT, JCSwitch newT, 
int[] bounds) {
 
     protected int diffCase(JCCase oldT, JCCase newT, int[] bounds) {
         int localPointer = bounds[0];
-        if (oldT.pat != null) {
-            int[] patBounds = getBounds(oldT.pat);
-            copyTo(localPointer, patBounds[0]);
-            localPointer = diffTree(oldT.pat, newT.pat, patBounds);
-            tokenSequence.move(patBounds[1]);
-            do { } while (tokenSequence.moveNext() && JavaTokenId.COLON != 
tokenSequence.token().id());
+        List<JCExpression> oldPatterns = getCasePatterns(oldT);
+        List<JCExpression> newPatterns = getCasePatterns(newT);
+        PositionEstimator patternEst = EstimatorFactory.casePatterns(
+                oldPatterns,
+                newPatterns,
+                diffContext
+        );
+        int posHint;
+        int endpos;
+        int copyTo;
+        if (oldPatterns.isEmpty()) {
+            moveFwdToOneOfTokens(tokenSequence, bounds[0], 
EnumSet.of(JavaTokenId.DEFAULT));
             tokenSequence.moveNext();
-            copyTo(localPointer, localPointer = tokenSequence.offset());
+            copyTo = endpos = posHint = tokenSequence.offset();
+
+            if (!newPatterns.isEmpty()) {
+                copyTo = getOldPos(oldT);
+            }
+        } else {
+            copyTo = posHint = 
oldPatterns.iterator().next().getStartPosition();
+            endpos = endPos(oldPatterns.get(oldPatterns.size() - 1));
+
+            if (newPatterns.isEmpty()) {
+                localPointer = copyTo = posHint = endpos;
+                printer.print("default");
+            }
         }
-        // todo (#pf): hot-fix of #113313, think about correct matching later
-        if (oldT.pat == null && newT.pat != null) {
-            printer.print(newT);
-            printer.newline();
-            return bounds[1];
+        copyTo(localPointer, copyTo);
+        localPointer = diffList2(oldPatterns, newPatterns, posHint, 
patternEst);
+        tokenSequence.move(endpos);
+        do { } while (tokenSequence.moveNext() && JavaTokenId.COLON != 
tokenSequence.token().id() && JavaTokenId.ARROW != tokenSequence.token().id());
+        boolean reindentStatements = false;
+        if (Objects.equals(getCaseKind(oldT), getCaseKind(newT))) {
+            tokenSequence.moveNext();
+            copyTo(localPointer, localPointer = tokenSequence.offset());
+        } else {
+            if (JavaTokenId.COLON == tokenSequence.token().id()) {
+                //: => ->
+                printer.out.needSpace();
+                printer.print("-> ");
+                moveToDifferentThan(tokenSequence, Direction.FORWARD, 
EnumSet.of(JavaTokenId.WHITESPACE));
+                localPointer = tokenSequence.offset();
+            } else if (JavaTokenId.ARROW == tokenSequence.token().id()) {
+                //-> => :
+                printer.print(":");
+                if (newT.stats.size() > 1) {
+                    printer.newline();
+                } else {
+                    printer.out.needSpace();
+                }
+                tokenSequence.moveNext();
+                moveToDifferentThan(tokenSequence, Direction.FORWARD, 
EnumSet.of(JavaTokenId.WHITESPACE));
+                localPointer = tokenSequence.offset();
+                reindentStatements = true;
+            }
         }
         PositionEstimator est = EstimatorFactory.statements(
                 filterHidden(oldT.stats),
@@ -1897,6 +1938,13 @@ protected int diffCase(JCCase oldT, JCCase newT, int[] 
bounds) {
                 diffContext
         );
         int old = printer.indent();
+        SortedSet<int[]> oldReindentRegions = printer.reindentRegions;
+        printer.reindentRegions = new TreeSet<>(new Comparator<int[]>() { 
//XXX: copied from the initializer!!
+            @Override public int compare(int[] o1, int[] o2) {
+                return o1[0] - o2[0];
+            }
+        });
+        int reindentStart = localPointer;
         localPointer = diffInnerComments(oldT, newT, localPointer);
         JCClassDecl oldEnclosing = printer.enclClass;
         printer.enclClass = null;
@@ -1905,10 +1953,34 @@ protected int diffCase(JCCase oldT, JCCase newT, int[] 
bounds) {
         if (localPointer < endPos(oldT)) {
             copyTo(localPointer, localPointer = endPos(oldT));
         }
+        if (reindentStatements) {
+            printer.reindentRegions = oldReindentRegions;
+            printer.reindentRegions.add(new int[] {reindentStart, 
localPointer});
+        } else {
+            oldReindentRegions.addAll(printer.reindentRegions);
+            printer.reindentRegions = oldReindentRegions;
+        }
         printer.undent(old);
         return localPointer;
     }
 
+    public static List<JCExpression> getCasePatterns(JCCase cs) {
+        try {
+            return (List<JCExpression>) 
CaseTree.class.getDeclaredMethod("getExpressions").invoke(cs);
+        } catch (Throwable t) {
+            JCExpression pat = cs.getExpression();
+            return pat != null ? Collections.singletonList(pat) : 
Collections.emptyList();
+        }
+    }
+
+    public static Object getCaseKind(JCCase cs) {
+        try {
+            return CaseTree.class.getDeclaredMethod("getCaseKind").invoke(cs);
+        } catch (Throwable t) {
+            return null;
+        }
+    }
+
     protected int diffSynchronized(JCSynchronized oldT, JCSynchronized newT, 
int[] bounds) {
         int localPointer = bounds[0];
         // lock
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/EstimatorFactory.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/EstimatorFactory.java
index e4c61829a4..2993d91d11 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/EstimatorFactory.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/EstimatorFactory.java
@@ -40,6 +40,13 @@ static PositionEstimator throwz(List<? extends 
ExpressionTree> oldL,
         return new PositionEstimator.ThrowsEstimator(oldL, newL, diffContext);
     }
     
+    static PositionEstimator casePatterns(List<? extends ExpressionTree> oldL, 
+                                          List<? extends ExpressionTree> newL,
+                                          DiffContext diffContext)
+    {
+        return new PositionEstimator.CasePatternEstimator(oldL, newL, 
diffContext);
+    }
+    
     static PositionEstimator exportsOpensTo(List<? extends ExpressionTree> 
oldL, 
                                     List<? extends ExpressionTree> newL,
                                     DiffContext diffContext)
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/PositionEstimator.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/PositionEstimator.java
index 49bfb13c93..b7cb243d87 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/save/PositionEstimator.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/save/PositionEstimator.java
@@ -174,6 +174,21 @@ public LineInsertionType lineInsertType() {
         }
     }
     
+    static class CasePatternEstimator extends BaseEstimator {
+        CasePatternEstimator(List<? extends ExpressionTree> oldL, 
+                             List<? extends ExpressionTree> newL,
+                             DiffContext diffContext)
+        {
+            super(CASE, oldL, newL, diffContext);
+        }
+
+        @Override
+        public String head() {
+            return precToken.fixedText() + " ";
+        }
+        
+    }
+    
     static class ExportsOpensToEstimator extends BaseEstimator {
         
         ExportsOpensToEstimator(List<? extends ExpressionTree> oldL,
diff --git 
a/java/java.source.base/src/org/netbeans/modules/java/source/transform/ImmutableTreeTranslator.java
 
b/java/java.source.base/src/org/netbeans/modules/java/source/transform/ImmutableTreeTranslator.java
index c446d9a698..ce0648d62e 100644
--- 
a/java/java.source.base/src/org/netbeans/modules/java/source/transform/ImmutableTreeTranslator.java
+++ 
b/java/java.source.base/src/org/netbeans/modules/java/source/transform/ImmutableTreeTranslator.java
@@ -39,6 +39,7 @@
 import org.netbeans.api.java.source.GeneratorUtilities;
 import org.netbeans.api.java.source.TreeMaker;
 import org.netbeans.api.java.source.WorkingCopy;
+import org.netbeans.modules.java.source.TreeShims;
 import org.netbeans.modules.java.source.builder.ASTService;
 import org.netbeans.modules.java.source.builder.CommentHandlerService;
 import org.netbeans.modules.java.source.builder.QualIdentTree;
@@ -805,17 +806,31 @@ protected final SwitchTree rewriteChildren(SwitchTree 
tree) {
     }
 
     protected final CaseTree rewriteChildren(CaseTree tree) {
-       ExpressionTree pat = (ExpressionTree)translate(tree.getExpression());
-       List<? extends StatementTree> stats = translate(tree.getStatements());
-       if (pat!=tree.getExpression() || !stats.equals(tree.getStatements())) {
-            if (stats != tree.getStatements())
-                stats = optimize(stats);
-           CaseTree n = make.Case(pat, stats);
-            model.setType(n, model.getType(tree));
-           copyCommentTo(tree,n);
-            copyPosTo(tree,n);
-           tree = n;
-       }
+        Tree body = TreeShims.getBody(tree);
+        List<? extends ExpressionTree> expressions = 
TreeShims.getExpressions(tree);
+        if (body == null) {
+            List<? extends ExpressionTree> pats = translate(expressions);
+            List<? extends StatementTree> stats = 
translate(tree.getStatements());
+            if (!pats.equals(expressions) || 
!stats.equals(tree.getStatements())) {
+                if (stats != tree.getStatements())
+                    stats = optimize(stats);
+                CaseTree n = make.Case(pats, stats);
+                model.setType(n, model.getType(tree));
+                copyCommentTo(tree,n);
+                copyPosTo(tree,n);
+                tree = n;
+            }
+        } else {
+            List<? extends ExpressionTree> pats = translate(expressions);
+            Tree nueBody = translate(body);
+            if (!pats.equals(expressions) || body != nueBody) {
+                CaseTree n = make.Case(pats, nueBody);
+                model.setType(n, model.getType(tree));
+                copyCommentTo(tree,n);
+                copyPosTo(tree,n);
+                tree = n;
+            }
+        }
        return tree;
     }
 
diff --git 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestBase.java
 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestBase.java
index 65eacdb9de..7a9da3bbdb 100644
--- 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestBase.java
+++ 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestBase.java
@@ -38,6 +38,7 @@
 import org.netbeans.modules.java.source.transform.Transformer;
 import org.netbeans.modules.editor.java.JavaKit;
 import org.netbeans.modules.java.JavaDataLoader;
+import org.netbeans.modules.java.source.BootClassPathUtil;
 import org.netbeans.modules.java.source.ClassIndexTestCase;
 import org.netbeans.modules.java.source.indexing.TransactionContext;
 import org.netbeans.modules.java.source.save.Reindenter;
@@ -99,7 +100,7 @@ public ClassPath findClassPath(FileObject file, String type) 
{
                     if (type == ClassPath.COMPILE)
                         return ClassPathSupport.createClassPath(new 
FileObject[0]);
                     if (type == ClassPath.BOOT)
-                        return 
createClassPath(System.getProperty("sun.boot.class.path"));
+                        return BootClassPathUtil.getBootClassPath();
                     return null;
             }
         };
@@ -136,20 +137,6 @@ public void run(WorkingCopy wc) throws IOException {
         printFile();
     }
     
-    private static ClassPath createClassPath(String classpath) {
-        StringTokenizer tokenizer = new StringTokenizer(classpath, 
File.pathSeparator);
-        List/*<PathResourceImplementation>*/ list = new ArrayList();
-        while (tokenizer.hasMoreTokens()) {
-            String item = tokenizer.nextToken();
-            File f = FileUtil.normalizeFile(new File(item));
-            URL url = getRootURL(f);
-            if (url!=null) {
-                list.add(ClassPathSupport.createResource(url));
-            }
-        }
-        return ClassPathSupport.createClassPath(list);
-    }
-    
     // XXX this method could probably be removed... use standard FileUtil stuff
     private static URL getRootURL  (File f) {
         URL url = null;
diff --git 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestMDRCompat.java
 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestMDRCompat.java
index f7e37a285a..41aabd4177 100644
--- 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestMDRCompat.java
+++ 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/GeneratorTestMDRCompat.java
@@ -37,6 +37,7 @@
 import org.netbeans.api.java.source.JavaSource.Phase;
 import org.netbeans.modules.java.source.transform.Transformer;
 import org.netbeans.modules.java.JavaDataLoader;
+import org.netbeans.modules.java.source.BootClassPathUtil;
 import org.netbeans.modules.java.source.ClassIndexTestCase;
 import org.netbeans.modules.java.source.TestUtil;
 import org.netbeans.modules.java.source.save.Reindenter;
@@ -71,7 +72,7 @@ public ClassPath findClassPath(FileObject file, String type) {
                     if (type == ClassPath.COMPILE)
                         return ClassPathSupport.createClassPath(new 
FileObject[0]);
                     if (type == ClassPath.BOOT)
-                        return 
createClassPath(System.getProperty("sun.boot.class.path"));
+                        return BootClassPathUtil.getBootClassPath();
                     return null;
             }
         };
diff --git 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/MethodBodyTest.java
 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/MethodBodyTest.java
index 159bbf61fc..c222c05f34 100644
--- 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/MethodBodyTest.java
+++ 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/MethodBodyTest.java
@@ -275,7 +275,7 @@ public void run(WorkingCopy workingCopy) throws 
java.io.IOException {
                 
                 cases.add(treeMaker.Case(treeMaker.Literal(1), 
switchStatement.getCases().get(0).getStatements()));
                 cases.add(treeMaker.Case(treeMaker.Literal(2), 
switchStatement.getCases().get(0).getStatements()));
-                cases.add(treeMaker.Case(null, 
Collections.singletonList(treeMaker.Break(null))));
+                cases.add(treeMaker.Case((ExpressionTree) null, 
Collections.singletonList(treeMaker.Break(null))));
                 
                 workingCopy.rewrite(switchStatement, 
treeMaker.Switch(switchStatement.getExpression(), cases));
             }
diff --git 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/SwitchTest.java
 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/SwitchTest.java
index c21399e634..657e6eeac0 100644
--- 
a/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/SwitchTest.java
+++ 
b/java/java.source.base/test/unit/src/org/netbeans/api/java/source/gen/SwitchTest.java
@@ -20,11 +20,13 @@
 
 import com.sun.source.tree.BlockTree;
 import com.sun.source.tree.CaseTree;
+import com.sun.source.tree.ExpressionTree;
 import com.sun.source.tree.IfTree;
 import com.sun.source.tree.StatementTree;
 import com.sun.source.tree.SwitchTree;
 import com.sun.source.tree.Tree.Kind;
 import com.sun.source.util.TreePath;
+import com.sun.tools.javac.tree.JCTree;
 import org.netbeans.api.java.source.support.ErrorAwareTreePathScanner;
 import java.io.File;
 import java.io.IOException;
@@ -32,12 +34,15 @@
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.function.BiFunction;
+import org.netbeans.api.java.source.CompilationController;
 import org.netbeans.api.java.source.JavaSource;
 import org.netbeans.api.java.source.JavaSource.Phase;
 import org.netbeans.api.java.source.Task;
 import org.netbeans.api.java.source.TestUtilities;
 import org.netbeans.api.java.source.TreeMaker;
 import org.netbeans.api.java.source.WorkingCopy;
+import org.netbeans.modules.java.source.TreeShims;
 
 /**
  * The following shell script was used to generate the code snippets
@@ -233,6 +238,393 @@ public void run(final WorkingCopy copy) throws 
IOException {
         assertEquals(golden, res);
     }
 
+    public void testCaseMultiTest() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        class TestCase {
+            public final String caseText;
+            public final BiFunction<WorkingCopy, CaseTree, CaseTree> 
convertCase;
+            public final String expectedCaseText;
+
+            public TestCase(String caseText, BiFunction<WorkingCopy, CaseTree, 
CaseTree> convertCase, String expectedCaseText) {
+                this.caseText = caseText;
+                this.convertCase = convertCase;
+                this.expectedCaseText = expectedCaseText;
+            }
+
+        }
+        TestCase[] testCases = new TestCase[] {
+            new TestCase("case 0:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.add(copy.getTreeMaker().Literal(1));
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case 0, 1:"),
+            new TestCase("case 0:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.add(0, copy.getTreeMaker().Literal(-1));
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case -1, 0:"),
+            new TestCase("case 0:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.add(0, copy.getTreeMaker().Literal(-1));
+                             labels.add(copy.getTreeMaker().Literal(1));
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case -1, 0, 1:"),
+            new TestCase("case -1, 1:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.add(1, copy.getTreeMaker().Literal(0));
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case -1, 0, 1:"),
+            new TestCase("case -1, 0, 1:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.remove(0);
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case " + /*XXX: too many spaces:*/ " " + "0, 1:"),
+            new TestCase("case -1, 0, 1:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.remove(1);
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case -1, 1:"),
+            new TestCase("case -1, 0, 1:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.remove(2);
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case -1, 0:"),
+            new TestCase("default:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new 
ArrayList<>(TreeShims.getExpressions(tree));
+                             labels.add(copy.getTreeMaker().Literal(0));
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "case 0:"),
+            new TestCase("case 0:",
+                         (copy, tree) -> {
+                             List<ExpressionTree> labels = new ArrayList<>();
+                             return 
copy.getTreeMaker().CaseMultipleLabels(labels, tree.getStatements());
+                         },
+                         "default:"),
+        };
+        int idx = 0;
+        for (TestCase tc : testCases) {
+            testFile = new File(getWorkDir(), "Test" + idx + ".java");
+            String test = "public class Test" + idx + " {\n" +
+                          "    void m(int p) {\n" +
+                          "        switch (p) {\n" +
+                          "            " + tc.caseText + "\n" +
+                          "                System.err.println(0);\n" +
+                          "                break;\n" +
+                          "        }\n" +
+                          "    }\n" +
+                          "}\n";
+            idx++;
+            TestUtilities.copyStringToFile(testFile, test);
+            JavaSource src = getJavaSource(testFile);
+            Task<WorkingCopy> task = new Task<WorkingCopy>() {
+                public void run(final WorkingCopy copy) throws IOException {
+                    if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) 
< 0) {
+                        return;
+                    }
+                    new ErrorAwareTreePathScanner<Void, Void>() {
+                        @Override public Void visitCase(CaseTree node, Void p) 
{
+                            copy.rewrite(node, tc.convertCase.apply(copy, 
node));
+                            return super.visitCase(node, p);
+                        }
+                    }.scan(copy.getCompilationUnit(), null);
+                }
+            };
+            src.runModificationTask(task).commit();
+            String res = TestUtilities.copyFileToString(testFile);
+            src.runUserActionTask(new Task<CompilationController>() {
+                @Override
+                public void run(CompilationController cc) throws Exception {
+                    cc.toPhase(Phase.RESOLVED);
+                    new ErrorAwareTreePathScanner<Void, Void>() {
+                        @Override public Void visitCase(CaseTree node, Void p) 
{
+                            String actual = cc.getText()
+                                              .substring((int) 
cc.getTrees().getSourcePositions().getStartPosition(cc.getCompilationUnit(), 
node),
+                                                         (int) 
cc.getTrees().getSourcePositions().getStartPosition(cc.getCompilationUnit(), 
node.getStatements().get(0)))
+                                              .trim();
+                            String expected = tc.expectedCaseText;
+                            assertEquals(expected, actual);
+                            return super.visitCase(node, p);
+                        }
+                    }.scan(cc.getCompilationUnit(), null);
+                }
+            }, true);
+        }
+    }
+
+    public void testStatement2Rule() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        testFile = new File(getWorkDir(), "Test.java");
+        String test = "public class Test {\n" +
+                      "    void m(int p) {\n" +
+                      "        switch (p) {\n" +
+                      "            case 0:\n" +
+                      "                System.err.println(0);\n" +
+                      "                System.err.println(1);\n" +
+                      "                break;\n" +
+                      "        }\n" +
+                      "    }\n" +
+                      "}\n";
+        String golden = "public class Test {\n" +
+                        "    void m(int p) {\n" +
+                        "        switch (p) {\n" +
+                        "            case 0 -> {\n" +
+                        "                System.err.println(0);\n" +
+                        "                System.err.println(1);\n" +
+                        "            }\n" +
+                        "        }\n" +
+                        "    }\n" +
+                        "}\n";
+        TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
+        JavaSource src = getJavaSource(testFile);
+        Task<WorkingCopy> task = new Task<WorkingCopy>() {
+            public void run(final WorkingCopy copy) throws IOException {
+                if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 
0) {
+                    return;
+                }
+                final TreeMaker make = copy.getTreeMaker();
+                new ErrorAwareTreePathScanner<Void, Void>() {
+                    @Override public Void visitCase(CaseTree node, Void p) {
+                        copy.rewrite(getCurrentPath().getLeaf(),
+                                     make.Case(TreeShims.getExpressions(node), 
make.Block(node.getStatements().subList(0, 2), false)));
+                        return super.visitCase(node, p);
+                    }
+                }.scan(copy.getCompilationUnit(), null);
+            }
+        };
+        src.runModificationTask(task).commit();
+        String res = TestUtilities.copyFileToString(testFile);
+        System.err.println(res);
+        assertEquals(golden, res);
+    }
+
+    public void testRule2Statement() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        testFile = new File(getWorkDir(), "Test.java");
+        String test = "public class Test {\n" +
+                      "    void m(int p) {\n" +
+                      "        switch (p) {\n" +
+                      "            case 0 -> {\n" +
+                      "                System.err.println(0);\n" +
+                      "                System.err.println(1);\n" +
+                      "            }\n" +
+                      "        }\n" +
+                      "    }\n" +
+                      "}\n";
+        String golden = "public class Test {\n" +
+                        "    void m(int p) {\n" +
+                        "        switch (p) {\n" +
+                        "            case 0:\n" +
+                        "                System.err.println(0);\n" +
+                        "                System.err.println(1);\n" +
+                        "                break;\n" +
+                        "        }\n" +
+                        "    }\n" +
+                        "}\n";
+        TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
+        JavaSource src = getJavaSource(testFile);
+        Task<WorkingCopy> task = new Task<WorkingCopy>() {
+            public void run(final WorkingCopy copy) throws IOException {
+                if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 
0) {
+                    return;
+                }
+                final TreeMaker make = copy.getTreeMaker();
+                new ErrorAwareTreePathScanner<Void, Void>() {
+                    @Override public Void visitCase(CaseTree node, Void p) {
+                        List<StatementTree> statements = new 
ArrayList<>(((BlockTree) TreeShims.getBody(node)).getStatements());
+                        statements.add(make.Break(null));
+                        copy.rewrite(getCurrentPath().getLeaf(),
+                                     
make.CaseMultipleLabels(TreeShims.getExpressions(node), statements));
+                        return super.visitCase(node, p);
+                    }
+                }.scan(copy.getCompilationUnit(), null);
+            }
+        };
+        src.runModificationTask(task).commit();
+        String res = TestUtilities.copyFileToString(testFile);
+        System.err.println(res);
+        assertEquals(golden, res);
+    }
+
+    public void testDefaultRewrite() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        testFile = new File(getWorkDir(), "Test.java");
+        String test = "public class Test {\n" +
+                      "    void m(int p) {\n" +
+                      "        switch (p) {\n" +
+                      "            default: \n" +
+                      "                System.err.println(0);\n" +
+                      "                break;\n" +
+                      "        }\n" +
+                      "    }\n" +
+                      "}\n";
+        String golden = "public class Test {\n" +
+                        "    void m(int p) {\n" +
+                        "        switch (p) {\n" +
+                        "            default -> System.err.println(0);\n" +
+                        "        }\n" +
+                        "    }\n" +
+                        "}\n";
+        TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
+        JavaSource src = getJavaSource(testFile);
+        Task<WorkingCopy> task = new Task<WorkingCopy>() {
+            public void run(final WorkingCopy copy) throws IOException {
+                if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 
0) {
+                    return;
+                }
+                final TreeMaker make = copy.getTreeMaker();
+                new ErrorAwareTreePathScanner<Void, Void>() {
+                    @Override public Void visitCase(CaseTree node, Void p) {
+                        copy.rewrite(getCurrentPath().getLeaf(),
+                                     make.Case(TreeShims.getExpressions(node), 
node.getStatements().get(0)));
+                        return super.visitCase(node, p);
+                    }
+                }.scan(copy.getCompilationUnit(), null);
+            }
+        };
+        src.runModificationTask(task).commit();
+        String res = TestUtilities.copyFileToString(testFile);
+        System.err.println(res);
+        assertEquals(golden, res);
+    }
+
+    public void testStatement2RuleNoSpace() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        testFile = new File(getWorkDir(), "Test.java");
+        String test = "public class Test {\n" +
+                      "    void m(int p) {\n" +
+                      "        switch (p) {\n" +
+                      "            case 0:{\n" +
+                      "                System.err.println(0);\n" +
+                      "                System.err.println(1);\n" +
+                      "                break;\n" +
+                      "            }\n" +
+                      "        }\n" +
+                      "    }\n" +
+                      "}\n";
+        String golden = "public class Test {\n" +
+                        "    void m(int p) {\n" +
+                        "        switch (p) {\n" +
+                        "            case 0 -> {\n" +
+                        "                System.err.println(0);\n" +
+                        "                System.err.println(1);\n" +
+                        "                break;\n" +
+                        "            }\n" +
+                        "        }\n" +
+                        "    }\n" +
+                        "}\n";
+        TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
+        JavaSource src = getJavaSource(testFile);
+        Task<WorkingCopy> task = new Task<WorkingCopy>() {
+            public void run(final WorkingCopy copy) throws IOException {
+                if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 
0) {
+                    return;
+                }
+                final TreeMaker make = copy.getTreeMaker();
+                new ErrorAwareTreePathScanner<Void, Void>() {
+                    @Override public Void visitCase(CaseTree node, Void p) {
+                        copy.rewrite(getCurrentPath().getLeaf(),
+                                     make.Case(TreeShims.getExpressions(node), 
node.getStatements().get(0)));
+                        return super.visitCase(node, p);
+                    }
+                }.scan(copy.getCompilationUnit(), null);
+            }
+        };
+        src.runModificationTask(task).commit();
+        String res = TestUtilities.copyFileToString(testFile);
+        System.err.println(res);
+        assertEquals(golden, res);
+    }
+
+    public void testNestedSwitches() throws Exception {
+        if (!enhancedSwitchAvailable())
+            return;
+
+        testFile = new File(getWorkDir(), "Test.java");
+        String test = "public class Test {\n" +
+                      "    void m(int p) {\n" +
+                      "        switch (p) {\n" +
+                      "            case 0:\n" +
+                      "                switch (p) {\n" +
+                      "                    case 0: break;\n" +
+                      "                }\n" +
+                      "                break;\n" +
+                      "        }\n" +
+                      "    }\n" +
+                      "}\n";
+        String golden = "public class Test {\n" +
+                        "    void m(int p) {\n" +
+                        "        switch (p) {\n" +
+                        "            case 0 -> {\n" +
+                        "                switch (p) {\n" +
+                        "                    case 0 -> {\n" +
+                        "                        break;\n" +
+                        "                    }\n" +
+//                        "                }\n" +
+//                        "                break;\n" +
+                        "                }   break;\n" + //XXX
+                        "            }\n" +
+                        "        }\n" +
+                        "    }\n" +
+                        "}\n";
+        TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
+        JavaSource src = getJavaSource(testFile);
+        Task<WorkingCopy> task = new Task<WorkingCopy>() {
+            public void run(final WorkingCopy copy) throws IOException {
+                if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 
0) {
+                    return;
+                }
+                final TreeMaker make = copy.getTreeMaker();
+                new ErrorAwareTreePathScanner<Void, Void>() {
+                    @Override public Void visitCase(CaseTree node, Void p) {
+                        copy.rewrite(getCurrentPath().getLeaf(),
+                                     make.Case(TreeShims.getExpressions(node), 
make.Block(node.getStatements(), false)));
+                        return super.visitCase(node, p);
+                    }
+                }.scan(copy.getCompilationUnit(), null);
+            }
+        };
+        src.runModificationTask(task).commit();
+        String res = TestUtilities.copyFileToString(testFile);
+        System.err.println(res);
+        assertEquals(golden, res);
+    }
+    
+    private boolean enhancedSwitchAvailable() {
+        try {
+            Class.forName("com.sun.source.tree.CaseTree$CaseKind", false, 
JCTree.class.getClassLoader());
+            return true;
+        } catch (ClassNotFoundException ex) {
+            //OK
+            return false;
+        }
+    }
+
     // XXX I don't understand what these are used for
     @Override
     String getSourcePckg() {


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to