Skip to content

Commit a5bc8d4

Browse files
committed
Fix wrong suggestion for returning async closure
1 parent 6d8bc65 commit a5bc8d4

File tree

7 files changed

+161
-30
lines changed

7 files changed

+161
-30
lines changed

compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs

Lines changed: 70 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -805,17 +805,25 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
805805
&& let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
806806
&& inputs.is_empty()
807807
&& self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
808+
&& let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
809+
&& let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) =
810+
self.tcx.hir_node(*arg_hir_id)
808811
&& let Some(hir::Node::Expr(hir::Expr {
809-
kind:
810-
hir::ExprKind::Closure(hir::Closure {
811-
kind: hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async),
812-
fn_arg_span: Some(arg_span),
813-
..
814-
}),
815-
..
812+
kind: hir::ExprKind::Closure(closure), ..
816813
})) = self.tcx.hir_get_if_local(def_id)
817-
&& obligation.cause.span.contains(*arg_span)
814+
&& let hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async) = closure.kind
815+
&& let Some(arg_span) = closure.fn_arg_span
816+
&& obligation.cause.span.contains(arg_span)
818817
{
818+
let mut body = self.tcx.hir_body(closure.body).value;
819+
let peeled = body.peel_blocks().peel_drop_temps();
820+
if let hir::ExprKind::Closure(inner) = peeled.kind {
821+
body = self.tcx.hir_body(inner.body).value;
822+
}
823+
if !matches!(body.peel_blocks().peel_drop_temps().kind, hir::ExprKind::Block(..)) {
824+
return false;
825+
}
826+
819827
let sm = self.tcx.sess.source_map();
820828
let removal_span = if let Ok(snippet) =
821829
sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
@@ -824,7 +832,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
824832
// There's a space after `||`, include it in the removal
825833
arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
826834
} else {
827-
*arg_span
835+
arg_span
828836
};
829837
err.span_suggestion_verbose(
830838
removal_span,
@@ -864,23 +872,63 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
864872
.collect::<Vec<_>>()
865873
.join(", ");
866874

867-
if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
875+
if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
868876
&& obligation.cause.span.can_be_used_for_suggestions()
869877
{
870-
let (span, sugg) = if let Some(snippet) =
871-
self.tcx.sess.source_map().span_to_snippet(obligation.cause.span).ok()
872-
&& snippet.starts_with("|")
873-
{
874-
(obligation.cause.span, format!("({snippet})({args})"))
875-
} else {
876-
(obligation.cause.span.shrink_to_hi(), format!("({args})"))
878+
let span = obligation.cause.span;
879+
880+
let arg_expr = match self.tcx.hir_node(*arg_hir_id) {
881+
hir::Node::Expr(expr) => Some(expr),
882+
_ => None,
877883
};
878884

879-
// When the obligation error has been ensured to have been caused by
880-
// an argument, the `obligation.cause.span` points at the expression
881-
// of the argument, so we can provide a suggestion. Otherwise, we give
882-
// a more general note.
883-
err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
885+
let is_closure_expr =
886+
arg_expr.is_some_and(|expr| matches!(expr.kind, hir::ExprKind::Closure(..)));
887+
888+
// If the user wrote `|| {}()`, suggesting to call the closure would produce `(|| {}())()`,
889+
// which doesn't help and is often outright wrong.
890+
if args.is_empty()
891+
&& let Some(expr) = arg_expr
892+
&& let hir::ExprKind::Closure(closure) = expr.kind
893+
{
894+
let mut body = self.tcx.hir_body(closure.body).value;
895+
896+
// Async closures desugar to a closure returning a coroutine
897+
if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
898+
closure.kind
899+
{
900+
let peeled = body.peel_blocks().peel_drop_temps();
901+
if let hir::ExprKind::Closure(inner) = peeled.kind {
902+
body = self.tcx.hir_body(inner.body).value;
903+
}
904+
}
905+
906+
let peeled_body = body.peel_blocks().peel_drop_temps();
907+
if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
908+
&& call_args.is_empty()
909+
&& let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
910+
{
911+
return false;
912+
}
913+
}
914+
915+
if is_closure_expr {
916+
err.multipart_suggestions(
917+
msg,
918+
vec![vec![
919+
(span.shrink_to_lo(), "(".to_string()),
920+
(span.shrink_to_hi(), format!(")({args})")),
921+
]],
922+
Applicability::HasPlaceholders,
923+
);
924+
} else {
925+
err.span_suggestion_verbose(
926+
span.shrink_to_hi(),
927+
msg,
928+
format!("({args})"),
929+
Applicability::HasPlaceholders,
930+
);
931+
}
884932
} else if let DefIdOrName::DefId(def_id) = def_id_or_name {
885933
let name = match self.tcx.hir_get_if_local(def_id) {
886934
Some(hir::Node::Expr(hir::Expr {

tests/ui/async-await/async-closures/suggest-async-block-issue-140265.stderr

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,11 @@ LL | fn takes_future(_fut: impl Future<Output = ()>) {}
6666
| ^^^^^^^^^^^^^^^^^^^ required by this bound in `takes_future`
6767
help: use parentheses to call this closure
6868
|
69-
LL | }(/* i32 */));
70-
| +++++++++++
69+
LL ~ takes_future((async |x: i32| {
70+
LL |
71+
LL | println!("{x}");
72+
LL ~ })(/* i32 */));
73+
|
7174

7275
error: aborting due to 3 previous errors
7376

tests/ui/const-generics/adt_const_params/const_param_ty_bad.stderr

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@ LL | fn check(_: impl std::marker::ConstParamTy_) {}
3232
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `check`
3333
help: use parentheses to call this closure
3434
|
35-
LL - check(|| {});
36-
LL + check((|| {})());
37-
|
35+
LL | check((|| {})());
36+
| + +++
3837

3938
error[E0277]: `fn()` can't be used as a const parameter type
4039
--> $DIR/const_param_ty_bad.rs:9:11
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Regression test for #150701
2+
3+
//@ run-rustfix
4+
//@ edition: 2024
5+
6+
use std::future::Future;
7+
8+
fn f(_c: impl Future<Output = ()>) {}
9+
10+
fn main() {
11+
f((async || {})()); //~ ERROR: expected function, found `()`
12+
//~^ ERROR: is not a future
13+
f(async {});
14+
//~^ ERROR: is not a future
15+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Regression test for #150701
2+
3+
//@ run-rustfix
4+
//@ edition: 2024
5+
6+
use std::future::Future;
7+
8+
fn f(_c: impl Future<Output = ()>) {}
9+
10+
fn main() {
11+
f(async || {}()); //~ ERROR: expected function, found `()`
12+
//~^ ERROR: is not a future
13+
f(async || {});
14+
//~^ ERROR: is not a future
15+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
error[E0618]: expected function, found `()`
2+
--> $DIR/suggest-create-closure-issue-150701.rs:11:16
3+
|
4+
LL | f(async || {}());
5+
| ^^--
6+
| |
7+
| call expression requires function
8+
|
9+
help: if you meant to create this closure and immediately call it, surround the closure with parentheses
10+
|
11+
LL | f((async || {})());
12+
| + +
13+
14+
error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future
15+
--> $DIR/suggest-create-closure-issue-150701.rs:11:7
16+
|
17+
LL | f(async || {}());
18+
| - ^^^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future
19+
| |
20+
| required by a bound introduced by this call
21+
|
22+
= help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}`
23+
note: required by a bound in `f`
24+
--> $DIR/suggest-create-closure-issue-150701.rs:8:15
25+
|
26+
LL | fn f(_c: impl Future<Output = ()>) {}
27+
| ^^^^^^^^^^^^^^^^^^^ required by this bound in `f`
28+
29+
error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future
30+
--> $DIR/suggest-create-closure-issue-150701.rs:13:7
31+
|
32+
LL | f(async || {});
33+
| - ^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future
34+
| |
35+
| required by a bound introduced by this call
36+
|
37+
= help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}`
38+
note: required by a bound in `f`
39+
--> $DIR/suggest-create-closure-issue-150701.rs:8:15
40+
|
41+
LL | fn f(_c: impl Future<Output = ()>) {}
42+
| ^^^^^^^^^^^^^^^^^^^ required by this bound in `f`
43+
help: use `async {}` instead of `async || {}` to introduce an async block
44+
|
45+
LL - f(async || {});
46+
LL + f(async {});
47+
|
48+
49+
error: aborting due to 3 previous errors
50+
51+
Some errors have detailed explanations: E0277, E0618.
52+
For more information about an error, try `rustc --explain E0277`.

tests/ui/suggestions/use-parentheses-to-call-closure-issue-145404.stderr

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@ LL | fn call(&self, _: impl Display) {}
1414
| ^^^^^^^ required by this bound in `S::call`
1515
help: use parentheses to call this closure
1616
|
17-
LL - S.call(|| "hello");
18-
LL + S.call((|| "hello")());
19-
|
17+
LL | S.call((|| "hello")());
18+
| + +++
2019

2120
error: aborting due to 1 previous error
2221

0 commit comments

Comments
 (0)