Skip to content

Commit 81781bc

Browse files
authored
Rollup merge of #163115 - estebank:static-obligations-in-call, r=davidtwco
Point at `'static` obligations from an fn being called Add this note to lifetime errors: ```text error[E0521]: borrowed data escapes outside of function --> $DIR/static-impl-obligation.rs:163:9 | LL | fn bar<'a>(x: &'a &'a u32) { | -- - `x` is only valid in the function body | | | lifetime `'a` defined here LL | let y: &dyn Foo = x; LL | y.hello(); | ^^^^^^^^^ | | | `x` escapes the function body here | argument requires that `'a` must outlive `'static` | note: `'static` lifetime requirement from `<(dyn o::Foo + 'static)>::hello` introduced here --> $DIR/static-impl-obligation.rs:158:20 | LL | impl dyn Foo + 'static where Self: 'static { | ^^^^^^^ ^^^^^^^ lifetime requirement introduced here | | | lifetime requirement introduced here LL | fn hello(&'static self) where Self: 'static {} | ^^^^^^^^^^^^^ ^^^^^^^ lifetime requirement introduced here | | | lifetime requirement introduced here ``` Follow up to #121274, taking only a subset of that unmerged PR's functionality.
2 parents ea4ccf9 + a91d256 commit 81781bc

17 files changed

Lines changed: 1203 additions & 2 deletions

‎compiler/rustc_borrowck/src/diagnostics/region_errors.rs‎

Lines changed: 165 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
//! Error reporting machinery for lifetime errors.
22
3-
use rustc_data_structures::fx::FxIndexSet;
3+
use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
44
use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, msg};
55
use rustc_hir as hir;
66
use rustc_hir::GenericBound::Trait;
77
use rustc_hir::QPath::Resolved;
88
use rustc_hir::WherePredicateKind::BoundPredicate;
9+
use rustc_hir::def::DefKind;
910
use rustc_hir::def::Res::Def;
1011
use rustc_hir::def_id::DefId;
1112
use rustc_hir::intravisit::Visitor;
@@ -391,6 +392,165 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
391392
outlives_suggestion.add_suggestion(self);
392393
}
393394

