Skip to content

Diagnose if initializer is used as type annotation #974

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
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
31 changes: 29 additions & 2 deletions Sources/SwiftParser/Declarations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1713,7 +1713,7 @@ extension Parser {
var loopProgress = LoopProgressCondition()
repeat {

let (pattern, type) = self.parseTypedPattern()
var (pattern, typeAnnotation) = self.parseTypedPattern()

// Parse an initializer if present.
let initializer: RawInitializerClauseSyntax?
Expand All @@ -1732,6 +1732,33 @@ extension Parser {
value: value,
arena: self.arena
)
} else if self.at(.leftParen), !self.currentToken.isAtStartOfLine,
let typeAnnotationUnwrapped = typeAnnotation {
// If we have a '(' after the type in the annotation, the type annotation
// is probably a constructor call. Rewrite the nodes to remove the type
// annotation and form an initializer clause from it instead.
typeAnnotation = nil
let initExpr = parsePostfixExpressionSuffix(
RawExprSyntax(RawTypeExprSyntax(
type: typeAnnotationUnwrapped.type,
typeAnnotation?.unexpectedAfterType,
arena: self.arena
)),
.basic,
forDirective: false,
pattern: .none
)
initializer = RawInitializerClauseSyntax(
RawUnexpectedNodesSyntax(
(typeAnnotationUnwrapped.unexpectedBeforeColon?.elements ?? []) +
[RawSyntax(typeAnnotationUnwrapped.colon)] +
(typeAnnotationUnwrapped.unexpectedBetweenColonAndType?.elements ?? []),
arena: self.arena
),
equal: missingToken(.equal, text: nil),
value: initExpr,
arena: self.arena
)
} else {
initializer = nil
}
Expand All @@ -1746,7 +1773,7 @@ extension Parser {
keepGoing = self.consume(if: .comma)
elements.append(RawPatternBindingSyntax(
pattern: pattern,
typeAnnotation: type,
typeAnnotation: typeAnnotation,
initializer: initializer,
accessor: accessor,
trailingComma: keepGoing,
Expand Down
16 changes: 16 additions & 0 deletions Sources/SwiftParser/Diagnostics/ParseDiagnosticsGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,22 @@ public class ParseDiagnosticsGenerator: SyntaxAnyVisitor {
return .visitChildren
}

public override func visit(_ node: InitializerClauseSyntax) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
}
if node.equal.presence == .missing {
exchangeTokens(
unexpected: node.unexpectedBeforeEqual,
unexpectedTokenCondition: { $0.tokenKind == .colon },
correctTokens: [node.equal],
message: { _ in StaticParserError.initializerInPattern },
moveFixIt: { ReplaceTokensFixIt(replaceTokens: $0, replacement: node.equal) }
)
}
return .visitChildren
}

public override func visit(_ node: PrecedenceGroupAssignmentSyntax) -> SyntaxVisitorContinueKind {
if shouldSkip(node) {
return .skipChildren
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ extension DiagnosticMessage where Self == StaticParserError {
public static var expectedExpressionAfterTry: Self {
.init("expected expression after 'try'")
}
public static var initializerInPattern: Self {
.init("unexpected initializer in pattern; did you mean to use '='?")
}
public static var invalidFlagAfterPrecedenceGroupAssignment: Self {
.init("expected 'true' or 'false' after 'assignment'")
}
Expand Down
26 changes: 0 additions & 26 deletions Sources/SwiftParser/Expressions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2246,32 +2246,6 @@ extension Parser {
} while keepGoing != nil && loopProgress.evaluate(currentToken)
return result
}

/// Parse an argument list.
///
/// This is currently the same as parsing a tuple expression. In the future,
/// this will be a dedicated argument list type.
///
/// Grammar
/// =======
///
/// tuple-expression → '(' ')' | '(' tuple-element ',' tuple-element-list ')'
/// tuple-element-list → tuple-element | tuple-element ',' tuple-element-list
@_spi(RawSyntax)
public mutating func parseArgumentList(_ flavor: ExprFlavor, pattern: PatternContext) -> RawTupleExprSyntax {
let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen)
let args = self.parseArgumentListElements(pattern: pattern)
let (unexpectedBeforeRightParen, rparen) = self.expect(.rightParen)

// FIXME: Introduce new SyntaxKind for ArgumentList (rdar://81786229)
return RawTupleExprSyntax(
unexpectedBeforeLParen,
leftParen: lparen,
elementList: RawTupleExprElementListSyntax(elements: args, arena: self.arena),
unexpectedBeforeRightParen,
rightParen: rparen,
arena: self.arena)
}
}

extension Parser {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,72 @@

import XCTest

// https://github.com/apple/swift/issues/44070
final class DiagnoseInitializerAsTypedPatternTests: XCTestCase {
func testDiagnoseInitializerAsTypedPattern1() {
func testDiagnoseInitializerAsTypedPattern3a() {
AssertParse(
"""
// https://github.com/apple/swift/issues/44070
"""
let a1️⃣:[X]()
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
], fixedSource: "let a=[X]()"
)
}

func testDiagnoseInitializerAsTypedPattern2() {
func testDiagnoseInitializerAsTypedPattern3b() {
AssertParse(
"""
class X {}
func foo() {}
let b1️⃣: [X]()
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
], fixedSource: "let b= [X]()"
)
}

func testDiagnoseInitializerAsTypedPattern3c() {
AssertParse(
"""
let c 1️⃣:[X]()
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
], fixedSource: "let c =[X]()"
)
}

func testDiagnoseInitializerAsTypedPattern3() {
func testDiagnoseInitializerAsTypedPattern3d() {
AssertParse(
"""
let a:[X]1️⃣()
let b: [X]2️⃣()
let c :[X]3️⃣()
let d : [X]4️⃣()
let d 1️⃣: [X]()
""",
diagnostics: [
// TODO: Old parser expected error on line 1: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' = '
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 2: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 3: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 7 - 8 = '= '
DiagnosticSpec(locationMarker: "3️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 4: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 7 - 8 = '='
DiagnosticSpec(locationMarker: "4️⃣", message: "consecutive statements on a line must be separated by ';'"),
]
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
], fixedSource: "let d = [X]()"
)
}


func testDiagnoseInitializerAsTypedPattern4() {
AssertParse(
"""
let e: X1️⃣()2️⃣, ee: Int
let e1️⃣: X(), ee: Int
""",
diagnostics: [
// TODO: Old parser expected error on line 1: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'"),
DiagnosticSpec(locationMarker: "2️⃣", message: "extraneous code ', ee: Int' at top level"),
]
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?"),
], fixedSource: "let e= X(), ee: Int"
)
}

func testDiagnoseInitializerAsTypedPattern5() {
AssertParse(
"""
let f:/*comment*/[X]1️⃣()
let f1️⃣:/*comment*/[X]()
""",
diagnostics: [
// TODO: Old parser expected error on line 1: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' = '
DiagnosticSpec(message: "consecutive statements on a line must be separated by ';'")
]
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
], fixedSource: "let f=/*comment*/[X]()"
)
}

Expand All @@ -75,9 +80,9 @@ final class DiagnoseInitializerAsTypedPatternTests: XCTestCase {
}

func testDiagnoseInitializerAsTypedPattern7() {
// paren follows the type, but it's part of a separate (valid) expression
AssertParse(
"""
// paren follows the type, but it's part of a separate (valid) expression
let ff: X
(_1, _2) = (_2, _1)
let fff: X
Expand All @@ -86,52 +91,121 @@ final class DiagnoseInitializerAsTypedPatternTests: XCTestCase {
)
}

func testDiagnoseInitializerAsTypedPattern8() {
func testDiagnoseInitializerAsTypedPattern8a() {
AssertParse(
"""
let g1️⃣: X(x)
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern8b() {
AssertParse(
"""
let h1️⃣: X(x, y)
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern8c() {
AssertParse(
"""
let i1️⃣: X() { foo() }
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern8d() {
AssertParse(
"""
let g: X1️⃣(x)
let h: X2️⃣(x, y)
let i: X3️⃣() { foo() }
let j: X4️⃣(x) { foo() }
let k: X5️⃣(x, y) { foo() }
let j1️⃣: X(x) { foo() }
""",
diagnostics: [
// TODO: Old parser expected error on line 1: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 2: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 3: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "3️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 4: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "4️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 5: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 6 - 7 = ' ='
DiagnosticSpec(locationMarker: "5️⃣", message: "consecutive statements on a line must be separated by ';'"),
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9() {
func testDiagnoseInitializerAsTypedPattern8e() {
AssertParse(
"""
let k1️⃣: X(x, y) { foo() }
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9a() {
AssertParse(
"""
func nonTopLevel() {
let a:[X]1️⃣()
let i: X2️⃣() { foo() }
let j: X3️⃣(x) { foo() }
let k: X4️⃣(x, y) { foo() }
_ = (a, i, j, k)
let a1️⃣:[X]()
}
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9b() {
AssertParse(
"""
func nonTopLevel() {
let i1️⃣: X() { foo() }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 8 - 9 = ' = '
DiagnosticSpec(locationMarker: "1️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 3: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 8 - 9 = ' ='
DiagnosticSpec(locationMarker: "2️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 4: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 8 - 9 = ' ='
DiagnosticSpec(locationMarker: "3️⃣", message: "consecutive statements on a line must be separated by ';'"),
// TODO: Old parser expected error on line 5: unexpected initializer in pattern; did you mean to use '='?, Fix-It replacements: 8 - 9 = ' ='
DiagnosticSpec(locationMarker: "4️⃣", message: "consecutive statements on a line must be separated by ';'"),
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9c() {
AssertParse(
"""
func nonTopLevel() {
let j1️⃣: X(x) { foo() }
}
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9d() {
AssertParse(
"""
func nonTopLevel() {
let k1️⃣: X(x, y) { foo() }
}
""",
diagnostics: [
DiagnosticSpec(message: "unexpected initializer in pattern; did you mean to use '='?", fixIts: ["replace ':' by '='"]),
]
)
}

func testDiagnoseInitializerAsTypedPattern9e() {
AssertParse(
"""
func nonTopLevel() {
_ = (a, i, j, k)
}
"""
)
}

}