Skip to content

Commit 3cfa4de

Browse files
committed
Auto merge of #91403 - cjgillot:inherit-async, r=oli-obk
Inherit lifetimes for async fn instead of duplicating them. The current desugaring of `async fn foo<'a>(&usize) -> &u8` is equivalent to ```rust fn foo<'a, '0>(&'0 usize) -> foo<'static, 'static>::Opaque<'a, '0, '_>; type foo<'_a, '_0>::Opaque<'a, '0, '1> = impl Future<Output = &'1 u8>; ``` following the RPIT model. Duplicating all the inherited lifetime parameters and setting the inherited version to `'static` makes lowering more complex and causes issues like #61949. This PR removes the duplication of inherited lifetimes to directly use ```rust fn foo<'a, '0>(&'0 usize) -> foo<'a, '0>::Opaque<'_>; type foo<'a, '0>::Opaque<'1> = impl Future<Output = &'1 u8>; ``` following the TAIT model. Fixes #61949
2 parents 5d8767c + 10cf626 commit 3cfa4de

34 files changed

+227
-281
lines changed

compiler/rustc_ast_lowering/src/lib.rs

+19-50
Original file line numberDiff line numberDiff line change
@@ -1659,11 +1659,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
16591659

16601660
// When we create the opaque type for this async fn, it is going to have
16611661
// to capture all the lifetimes involved in the signature (including in the
1662-
// return type). This is done by introducing lifetime parameters for:
1662+
// return type). This is done by:
16631663
//
1664-
// - all the explicitly declared lifetimes from the impl and function itself;
1665-
// - all the elided lifetimes in the fn arguments;
1666-
// - all the elided lifetimes in the return type.
1664+
// - making the opaque type inherit all lifetime parameters from its parent;
1665+
// - make all the elided lifetimes in the fn arguments into parameters;
1666+
// - manually introducing parameters on the opaque type for elided
1667+
// lifetimes in the return type.
16671668
//
16681669
// So for example in this snippet:
16691670
//
@@ -1679,44 +1680,22 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
16791680
// we would create an opaque type like:
16801681
//
16811682
// ```
1682-
// type Bar<'a, 'b, '0, '1, '2> = impl Future<Output = &'2 u32>;
1683+
// type Foo<'a>::bar<'b, '0, '1>::Bar<'2> = impl Future<Output = &'2 u32>;
16831684
// ```
16841685
//
16851686
// and we would then desugar `bar` to the equivalent of:
16861687
//
16871688
// ```rust
16881689
// impl<'a> Foo<'a> {
1689-
// fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'a, 'b, '0, '1, '_>
1690+
// fn bar<'b, '0, '1>(&'0 self, x: &'b Vec<f64>, y: &'1 str) -> Bar<'_>
16901691
// }
16911692
// ```
16921693
//
16931694
// Note that the final parameter to `Bar` is `'_`, not `'2` --
16941695
// this is because the elided lifetimes from the return type
16951696
// should be figured out using the ordinary elision rules, and
16961697
// this desugaring achieves that.
1697-
1698-
debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", self.in_scope_lifetimes);
1699-
debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", self.lifetimes_to_define);
1700-
1701-
// Calculate all the lifetimes that should be captured
1702-
// by the opaque type. This should include all in-scope
1703-
// lifetime parameters, including those defined in-band.
1704-
//
1705-
// `lifetime_params` is a vector of tuple (span, parameter name, lifetime name).
1706-
1707-
// Input lifetime like `'a` or `'1`:
1708-
let mut lifetime_params: Vec<_> = self
1709-
.in_scope_lifetimes
1710-
.iter()
1711-
.cloned()
1712-
.map(|name| (name.ident().span, name, hir::LifetimeName::Param(name)))
1713-
.chain(
1714-
self.lifetimes_to_define
1715-
.iter()
1716-
.map(|&(span, name)| (span, name, hir::LifetimeName::Param(name))),
1717-
)
1718-
.collect();
1719-
1698+
let mut lifetime_params = Vec::new();
17201699
self.with_hir_id_owner(opaque_ty_node_id, |this| {
17211700
// We have to be careful to get elision right here. The
17221701
// idea is that we create a lifetime parameter for each
@@ -1735,16 +1714,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
17351714
debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound);
17361715
debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", lifetimes_to_define);
17371716

1738-
lifetime_params.extend(
1739-
// Output lifetime like `'_`:
1740-
lifetimes_to_define
1741-
.into_iter()
1742-
.map(|(span, name)| (span, name, hir::LifetimeName::Implicit(false))),
1743-
);
1717+
// Output lifetime like `'_`:
1718+
lifetime_params = lifetimes_to_define;
17441719
debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params);
17451720

