Skip to content

Add diagnostic for unexpected second identifier #1382

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
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
17 changes: 15 additions & 2 deletions Sources/SwiftParser/Patterns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,22 @@ extension Parser {
while !self.at(.eof, .rightParen) && keepGoing && loopProgress.evaluate(currentToken) {
// If the tuple element has a label, parse it.
let labelAndColon = self.consume(if: .identifier, followedBy: .colon)
let (label, colon) = (labelAndColon?.0, labelAndColon?.1)
var (label, colon) = (labelAndColon?.0, labelAndColon?.1)

/// If we have something like `x SomeType`, use the indication that `SomeType` starts with a capital letter (and is thus probably a type name)
/// as an indication that the user forgot to write the colon instead of forgetting to write the comma to separate two elements.
if label == nil, colon == nil, peek().rawTokenKind == .identifier, peek().tokenText.isStartingWithUppercase {
label = consumeAnyToken()
colon = self.missingToken(.colon)
}

let pattern = self.parsePattern()
let trailingComma = self.consume(if: .comma)
var trailingComma = self.consume(if: .comma)

if trailingComma == nil && self.at(TokenSpec(.identifier, allowAtStartOfLine: false)) {
trailingComma = self.missingToken(RawTokenKind.comma)
}

keepGoing = trailingComma != nil
elements.append(
RawTuplePatternElementSyntax(
Expand Down
8 changes: 8 additions & 0 deletions Sources/SwiftParser/SyntaxUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ extension SyntaxText {
var isEditorPlaceholder: Bool {
return self.starts(with: SyntaxText("<#")) && self.hasSuffix(SyntaxText("#>"))
}

var isStartingWithUppercase: Bool {
if !self.isEmpty, let firstCharacterByte = self.baseAddress?.pointee {
return 65 <= firstCharacterByte && firstCharacterByte <= 90
} else {
return false
}
}
}

extension RawTokenKind {
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftParser/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ extension Parser {
if let first = first,
second == nil,
colon?.isMissing == true,
first.tokenText.description.first?.isUppercase == true
first.tokenText.isStartingWithUppercase
{
elements.append(
RawTupleTypeElementSyntax(
Expand Down
8 changes: 4 additions & 4 deletions Sources/SwiftParserDiagnostics/DiagnosticExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ extension FixIt.MultiNodeChange {
}
}

/// Transfers the leading and trivia trivia of `nodes` to the trailing trivia
/// of the previous token. While doing this, it tries to be smart, merging trivia
/// where it makes sense and refusing to add e.g. a space after punctuation,
/// where it usually doesn't make sense.
/// Transfers the leading and trailing trivia of `nodes` to the previous token
/// While doing this, it tries to be smart, merging trivia where it makes sense
/// and refusing to add e.g. a space after punctuation, where it usually
/// doesn't make sense.
static func transferTriviaAtSides<SyntaxType: SyntaxProtocol>(from nodes: [SyntaxType]) -> Self {
let removedTriviaAtSides = (nodes.first?.leadingTrivia ?? []).merging(nodes.last?.trailingTrivia ?? [])
if !removedTriviaAtSides.isEmpty, let previousToken = nodes.first?.previousToken(viewMode: .sourceAccurate) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
FixIt(
message: .joinIdentifiers,
changes: [
FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joined), presence: .present)))),
FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joined), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)))),
.makeMissing(tokens),
]
)
Expand All @@ -338,7 +338,7 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
FixIt(
message: .joinIdentifiersWithCamelCase,
changes: [
FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joinedUsingCamelCase), presence: .present)))),
FixIt.MultiNodeChange(.replace(oldNode: Syntax(previousToken), newNode: Syntax(TokenSyntax(.identifier(joinedUsingCamelCase), trailingTrivia: tokens.last?.trailingTrivia ?? [], presence: .present)))),
.makeMissing(tokens),
]
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,9 +383,9 @@ public struct SpaceSeparatedIdentifiersError: ParserError {
if let name = firstToken.parent?.ancestorOrSelf(mapping: {
$0.nodeTypeNameForDiagnostics(allowBlockNames: false)
}) {
return "found an unexpected second identifier in \(name)"
return "found an unexpected second identifier in \(name); is there an accidental break?"
} else {
return "found an unexpected second identifier"
return "found an unexpected second identifier; is there an accidental break?"
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Tests/SwiftParserTest/ParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public class ParserTests: XCTestCase {
}
}

/// Run parsr tests on all of the Swift files in the given path, recursively.
/// Run parser tests on all of the Swift files in the given path, recursively.
func runParserTests(
name: String,
path: URL,
Expand Down
9 changes: 5 additions & 4 deletions Tests/SwiftParserTest/TypeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@
import XCTest

final class TypeTests: XCTestCase {

func testMissingColonInType() {
assertParse(
"""
var foo 1️⃣Bar = 1
""",
diagnostics: [
DiagnosticSpec(message: "expected ':' in type annotation")
]
DiagnosticSpec(message: "expected ':' in type annotation", fixIts: ["insert ':'"])
],
fixedSource: """
var foo: Bar = 1
"""
)
}

Expand Down Expand Up @@ -65,7 +67,6 @@ final class TypeTests: XCTestCase {
}

func testClosureSignatures() {

assertParse(
"""
simple { [] str in
Expand Down
151 changes: 72 additions & 79 deletions Tests/SwiftParserTest/translated/InvalidTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -388,92 +388,85 @@ final class InvalidTests: XCTestCase {
)
}

func testInvalid23a() {
assertParse(
"""
func dog 1️⃣cow() {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: ["join the identifiers together"],
fixedSource: "func dogcow() {}"
)
}

func testInvalid23b() {
assertParse(
"""
func dog 1️⃣cow() {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: ["join the identifiers together with camel-case"],
fixedSource: "func dogCow() {}"
)
func testInvalid23() {
let testCases: [UInt: (fixIt: String, fixedSource: String)] = [
#line: ("join the identifiers together", "func dogcow() {}"),
#line: ("join the identifiers together with camel-case", "func dogCow() {}"),
]

for (line, testCase) in testCases {
assertParse(
"""
func dog 1️⃣cow() {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function; is there an accidental break?",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: [testCase.fixIt],
fixedSource: testCase.fixedSource,
line: line
)
}
}

func testThreeIdentifersForFunctionName() {
assertParse(
"""
func dog 1️⃣cow sheep() {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: ["join the identifiers together with camel-case"],
fixedSource: "func dogCowSheep() {}"
)
}
let testCases: [UInt: (fixIt: String, fixedSource: String)] = [
#line: ("join the identifiers together", "func dogcowsheep() {}"),
#line: ("join the identifiers together with camel-case", "func dogCowSheep() {}"),
]

func testInvalid24() {
assertParse(
"""
func cat 1️⃣Mouse() {}
""",
diagnostics: [
DiagnosticSpec(message: "found an unexpected second identifier in function", fixIts: ["join the identifiers together"])
],
fixedSource: "func catMouse() {}"
)
for (line, testCase) in testCases {
assertParse(
"""
func dog 1️⃣cow sheep() {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function; is there an accidental break?",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: [testCase.fixIt],
fixedSource: testCase.fixedSource,
line: line
)
}
}

func testInvalid25() {
assertParse(
"""
func friend 1️⃣ship<T>(x: T) {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: ["join the identifiers together with camel-case"],
fixedSource: "func friendShip<T>(x: T) {}"
)
let testCases: [UInt: (fixIt: String, fixedSource: String)] = [
#line: ("join the identifiers together", "func friendship<T>(x: T) {}"),
#line: ("join the identifiers together with camel-case", "func friendShip<T>(x: T) {}"),
]

for (line, testCase) in testCases {
assertParse(
"""
func friend 1️⃣ship<T>(x: T) {}
""",
diagnostics: [
DiagnosticSpec(
message: "found an unexpected second identifier in function; is there an accidental break?",
fixIts: [
"join the identifiers together",
"join the identifiers together with camel-case",
]
)
],
applyFixIts: [testCase.fixIt],
fixedSource: testCase.fixedSource,
line: line
)
}
}

func testInvalid26() {
Expand Down
Loading