You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@netbeans.apache.org by ak...@apache.org on 2022/05/12 10:52:50 UTC

[netbeans] branch master updated: [NETBEANS-6241] - Fixed switchToRuleSwitch Hint for BindingPattern and GuardedPattern (#3343)

This is an automated email from the ASF dual-hosted git repository.

akhileshsingh pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/netbeans.git


The following commit(s) were added to refs/heads/master by this push:
     new 29cc36b9d3 [NETBEANS-6241] - Fixed switchToRuleSwitch Hint for BindingPattern and GuardedPattern (#3343)
29cc36b9d3 is described below

commit 29cc36b9d3e2f59e8f938d2bd24dabe7f1cf212f
Author: Sandeep Mishra <72...@users.noreply.github.com>
AuthorDate: Thu May 12 16:22:44 2022 +0530

    [NETBEANS-6241] - Fixed switchToRuleSwitch Hint for BindingPattern and GuardedPattern (#3343)
    
    * Fixed switchToRuleSwitch Hint for BindingPattern and GuardedPattern
    
    * changed source version of switch pattern matching tests
    
    * removed reflection methods
    
    * Update Utilities.java
    
    Removed unnecessary whitespace and imports
---
 .../modules/java/hints/errors/Utilities.java       |   4 +-
 .../hints/jdk/ConvertSwitchToRuleSwitchTest.java   | 108 +++++++++++++++++++++
 .../netbeans/modules/java/source/TreeShims.java    |   4 +-
 .../modules/java/source/pretty/VeryPretty.java     |   2 +-
 .../modules/java/source/save/CasualDiff.java       |  47 ++++-----
 .../modules/java/source/save/EstimatorFactory.java |   4 +-
 .../java/source/save/PositionEstimator.java        |   4 +-
 7 files changed, 136 insertions(+), 37 deletions(-)

diff --git a/java/java.hints/src/org/netbeans/modules/java/hints/errors/Utilities.java b/java/java.hints/src/org/netbeans/modules/java/hints/errors/Utilities.java
index 33e022ffb4..8ef45ac2eb 100644
--- a/java/java.hints/src/org/netbeans/modules/java/hints/errors/Utilities.java
+++ b/java/java.hints/src/org/netbeans/modules/java/hints/errors/Utilities.java
@@ -39,7 +39,6 @@ import com.sun.source.tree.ArrayTypeTree;
 import com.sun.source.tree.AssignmentTree;
 import com.sun.source.tree.BinaryTree;
 import com.sun.source.tree.BlockTree;
-import com.sun.source.tree.CaseLabelTree;
 import com.sun.source.tree.CaseTree;
 import com.sun.source.tree.CatchTree;
 import com.sun.source.tree.ClassTree;
@@ -3182,7 +3181,8 @@ public class Utilities {
         ExpressionTree switchExpr;
         List<? extends CaseTree> cases;
         Set<VariableElement> variablesDeclaredInOtherCases = new HashSet<>();
-        List<CaseLabelTree> patterns = new ArrayList<>();
+
+        List<Tree> patterns = new ArrayList<>();
         Tree leftVariable = null;
         boolean ruleSwitchFlag = st.getKind() == Kind.SWITCH_EXPRESSION;
         if (ruleSwitchFlag) {
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
index 3b02eb08ed..b87dc9f25e 100644
--- 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
@@ -940,6 +940,114 @@ public class ConvertSwitchToRuleSwitchTest extends NbTestCase {
                         "     }\n" +
                         "}\n");
     }
+    
+        public void testSwitchToRuleSwitchBindingPattern() throws Exception {
+        try {
+            SourceVersion.valueOf("RELEASE_17"); //NOI18N
+        } catch (IllegalArgumentException ex) {
+            //OK, no RELEASE_17, skip tests
+            return;
+        }
+        HintTest.create()
+                .input("package test;" +
+                        "public class Test {\n" +
+                        "     private void test(Object p) {\n" +
+                        "         String result;\n" +
+                        "         switch (p) {\n" +
+                        "            case Integer i : result = \"a\"; break;\n" +
+                        "            default : System.err.println(\"No.\"); break;\n" +
+                        "         }\n" +
+                        "     }\n" +
+                        "}\n")
+                .sourceLevel("17")
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + Bundle.ERR_ConvertSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertVerbatimOutput("package test;" +
+                        "public class Test {\n" +
+                        "     private void test(Object p) {\n" +
+                        "         String result;\n" +
+                        "         switch (p) {\n" +
+                        "            case Integer i -> result = \"a\";\n" +
+                        "            default -> System.err.println(\"No.\");\n" +
+                        "         }\n" +
+                        "     }\n" +
+                        "}\n");
+    }
+    
+    public void testSwitchToRuleSwitchGuardedPattern() throws Exception {
+        try {
+            SourceVersion.valueOf("RELEASE_17"); //NOI18N
+        } catch (IllegalArgumentException ex) {
+            //OK, no RELEASE_17, skip tests
+            return;
+        }
+        HintTest.create()
+                .input("package test;" +
+                        "public class Test {\n" +
+                        "     private void test(int p) {\n" +
+                        "         String result;\n" +
+                        "         switch (p) {\n" +
+                        "            case Integer i && (i > 10): result = \"a\"; break;\n" +
+                        "            default: System.err.println(\"No.\"); break;\n" +
+                        "         }\n" +
+                        "     }\n" +
+                        "}\n")
+                .sourceLevel("17")
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("3:9-3:15:verifier:" + Bundle.ERR_ConvertSwitchToRuleSwitch())
+                .applyFix()
+                .assertCompilable()
+                .assertVerbatimOutput("package test;" +
+                        "public class Test {\n" +
+                        "     private void test(int p) {\n" +
+                        "         String result;\n" +
+                        "         switch (p) {\n" +
+                        "            case Integer i && (i > 10) -> result = \"a\";\n" +
+                        "            default -> System.err.println(\"No.\");\n" +
+                        "         }\n" +
+                        "     }\n" +
+                        "}\n");
+    }
+    
+        public void testSwitchExpressionGuardedPattern() throws Exception {
+        try {
+            SourceVersion.valueOf("RELEASE_17"); //NOI18N
+        } catch (IllegalArgumentException ex) {
+            //OK, no RELEASE_17, skip tests
+            return;
+        }
+        HintTest.create()
+                .input("package test;"
+                        + "class Test {\n"
+                        + "    public String test(Object p, Object o1, Object o2) {\n"
+                        + "        switch (p) {\n"
+                        + "            case (Integer i  && (i > 10)):\n"
+                        + "               return (String) o1;\n"
+                        + "            default :\n"
+                        + "                return (String) o2;\n"
+                        + "        }\n"
+                        + "    }\n"
+                        + "}")
+                .sourceLevel("17")
+                .options("--enable-preview")
+                .run(ConvertSwitchToRuleSwitch.class)
+                .findWarning("2:8-2:14:verifier:" + Bundle.ERR_ConvertSwitchToSwitchExpression())
+                .applyFix()
+                .assertCompilable()
+                .assertVerbatimOutput("package test;"
+                            + "class Test {\n"
+                            + "    public String test(Object p, Object o1, Object o2) {\n"
+                            + "        return (String) (switch (p) {\n"
+                            + "            case (Integer i  && (i > 10)) -> o1;\n"
+                            + "            default -> o2;\n"
+                            + "        });\n"
+                            + "    }\n"
+                            + "}");
+    }
 
     public static Test suite() {
         TestSuite suite = new TestSuite();
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
index 176d9070f1..7a309cd9f9 100644
--- 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
@@ -412,7 +412,9 @@ public class TreeShims {
         if (isJDKVersionRelease17_Or_Above()) {
             try {
                 return node.getClass().getField("patternSwitch").getBoolean(node);
-            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ex) {
+            } catch(NoSuchFieldException e){
+                return false;
+            }catch (IllegalArgumentException | IllegalAccessException | SecurityException ex) {
                 throw TreeShims.<RuntimeException>throwAny(ex);
             }
         }
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 e2b51013de..8c8867f38e 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
@@ -1342,7 +1342,7 @@ public final class VeryPretty extends JCTree.Visitor implements DocTreeVisitor<V
                 sep = ", "; //TODO: space or not should be a configuration setting
             }
         }
-        Object caseKind = CasualDiff.getCaseKind(tree);
+        Object caseKind = tree.getCaseKind();
         if (caseKind == null || !String.valueOf(caseKind).equals("RULE")) {
             print(':');
             newline();
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 7dbfd249de..3441ee964c 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
@@ -173,6 +173,7 @@ import org.openide.util.Exceptions;
 import org.openide.util.NbBundle;
 import org.openide.util.NbCollections;
 import javax.lang.model.type.TypeKind;
+import org.netbeans.modules.java.source.TreeShims;
 import org.netbeans.modules.java.source.transform.TreeHelpers;
 
 public class CasualDiff {
@@ -1926,7 +1927,7 @@ public class CasualDiff {
         
         List<JCCase> cases = newT.cases;
         if (cases.size() != 0) {
-            String caseKind = String.valueOf(CasualDiff.getCaseKind(cases.get(0)));
+            String caseKind = String.valueOf(cases.get(0).getCaseKind());
             if (caseKind.equals("RULE")) { // NOI18N
                 printer.newline();
             }
@@ -1966,8 +1967,21 @@ public class CasualDiff {
 
     protected int diffCase(JCCase oldT, JCCase newT, int[] bounds) {
         int localPointer = bounds[0];
-        List<JCExpression> oldPatterns = getCasePatterns(oldT);
-        List<JCExpression> newPatterns = getCasePatterns(newT);
+        List<? extends JCTree> oldPatterns;
+        List<? extends JCTree> newPatterns;
+        
+        if(!(oldT.getLabels().size()==1 && oldT.getLabels().get(0).getKind().toString().equals("DEFAULT_CASE_LABEL"))){
+            oldPatterns = oldT.getLabels();            
+        }else{
+            oldPatterns = oldT.getExpressions();           
+        }
+        
+        if(!(newT.getLabels().size() == 1 && newT.getLabels().get(0).getKind().toString().equals("DEFAULT_CASE_LABEL"))){
+            newPatterns = newT.getLabels();            
+        }else{
+            newPatterns = newT.getExpressions();           
+        }
+        
         PositionEstimator patternEst = EstimatorFactory.casePatterns(
                 oldPatterns,
                 newPatterns,
@@ -2001,7 +2015,7 @@ public class CasualDiff {
         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))) {
+        if (Objects.equals(oldT.getCaseKind(), newT.getCaseKind())) {
             tokenSequence.moveNext();
             copyTo(localPointer, localPointer = tokenSequence.offset());
         } else {
@@ -2057,31 +2071,6 @@ public class CasualDiff {
         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 List<JCTree> getCaseLabelPatterns(JCCase cs) {
-        try {
-            return (List<JCTree>) CaseTree.class.getDeclaredMethod("getLabels").invoke(cs);
-        } catch (Throwable t) {
-            return 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 2993d91d11..c7733a817c 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,8 +40,8 @@ final class EstimatorFactory {
         return new PositionEstimator.ThrowsEstimator(oldL, newL, diffContext);
     }
     
-    static PositionEstimator casePatterns(List<? extends ExpressionTree> oldL, 
-                                          List<? extends ExpressionTree> newL,
+    static PositionEstimator casePatterns(List<? extends Tree> oldL, 
+                                          List<? extends Tree> newL,
                                           DiffContext diffContext)
     {
         return new PositionEstimator.CasePatternEstimator(oldL, newL, 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 17cf4c060b..cc9d432ac6 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,8 +174,8 @@ public abstract class PositionEstimator {
     }
     
     static class CasePatternEstimator extends BaseEstimator {
-        CasePatternEstimator(List<? extends ExpressionTree> oldL, 
-                             List<? extends ExpressionTree> newL,
+        CasePatternEstimator(List<? extends Tree> oldL, 
+                             List<? extends Tree> newL,
                              DiffContext diffContext)
         {
             super(CASE, oldL, newL, diffContext);


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@netbeans.apache.org
For additional commands, e-mail: commits-help@netbeans.apache.org

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