17461721
let generic_params =
1747-
this.arena.alloc_from_iter(lifetime_params.iter().map(|&(span, hir_name, _)| {
1722+
this.arena.alloc_from_iter(lifetime_params.iter().map(|&(span, hir_name)| {
17481723
this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_id)
17491724
}));
17501725

@@ -1762,28 +1737,22 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
17621737
this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
17631738
});
17641739

1765-
// As documented above on the variable
1766-
// `input_lifetimes_count`, we need to create the lifetime
1767-
// arguments to our opaque type. Continuing with our example,
1768-
// we're creating the type arguments for the return type:
1740+
// We need to create the lifetime arguments to our opaque type.
1741+
// Continuing with our example, we're creating the type arguments
1742+
// for the return type:
17691743
//
17701744
// ```
1771-
// Bar<'a, 'b, '0, '1, '_>
1745+
// For<'a>::bar<'b, '0, '1>::Bar<'_>
17721746
// ```
17731747
//
1774-
// For the "input" lifetime parameters, we wish to create
1775-
// references to the parameters themselves, including the
1776-
// "implicit" ones created from parameter types (`'a`, `'b`,
1777-
// '`0`, `'1`).
1778-
//
1779-
// For the "output" lifetime parameters, we just want to
1780-
// generate `'_`.
1748+
// For the "input" lifetime parameters are inherited automatically.
1749+
// For the "output" lifetime parameters, we just want to generate `'_`.
17811750
let generic_args =
1782-
self.arena.alloc_from_iter(lifetime_params.into_iter().map(|(span, _, name)| {
1751+
self.arena.alloc_from_iter(lifetime_params.into_iter().map(|(span, _)| {
17831752
GenericArg::Lifetime(hir::Lifetime {
17841753
hir_id: self.next_id(),
17851754
span: self.lower_span(span),
1786-
name,
1755+
name: hir::LifetimeName::Implicit(false),
17871756
})
17881757
}));
17891758

compiler/rustc_borrowck/src/region_infer/mod.rs

+18
Original file line numberDiff line numberDiff line change
@@ -2156,6 +2156,24 @@ impl<'tcx> RegionInferenceContext<'tcx> {
21562156
}
21572157
}
21582158

2159+
// When in async fn, prefer errors that come from inside the closure.
2160+
if !categorized_path[i].from_closure {
2161+
let span = categorized_path.iter().find_map(|p| {
2162+
if p.from_closure
2163+
&& p.category == categorized_path[i].category
2164+
&& categorized_path[i].cause.span.contains(p.cause.span)
2165+
{
2166+
Some(p.cause.span)
2167+
} else {
2168+
None
2169+
}
2170+
});
2171+
2172+
if let Some(span) = span {
2173+
categorized_path[i].cause.span = span;
2174+
}
2175+
}
2176+
21592177
return categorized_path[i].clone();
21602178
}
21612179

compiler/rustc_error_codes/src/error_codes/E0760.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
`async fn`/`impl trait` return type cannot contain a projection
1+
`impl trait` return type cannot contain a projection
22
or `Self` that references lifetimes from a parent scope.
33

44
Erroneous code example:
@@ -7,7 +7,7 @@ Erroneous code example:
77
struct S<'a>(&'a i32);
88
99
impl<'a> S<'a> {
10-
async fn new(i: &'a i32) -> Self {
10+
fn new(i: &'a i32) -> impl Into<Self> {
1111
S(&22)
1212
}
1313
}
@@ -19,7 +19,7 @@ To fix this error we need to spell out `Self` to `S<'a>`:
1919
struct S<'a>(&'a i32);
2020
2121
impl<'a> S<'a> {
22-
async fn new(i: &'a i32) -> S<'a> {
22+
fn new(i: &'a i32) -> impl Into<S<'a>> {
2323
S(&22)
2424
}
2525
}

compiler/rustc_infer/src/infer/opaque_types.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
276276
debug!(?concrete_ty);
277277

278278
let first_own_region = match opaque_defn.origin {
279-
hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {
279+
hir::OpaqueTyOrigin::FnReturn(..) => {
280280
// We lower
281281
//
282282
// fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
@@ -291,7 +291,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
291291
}
292292
// These opaque type inherit all lifetime parameters from their
293293
// parent, so we have to check them all.
294-
hir::OpaqueTyOrigin::TyAlias => 0,
294+
hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::TyAlias => 0,
295295
};
296296

297297
// For a case like `impl Foo<'a, 'b>`, we would generate a constraint

compiler/rustc_resolve/src/late/lifetimes.rs

+26-8
Original file line numberDiff line numberDiff line change
@@ -729,9 +729,16 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
729729
match item.kind {
730730
hir::ItemKind::Fn(ref sig, ref generics, _) => {
731731
self.missing_named_lifetime_spots.push(generics.into());
732-
self.visit_early_late(None, item.hir_id(), &sig.decl, generics, |this| {
733-
intravisit::walk_item(this, item);
734-
});
732+
self.visit_early_late(
733+
None,
734+
item.hir_id(),
735+
&sig.decl,
736+
generics,
737+
sig.header.asyncness,
738+
|this| {
739+
intravisit::walk_item(this, item);
740+
},
741+
);
735742
self.missing_named_lifetime_spots.pop();
736743
}
737744

@@ -849,11 +856,16 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
849856

850857
fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
851858
match item.kind {
852-
hir::ForeignItemKind::Fn(ref decl, _, ref generics) => {
853-
self.visit_early_late(None, item.hir_id(), decl, generics, |this| {
859+
hir::ForeignItemKind::Fn(ref decl, _, ref generics) => self.visit_early_late(
860+
None,
861+
item.hir_id(),
862+
decl,
863+
generics,
864+
hir::IsAsync::NotAsync,
865+
|this| {
854866
intravisit::walk_foreign_item(this, item);
855-
})
856-
}
867+
},
868+
),
857869
hir::ForeignItemKind::Static(..) => {
858870
intravisit::walk_foreign_item(self, item);
859871
}
@@ -1130,6 +1142,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
11301142
trait_item.hir_id(),
11311143
&sig.decl,
11321144
&trait_item.generics,
1145+
sig.header.asyncness,
11331146
|this| intravisit::walk_trait_item(this, trait_item),
11341147
);
11351148
self.missing_named_lifetime_spots.pop();
@@ -1199,6 +1212,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
11991212
impl_item.hir_id(),
12001213
&sig.decl,
12011214
&impl_item.generics,
1215+
sig.header.asyncness,
12021216
|this| intravisit::walk_impl_item(this, impl_item),
12031217
);
12041218
self.missing_named_lifetime_spots.pop();
@@ -2159,11 +2173,15 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
21592173
hir_id: hir::HirId,
21602174
decl: &'tcx hir::FnDecl<'tcx>,
21612175
generics: &'tcx hir::Generics<'tcx>,
2176+
asyncness: hir::IsAsync,
21622177
walk: F,
21632178
) where
21642179
F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>),
21652180
{
2166-
insert_late_bound_lifetimes(self.map, decl, generics);
2181+
// Async fns need all their lifetime parameters to be early bound.
2182+
if asyncness != hir::IsAsync::Async {
2183+
insert_late_bound_lifetimes(self.map, decl, generics);
2184+
}
21672185

21682186
// Find the start of nested early scopes, e.g., in methods.
21692187
let mut next_early_index = 0;

compiler/rustc_typeck/src/astconv/mod.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -2408,16 +2408,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
24082408
let def_id = item_id.def_id.to_def_id();
24092409

24102410
match opaque_ty.kind {
2411-
hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => self
2412-
.impl_trait_ty_to_ty(
2413-
def_id,
2414-
lifetimes,
2415-
matches!(
2416-
origin,
2417-
hir::OpaqueTyOrigin::FnReturn(..)
2418-
| hir::OpaqueTyOrigin::AsyncFn(..)
2419-
),
2420-
),
2411+
hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2412+
let replace_parent_lifetimes =
2413+
matches!(origin, hir::OpaqueTyOrigin::FnReturn(..));
2414+
self.impl_trait_ty_to_ty(def_id, lifetimes, replace_parent_lifetimes)
2415+
}
24212416
ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
24222417
}
24232418
}

compiler/rustc_typeck/src/check/check.rs

+3-12
Original file line numberDiff line numberDiff line change
@@ -535,10 +535,8 @@ pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
535535
}
536536
}
537537

