Skip to content

Commit 2c3fd1a

Browse files
committed
Suggest pin!() instead of Pin::new() when appropriate
When encountering a type that needs to be pinned but that is `!Unpin`, suggest using the `pin!()` macro. Fix rust-lang#57994.
1 parent 3071e0a commit 2c3fd1a

File tree

5 files changed

+85
-15
lines changed

5 files changed

+85
-15
lines changed

compiler/rustc_hir_typeck/src/method/suggest.rs

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2495,10 +2495,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
24952495
// Try alternative arbitrary self types that could fulfill this call.
24962496
// FIXME: probe for all types that *could* be arbitrary self-types, not
24972497
// just this list.
2498-
for (rcvr_ty, post) in &[
2499-
(rcvr_ty, ""),
2500-
(Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty), "&mut "),
2501-
(Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty), "&"),
2498+
for (rcvr_ty, post, pin_call) in &[
2499+
(rcvr_ty, "", ""),
2500+
(
2501+
Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty),
2502+
"&mut ",
2503+
"as_mut",
2504+
),
2505+
(Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rcvr_ty), "&", "as_ref"),
25022506
] {
25032507
match self.lookup_probe_for_diagnostic(
25042508
item_name,
@@ -2532,6 +2536,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25322536
Err(_) => (),
25332537
}
25342538

2539+
let pred = ty::TraitRef::new(
2540+
self.tcx,
2541+
self.tcx.lang_items().unpin_trait().unwrap(),
2542+
[*rcvr_ty],
2543+
);
2544+
let unpin = self.predicate_must_hold_considering_regions(&Obligation::new(
2545+
self.tcx,
2546+
ObligationCause::misc(rcvr.span, self.body_id),
2547+
self.param_env,
2548+
pred,
2549+
));
25352550
for (rcvr_ty, pre) in &[
25362551
(Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::OwnedBox), "Box::new"),
25372552
(Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin), "Pin::new"),
@@ -2555,7 +2570,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25552570
// Explicitly ignore the `Pin::as_ref()` method as `Pin` does not
25562571
// implement the `AsRef` trait.
25572572
let skip = skippable.contains(&did)
2558-
|| (("Pin::new" == *pre) && (sym::as_ref == item_name.name))
2573+
|| (("Pin::new" == *pre) && ((sym::as_ref == item_name.name) || !unpin))
25592574
|| inputs_len.is_some_and(|inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() != inputs_len);
25602575
// Make sure the method is defined for the *actual* receiver: we don't
25612576
// want to treat `Box<Self>` as a receiver if it only works because of
@@ -2567,7 +2582,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25672582
);
25682583
err.multipart_suggestion(
25692584
"consider wrapping the receiver expression with the \
2570-
appropriate type",
2585+
appropriate type",
25712586
vec![
25722587
(rcvr.span.shrink_to_lo(), format!("{pre}({post}")),
25732588
(rcvr.span.shrink_to_hi(), ")".to_string()),
@@ -2579,6 +2594,39 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25792594
}
25802595
}
25812596
}
2597+
// We special case the situation where `Pin::new` wouldn't work, and isntead
2598+
// suggest using the `pin!()` macro instead.
2599+
if let Some(new_rcvr_t) = Ty::new_lang_item(self.tcx, *rcvr_ty, LangItem::Pin)
2600+
&& !alt_rcvr_sugg
2601+
&& !unpin
2602+
&& sym::as_ref != item_name.name
2603+
&& *pin_call != ""
2604+
&& let Ok(pick) = self.lookup_probe_for_diagnostic(
2605+
item_name,
2606+
new_rcvr_t,
2607+
rcvr,
2608+
ProbeScope::AllTraits,
2609+
return_type,
2610+
)
2611+
&& !skippable.contains(&Some(pick.item.container_id(self.tcx)))
2612+
&& pick.autoderefs == 0
2613+
&& inputs_len.is_some_and(|inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() == inputs_len)
2614+
{
2615+
let indent = self.tcx.sess
2616+
.source_map()
2617+
.indentation_before(rcvr.span)
2618+
.unwrap_or_else(|| " ".to_string());
2619+
err.multipart_suggestion(
2620+
"consider pinning the expression",
2621+
vec![
2622+
(rcvr.span.shrink_to_lo(), format!("let mut pinned = std::pin::pin!(")),
2623+
(rcvr.span.shrink_to_hi(), format!(");\n{indent}pinned.{pin_call}()")),
2624+
],
2625+
Applicability::MaybeIncorrect,
2626+
);
2627+
// We don't care about the other suggestions.
2628+
alt_rcvr_sugg = true;
2629+
}
25822630
}
25832631
}
25842632
if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// edition: 2021
2+
// run-rustfix
3+
#![allow(unused_must_use, dead_code)]
4+
5+
use std::future::Future;
6+
fn foo() -> impl Future<Output=()> {
7+
async { }
8+
}
9+
10+
fn bar(cx: &mut std::task::Context<'_>) {
11+
let fut = foo();
12+
let mut pinned = std::pin::pin!(fut);
13+
pinned.as_mut().poll(cx);
14+
//~^ ERROR no method named `poll` found for opaque type `impl Future<Output = ()>` in the current scope [E0599]
15+
}
16+
fn main() {}

tests/ui/async-await/issue-108572.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
// edition: 2021
2+
// run-rustfix
3+
#![allow(unused_must_use, dead_code)]
24

35
use std::future::Future;
46
fn foo() -> impl Future<Output=()> {
57
async { }
68
}
79

8-
fn main() {
10+
fn bar(cx: &mut std::task::Context<'_>) {
911
let fut = foo();
10-
fut.poll();
12+
fut.poll(cx);
1113
//~^ ERROR no method named `poll` found for opaque type `impl Future<Output = ()>` in the current scope [E0599]
1214
}
15+
fn main() {}

tests/ui/async-await/issue-108572.stderr

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
error[E0599]: no method named `poll` found for opaque type `impl Future<Output = ()>` in the current scope
2-
--> $DIR/issue-108572.rs:10:9
2+
--> $DIR/issue-108572.rs:12:9
33
|
4-
LL | fut.poll();
4+
LL | fut.poll(cx);
55
| ^^^^ method not found in `impl Future<Output = ()>`
66
|
77
= help: method `poll` found on `Pin<&mut impl Future<Output = ()>>`, see documentation for `std::pin::Pin`
88
= help: self type must be pinned to call `Future::poll`, see https://rust-lang.github.io/async-book/04_pinning/01_chapter.html#pinning-in-practice
9+
help: consider pinning the expression
10+
|
11+
LL ~ let mut pinned = std::pin::pin!(fut);
12+
LL ~ pinned.as_mut().poll(cx);
13+
|
914

1015
error: aborting due to previous error
1116

tests/ui/async-await/pin-needed-to-poll.stderr

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,12 @@ LL | struct Sleep;
66
...
77
LL | self.sleep.poll(cx)
88
| ^^^^ method not found in `Sleep`
9-
--> $SRC_DIR/core/src/future/future.rs:LL:COL
109
|
11-
= note: the method is available for `Pin<&mut Sleep>` here
10+
help: consider pinning the expression
1211
|
13-
help: consider wrapping the receiver expression with the appropriate type
12+
LL ~ let mut pinned = std::pin::pin!(self.sleep);
13+
LL ~ pinned.as_mut().poll(cx)
1414
|
15-
LL | Pin::new(&mut self.sleep).poll(cx)
16-
| +++++++++++++ +
1715

1816
error: aborting due to previous error
1917

0 commit comments

Comments
 (0)