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 2fc9aad3533a..2126b3f5be75 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 @@ -2144,7 +2144,7 @@ protected int diffCase(JCCase oldT, JCCase newT, int[] bounds) { if (oldT.guard != null && newT.guard != null) { int[] guardBounds = getBounds(oldT.guard); copyTo(localPointer, guardBounds[0]); - diffTree(oldT.guard, newT.guard, guardBounds); + localPointer = diffTree(oldT.guard, newT.guard, guardBounds); } else if (oldT.guard != null && newT.guard == null) { //TODO: } else if (oldT.guard == null && newT.guard != null) { 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 3ddd675bcf54..ef07e9561474 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 @@ -657,6 +657,59 @@ public Void visitSwitch(SwitchTree node, Void p) { assertEquals(golden, res); } + // test as advised by lahodaj + public void testGuardPreserved() throws Exception { + testFile = new File(getWorkDir(), "Test.java"); + String test + = """ + public class Test { + void m(Object o) { + switch (o) { + case String str when str.isEmpty() -> System.err.println(); + default -> {} + } + } + } + """; + String golden + = """ + public class Test { + void m(Object o) { + switch (o) { + case String str when str.isEmpty() -> { + } + default -> {} + } + } + } + """; + TestUtilities.copyStringToFile(testFile, test.replace("|", "")); + JavaSource src = getJavaSource(testFile); + Task task = new Task() { + 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() { + @Override + public Void visitCase(CaseTree node, Void p) { + if (!node.getLabels().isEmpty()) { + copy.rewrite(getCurrentPath().getLeaf(), + make.CasePatterns(node.getLabels(), node.getGuard(), make.Block(List.of(), 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); + } + + // XXX I don't understand what these are used for @Override String getSourcePckg() {