538-
if let ItemKind::OpaqueTy(hir::OpaqueTy {
539-
origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
540-
..
541-
}) = item.kind
538+
if let ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(..), .. }) =
539+
item.kind
542540
{
543541
let mut visitor = ProhibitOpaqueVisitor {
544542
opaque_identity_ty: tcx.mk_opaque(
@@ -560,20 +558,13 @@ pub(super) fn check_opaque_for_inheriting_lifetimes<'tcx>(
560558

561559
if let Some(ty) = prohibit_opaque.break_value() {
562560
visitor.visit_item(&item);
563-
let is_async = match item.kind {
564-
ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
565-
matches!(origin, hir::OpaqueTyOrigin::AsyncFn(..))
566-
}
567-
_ => unreachable!(),
568-
};
569561

570562
let mut err = struct_span_err!(
571563
tcx.sess,
572564
span,
573565
E0760,
574-
"`{}` return type cannot contain a projection or `Self` that references lifetimes from \
566+
"`impl Trait` return type cannot contain a projection or `Self` that references lifetimes from \
575567
a parent scope",
576-
if is_async { "async fn" } else { "impl Trait" },
577568
);
578569

579570
for (span, name) in visitor.selftys {

compiler/rustc_typeck/src/collect.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -2162,8 +2162,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP
21622162
generics
21632163
}
21642164
ItemKind::OpaqueTy(OpaqueTy {
2165-
origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::FnReturn(..),
2166-
..
2165+
origin: hir::OpaqueTyOrigin::FnReturn(..), ..
21672166
}) => {
21682167
// return-position impl trait
21692168
//
@@ -2183,7 +2182,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericP
21832182
}
21842183
ItemKind::OpaqueTy(OpaqueTy {
21852184
ref generics,
2186-
origin: hir::OpaqueTyOrigin::TyAlias,
2185+
origin: hir::OpaqueTyOrigin::AsyncFn(..) | hir::OpaqueTyOrigin::TyAlias,
21872186
..
21882187
}) => {
21892188
// type-alias impl trait

src/librustdoc/clean/mod.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,12 @@ fn clean_ty_generics(
585585
.params
586586
.iter()
587587
.filter_map(|param| match param.kind {
588-
ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
588+
ty::GenericParamDefKind::Lifetime => {
589+
if param.name == kw::UnderscoreLifetime {
590+
return None;
591+
}
592+
Some(param.clean(cx))
593+
}
589594
ty::GenericParamDefKind::Type { synthetic, .. } => {
590595
if param.name == kw::SelfUpper {
591596
assert_eq!(param.index, 0);

src/test/ui/async-await/issue-61949-self-return-type.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ pub struct Foo<'a> {
88

99
impl<'a> Foo<'a> {
1010
pub async fn new(_bar: &'a i32) -> Self {
11-
//~^ ERROR `async fn` return type cannot contain a projection or `Self` that references lifetimes from a parent scope
1211
Foo {
1312
bar: &22
1413
}
@@ -19,6 +18,7 @@ async fn foo() {
1918
let x = {
2019
let bar = 22;
2120
Foo::new(&bar).await
21+
//~^ ERROR `bar` does not live long enough [E0597]
2222
};
2323
drop(x);
2424
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1-
error[E0760]: `async fn` return type cannot contain a projection or `Self` that references lifetimes from a parent scope
2-
--> $DIR/issue-61949-self-return-type.rs:10:40
1+
error[E0597]: `bar` does not live long enough
2+
--> $DIR/issue-61949-self-return-type.rs:20:18
33
|
4-
LL | pub async fn new(_bar: &'a i32) -> Self {
5-
| ^^^^ help: consider spelling out the type instead: `Foo<'a>`
4+
LL | let x = {
5+
| - borrow later stored here
6+
LL | let bar = 22;
7+
LL | Foo::new(&bar).await
8+
| ^^^^ borrowed value does not live long enough
9+
LL |
10+
LL | };
11+
| - `bar` dropped here while still borrowed
612

713
error: aborting due to previous error
814

9-
For more information about this error, try `rustc --explain E0760`.
15+
For more information about this error, try `rustc --explain E0597`.

0 commit comments

Comments
 (0)