From 02d0ee9568898b75e7324bf9665e8f4089032bd8 Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Sat, 13 Jan 2024 02:12:15 +0100 Subject: [PATCH] `SpacesVisitor`: Remove spaces before statement semicolon (#3905) --- .../openrewrite/java/format/SpacesTest.java | 35 ++++++++++++++++++- .../java/format/SpacesVisitor.java | 11 +++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/format/SpacesTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/format/SpacesTest.java index 5c3f14c9c4c..4c93be09578 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/format/SpacesTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/format/SpacesTest.java @@ -202,7 +202,7 @@ void beforeParensMethodCallTrue() { """ class Test { void foo() { - foo(); + foo() ; Test test = new Test(); } } @@ -219,6 +219,39 @@ void foo() { ); } + @Test + void noSpaceBeforeSemicolon() { + rewriteRun( + spaces(style -> style), + java( + """ + class Test { + boolean b = true ; + void foo() { + foo() ; + Test test = new Test() + ; + if (b) + System.out.println("OK") ; + } + } + """, + """ + class Test { + boolean b = true; + void foo() { + foo(); + Test test = new Test() + ; + if (b) + System.out.println("OK"); + } + } + """ + ) + ); + } + @Test void beforeParensMethodCallFalse() { rewriteRun( diff --git a/rewrite-java/src/main/java/org/openrewrite/java/format/SpacesVisitor.java b/rewrite-java/src/main/java/org/openrewrite/java/format/SpacesVisitor.java index 295e18a3719..9175527901e 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/format/SpacesVisitor.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/format/SpacesVisitor.java @@ -230,6 +230,15 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, P return c; } + @Override + public J.Block visitBlock(J.Block block, P p) { + J.Block b = super.visitBlock(block, p); + b = b.getPadding().withStatements( + ListUtils.map(b.getPadding().getStatements(), stmt -> spaceAfter(stmt, false)) + ); + return b; + } + @Override public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, P p) { J.MethodDeclaration m = super.visitMethodDeclaration(method, p); @@ -391,7 +400,7 @@ public J.MultiCatch visitMultiCatch(J.MultiCatch multiCatch, P p) { public J.If visitIf(J.If iff, P p) { J.If i = super.visitIf(iff, p); i = i.withIfCondition(spaceBefore(i.getIfCondition(), style.getBeforeParentheses().getIfParentheses())); - i = i.getPadding().withThenPart(spaceBeforeRightPaddedElement(i.getPadding().getThenPart(), style.getBeforeLeftBrace().getIfLeftBrace())); + i = i.getPadding().withThenPart(spaceAfter(spaceBeforeRightPaddedElement(i.getPadding().getThenPart(), style.getBeforeLeftBrace().getIfLeftBrace()), false)); boolean useSpaceWithinIfParentheses = style.getWithin().getIfParentheses(); i = i.withIfCondition( i.getIfCondition().getPadding().withTree(