1 //! Error reporting machinery for lifetime errors.
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_infer::infer::{
5 error_reporting::nice_region_error::NiceRegionError,
6 error_reporting::unexpected_hidden_region_diagnostic, NllRegionVariableOrigin,
8 use rustc_middle::mir::{ConstraintCategory, ReturnConstraint};
9 use rustc_middle::ty::subst::Subst;
10 use rustc_middle::ty::{self, RegionVid, Ty};
11 use rustc_span::symbol::{kw, sym};
12 use rustc_span::{BytePos, Span};
14 use crate::util::borrowck_errors;
16 use crate::borrow_check::region_infer::BlameConstraint;
17 use crate::borrow_check::{
18 nll::ConstraintDescription,
19 region_infer::{values::RegionElement, TypeTest},
20 universal_regions::DefiningTy,
24 use super::{OutlivesSuggestionBuilder, RegionName};
26 impl ConstraintDescription for ConstraintCategory {
27 fn description(&self) -> &'static str {
28 // Must end with a space. Allows for empty names to be provided.
30 ConstraintCategory::Assignment => "assignment ",
31 ConstraintCategory::Return(_) => "returning this value ",
32 ConstraintCategory::Yield => "yielding this value ",
33 ConstraintCategory::UseAsConst => "using this value as a constant ",
34 ConstraintCategory::UseAsStatic => "using this value as a static ",
35 ConstraintCategory::Cast => "cast ",
36 ConstraintCategory::CallArgument => "argument ",
37 ConstraintCategory::TypeAnnotation => "type annotation ",
38 ConstraintCategory::ClosureBounds => "closure body ",
39 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
40 ConstraintCategory::CopyBound => "copying this value ",
41 ConstraintCategory::OpaqueType => "opaque type ",
42 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
43 ConstraintCategory::Boring
44 | ConstraintCategory::BoringNoLocation
45 | ConstraintCategory::Internal => "",
50 /// A collection of errors encountered during region inference. This is needed to efficiently
51 /// report errors after borrow checking.
53 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
54 /// allocation most of the time.
55 crate type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
57 #[derive(Clone, Debug)]
58 crate enum RegionErrorKind<'tcx> {
59 /// A generic bound failure for a type test (`T: 'a`).
60 TypeTestError { type_test: TypeTest<'tcx> },
62 /// An unexpected hidden region for an opaque type.
63 UnexpectedHiddenRegion {
64 /// The span for the member constraint.
68 /// The unexpected region.
69 member_region: ty::Region<'tcx>,
72 /// Higher-ranked subtyping error.
73 BoundUniversalRegionError {
74 /// The placeholder free region.
76 /// The region element that erroneously must be outlived by `longer_fr`.
77 error_element: RegionElement,
78 /// The origin of the placeholder region.
79 fr_origin: NllRegionVariableOrigin,
82 /// Any other lifetime error.
84 /// The origin of the region.
85 fr_origin: NllRegionVariableOrigin,
86 /// The region that should outlive `shorter_fr`.
88 /// The region that should be shorter, but we can't prove it.
89 shorter_fr: RegionVid,
90 /// Indicates whether this is a reported error. We currently only report the first error
91 /// encountered and leave the rest unreported so as not to overwhelm the user.
96 /// Information about the various region constraints involved in a borrow checker error.
97 #[derive(Clone, Debug)]
98 pub struct ErrorConstraintInfo {
100 pub(super) fr: RegionVid,
101 pub(super) fr_is_local: bool,
102 pub(super) outlived_fr: RegionVid,
103 pub(super) outlived_fr_is_local: bool,
105 // Category and span for best blame constraint
106 pub(super) category: ConstraintCategory,
107 pub(super) span: Span,
110 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
111 /// Converts a region inference variable into a `ty::Region` that
112 /// we can use for error reporting. If `r` is universally bound,
113 /// then we use the name that we have on record for it. If `r` is
114 /// existentially bound, then we check its inferred value and try
115 /// to find a good name from that. Returns `None` if we can't find
116 /// one (e.g., this is just some random part of the CFG).
117 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
118 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
121 /// Returns the `RegionVid` corresponding to the region returned by
122 /// `to_error_region`.
123 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
124 if self.regioncx.universal_regions().is_universal_region(r) {
127 // We just want something nameable, even if it's not
128 // actually an upper bound.
129 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
131 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
132 self.to_error_region_vid(upper_bound)
139 /// Returns `true` if a closure is inferred to be an `FnMut` closure.
140 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
141 if let Some(ty::ReFree(free_region)) = self.to_error_region(fr) {
142 if let ty::BoundRegionKind::BrEnv = free_region.bound_region {
143 if let DefiningTy::Closure(_, substs) =
144 self.regioncx.universal_regions().defining_ty
146 return substs.as_closure().kind() == ty::ClosureKind::FnMut;
154 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
155 pub(in crate::borrow_check) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
156 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
157 // buffered in the `MirBorrowckCtxt`.
159 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
161 for nll_error in nll_errors.into_iter() {
163 RegionErrorKind::TypeTestError { type_test } => {
164 // Try to convert the lower-bound region into something named we can print for the user.
165 let lower_bound_region = self.to_error_region(type_test.lower_bound);
167 let type_test_span = type_test.locations.span(&self.body);
169 if let Some(lower_bound_region) = lower_bound_region {
171 .construct_generic_bound_failure(
174 type_test.generic_kind,
177 .buffer(&mut self.errors_buffer);
179 // FIXME. We should handle this case better. It
180 // indicates that we have e.g., some region variable
181 // whose value is like `'a+'b` where `'a` and `'b` are
182 // distinct unrelated univesal regions that are not
183 // known to outlive one another. It'd be nice to have
184 // some examples where this arises to decide how best
185 // to report it; we could probably handle it by
186 // iterating over the universal regions and reporting
187 // an error that multiple bounds are required.
193 &format!("`{}` does not live long enough", type_test.generic_kind),
195 .buffer(&mut self.errors_buffer);
199 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
200 let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
201 let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
202 unexpected_hidden_region_diagnostic(
208 .buffer(&mut self.errors_buffer);
211 RegionErrorKind::BoundUniversalRegionError {
216 let error_region = self.regioncx.region_from_element(longer_fr, error_element);
218 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
219 let (_, span) = self.regioncx.find_outlives_blame_span(
226 // FIXME: improve this error message
230 .struct_span_err(span, "higher-ranked subtype error")
231 .buffer(&mut self.errors_buffer);
234 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
236 self.report_region_error(
240 &mut outlives_suggestion,
243 // We only report the first error, so as not to overwhelm the user. See
244 // `RegRegionErrorKind` docs.
246 // FIXME: currently we do nothing with these, but perhaps we can do better?
247 // FIXME: try collecting these constraints on the outlives suggestion
248 // builder. Does it make the suggestions any better?
250 "Unreported region error: can't prove that {:?}: {:?}",
251 longer_fr, shorter_fr
258 // Emit one outlives suggestions for each MIR def we borrowck
259 outlives_suggestion.add_suggestion(self);
262 /// Report an error because the universal region `fr` was required to outlive
263 /// `outlived_fr` but it is not known to do so. For example:
266 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
269 /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
270 pub(in crate::borrow_check) fn report_region_error(
273 fr_origin: NllRegionVariableOrigin,
274 outlived_fr: RegionVid,
275 outlives_suggestion: &mut OutlivesSuggestionBuilder,
277 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
279 let BlameConstraint { category, span, variance_info, from_closure: _ } =
280 self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
281 self.regioncx.provides_universal_region(r, fr, outlived_fr)
284 debug!("report_region_error: category={:?} {:?} {:?}", category, span, variance_info);
285 // Check if we can use one of the "nice region errors".
286 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
287 let nice = NiceRegionError::new_from_span(self.infcx, span, o, f);
288 if let Some(diag) = nice.try_report_from_nll() {
289 diag.buffer(&mut self.errors_buffer);
294 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
295 self.regioncx.universal_regions().is_local_free_region(fr),
296 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
300 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
301 fr_is_local, outlived_fr_is_local, category
304 let errci = ErrorConstraintInfo {
308 outlived_fr_is_local,
313 let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
314 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
315 self.report_fnmut_error(&errci, kind)
317 (ConstraintCategory::Assignment, true, false)
318 | (ConstraintCategory::CallArgument, true, false) => {
319 let mut db = self.report_escaping_data_error(&errci);
321 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
322 outlives_suggestion.collect_constraint(fr, outlived_fr);
327 let mut db = self.report_general_error(&errci);
329 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
330 outlives_suggestion.collect_constraint(fr, outlived_fr);
336 match variance_info {
337 ty::VarianceDiagInfo::None => {}
338 ty::VarianceDiagInfo::Mut { kind, ty } => {
339 let kind_name = match kind {
340 ty::VarianceDiagMutKind::Ref => "reference",
341 ty::VarianceDiagMutKind::RawPtr => "pointer",
343 diag.note(&format!("requirement occurs because of a mutable {kind_name} to {ty}",));
344 diag.note(&format!("mutable {kind_name}s are invariant over their type parameter"));
345 diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
349 diag.buffer(&mut self.errors_buffer);
352 /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
353 /// This function expects `fr` to be local and `outlived_fr` to not be local.
356 /// error: captured variable cannot escape `FnMut` closure body
357 /// --> $DIR/issue-53040.rs:15:8
360 /// | -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
362 /// | inferred to be a `FnMut` closure
364 /// = note: `FnMut` closures only have access to their captured variables while they are
366 /// = note: ...therefore, returned references to captured variables will escape the closure
368 fn report_fnmut_error(
370 errci: &ErrorConstraintInfo,
371 kind: ReturnConstraint,
372 ) -> DiagnosticBuilder<'tcx> {
373 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
379 .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
381 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
382 if let ty::Opaque(def_id, _) = *output_ty.kind() {
383 output_ty = self.infcx.tcx.type_of(def_id)
386 debug!("report_fnmut_error: output_ty={:?}", output_ty);
388 let message = match output_ty.kind() {
389 ty::Closure(_, _) => {
390 "returns a closure that contains a reference to a captured variable, which then \
391 escapes the closure body"
393 ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did) => {
394 "returns an `async` block that contains a reference to a captured variable, which then \
395 escapes the closure body"
397 _ => "returns a reference to a captured variable which escapes the closure body",
400 diag.span_label(*span, message);
402 // FIXME(project-rfc-2229#48): This should store a captured_place not a hir id
403 if let ReturnConstraint::ClosureUpvar(upvar) = kind {
404 let def_id = match self.regioncx.universal_regions().defining_ty {
405 DefiningTy::Closure(def_id, _) => def_id,
406 ty => bug!("unexpected DefiningTy {:?}", ty),
409 let upvar_def_span = self.infcx.tcx.hir().span(upvar);
410 let upvar_span = self.infcx.tcx.upvars_mentioned(def_id).unwrap()[&upvar].span;
411 diag.span_label(upvar_def_span, "variable defined here");
412 diag.span_label(upvar_span, "variable captured here");
415 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
416 diag.span_label(fr_span, "inferred to be a `FnMut` closure");
420 "`FnMut` closures only have access to their captured variables while they are \
423 diag.note("...therefore, they cannot allow references to captured variables to escape");
428 /// Reports a error specifically for when data is escaping a closure.
431 /// error: borrowed data escapes outside of function
432 /// --> $DIR/lifetime-bound-will-change-warning.rs:44:5
434 /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
435 /// | - `x` is a reference that is only valid in the function body
436 /// LL | // but ref_obj will not, so warn.
438 /// | ^^^^^^^^^^ `x` escapes the function body here
440 fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
441 let ErrorConstraintInfo { span, category, .. } = errci;
443 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
450 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
458 let (_, escapes_from) = self
461 .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
463 // Revert to the normal error in these cases.
464 // Assignments aren't "escapes" in function items.
465 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
466 || (*category == ConstraintCategory::Assignment
467 && self.regioncx.universal_regions().defining_ty.is_fn_def())
468 || self.regioncx.universal_regions().defining_ty.is_const()
470 return self.report_general_error(&ErrorConstraintInfo {
472 outlived_fr_is_local: false,
478 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
480 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
484 "`{}` declared here, outside of the {} body",
485 outlived_fr_name, escapes_from
490 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
494 "`{}` is a reference that is only valid in the {} body",
495 fr_name, escapes_from
499 diag.span_label(*span, format!("`{}` escapes the {} body here", fr_name, escapes_from));
505 /// Reports a region inference error for the general case with named/synthesized lifetimes to
506 /// explain what is happening.
509 /// error: unsatisfied lifetime constraints
510 /// --> $DIR/regions-creating-enums3.rs:17:5
512 /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
513 /// | -- -- lifetime `'b` defined here
515 /// | lifetime `'a` defined here
516 /// LL | ast::add(x, y)
517 /// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
518 /// | is returning data with lifetime `'b`
520 fn report_general_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
521 let ErrorConstraintInfo {
525 outlived_fr_is_local,
532 self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
534 let (_, mir_def_name) =
535 self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
537 let fr_name = self.give_region_a_name(*fr).unwrap();
538 fr_name.highlight_region_name(&mut diag);
539 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
540 outlived_fr_name.highlight_region_name(&mut diag);
542 match (category, outlived_fr_is_local, fr_is_local) {
543 (ConstraintCategory::Return(_), true, _) => {
547 "{} was supposed to return data with lifetime `{}` but it is returning \
548 data with lifetime `{}`",
549 mir_def_name, outlived_fr_name, fr_name
557 "{}requires that `{}` must outlive `{}`",
558 category.description(),
566 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
571 /// Adds a suggestion to errors where a `impl Trait` is returned.
574 /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
577 /// LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
578 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
580 fn add_static_impl_trait_suggestion(
582 diag: &mut DiagnosticBuilder<'tcx>,
584 // We need to pass `fr_name` - computing it again will label it twice.
586 outlived_fr: RegionVid,
588 if let (Some(f), Some(ty::RegionKind::ReStatic)) =
589 (self.to_error_region(fr), self.to_error_region(outlived_fr))
591 if let Some(&ty::Opaque(did, substs)) = self
594 .is_suitable_region(f)
596 .and_then(|id| self.infcx.tcx.return_type_impl_trait(id))
597 .map(|(ty, _)| ty.kind())
599 // Check whether or not the impl trait return type is intended to capture
600 // data with the static lifetime.
602 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
603 let has_static_predicate = {
604 let bounds = self.infcx.tcx.explicit_item_bounds(did);
606 let mut found = false;
607 for (bound, _) in bounds {
608 if let ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_, r)) =
609 bound.kind().skip_binder()
611 let r = r.subst(self.infcx.tcx, substs);
612 if let ty::RegionKind::ReStatic = r {
616 // If there's already a lifetime bound, don't
627 "add_static_impl_trait_suggestion: has_static_predicate={:?}",
630 let static_str = kw::StaticLifetime;
631 // If there is a static predicate, then the only sensible suggestion is to replace
632 // fr with `'static`.
633 if has_static_predicate {
634 diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
636 // Otherwise, we should suggest adding a constraint on the return type.
637 let span = self.infcx.tcx.def_span(did);
638 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
639 let suggestable_fr_name = if fr_name.was_named() {
644 let span = if snippet.ends_with(';') {
645 // `type X = impl Trait;`
646 span.with_hi(span.hi() - BytePos(1))
650 let suggestion = format!(" + {}", suggestable_fr_name);
651 let span = span.shrink_to_hi();
652 diag.span_suggestion(
655 "to allow this `impl Trait` to capture borrowed data with lifetime \
656 `{}`, add `{}` as a bound",
657 fr_name, suggestable_fr_name,
660 Applicability::MachineApplicable,