From 1c21420c6a08184d6e2ddb0d3fd1b4f0147c2241 Mon Sep 17 00:00:00 2001 From: Kun Li <122563761+kunli2@users.noreply.github.com> Date: Wed, 15 Nov 2023 15:26:57 -0800 Subject: [PATCH] Fix CRLF in the stringTemplate (#411) --- .../internal/KotlinTreeParserVisitor.java | 17 ++++++++++++++--- .../org/openrewrite/kotlin/tree/CRLFTest.java | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java b/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java index 54727f1b0..39992dd31 100644 --- a/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java +++ b/src/main/java/org/openrewrite/kotlin/internal/KotlinTreeParserVisitor.java @@ -2955,9 +2955,19 @@ public J visitStringTemplateExpression(KtStringTemplateExpression expression, Ex ); } - String valueSource = expression.getText(); StringBuilder valueSb = new StringBuilder(); - Arrays.stream(entries).forEach(x -> valueSb.append(x.getText())); + Arrays.stream(entries).forEach(entry -> valueSb.append(maybeAdjustCRLF(entry)) + ); + + PsiElement openQuote = expression.getFirstChild(); + PsiElement closingQuota = expression.getLastChild(); + if (openQuote == null || closingQuota == null || + openQuote.getNode().getElementType() != KtTokens.OPEN_QUOTE || + closingQuota.getNode().getElementType() != KtTokens.CLOSING_QUOTE) { + throw new UnsupportedOperationException("This should never happen"); + } + + String valueSource = openQuote.getText() + valueSb + closingQuota.getText(); return new J.Literal( randomId(), @@ -3866,7 +3876,8 @@ private Space toSpace(@Nullable PsiElement element) { // replace `\n` to CRLF back if it's CRLF in the source private String maybeAdjustCRLF(PsiElement element) { String text = element.getText(); - if (!isSpace(element.getNode())) { + boolean isStringTemplateEntry = element instanceof KtLiteralStringTemplateEntry; + if (!isSpace(element.getNode()) && !isStringTemplateEntry) { return text; } diff --git a/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java b/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java index 434a5cecc..b512d0f04 100644 --- a/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java +++ b/src/test/java/org/openrewrite/kotlin/tree/CRLFTest.java @@ -16,6 +16,7 @@ package org.openrewrite.kotlin.tree; import org.junit.jupiter.api.Test; +import org.openrewrite.Issue; import org.openrewrite.test.RewriteTest; import static org.openrewrite.kotlin.Assertions.kotlin; @@ -82,4 +83,17 @@ void crlfInBlockComment() { ) ); } + + @Issue("https://github.com/openrewrite/rewrite-kotlin/issues/402") + @Test + void crlfInMultilineString() { + rewriteRun( + kotlin( + "val s = \"\"\"\r\n" + + "l1\r\n" + + "l2\n" + + "\"\"\"" + ) + ); + } }