Skip to content

Diagnose singe-line strings #1278

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 1 commit into from
Jan 26, 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
19 changes: 16 additions & 3 deletions Sources/SwiftParser/StringLiterals.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ extension Parser {
let openDelimiter = self.consume(if: .rawStringDelimiter)

/// Parse open quote.
let (unexpectedBeforeOpenQuote, openQuote) = self.expectAny([.stringQuote, .multilineStringQuote, .singleQuote], default: .stringQuote)
var (unexpectedBeforeOpenQuote, openQuote) = self.expectAny([.stringQuote, .multilineStringQuote], default: .stringQuote)
var openQuoteKind: RawTokenKind = openQuote.tokenKind
if openQuote.isMissing, let singleQuote = self.consume(if: .singleQuote) {
unexpectedBeforeOpenQuote = RawUnexpectedNodesSyntax(combining: unexpectedBeforeOpenQuote, singleQuote, arena: self.arena)
openQuoteKind = .singleQuote
}

/// Parse segments.
var segments: [RawStringLiteralSegmentsSyntax.Element] = []
Expand All @@ -68,7 +73,7 @@ extension Parser {
// This allows us to skip over extraneous identifiers etc. in an unterminated string interpolation.
var unexpectedBeforeRightParen: [RawTokenSyntax] = []
var unexpectedProgress = LoopProgressCondition()
while !self.at(any: [.rightParen, .stringSegment, .backslash, openQuote.tokenKind, .eof]) && unexpectedProgress.evaluate(self.currentToken) {
while !self.at(any: [.rightParen, .stringSegment, .backslash, openQuoteKind, .eof]) && unexpectedProgress.evaluate(self.currentToken) {
unexpectedBeforeRightParen.append(self.consumeAnyToken())
}
let rightParen = self.expectWithoutRecovery(.rightParen)
Expand Down Expand Up @@ -106,7 +111,15 @@ extension Parser {
}

/// Parse close quote.
let (unexpectedBeforeCloseQuote, closeQuote) = self.expect(openQuote.tokenKind)
let unexpectedBeforeCloseQuote: RawUnexpectedNodesSyntax?
let closeQuote: RawTokenSyntax
if openQuoteKind == .singleQuote {
let (unexpectedBeforeSingleQuote, singleQuote) = self.expect(.singleQuote)
unexpectedBeforeCloseQuote = RawUnexpectedNodesSyntax(combining: unexpectedBeforeSingleQuote, singleQuote, arena: self.arena)
closeQuote = missingToken(.stringQuote)
} else {
(unexpectedBeforeCloseQuote, closeQuote) = self.expect(openQuote.tokenKind)
}

let (unexpectedBeforeCloseDelimiter, closeDelimiter) = self.parseStringDelimiter(openDelimiter: openDelimiter)

Expand Down
5 changes: 4 additions & 1 deletion Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ extension FixIt.Changes {

/// If `transferTrivia` is `true`, the leading and trailing trivia of the
/// removed node will be transferred to the trailing trivia of the previous token.
static func makeMissing<SyntaxType: SyntaxProtocol>(_ node: SyntaxType, transferTrivia: Bool = true) -> Self {
static func makeMissing<SyntaxType: SyntaxProtocol>(_ node: SyntaxType?, transferTrivia: Bool = true) -> Self {
guard let node = node else {
return FixIt.Changes(changes: [])
}
var changes = [FixIt.Change.replace(oldNode: Syntax(node), newNode: MissingMaker().visit(Syntax(node)))]
if transferTrivia {
changes += FixIt.Changes.transferTriviaAtSides(from: [node]).changes
Expand Down
31 changes: 31 additions & 0 deletions Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,37 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
return .visitChildren
}

public override func visit(_ node: StringLiteralExprSyntax) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
}

if let singleQuote = node.unexpectedBetweenOpenDelimiterAndOpenQuote?.onlyToken(where: { $0.tokenKind == .singleQuote }) {
let fixIt = FixIt(
message: ReplaceTokensFixIt(replaceTokens: [singleQuote], replacement: node.openQuote),
changes: [
.makeMissing(singleQuote, transferTrivia: false),
.makePresent(node.openQuote, leadingTrivia: singleQuote.leadingTrivia ?? []),
.makeMissing(node.unexpectedBetweenSegmentsAndCloseQuote, transferTrivia: false),
.makePresent(node.closeQuote, trailingTrivia: node.unexpectedBetweenSegmentsAndCloseQuote?.trailingTrivia ?? []),
]
)
addDiagnostic(
singleQuote,
.singleQuoteStringLiteral,
fixIts: [fixIt],
handledNodes: [
node.unexpectedBetweenOpenDelimiterAndOpenQuote?.id,
node.openQuote.id,
node.unexpectedBetweenSegmentsAndCloseQuote?.id,
node.closeQuote.id,
].compactMap { $0 }
)
}

return .visitChildren
}

public override func visit(_ node: SwitchCaseSyntax) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ extension DiagnosticMessage where Self == StaticParserError {
public static var operatorShouldBeDeclaredWithoutBody: Self {
.init("operator should not be declared with body")
}
public static var singleQuoteStringLiteral: Self {
.init(#"Single-quoted string literal found, use '"'"#)
}
public static var standaloneSemicolonStatement: Self {
.init("standalone ';' statements are not allowed")
}
Expand Down
22 changes: 20 additions & 2 deletions Tests/SwiftParserTest/ExpressionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -632,8 +632,26 @@ final class ExpressionTests: XCTestCase {
func testSingleQuoteStringLiteral() {
AssertParse(
#"""
'red'
"""#
1️⃣'red'
"""#,
diagnostics: [
DiagnosticSpec(message: #"Single-quoted string literal found, use '"'"#, fixIts: [#"replace ''' by '"'"#])
],
fixedSource: """
"red"
"""
)

AssertParse(
#"""
1️⃣' red ' + 1
"""#,
diagnostics: [
DiagnosticSpec(message: #"Single-quoted string literal found, use '"'"#, fixIts: [#"replace ''' by '"'"#])
],
fixedSource: """
" red " + 1
"""
)
}

Expand Down