Skip to content

Commit e91f59e

Browse files
timtebeekTim te Beek
andauthored
Prevent UseTextBlocks from dropping comments in concatenations (#985)
Skip text block conversion if any comments exist in the binary expression tree, since text blocks (single J.Literal nodes) have nowhere to preserve inline comments from the middle of concatenations. Co-authored-by: Tim te Beek <tim@mac.home>
1 parent 21993f5 commit e91f59e

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

src/main/java/org/openrewrite/java/migrate/lang/UseTextBlocks.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@ public J visitBinary(J.Binary binary, ExecutionContext ctx) {
100100
return binary; // Not super.visitBinary(binary, ctx) because we don't want to visit the children
101101
}
102102

103+
if (containsComments(binary)) {
104+
return binary;
105+
}
106+
103107
boolean flattenable = flatAdditiveStringLiterals(binary, stringLiterals, contentSb, concatenationSb);
104108
if (!flattenable) {
105109
return super.visitBinary(binary, ctx);
@@ -195,6 +199,18 @@ private boolean isEndsWithSpecialCharacters(String content) {
195199
});
196200
}
197201

202+
private static boolean containsComments(Expression expression) {
203+
if (expression instanceof J.Binary) {
204+
J.Binary b = (J.Binary) expression;
205+
if (!b.getPrefix().getComments().isEmpty() ||
206+
!b.getPadding().getOperator().getBefore().getComments().isEmpty()) {
207+
return true;
208+
}
209+
return containsComments(b.getLeft()) || containsComments(b.getRight());
210+
}
211+
return expression instanceof J.Literal && !expression.getPrefix().getComments().isEmpty();
212+
}
213+
198214
private static boolean allLiterals(Expression exp) {
199215
return isRegularStringLiteral(exp) || exp instanceof J.Binary &&
200216
((J.Binary) exp).getOperator() == J.Binary.Type.Addition &&

src/test/java/org/openrewrite/java/migrate/lang/UseTextBlocksTest.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,37 @@ class Test {
256256
);
257257
}
258258

259+
@Test
260+
void doNotDropLineComments() {
261+
rewriteRun(
262+
//language=java
263+
java(
264+
"""
265+
class Test {
266+
String query = "SELECT * FROM\\n" + // table query
267+
"my_table\\n" +
268+
"WHERE something = 1;";
269+
}
270+
"""
271+
)
272+
);
273+
}
274+
275+
@Test
276+
void doNotDropBlockComments() {
277+
rewriteRun(
278+
//language=java
279+
java(
280+
"""
281+
class Test {
282+
String query = "SELECT * FROM\\n" + /* table name */ "my_table\\n" +
283+
"WHERE something = 1;";
284+
}
285+
"""
286+
)
287+
);
288+
}
289+
259290
@Test
260291
void preferNoChangeIfCarriageReturnInContent() {
261292
rewriteRun(

0 commit comments

Comments
 (0)