Skip to content
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

Fix parsing invalid function parameters #2927

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
24 changes: 22 additions & 2 deletions Sources/SwiftParser/Parameters.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,31 @@ extension Parser {
let modifiers = parseParameterModifiers(isClosure: false)
let misplacedSpecifiers = parseMisplacedSpecifiers()

var names = self.parseParameterNames()
let (unexpectedBeforeColon, colon) = self.expect(.colon)
var names: ParameterNames

let unexpectedBeforeColon: RawUnexpectedNodesSyntax?
let colon: RawTokenSyntax
let type: RawTypeSyntax

// try to parse the type regardless of the presence of the preceding colon
// to tackle any unnamed parameter or missing colon
// e.g. [X], (:[X]) or (x [X])
let canParseType = withLookahead { $0.canParseType() && $0.at(.comma, .rightParen) }

if canParseType {
names = ParameterNames(
unexpectedBeforeFirstName: nil,
firstName: nil,
unexpectedBeforeSecondName: nil,
secondName: nil
)
unexpectedBeforeColon = nil
colon = missingToken(.colon)
} else {
names = self.parseParameterNames()
(unexpectedBeforeColon, colon) = self.expect(.colon)
}

if colon.presence == .missing,
let secondName = names.secondName,
secondName.tokenKind == .identifier,
Expand Down
26 changes: 26 additions & 0 deletions Tests/SwiftParserTest/ExpressionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3369,4 +3369,30 @@ final class StatementExpressionTests: ParserTestCase {
substructureAfterMarker: "1️⃣"
)
}

func testFunctionParameterWithMalformedParameters() {
assertParse(
"""
init(1️⃣String.Index, x:(Int) -> Int) rethrows
""",
diagnostics: [
DiagnosticSpec(message: "expected identifier and ':' in parameter", fixIts: ["insert identifier and ':'"])
],
fixedSource: """
init(<#identifier#>: String.Index, x:(Int) -> Int) rethrows
"""
)

assertParse(
"""
init(1️⃣String.Index) rethrows
""",
diagnostics: [
DiagnosticSpec(message: "expected identifier and ':' in parameter", fixIts: ["insert identifier and ':'"])
],
fixedSource: """
init(<#identifier#>: String.Index) rethrows
"""
)
}
}