Skip to content

Commit 81faa8f

Browse files
Fixes wrong escape when creating a string literal where a pound sign follows a sequence of double quotes or backslashes.
This pull request fixes a problem where escaping fails when a pound sign follows a sequence of double quotes or backslashes. As shown in the added test case, `foobar""#` and `foobar\\#` require two pound signs as delimiter for escaping, but the current implementation only adds one pound sign, resulting in an incorrect string literal. The reason for this is that a sequence of double quotes or backslashes will stop counting pound signs if they are not followed by a pound sign. If a double quotation mark or backslash is followed by a double quotation mark or backslash, it must continue in pound sign counting mode.
1 parent 8957ef3 commit 81faa8f

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,9 @@ extension StringLiteralExprSyntax {
262262
case (true, _) where c.unicodeScalars.contains("#"):
263263
consecutivePounds += 1
264264
maxPounds = max(maxPounds, consecutivePounds)
265+
case (true, "\""), (true, "\\"):
266+
countingPounds = true
267+
requiresEscaping = true
265268
case (true, _):
266269
countingPounds = false
267270
consecutivePounds = 0

Tests/SwiftSyntaxBuilderTest/StringLiteralExprSyntaxTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,24 @@ final class StringLiteralExprSyntaxTests: XCTestCase {
7171
)
7272
}
7373
74+
func testEscapePoundsAfterConsecutiveQuotes() {
75+
assertBuildResult(
76+
StringLiteralExprSyntax(content: ##"foobar""#"##),
77+
"""
78+
##"foobar""#"##
79+
"""
80+
)
81+
}
82+
83+
func testEscapePoundsAfterConsecutiveBackslashes() {
84+
assertBuildResult(
85+
StringLiteralExprSyntax(content: ##"foobar\\#"##),
86+
##"""
87+
##"foobar\\#"##
88+
"""##
89+
)
90+
}
91+
7492
func testEscapePoundEmojis() {
7593
assertBuildResult(
7694
StringLiteralExprSyntax(content: ##"foo"#️⃣"bar"##),

0 commit comments

Comments
 (0)