395+
/// Point at `'static` obligations from the item being called.
396+
///
397+
/// ```text
398+
/// error[E0521]: borrowed data escapes outside of function
399+
/// --> $DIR/static-impl-obligation.rs:163:9
400+
/// |
401+
/// LL | fn bar<'a>(x: &'a &'a u32) {
402+
/// | -- - `x` is only valid in the function body
403+
/// | |
404+
/// | lifetime `'a` defined here
405+
/// LL | let y: &dyn Foo = x;
406+
/// LL | y.hello();
407+
/// | ^^^^^^^^^
408+
/// | |
409+
/// | `x` escapes the function body here
410+
/// | argument requires that `'a` must outlive `'static`
411+
/// |
412+
/// note: `'static` lifetime requirement from `<(dyn o::Foo + 'static)>::hello` introduced here
413+
/// --> $DIR/static-impl-obligation.rs:158:20
414+
/// |
415+
/// LL | impl dyn Foo + 'static where Self: 'static {
416+
/// | ^^^^^^^ ^^^^^^^ lifetime requirement introduced here
417+
/// | |
418+
/// | lifetime requirement introduced here
419+
/// LL | fn hello(&'static self) where Self: 'static {}
420+
/// | ^^^^^^^^^^^^^ ^^^^^^^ lifetime requirement introduced here
421+
/// | |
422+
/// | lifetime requirement introduced here
423+
/// ```
424+
fn explain_impl_static_obligation(
425+
&self,
426+
diag: &mut Diag<'_>,
427+
ty: Ty<'tcx>,
428+
outlived_fr: RegionVid,
429+
) {
430+
let tcx = self.infcx.tcx;
431+
if self.regioncx.to_error_region(outlived_fr) != Some(tcx.lifetimes.re_static) {
432+
return;
433+
}
434+
let ty::FnDef(def_id, args) = ty.kind() else {
435+
return;
436+
};
437+
let typing_env = self.infcx.typing_env(self.infcx.param_env);
438+
let Ok(Some(instance)) = ty::Instance::try_resolve(
439+
tcx,
440+
typing_env,
441+
*def_id,
442+
self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
443+
) else {
444+
return;
445+
};
446+
let def_id = instance.def_id();
447+
let mut bounds =
448+
tcx.clauses_of(def_id)
449+
.instantiate(tcx, instance.args)
450+
.into_iter()
451+
.map(|(c, sp)| (c.skip_norm_wip().as_predicate(), sp))
452+
.filter(|(pred, _)| match pred.kind().skip_binder() {
453+
ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
454+
ty::OutlivesClause(_, lt),
455+
))
456+
| ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
457+
ty::OutlivesClause(_, lt),
458+
)) if lt.is_static() => true,
459+
_ => false,
460+
})
461+
.map(|(_, sp)| sp)
462+
.collect::<Vec<Span>>();
463+
464+
let mut labels = FxHashMap::default();
465+
466+
let parent = tcx.parent(def_id);
467+
if let Some(rcvr) =
468+
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
469+
{
470+
// Look at the receiver for `&'static self`, which introduces a `'static` obligation.
471+
// ```
472+
// impl Foo {
473+
// fn foo(&'static self) {}
474+
// ^^^^^^^^^^^^^
475+
// ```
476+
if let ty::Ref(region, _, _) = rcvr.kind()
477+
&& *region == tcx.lifetimes.re_static
478+
&& let Some(assoc) = tcx.opt_associated_item(def_id)
479+
&& assoc.is_method()
480+
{
481+
let def_span = tcx.def_span(def_id);
482+
// We have a `&'static self` receiver.
483+
if let Some(def_id) = def_id.as_local()
484+
&& let owner = tcx.expect_hir_owner_node(def_id)
485+
&& let Some(decl) = owner.fn_decl()
486+
&& let Some(ty) = decl.inputs.get(0)
487+
{
488+
// Point at the `&'static self` receiver.
489+
bounds.push(ty.span);
490+
} else if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
491+
// The method is not defined on the local crate, point at the signature instead of
492+
// just the receiver as an approximation. We don't add it if there are already
493+
// other spans with overlap with the def `Span`, as the other will be more specific.
494+
bounds.push(def_span)
495+
}
496+
}
497+
498+
if let DefKind::Impl { .. } = tcx.def_kind(parent)
499+
&& let ty = tcx.type_of(parent).instantiate_identity().skip_norm_wip()
500+
&& let ty::Dynamic(_, region) = ty.kind()
501+
&& *region == tcx.lifetimes.re_static
502+
{
503+
// We have a call into a method of either `impl dyn Trait {}` or
504+
// `impl dyn Trait + 'static {}`.
505+
if let Some(def_id) = parent.as_local()
506+
&& let hir::OwnerNode::Item(item) = tcx.expect_hir_owner_node(def_id)
507+
&& let hir::ItemKind::Impl(impl_) = item.kind
508+
&& let hir::TyKind::TraitObject(_, tagged_ref) = impl_.self_ty.kind
509+
{
510+
if tagged_ref.is_static() {
511+
// impl dyn Trait + 'static {
512+
// ^^^^^^^ lifetime requirement introduced here
513+
bounds.push(tagged_ref.pointer().ident.span);
514+
} else if tagged_ref.is_implicit() {
515+
// impl dyn Trait {
516+
// ^^^^^^^^^ `dyn Trait` introduces an...
517+
bounds.push(impl_.self_ty.span);
518+
labels.insert(
519+
impl_.self_ty.span,
520+
"`dyn Trait` introduces an implicit `'static` lifetime requirement",
521+
);
522+
}
523+
} else {
524+
// Non-local `impl`, we don't have a way to differentiate between `+ 'static`
525+
// and bare `dyn Trait`. We point at the whole def `Span` for now.
526+
let def_span = tcx.def_span(parent);
527+
if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
528+
bounds.push(def_span);
529+
}
530+
}
531+
}
532+
}
533+
534+
if !bounds.is_empty() {
535+
let mut multispan: MultiSpan = bounds.clone().into();
536+
for span in bounds {
537+
let label = labels.get(&span).unwrap_or(&"lifetime requirement introduced here");
538+
multispan.push_span_label(span, *label);
539+
}
540+
multispan.push_span_context(tcx.def_span(def_id).shrink_to_lo());
541+
if let DefKind::Impl { .. } | DefKind::Trait = tcx.def_kind(parent) {
542+
multispan.push_span_context(tcx.def_span(parent).shrink_to_lo());
543+
}
544+
diag.span_note(
545+
multispan,
546+
format!(
547+
"`'static` lifetime requirement from `{}` introduced here",
548+
tcx.def_path_str(def_id)
549+
),
550+
);
551+
}
552+
}
553+
394554
/// Report that `longer_fr: error_vid`, which doesn't hold,
395555
/// where `longer_fr` is a placeholder.
396556
fn report_erroneous_rvid_reaches_placeholder(
@@ -503,6 +663,10 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
503663
}
504664
};
505665

