Skip to content

[CSSimplify] Increase fix impact when passing closure to a non-function type parameter #37373

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 3 commits into from
May 12, 2021
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/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,9 @@ FIXIT(insert_closure_return_type_placeholder,
"%select{| () }0-> <#Result#> %select{|in }0",
(bool))

NOTE(use_of_anon_closure_param,none,
"anonymous closure parameter %0 is used here", (Identifier))

ERROR(incorrect_explicit_closure_result,none,
"declared closure result %0 is incompatible with contextual type %1",
(Type, Type))
Expand Down
57 changes: 53 additions & 4 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4984,20 +4984,69 @@ bool ExtraneousArgumentsFailure::diagnoseAsError() {
params->getStartLoc(), diag::closure_argument_list_tuple, fnType,
fnType->getNumParams(), params->size(), (params->size() == 1));

bool onlyAnonymousParams =
// Unsed parameter is represented by `_` before `in`.
bool onlyUnusedParams =
std::all_of(params->begin(), params->end(),
[](ParamDecl *param) { return !param->hasName(); });

// If closure expects no parameters but N was given,
// and all of them are anonymous let's suggest removing them.
if (fnType->getNumParams() == 0 && onlyAnonymousParams) {
// and all of them are unused, let's suggest removing them.
if (fnType->getNumParams() == 0 && onlyUnusedParams) {
auto inLoc = closure->getInLoc();
auto &sourceMgr = getASTContext().SourceMgr;

if (inLoc.isValid())
if (inLoc.isValid()) {
diag.fixItRemoveChars(params->getStartLoc(),
Lexer::getLocForEndOfToken(sourceMgr, inLoc));
return true;
}
}

diag.flush();

// If all of the parameters are anonymous, let's point out references
// to make it explicit where parameters are used in complex closure body,
// which helps in situations where braces are missing for potential inner
// closures e.g.
//
// func a(_: () -> Void) {}
// func b(_: (Int) -> Void) {}
//
// a {
// ...
// b($0.member)
// }
//
// Here `$0` is associated with `a` since braces around `member` reference
// are missing.
if (!closure->hasSingleExpressionBody() &&
llvm::all_of(params->getArray(),
[](ParamDecl *P) { return P->isAnonClosureParam(); })) {
if (auto *body = closure->getBody()) {
struct ParamRefFinder : public ASTWalker {
DiagnosticEngine &D;
ParameterList *Params;

ParamRefFinder(DiagnosticEngine &diags, ParameterList *params)
: D(diags), Params(params) {}

std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
if (llvm::is_contained(Params->getArray(), DRE->getDecl())) {
auto *P = cast<ParamDecl>(DRE->getDecl());
D.diagnose(DRE->getLoc(), diag::use_of_anon_closure_param,
P->getName());
}
}
return {true, E};
}
};

ParamRefFinder finder(getASTContext().Diags, params);
body->walk(finder);
}
}

return true;
}

Expand Down
10 changes: 10 additions & 0 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11393,6 +11393,16 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
}))
impact += 3;

// Passing a closure to a parameter that doesn't expect one should
// be scored lower because there might be an overload that expects
// a closure but has other issues e.g. wrong number of parameters.
if (!type2->lookThroughAllOptionalTypes()->is<FunctionType>()) {
auto argument = simplifyLocatorToAnchor(fix->getLocator());
if (isExpr<ClosureExpr>(argument)) {
impact += 2;
}
}

return recordFix(fix, impact) ? SolutionKind::Error : SolutionKind::Solved;
}

Expand Down
18 changes: 18 additions & 0 deletions test/Constraints/closures.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1114,3 +1114,21 @@ func rdar77022842(argA: Bool? = nil, argB: Bool? = nil) {
// expected-error@-3 {{expected expression in conditional}}
} // expected-error {{expected '{' after 'if' condition}}
}

// rdar://76058892 - spurious ambiguity diagnostic
func rdar76058892() {
struct S {
var test: Int = 0
}

func test(_: Int) {}
func test(_: () -> String) {}

func experiment(arr: [S]?) {
test { // expected-error {{contextual closure type '() -> String' expects 0 arguments, but 1 was used in closure body}}
if let arr = arr {
arr.map($0.test) // expected-note {{anonymous closure parameter '$0' is used here}}
}
}
}
}