Skip to content

[QoI] Diagnose initializers written as typed patterns (SR-1461) #4371

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
Aug 24, 2016
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
3 changes: 3 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,9 @@ ERROR(parameter_unnamed,none,
ERROR(parameter_curry_syntax_removed,none,
"curried function declaration syntax has been removed; use a single parameter list", ())

ERROR(initializer_as_typed_pattern,none,
"unexpected initializer in pattern; did you mean to use '='?", ())

//------------------------------------------------------------------------------
// Statement parsing diagnostics
//------------------------------------------------------------------------------
Expand Down
52 changes: 50 additions & 2 deletions lib/Parse/ParsePattern.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -786,15 +786,63 @@ ParserResult<Pattern> Parser::parseTypedPattern() {
auto result = parsePattern();

// Now parse an optional type annotation.
if (consumeIf(tok::colon)) {
if (Tok.is(tok::colon)) {
SourceLoc pastEndOfPrevLoc = getEndOfPreviousLoc();
SourceLoc colonLoc = consumeToken(tok::colon);
SourceLoc startOfNextLoc = Tok.getLoc();

if (result.isNull()) // Recover by creating AnyPattern.
result = makeParserErrorResult(new (Context) AnyPattern(PreviousLoc));

ParserResult<TypeRepr> Ty = parseType();
if (Ty.hasCodeCompletion())
return makeParserCodeCompletionResult<Pattern>();
if (Ty.isNull())
if (!Ty.isNull()) {
// Attempt to diagnose initializer calls incorrectly written
// as typed patterns, such as "var x: [Int]()".
if (Tok.isFollowingLParen()) {
BacktrackingScope backtrack(*this);

// Create a local context if needed so we can parse trailing closures.
LocalContext dummyContext;
Optional<ContextChange> contextChange;
if (!CurLocalContext) {
contextChange.emplace(*this, CurDeclContext, &dummyContext);
}

SourceLoc lParenLoc, rParenLoc;
SmallVector<Expr *, 2> args;
SmallVector<Identifier, 2> argLabels;
SmallVector<SourceLoc, 2> argLabelLocs;
Expr *trailingClosure;
ParserStatus status = parseExprList(tok::l_paren, tok::r_paren,
/*isPostfix=*/true,
/*isExprBasic=*/false,
lParenLoc, args, argLabels,
argLabelLocs, rParenLoc,
trailingClosure);
if (status.isSuccess()) {
backtrack.cancelBacktrack();

// Suggest replacing ':' with '=' (ensuring proper whitespace).

bool needSpaceBefore = (pastEndOfPrevLoc == colonLoc);
bool needSpaceAfter =
SourceMgr.getByteDistance(colonLoc, startOfNextLoc) <= 1;
Copy link
Member

@rintaro rintaro Aug 25, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jtbandes
Sorry, this didn't work when a comment is involved:

let i:/* comment */Int(42)
let i =/* comment */Int(42) // As of now, we can't parse this.

How do you think about #4499?


StringRef replacement = " = ";
if (!needSpaceBefore) replacement = replacement.drop_front();
if (!needSpaceAfter) replacement = replacement.drop_back();

diagnose(lParenLoc, diag::initializer_as_typed_pattern)
.highlight({Ty.get()->getStartLoc(), rParenLoc})
.fixItReplace(colonLoc, replacement);
result.setIsParseError();
}
}
} else {
Ty = makeParserResult(new (Context) ErrorTypeRepr(PreviousLoc));
}

result = makeParserResult(result,
new (Context) TypedPattern(result.get(), Ty.get()));
Expand Down
35 changes: 35 additions & 0 deletions test/Parse/diagnose_initializer_as_typed_pattern.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// RUN: %target-parse-verify-swift

// https://bugs.swift.org/browse/SR-1461

class X {}
func foo() {}

let a:[X]() // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= = }}
let b: [X]() // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}
let c :[X]() // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{7-8== }}
let d : [X]() // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{7-8==}}

let e: X(), ee: Int // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}

var _1 = 1, _2 = 2

// paren follows the type, but it's part of a separate (valid) expression
let ff: X
(_1, _2) = (_2, _1)
let fff: X
(_1, _2) = (_2, _1)

let g: X(x) // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}
let h: X(x, y) // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}
let i: X() { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}
let j: X(x) { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}
let k: X(x, y) { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{6-7= =}}

func nonTopLevel() {
let a:[X]() // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{8-9= = }}
let i: X() { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{8-9= =}}
let j: X(x) { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{8-9= =}}
let k: X(x, y) { foo() } // expected-error{{unexpected initializer in pattern; did you mean to use '='?}} {{8-9= =}}
_ = (a, i, j, k)
}