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::{self, RegionVid, Ty};
10 use rustc_span::symbol::{kw, sym};
13 use crate::util::borrowck_errors;
15 use crate::borrow_check::{
16 nll::ConstraintDescription,
17 region_infer::{values::RegionElement, TypeTest},
18 universal_regions::DefiningTy,
22 use super::{OutlivesSuggestionBuilder, RegionName};
24 impl ConstraintDescription for ConstraintCategory {
25 fn description(&self) -> &'static str {
26 // Must end with a space. Allows for empty names to be provided.
28 ConstraintCategory::Assignment => "assignment ",
29 ConstraintCategory::Return(_) => "returning this value ",
30 ConstraintCategory::Yield => "yielding this value ",
31 ConstraintCategory::UseAsConst => "using this value as a constant ",
32 ConstraintCategory::UseAsStatic => "using this value as a static ",
33 ConstraintCategory::Cast => "cast ",
34 ConstraintCategory::CallArgument => "argument ",
35 ConstraintCategory::TypeAnnotation => "type annotation ",
36 ConstraintCategory::ClosureBounds => "closure body ",
37 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
38 ConstraintCategory::CopyBound => "copying this value ",
39 ConstraintCategory::OpaqueType => "opaque type ",
40 ConstraintCategory::ClosureUpvar(_) => "closure capture ",
41 ConstraintCategory::Boring
42 | ConstraintCategory::BoringNoLocation
43 | ConstraintCategory::Internal => "",
48 /// A collection of errors encountered during region inference. This is needed to efficiently
49 /// report errors after borrow checking.
51 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
52 /// allocation most of the time.
53 crate type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
55 #[derive(Clone, Debug)]
56 crate enum RegionErrorKind<'tcx> {
57 /// A generic bound failure for a type test (`T: 'a`).
58 TypeTestError { type_test: TypeTest<'tcx> },
60 /// An unexpected hidden region for an opaque type.
61 UnexpectedHiddenRegion {
62 /// The span for the member constraint.
66 /// The unexpected region.
67 member_region: ty::Region<'tcx>,
70 /// Higher-ranked subtyping error.
71 BoundUniversalRegionError {
72 /// The placeholder free region.
74 /// The region element that erroneously must be outlived by `longer_fr`.
75 error_element: RegionElement,
76 /// The origin of the placeholder region.
77 fr_origin: NLLRegionVariableOrigin,
80 /// Any other lifetime error.
82 /// The origin of the region.
83 fr_origin: NLLRegionVariableOrigin,
84 /// The region that should outlive `shorter_fr`.
86 /// The region that should be shorter, but we can't prove it.
87 shorter_fr: RegionVid,
88 /// Indicates whether this is a reported error. We currently only report the first error
89 /// encountered and leave the rest unreported so as not to overwhelm the user.
94 /// Information about the various region constraints involved in a borrow checker error.
95 #[derive(Clone, Debug)]
96 pub struct ErrorConstraintInfo {
98 pub(super) fr: RegionVid,
99 pub(super) fr_is_local: bool,
100 pub(super) outlived_fr: RegionVid,
101 pub(super) outlived_fr_is_local: bool,
103 // Category and span for best blame constraint
104 pub(super) category: ConstraintCategory,
105 pub(super) span: Span,
108 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
109 /// Converts a region inference variable into a `ty::Region` that
110 /// we can use for error reporting. If `r` is universally bound,
111 /// then we use the name that we have on record for it. If `r` is
112 /// existentially bound, then we check its inferred value and try
113 /// to find a good name from that. Returns `None` if we can't find
114 /// one (e.g., this is just some random part of the CFG).
115 pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
116 self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
119 /// Returns the `RegionVid` corresponding to the region returned by
120 /// `to_error_region`.
121 pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
122 if self.regioncx.universal_regions().is_universal_region(r) {
125 // We just want something nameable, even if it's not
126 // actually an upper bound.
127 let upper_bound = self.regioncx.approx_universal_upper_bound(r);
129 if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
130 self.to_error_region_vid(upper_bound)
137 /// Returns `true` if a closure is inferred to be an `FnMut` closure.
138 fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
139 if let Some(ty::ReFree(free_region)) = self.to_error_region(fr) {
140 if let ty::BoundRegion::BrEnv = free_region.bound_region {
141 if let DefiningTy::Closure(_, substs) =
142 self.regioncx.universal_regions().defining_ty
144 return substs.as_closure().kind() == ty::ClosureKind::FnMut;
152 /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
153 pub(in crate::borrow_check) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
154 // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
155 // buffered in the `MirBorrowckCtxt`.
157 let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
159 for nll_error in nll_errors.into_iter() {
161 RegionErrorKind::TypeTestError { type_test } => {
162 // Try to convert the lower-bound region into something named we can print for the user.
163 let lower_bound_region = self.to_error_region(type_test.lower_bound);
165 let type_test_span = type_test.locations.span(&self.body);
167 if let Some(lower_bound_region) = lower_bound_region {
169 .construct_generic_bound_failure(
172 type_test.generic_kind,
175 .buffer(&mut self.errors_buffer);
177 // FIXME. We should handle this case better. It
178 // indicates that we have e.g., some region variable
179 // whose value is like `'a+'b` where `'a` and `'b` are
180 // distinct unrelated univesal regions that are not
181 // known to outlive one another. It'd be nice to have
182 // some examples where this arises to decide how best
183 // to report it; we could probably handle it by
184 // iterating over the universal regions and reporting
185 // an error that multiple bounds are required.
191 &format!("`{}` does not live long enough", type_test.generic_kind),
193 .buffer(&mut self.errors_buffer);
197 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
198 let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
199 let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
200 unexpected_hidden_region_diagnostic(
206 .buffer(&mut self.errors_buffer);
209 RegionErrorKind::BoundUniversalRegionError {
214 let error_region = self.regioncx.region_from_element(longer_fr, error_element);
216 // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
217 let (_, span) = self.regioncx.find_outlives_blame_span(
224 // FIXME: improve this error message
228 .struct_span_err(span, "higher-ranked subtype error")
229 .buffer(&mut self.errors_buffer);
232 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
234 self.report_region_error(
238 &mut outlives_suggestion,
241 // We only report the first error, so as not to overwhelm the user. See
242 // `RegRegionErrorKind` docs.
244 // FIXME: currently we do nothing with these, but perhaps we can do better?
245 // FIXME: try collecting these constraints on the outlives suggestion
246 // builder. Does it make the suggestions any better?
248 "Unreported region error: can't prove that {:?}: {:?}",
249 longer_fr, shorter_fr
256 // Emit one outlives suggestions for each MIR def we borrowck
257 outlives_suggestion.add_suggestion(self);
260 /// Report an error because the universal region `fr` was required to outlive
261 /// `outlived_fr` but it is not known to do so. For example:
264 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
267 /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
268 pub(in crate::borrow_check) fn report_region_error(
271 fr_origin: NLLRegionVariableOrigin,
272 outlived_fr: RegionVid,
273 outlives_suggestion: &mut OutlivesSuggestionBuilder,
275 debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
277 let (category, _, span) =
278 self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
279 self.regioncx.provides_universal_region(r, fr, outlived_fr)
282 debug!("report_region_error: category={:?} {:?}", category, span);
283 // Check if we can use one of the "nice region errors".
284 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
285 let nice = NiceRegionError::new_from_span(self.infcx, span, o, f);
286 if let Some(diag) = nice.try_report_from_nll() {
287 diag.buffer(&mut self.errors_buffer);
292 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
293 self.regioncx.universal_regions().is_local_free_region(fr),
294 self.regioncx.universal_regions().is_local_free_region(outlived_fr),
298 "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
299 fr_is_local, outlived_fr_is_local, category
302 let errci = ErrorConstraintInfo {
306 outlived_fr_is_local,
311 let diag = match (category, fr_is_local, outlived_fr_is_local) {
312 (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
313 self.report_fnmut_error(&errci, kind)
315 (ConstraintCategory::Assignment, true, false)
316 | (ConstraintCategory::CallArgument, true, false) => {
317 let mut db = self.report_escaping_data_error(&errci);
319 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
320 outlives_suggestion.collect_constraint(fr, outlived_fr);
325 let mut db = self.report_general_error(&errci);
327 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
328 outlives_suggestion.collect_constraint(fr, outlived_fr);
334 diag.buffer(&mut self.errors_buffer);
337 /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
338 /// This function expects `fr` to be local and `outlived_fr` to not be local.
341 /// error: captured variable cannot escape `FnMut` closure body
342 /// --> $DIR/issue-53040.rs:15:8
345 /// | -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
347 /// | inferred to be a `FnMut` closure
349 /// = note: `FnMut` closures only have access to their captured variables while they are
351 /// = note: ...therefore, returned references to captured variables will escape the closure
353 fn report_fnmut_error(
355 errci: &ErrorConstraintInfo,
356 kind: ReturnConstraint,
357 ) -> DiagnosticBuilder<'tcx> {
358 let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
364 .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
366 let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
367 if let ty::Opaque(def_id, _) = output_ty.kind {
368 output_ty = self.infcx.tcx.type_of(def_id)
371 debug!("report_fnmut_error: output_ty={:?}", output_ty);
373 let message = match output_ty.kind {
374 ty::Closure(_, _) => {
375 "returns a closure that contains a reference to a captured variable, which then \
376 escapes the closure body"
378 ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did) => {
379 "returns an `async` block that contains a reference to a captured variable, which then \
380 escapes the closure body"
382 _ => "returns a reference to a captured variable which escapes the closure body",
385 diag.span_label(*span, message);
387 if let ReturnConstraint::ClosureUpvar(upvar) = kind {
388 let def_id = match self.regioncx.universal_regions().defining_ty {
389 DefiningTy::Closure(def_id, _) => def_id,
390 ty @ _ => bug!("unexpected DefiningTy {:?}", ty),
393 let upvar_def_span = self.infcx.tcx.hir().span(upvar);
394 let upvar_span = self.infcx.tcx.upvars_mentioned(def_id).unwrap()[&upvar].span;
395 diag.span_label(upvar_def_span, "variable defined here");
396 diag.span_label(upvar_span, "variable captured here");
399 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
400 diag.span_label(fr_span, "inferred to be a `FnMut` closure");
404 "`FnMut` closures only have access to their captured variables while they are \
407 diag.note("...therefore, they cannot allow references to captured variables to escape");
412 /// Reports a error specifically for when data is escaping a closure.
415 /// error: borrowed data escapes outside of function
416 /// --> $DIR/lifetime-bound-will-change-warning.rs:44:5
418 /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
419 /// | - `x` is a reference that is only valid in the function body
420 /// LL | // but ref_obj will not, so warn.
422 /// | ^^^^^^^^^^ `x` escapes the function body here
424 fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
425 let ErrorConstraintInfo { span, category, .. } = errci;
427 let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
434 let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
442 let (_, escapes_from) = self
445 .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
447 // Revert to the normal error in these cases.
448 // Assignments aren't "escapes" in function items.
449 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
450 || (*category == ConstraintCategory::Assignment
451 && self.regioncx.universal_regions().defining_ty.is_fn_def())
452 || self.regioncx.universal_regions().defining_ty.is_const()
454 return self.report_general_error(&ErrorConstraintInfo {
456 outlived_fr_is_local: false,
462 borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
464 if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
468 "`{}` declared here, outside of the {} body",
469 outlived_fr_name, escapes_from
474 if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
478 "`{}` is a reference that is only valid in the {} body",
479 fr_name, escapes_from
483 diag.span_label(*span, format!("`{}` escapes the {} body here", fr_name, escapes_from));
489 /// Reports a region inference error for the general case with named/synthesized lifetimes to
490 /// explain what is happening.
493 /// error: unsatisfied lifetime constraints
494 /// --> $DIR/regions-creating-enums3.rs:17:5
496 /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
497 /// | -- -- lifetime `'b` defined here
499 /// | lifetime `'a` defined here
500 /// LL | ast::add(x, y)
501 /// | ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
502 /// | is returning data with lifetime `'b`
504 fn report_general_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
505 let ErrorConstraintInfo {
509 outlived_fr_is_local,
516 self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
518 let (_, mir_def_name) = self.infcx.tcx.article_and_description(self.mir_def_id.to_def_id());
520 let fr_name = self.give_region_a_name(*fr).unwrap();
521 fr_name.highlight_region_name(&mut diag);
522 let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
523 outlived_fr_name.highlight_region_name(&mut diag);
525 match (category, outlived_fr_is_local, fr_is_local) {
526 (ConstraintCategory::Return(_), true, _) => {
530 "{} was supposed to return data with lifetime `{}` but it is returning \
531 data with lifetime `{}`",
532 mir_def_name, outlived_fr_name, fr_name
540 "{}requires that `{}` must outlive `{}`",
541 category.description(),
549 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
554 /// Adds a suggestion to errors where a `impl Trait` is returned.
557 /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
560 /// LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
561 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
563 fn add_static_impl_trait_suggestion(
565 diag: &mut DiagnosticBuilder<'tcx>,
567 // We need to pass `fr_name` - computing it again will label it twice.
569 outlived_fr: RegionVid,
571 if let (Some(f), Some(ty::RegionKind::ReStatic)) =
572 (self.to_error_region(fr), self.to_error_region(outlived_fr))
574 if let Some((&ty::TyS { kind: ty::Opaque(did, substs), .. }, _)) = self
577 .is_suitable_region(f)
579 .map(|id| self.infcx.tcx.return_type_impl_trait(id))
582 // Check whether or not the impl trait return type is intended to capture
583 // data with the static lifetime.
585 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
586 let has_static_predicate = {
587 let predicates_of = self.infcx.tcx.predicates_of(did);
588 let bounds = predicates_of.instantiate(self.infcx.tcx, substs);
590 let mut found = false;
591 for predicate in bounds.predicates {
592 if let ty::PredicateKind::TypeOutlives(binder) = predicate.kind() {
593 if let ty::OutlivesPredicate(_, ty::RegionKind::ReStatic) =
599 // If there's already a lifetime bound, don't
610 "add_static_impl_trait_suggestion: has_static_predicate={:?}",
613 let static_str = kw::StaticLifetime;
614 // If there is a static predicate, then the only sensible suggestion is to replace
615 // fr with `'static`.
616 if has_static_predicate {
617 diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
619 // Otherwise, we should suggest adding a constraint on the return type.
620 let span = self.infcx.tcx.def_span(did);
621 if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
622 let suggestable_fr_name = if fr_name.was_named() {
627 let suggestion = if snippet.ends_with(';') {
628 // `type X = impl Trait;`
629 format!("{} + {};", &snippet[..snippet.len() - 1], suggestable_fr_name)
631 format!("{} + {}", snippet, suggestable_fr_name)
633 diag.span_suggestion(
636 "to allow this `impl Trait` to capture borrowed data with lifetime \
637 `{}`, add `{}` as a bound",
638 fr_name, suggestable_fr_name,
641 Applicability::MachineApplicable,