Skip to content

Fix multiline string when using string interpolation #1335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,14 @@ let basicFormatFile = SourceFileSyntax(leadingTrivia: generateCopyrightHeader(fo
if requiresTrailingSpace(node) && trailingTrivia.isEmpty {
trailingTrivia += .space
}
if let keyPath = getKeyPath(Syntax(node)), requiresLeadingNewline(keyPath), !(leadingTrivia.first?.isNewline ?? false) {
if let keyPath = getKeyPath(Syntax(node)), requiresLeadingNewline(keyPath), !(leadingTrivia.first?.isNewline ?? false), !shouldOmitNewline(node) {
leadingTrivia = .newline + leadingTrivia
}
leadingTrivia = leadingTrivia.indented(indentation: indentation)
trailingTrivia = trailingTrivia.indented(indentation: indentation)
var isOnNewline: Bool = (lastRewrittenToken?.trailingTrivia.pieces.last?.isNewline == true)
if case .stringSegment(let text) = lastRewrittenToken?.tokenKind {
isOnNewline = isOnNewline || (text.last?.isNewline == true)
}
leadingTrivia = leadingTrivia.indented(indentation: indentation, isOnNewline: isOnNewline)
let rewritten = TokenSyntax(
node.tokenKind,
leadingTrivia: leadingTrivia,
Expand All @@ -110,6 +113,25 @@ let basicFormatFile = SourceFileSyntax(leadingTrivia: generateCopyrightHeader(fo
"""
)

DeclSyntax(
"""
/// If this returns `true`, ``BasicFormat`` will not wrap `node` to a new line. This can be used to e.g. keep string interpolation segments on a single line.
/// - Parameter node: the node that is being visited
/// - Returns: returns true if newline should be omitted
open func shouldOmitNewline(_ node: TokenSyntax) -> Bool {
var ancestor: Syntax = Syntax(node)
while let parent = ancestor.parent {
ancestor = parent
if ancestor.is(ExpressionSegmentSyntax.self) {
return true
}
}

return false
}
"""
)

try FunctionDeclSyntax("open func shouldIndent(_ keyPath: AnyKeyPath) -> Bool") {
try SwitchExprSyntax("switch keyPath") {
for node in SYNTAX_NODES where !node.isBase {
Expand Down
24 changes: 17 additions & 7 deletions Sources/SwiftBasicFormat/Trivia+Indented.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,35 @@
import SwiftSyntax

extension Trivia {
func indented(indentation: TriviaPiece) -> Trivia {
/// Makes sure each newline of this trivia is followed by `indentation`. If this is not the case, the existing indentation is extended to `indentation`.
/// `isOnNewline` determines whether the trivia starts on a new line. If this is the case, the function makes sure that the returned trivia starts with `indentation`.
func indented(indentation: TriviaPiece, isOnNewline: Bool = false) -> Trivia {
var indentedPieces: [TriviaPiece] = []
for (index, piece) in self.enumerated() {
let nextPiece = index < pieces.count - 1 ? pieces[index + 1] : nil
indentedPieces.append(piece)
if piece.isNewline {
switch (nextPiece, indentation) {
case (.spaces(let nextPieceSpaces)?, .spaces(let indentationSpaces)):
let previousPieceIsNewline: Bool
if index == 0 {
previousPieceIsNewline = isOnNewline
} else {
previousPieceIsNewline = pieces[index - 1].isNewline
}
if previousPieceIsNewline {
switch (piece, indentation) {
case (.spaces(let nextPieceSpaces), .spaces(let indentationSpaces)):
if nextPieceSpaces < indentationSpaces {
indentedPieces.append(.spaces(indentationSpaces - nextPieceSpaces))
}
case (.tabs(let nextPieceTabs)?, .tabs(let indentationTabs)):
case (.tabs(let nextPieceTabs), .tabs(let indentationTabs)):
if nextPieceTabs < indentationTabs {
indentedPieces.append(.tabs(indentationTabs - nextPieceTabs))
}
default:
indentedPieces.append(indentation)
}
}
indentedPieces.append(piece)
}
if self.pieces.last?.isNewline == true {
indentedPieces.append(indentation)
}
return Trivia(pieces: indentedPieces)
}
Expand Down
24 changes: 21 additions & 3 deletions Sources/SwiftBasicFormat/generated/BasicFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ open class BasicFormat: SyntaxRewriter {
if requiresTrailingSpace(node) && trailingTrivia.isEmpty {
trailingTrivia += .space
}
if let keyPath = getKeyPath(Syntax(node)), requiresLeadingNewline(keyPath), !(leadingTrivia.first?.isNewline ?? false) {
if let keyPath = getKeyPath(Syntax(node)), requiresLeadingNewline(keyPath), !(leadingTrivia.first?.isNewline ?? false), !shouldOmitNewline(node) {
leadingTrivia = .newline + leadingTrivia
}
leadingTrivia = leadingTrivia.indented(indentation: indentation)
trailingTrivia = trailingTrivia.indented(indentation: indentation)
var isOnNewline: Bool = (lastRewrittenToken?.trailingTrivia.pieces.last?.isNewline == true)
if case .stringSegment(let text) = lastRewrittenToken?.tokenKind {
isOnNewline = isOnNewline || (text.last?.isNewline == true)
}
leadingTrivia = leadingTrivia.indented(indentation: indentation, isOnNewline: isOnNewline)
let rewritten = TokenSyntax(
node.tokenKind,
leadingTrivia: leadingTrivia,
Expand All @@ -71,6 +74,21 @@ open class BasicFormat: SyntaxRewriter {
return rewritten
}

/// If this returns `true`, ``BasicFormat`` will not wrap `node` to a new line. This can be used to e.g. keep string interpolation segments on a single line.
/// - Parameter node: the node that is being visited
/// - Returns: returns true if newline should be omitted
open func shouldOmitNewline(_ node: TokenSyntax) -> Bool {
var ancestor: Syntax = Syntax(node)
while let parent = ancestor.parent {
ancestor = parent
if ancestor.is(ExpressionSegmentSyntax.self) {
return true
}
}

return false
}

open func shouldIndent(_ keyPath: AnyKeyPath) -> Bool {
switch keyPath {
case \AccessorBlockSyntax.accessors:
Expand Down
155 changes: 155 additions & 0 deletions Tests/SwiftSyntaxBuilderTest/StringLiteralTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,159 @@ final class StringLiteralTests: XCTestCase {
"""#
)
}

func testStringLiteralInExpr() {
let buildable = ExprSyntax(
#"""
"Validation failures: \(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"
"""#
)

AssertBuildResult(
buildable,
#"""
"Validation failures: \(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"
"""#
)
}

func testStringSegmentWithCode() {
let buildable = StringSegmentSyntax(content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#))

AssertBuildResult(
buildable,
#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#
)
}

func testStringLiteralSegmentWithCode() {
let buildable = StringLiteralSegmentsSyntax {
StringSegmentSyntax(content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), trailingTrivia: .newline)
StringSegmentSyntax(content: .stringSegment(#"Node did not satisfy any node choice requirement."#), trailingTrivia: .newline)
StringSegmentSyntax(content: .stringSegment(#"Validation failures:"#), trailingTrivia: .newline)
StringSegmentSyntax(content: .stringSegment(#"\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#))
}

AssertBuildResult(
buildable,
#"""
Error validating child at index \(index) of \(nodeKind):
Node did not satisfy any node choice requirement.
Validation failures:
\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))
"""#
)
}

func testMultiLineStringWithResultBuilder() {
let buildable = StringLiteralExprSyntax(
openQuote: .multilineStringQuoteToken(trailingTrivia: .newline),
segments: StringLiteralSegmentsSyntax {
StringSegmentSyntax(content: .stringSegment(#"Error validating child at index \(index) of \(nodeKind):"#), trailingTrivia: .newline)
StringSegmentSyntax(content: .stringSegment(#"Node did not satisfy any node choice requirement."#), trailingTrivia: .newline)
StringSegmentSyntax(content: .stringSegment(#"Validation failures:"#), trailingTrivia: .newline)
ExpressionSegmentSyntax(
expressions: TupleExprElementListSyntax {
TupleExprElementSyntax(expression: ExprSyntax(#"nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))"#))
}
)
},
closeQuote: .multilineStringQuoteToken(leadingTrivia: .newline)
)

AssertBuildResult(
buildable,
#"""
"""
Error validating child at index \(index) of \(nodeKind):
Node did not satisfy any node choice requirement.
Validation failures:
\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n")))
"""
"""#
)
}

func testMultiStringLiteralInExpr() {
let buildable = ExprSyntax(
#"""
assertionFailure("""
Error validating child at index \(index) of \(nodeKind):
Node did not satisfy any node choice requirement.
Validation failures:
\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))
""", file: file, line: line)
"""#
)

AssertBuildResult(
buildable,
#"""
assertionFailure("""
Error validating child at index \(index) of \(nodeKind):
Node did not satisfy any node choice requirement.
Validation failures:
\(nonNilErrors.map({ "- \($0.description)" }).joined(separator: "\n"))
""", file: file, line: line)
"""#
)
}

func testMultiStringLiteralInIfExpr() {
let buildable = ExprSyntax(
#"""
if true {
assertionFailure("""
Error validating child at index
Node did not satisfy any node choice requirement.
Validation failures:
""")
}
"""#
)

AssertBuildResult(
buildable,
#"""
if true {
assertionFailure("""
Error validating child at index
Node did not satisfy any node choice requirement.
Validation failures:
""")
}
"""#
)
}

func testMultiStringLiteralOnNewlineInIfExpr() {
let buildable = ExprSyntax(
#"""
if true {
assertionFailure(
"""
Error validating child at index
Node did not satisfy any node choice requirement.
Validation failures:
"""
)
}
"""#
)

AssertBuildResult(
buildable,
#"""
if true {
assertionFailure(
"""
Error validating child at index
Node did not satisfy any node choice requirement.
Validation failures:
"""
)
}
"""#
)
}
}