Skip to content

Improve diagnostics message for init declaration #1397

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 6 commits into from
Mar 12, 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
15 changes: 12 additions & 3 deletions Sources/SwiftParser/Declarations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,7 @@ extension Parser {
}

// Parse the signature.
let signature = self.parseFunctionSignature()
let signature = self.parseFunctionSignature(allowOutput: false)

let whereClause: RawGenericWhereClauseSyntax?
if self.at(.keyword(.where)) {
Expand Down Expand Up @@ -1389,12 +1389,12 @@ extension Parser {
}

@_spi(RawSyntax)
public mutating func parseFunctionSignature() -> RawFunctionSignatureSyntax {
public mutating func parseFunctionSignature(allowOutput: Bool = true) -> RawFunctionSignatureSyntax {
let input = self.parseParameterClause(for: .functionParameters)

var effectSpecifiers = self.parseDeclEffectSpecifiers()

let output: RawReturnClauseSyntax?
var output: RawReturnClauseSyntax?

/// Only allow recovery to the arrow with exprKeyword precedence so we only
/// skip over misplaced identifiers and don't e.g. recover to an arrow in a 'where' clause.
Expand All @@ -1404,10 +1404,19 @@ extension Parser {
output = nil
}

var unexpectedAfterOutput: RawUnexpectedNodesSyntax?
if !allowOutput,
let unexpectedOutput = output
{
output = nil
unexpectedAfterOutput = RawUnexpectedNodesSyntax([unexpectedOutput], arena: self.arena)
}

return RawFunctionSignatureSyntax(
input: input,
effectSpecifiers: effectSpecifiers,
output: output,
unexpectedAfterOutput,
arena: self.arena
)
}
Expand Down
35 changes: 35 additions & 0 deletions Sources/SwiftParserDiagnostics/ParseDiagnosticsGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,41 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
return .visitChildren
}

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

if let unexpectedName = node.signature.input.unexpectedBeforeLeftParen,
let previous = unexpectedName.previousToken(viewMode: .sourceAccurate)
{
addDiagnostic(
unexpectedName,
.initializerCannotHaveName,
fixIts: [
FixIt(
message: RemoveNodesFixIt(unexpectedName),
changes: [
.makeMissing(unexpectedName),
FixIt.Changes(changes: [.replaceTrailingTrivia(token: previous, newTrivia: .zero)]),
]
)
],
handledNodes: [unexpectedName.id]
)
}

if let unexpectedOutput = node.signature.unexpectedAfterOutput {
addDiagnostic(
unexpectedOutput,
.initializerCannotHaveResultType,
handledNodes: [unexpectedOutput.id]
)
}

return .visitChildren
}

public override func visit(_ node: MemberDeclListItemSyntax) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ extension DiagnosticMessage where Self == StaticParserError {
public static var initializerInPattern: Self {
.init("unexpected initializer in pattern; did you mean to use '='?")
}
public static var initializerCannotHaveName: Self {
.init("initializers cannot have a name")
}
public static var initializerCannotHaveResultType: Self {
.init("initializers cannot have a result type")
}
public static var invalidFlagAfterPrecedenceGroupAssignment: Self {
.init("expected 'true' or 'false' after 'assignment'")
}
Expand Down
15 changes: 13 additions & 2 deletions Tests/SwiftParserTest/translated/InitDeinitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ final class InitDeinitTests: XCTestCase {
AssertParse(
"""
struct FooStructConstructorD {
init() -> FooStructConstructorD { }
init() 1️⃣-> FooStructConstructorD { }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: initializers cannot have a result type
DiagnosticSpec(message: "initializers cannot have a result type")
]
)
}
Expand Down Expand Up @@ -391,6 +391,17 @@ final class InitDeinitTests: XCTestCase {
)
}

func testInitDeinit28() {
AssertParse(
"""
init(_ foo: T) 1️⃣-> Int where T: Comparable {}
""",
diagnostics: [
DiagnosticSpec(message: "initializers cannot have a result type")
]
)
}

func testDeinitInSwiftinterfaceIsFollowedByFinalFunc() {
AssertParse(
"""
Expand Down
34 changes: 21 additions & 13 deletions Tests/SwiftParserTest/translated/RecoveryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1741,7 +1741,7 @@ final class RecoveryTests: XCTestCase {
DiagnosticSpec(locationMarker: "1️⃣", message: "expected '>' to end generic parameter clause"),
DiagnosticSpec(locationMarker: "2️⃣", message: "expected type and ')' to end parameter clause"),
DiagnosticSpec(locationMarker: "3️⃣", message: "unexpected code ')}' before struct"),
DiagnosticSpec(locationMarker: "4️⃣", message: "unexpected code 'x' before parameter clause"),
DiagnosticSpec(locationMarker: "4️⃣", message: "initializers cannot have a name", fixIts: ["remove 'x'"]),
]
)
}
Expand All @@ -1752,9 +1752,11 @@ final class RecoveryTests: XCTestCase {
init 1️⃣a(b: Int) {}
""",
diagnostics: [
// TODO: (good first issue) Old parser expected error on line 3: initializers cannot have a name, Fix-It replacements: 8 - 9 = ''
DiagnosticSpec(message: "unexpected code 'a' before parameter clause")
]
DiagnosticSpec(message: "initializers cannot have a name", fixIts: ["remove 'a'"])
],
fixedSource: """
init(b: Int) {}
"""
)
}

Expand All @@ -1764,9 +1766,11 @@ final class RecoveryTests: XCTestCase {
init? 1️⃣c(_ d: Int) {}
""",
diagnostics: [
// TODO: (good first issue) Old parser expected error on line 1: initializers cannot have a name, Fix-It replacements: 9 - 10 = ''
DiagnosticSpec(message: "unexpected code 'c' before parameter clause")
]
DiagnosticSpec(message: "initializers cannot have a name", fixIts: ["remove 'c'"])
],
fixedSource: """
init?(_ d: Int) {}
"""
)
}

Expand All @@ -1776,9 +1780,11 @@ final class RecoveryTests: XCTestCase {
init 1️⃣e<T>(f: T) {}
""",
diagnostics: [
// TODO: (good first issue) Old parser expected error on line 1: initializers cannot have a name, Fix-It replacements: 8 - 9 = ''
DiagnosticSpec(message: "unexpected code 'e<T>' before parameter clause")
]
DiagnosticSpec(message: "initializers cannot have a name", fixIts: ["remove 'e<T>'"])
],
fixedSource: """
init(f: T) {}
"""
)
}

Expand All @@ -1788,9 +1794,11 @@ final class RecoveryTests: XCTestCase {
init? 1️⃣g<T>(_: T) {}
""",
diagnostics: [
// TODO: (good first issue) Old parser expected error on line 1: initializers cannot have a name, Fix-It replacements: 9 - 10 = ''
DiagnosticSpec(message: "unexpected code 'g<T>' before parameter clause")
]
DiagnosticSpec(message: "initializers cannot have a name", fixIts: ["remove 'g<T>'"])
],
fixedSource: """
init?(_: T) {}
"""
)
}

Expand Down