Skip to content

Commit c51b0d6

Browse files
committed
Fix missing newline for opening quote for multilines strings
1 parent 319a625 commit c51b0d6

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Sources/SwiftBasicFormat/BasicFormat.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,22 @@ open class BasicFormat: SyntaxRewriter {
180180
}
181181
}
182182

183+
/// Whether a trailing newline on `token` should be added.
184+
open func requiresTrailingNewline(_ token: TokenSyntax) -> Bool {
185+
// We don't want to add newlines inside string interpolation
186+
if isInsideStringInterpolation(token) && token.tokenKind != .multilineStringQuote {
187+
return false
188+
}
189+
190+
let syntaxToken: Syntax = Syntax(token)
191+
switch syntaxToken.keyPathInParent {
192+
case \StringLiteralExprSyntax.openQuote:
193+
return token.tokenKind == .multilineStringQuote
194+
default:
195+
return false
196+
}
197+
}
198+
183199
open func requiresWhitespace(between first: TokenSyntax?, and second: TokenSyntax?) -> Bool {
184200
switch (first?.tokenKind, second?.tokenKind) {
185201
case (.atSign, _),
@@ -368,6 +384,12 @@ open class BasicFormat: SyntaxRewriter {
368384
anchorPoints[token] = currentIndentationLevel
369385
}
370386

387+
if requiresTrailingNewline(token) {
388+
if !trailingTrivia.endsWithNewline && nextToken?.leadingTrivia.startsWithNewline == false {
389+
trailingTrivia += .newline
390+
}
391+
}
392+
371393
// Add a trailing space to the token unless
372394
// - it already ends with a whitespace or
373395
// - the next token will start starts with a newline after the rewrite

Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,4 +334,42 @@ final class StringLiteralExprSyntaxTests: XCTestCase {
334334
"""#
335335
)
336336
}
337+
338+
func testMultiStringOpeningQuote() {
339+
// assertBuildResult(
340+
// StringLiteralExprSyntax(openQuote: .multilineStringQuoteToken(), content: "a", closeQuote: .multilineStringQuoteToken()),
341+
// #"""
342+
// """
343+
// a
344+
// """
345+
// """#
346+
// )
347+
348+
assertBuildResult(
349+
StringLiteralExprSyntax(
350+
openQuote: .multilineStringQuoteToken(),
351+
segments: StringLiteralSegmentsSyntax {
352+
.expressionSegment(
353+
ExpressionSegmentSyntax(
354+
expressions: TupleExprElementListSyntax {
355+
TupleExprElementSyntax(
356+
expression: StringLiteralExprSyntax(
357+
openQuote: .multilineStringQuoteToken(),
358+
content: "a",
359+
closeQuote: .multilineStringQuoteToken()
360+
)
361+
)
362+
}
363+
)
364+
)
365+
},
366+
closeQuote: .multilineStringQuoteToken()
367+
),
368+
#"""
369+
"""
370+
a
371+
"""
372+
"""#
373+
)
374+
}
337375
}

0 commit comments

Comments
 (0)