666+
if let ConstraintCategory::CallArgument(Some(ty)) = category {
667+
self.explain_impl_static_obligation(&mut diag, ty, outlived_fr);
668+
}
669+
506670
match variance_info {
507671
ty::VarianceDiagInfo::None => {}
508672
ty::VarianceDiagInfo::Invariant { ty, param_index } => {

‎src/tools/clippy/tests/ui/crashes/ice-6256.stderr‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@ LL | let f = |x: &dyn TT| x.func();
88
| | | argument requires that `'1` must outlive `'static`
99
| | let's call the lifetime of this reference `'1`
1010
| `x` is only valid in the closure body
11+
|
12+
note: `'static` lifetime requirement from `<(dyn TT + 'static)>::func` introduced here
13+
--> tests/ui/crashes/ice-6256.rs:7:6
14+
|
15+
LL | impl dyn TT {
16+
| ^^^^^^ `dyn Trait` introduces an implicit `'static` lifetime requirement
17+
LL | fn func(&self) {}
18+
|
1119

1220
error: aborting due to 1 previous error
1321

‎tests/ui/async-await/issues/issue-62097.stderr‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ LL | foo(|| self.bar()).await;
1111
| |
1212
| `self` escapes the method body here
1313
| argument requires that `'1` must outlive `'static`
14+
|
15+
note: `'static` lifetime requirement from `foo` introduced here
16+
--> $DIR/issue-62097.rs:4:19
17+
|
18+
LL | async fn foo<F>(fun: F)
19+
LL | where
20+
LL | F: FnOnce() + 'static
21+
| ^^^^^^^ lifetime requirement introduced here
1422

1523
error[E0373]: closure may outlive the current function, but it borrows `self`, which is owned by the current function
1624
--> $DIR/issue-62097.rs:13:13

‎tests/ui/async-await/issues/issue-72312.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//@ edition:2018
22
fn require_static<T: 'static>(val: T) -> T {
3+
//~^ NOTE: `'static` lifetime requirement from `require_static` introduced here
4+
//~| NOTE: lifetime requirement introduced here
35
val
46
}
57

‎tests/ui/async-await/issues/issue-72312.stderr‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error[E0521]: borrowed data escapes outside of method
2-
--> $DIR/issue-72312.rs:12:9
2+
--> $DIR/issue-72312.rs:14:9
33
|
44
LL | pub async fn start(&self) {
55
| -----
@@ -14,6 +14,12 @@ LL | | });
1414
| | |
1515
| |__________`self` escapes the method body here
1616
| argument requires that `'1` must outlive `'static`
17+
|
18+
note: `'static` lifetime requirement from `require_static` introduced here
19+
--> $DIR/issue-72312.rs:2:22
20+
|
21+
LL | fn require_static<T: 'static>(val: T) -> T {
22+
| ^^^^^^^ lifetime requirement introduced here
1723

1824
error: aborting due to 1 previous error
1925

‎tests/ui/borrowck/issue-103624.stderr‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ LL | | })
1616
| | |
1717
| |__________`self` escapes the method body here
1818
| argument requires that `'1` must outlive `'static`
19+
|
20+
note: `'static` lifetime requirement from `spawn_blocking` introduced here
21+
--> $DIR/issue-103624.rs:7:64
22+
|
23+
LL | async fn spawn_blocking<T>(f: impl (Fn() -> T) + Send + Sync + 'static) -> T {
24+
| ^^^^^^^ lifetime requirement introduced here
1925

2026
error[E0507]: cannot move out of `self.b`, as `self` is a captured variable in an `Fn` closure
2127
--> $DIR/issue-103624.rs:16:13

‎tests/ui/borrowck/var-matching-lifetime-but-unused-not-mentioned.stderr‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ LL | consume(c);
1111
| |
1212
| `used_arg` escapes the function body here
1313
| argument requires that `'a` must outlive `'static`
14+
|
15+
note: `'static` lifetime requirement from `consume` introduced here
16+
--> $DIR/var-matching-lifetime-but-unused-not-mentioned.rs:5:15
17+
|
18+
LL | fn consume<T: 'static>(_: T) {}
19+
| ^^^^^^^ lifetime requirement introduced here
1420

1521
error: aborting due to 1 previous error
1622

‎tests/ui/closures/closure-bounds-static-cant-capture-borrowed.stderr‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ LL | | })
1414
| | |
1515
| |______`x` escapes the function body here
1616
| argument requires that `'1` must outlive `'static`
17+
|
18+
note: `'static` lifetime requirement from `bar` introduced here
19+
--> $DIR/closure-bounds-static-cant-capture-borrowed.rs:2:39
20+
|
21+
LL | fn bar<F>(blk: F) where F: FnOnce() + 'static {
22+
| ^^^^^^^ lifetime requirement introduced here
1723

1824
error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function
1925
--> $DIR/closure-bounds-static-cant-capture-borrowed.rs:6:9

‎tests/ui/coroutine/resume-arg-outlives-2.stderr‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ LL | | })
1515
| | |
1616
| |______`s` escapes the function body here
1717
| argument requires that `'not_static` must outlive `'static`
18+
|
19+
note: `'static` lifetime requirement from `spawn` introduced here
20+
--> $SRC_DIR/std/src/thread/functions.rs:LL:COL
21+
::: $SRC_DIR/std/src/thread/functions.rs:LL:COL
22+
|
23+
= note: lifetime requirement introduced here
24+
::: $SRC_DIR/std/src/thread/functions.rs:LL:COL
25+
|
26+
= note: lifetime requirement introduced here
1827

1928
error: aborting due to 1 previous error
2029

0 commit comments

Comments
 (0)