Skip to content

Commit 4cd2123

Browse files
authored
Keep \t and \f escapes in UseTextBlocks to avoid incidental whitespace stripping (#1160)
Fixes #1158
1 parent 16e662d commit 4cd2123

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ private J.Literal toTextBlock(J.Binary binary, String content, List<J.Literal> s
168168
content = sb.toString();
169169
// escape backslashes
170170
content = content.replace("\\", "\\\\");
171+
// re-escape tab and form feed characters as escape sequences. A literal tab or form feed is
172+
// indistinguishable from incidental leading whitespace, so javac may strip it during text block
173+
// whitespace processing (JLS 3.10.6), silently changing the string's value.
174+
content = content.replace("\t", "\\t");
175+
content = content.replace("\f", "\\f");
171176
// escape triple quotes
172177
content = content.replace("\"\"\"", "\"\"\\\"");
173178
// preserve trailing spaces before a newline

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,54 @@ class Test {
560560
);
561561
}
562562

563+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1158")
564+
@Test
565+
void keepTabEscapeToAvoidIncidentalWhitespaceStripping() {
566+
rewriteRun(
567+
//language=java
568+
java(
569+
"""
570+
class Main {
571+
String s =
572+
""
573+
+ "\\tb";
574+
}
575+
""",
576+
"""
577+
class Main {
578+
String s =
579+
\"""
580+
\\tb\""";
581+
}
582+
"""
583+
)
584+
);
585+
}
586+
587+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1158")
588+
@Test
589+
void keepFormFeedEscapeToAvoidIncidentalWhitespaceStripping() {
590+
rewriteRun(
591+
//language=java
592+
java(
593+
"""
594+
class Main {
595+
String s =
596+
""
597+
+ "\\fb";
598+
}
599+
""",
600+
"""
601+
class Main {
602+
String s =
603+
\"""
604+
\\fb\""";
605+
}
606+
"""
607+
)
608+
);
609+
}
610+
563611
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/195")
564612
@Test
565613
void newlinesAlignment() {

0 commit comments

Comments
 (0)