rustc_borrowck/diagnostics/
region_errors.rs

1//! Error reporting machinery for lifetime errors.
2
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
5use rustc_hir as hir;
6use rustc_hir::GenericBound::Trait;
7use rustc_hir::QPath::Resolved;
8use rustc_hir::WherePredicateKind::BoundPredicate;
9use rustc_hir::def::Res::Def;
10use rustc_hir::def_id::DefId;
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate};
13use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin};
14use rustc_middle::bug;
15use rustc_middle::hir::place::PlaceBase;
16use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
17use rustc_middle::ty::{
18    self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions,
19};
20use rustc_span::{Ident, Span, kw};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::error_reporting::infer::nice_region_error::{
23    self, HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, find_anon_type,
24    find_param_with_region, suggest_adding_lifetime_params,
25};
26use rustc_trait_selection::infer::InferCtxtExt;
27use rustc_trait_selection::traits::{Obligation, ObligationCtxt};
28use tracing::{debug, instrument, trace};
29
30use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource};
31use crate::nll::ConstraintDescription;
32use crate::region_infer::values::RegionElement;
33use crate::region_infer::{BlameConstraint, TypeTest};
34use crate::session_diagnostics::{
35    FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr,
36    LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
37};
38use crate::universal_regions::DefiningTy;
39use crate::{MirBorrowckCtxt, borrowck_errors, fluent_generated as fluent};
40
41impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
42    fn description(&self) -> &'static str {
43        // Must end with a space. Allows for empty names to be provided.
44        match self {
45            ConstraintCategory::Assignment => "assignment ",
46            ConstraintCategory::Return(_) => "returning this value ",
47            ConstraintCategory::Yield => "yielding this value ",
48            ConstraintCategory::UseAsConst => "using this value as a constant ",
49            ConstraintCategory::UseAsStatic => "using this value as a static ",
50            ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ",
51            ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ",
52            ConstraintCategory::CallArgument(_) => "argument ",
53            ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => "generic argument ",
54            ConstraintCategory::TypeAnnotation(_) => "type annotation ",
55            ConstraintCategory::SizedBound => "proving this value is `Sized` ",
56            ConstraintCategory::CopyBound => "copying this value ",
57            ConstraintCategory::OpaqueType => "opaque type ",
58            ConstraintCategory::ClosureUpvar(_) => "closure capture ",
59            ConstraintCategory::Usage => "this usage ",
60            ConstraintCategory::Predicate(_)
61            | ConstraintCategory::Boring
62            | ConstraintCategory::BoringNoLocation
63            | ConstraintCategory::Internal
64            | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
65        }
66    }
67}
68
69/// A collection of errors encountered during region inference. This is needed to efficiently
70/// report errors after borrow checking.
71///
72/// Usually we expect this to either be empty or contain a small number of items, so we can avoid
73/// allocation most of the time.
74pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
75
76impl<'tcx> RegionErrors<'tcx> {
77    pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
78        Self(vec![], tcx)
79    }
80    #[track_caller]
81    pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
82        let val = val.into();
83        let guar = self.1.sess.dcx().delayed_bug(format!("{val:?}"));
84        self.0.push((val, guar));
85    }
86    pub(crate) fn is_empty(&self) -> bool {
87        self.0.is_empty()
88    }
89    pub(crate) fn into_iter(
90        self,
91    ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
92        self.0.into_iter()
93    }
94}
95
96impl std::fmt::Debug for RegionErrors<'_> {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_tuple("RegionErrors").field(&self.0).finish()
99    }
100}
101
102#[derive(Clone, Debug)]
103pub(crate) enum RegionErrorKind<'tcx> {
104    /// A generic bound failure for a type test (`T: 'a`).
105    TypeTestError { type_test: TypeTest<'tcx> },
106
107    /// Higher-ranked subtyping error.
108    BoundUniversalRegionError {
109        /// The placeholder free region.
110        longer_fr: RegionVid,
111        /// The region element that erroneously must be outlived by `longer_fr`.
112        error_element: RegionElement,
113        /// The placeholder region.
114        placeholder: ty::PlaceholderRegion,
115    },
116
117    /// Any other lifetime error.
118    RegionError {
119        /// The origin of the region.
120        fr_origin: NllRegionVariableOrigin,
121        /// The region that should outlive `shorter_fr`.
122        longer_fr: RegionVid,
123        /// The region that should be shorter, but we can't prove it.
124        shorter_fr: RegionVid,
125        /// Indicates whether this is a reported error. We currently only report the first error
126        /// encountered and leave the rest unreported so as not to overwhelm the user.
127        is_reported: bool,
128    },
129}
130
131/// Information about the various region constraints involved in a borrow checker error.
132#[derive(Clone, Debug)]
133pub(crate) struct ErrorConstraintInfo<'tcx> {
134    // fr: outlived_fr
135    pub(super) fr: RegionVid,
136    pub(super) outlived_fr: RegionVid,
137
138    // Category and span for best blame constraint
139    pub(super) category: ConstraintCategory<'tcx>,
140    pub(super) span: Span,
141}
142
143impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
144    /// Converts a region inference variable into a `ty::Region` that
145    /// we can use for error reporting. If `r` is universally bound,
146    /// then we use the name that we have on record for it. If `r` is
147    /// existentially bound, then we check its inferred value and try
148    /// to find a good name from that. Returns `None` if we can't find
149    /// one (e.g., this is just some random part of the CFG).
150    pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
151        self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
152    }
153
154    /// Returns the `RegionVid` corresponding to the region returned by
155    /// `to_error_region`.
156    pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
157        if self.regioncx.universal_regions().is_universal_region(r) {
158            Some(r)
159        } else {
160            // We just want something nameable, even if it's not
161            // actually an upper bound.
162            let upper_bound = self.regioncx.approx_universal_upper_bound(r);
163
164            if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
165                self.to_error_region_vid(upper_bound)
166            } else {
167                None
168            }
169        }
170    }
171
172    /// Map the regions in the type to named regions, where possible.
173    fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
174    where
175        T: TypeFoldable<TyCtxt<'tcx>>,
176    {
177        fold_regions(tcx, ty, |region, _| match region.kind() {
178            ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
179            _ => region,
180        })
181    }
182
183    /// Returns `true` if a closure is inferred to be an `FnMut` closure.
184    fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
185        if let Some(r) = self.to_error_region(fr)
186            && let ty::ReLateParam(late_param) = r.kind()
187            && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
188            && let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty
189        {
190            return args.as_closure().kind() == ty::ClosureKind::FnMut;
191        }
192
193        false
194    }
195
196    // For generic associated types (GATs) which implied 'static requirement
197    // from higher-ranked trait bounds (HRTB). Try to locate span of the trait
198    // and the span which bounded to the trait for adding 'static lifetime suggestion
199    #[allow(rustc::diagnostic_outside_of_impl)]
200    fn suggest_static_lifetime_for_gat_from_hrtb(
201        &self,
202        diag: &mut Diag<'_>,
203        lower_bound: RegionVid,
204    ) {
205        let tcx = self.infcx.tcx;
206
207        // find generic associated types in the given region 'lower_bound'
208        let gat_id_and_generics = self
209            .regioncx
210            .placeholders_contained_in(lower_bound)
211            .map(|placeholder| {
212                if let Some(id) = placeholder.bound.kind.get_id()
213                    && let Some(placeholder_id) = id.as_local()
214                    && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
215                    && let Some(generics_impl) =
216                        tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
217                {
218                    Some((gat_hir_id, generics_impl))
219                } else {
220                    None
221                }
222            })
223            .collect::<Vec<_>>();
224        debug!(?gat_id_and_generics);
225
226        // Look for the where-bound which introduces the placeholder.
227        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
228        // and `T: for<'a> Trait`<'a>.
229        let mut hrtb_bounds = vec![];
230        gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
231            for pred in generics.predicates {
232                let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
233                    pred.kind
234                else {
235                    continue;
236                };
237                if bound_generic_params
238                    .iter()
239                    .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
240                    .is_some()
241                {
242                    for bound in *bounds {
243                        hrtb_bounds.push(bound);
244                    }
245                } else {
246                    for bound in *bounds {
247                        if let Trait(trait_bound) = bound {
248                            if trait_bound
249                                .bound_generic_params
250                                .iter()
251                                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
252                                .is_some()
253                            {
254                                hrtb_bounds.push(bound);
255                                return;
256                            }
257                        }
258                    }
259                }
260            }
261        });
262        debug!(?hrtb_bounds);
263
264        let mut suggestions = vec![];
265        hrtb_bounds.iter().for_each(|bound| {
266            let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
267                return;
268            };
269            diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
270            let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
271            else {
272                return;
273            };
274            let Def(_, trait_res_defid) = trait_ref.path.res else {
275                return;
276            };
277            debug!(?generics_fn);
278            generics_fn.predicates.iter().for_each(|predicate| {
279                let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
280                else {
281                    return;
282                };
283                bounds.iter().for_each(|bd| {
284                    if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
285                        && let Def(_, res_defid) = tr_ref.path.res
286                        && res_defid == trait_res_defid // trait id matches
287                        && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
288                        && let Def(_, defid) = path.res
289                        && generics_fn.params
290                            .iter()
291                            .rfind(|param| param.def_id.to_def_id() == defid)
292                            .is_some()
293                    {
294                        suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
295                    }
296                });
297            });
298        });
299        if suggestions.len() > 0 {
300            suggestions.dedup();
301            diag.multipart_suggestion_verbose(
302                fluent::borrowck_restrict_to_static,
303                suggestions,
304                Applicability::MaybeIncorrect,
305            );
306        }
307    }
308
309    /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
310    pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
311        // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
312        // buffered in the `MirBorrowckCtxt`.
313        let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
314        for (nll_error, _) in nll_errors.into_iter() {
315            match nll_error {
316                RegionErrorKind::TypeTestError { type_test } => {
317                    // Try to convert the lower-bound region into something named we can print for
318                    // the user.
319                    let lower_bound_region = self.to_error_region(type_test.lower_bound);
320
321                    let type_test_span = type_test.span;
322
323                    if let Some(lower_bound_region) = lower_bound_region {
324                        let generic_ty = self.name_regions(
325                            self.infcx.tcx,
326                            type_test.generic_kind.to_ty(self.infcx.tcx),
327                        );
328                        let origin =
329                            SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
330                        self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
331                            self.body.source.def_id().expect_local(),
332                            type_test_span,
333                            Some(origin),
334                            self.name_regions(self.infcx.tcx, type_test.generic_kind),
335                            lower_bound_region,
336                        ));
337                    } else {
338                        // FIXME. We should handle this case better. It
339                        // indicates that we have e.g., some region variable
340                        // whose value is like `'a+'b` where `'a` and `'b` are
341                        // distinct unrelated universal regions that are not
342                        // known to outlive one another. It'd be nice to have
343                        // some examples where this arises to decide how best
344                        // to report it; we could probably handle it by
345                        // iterating over the universal regions and reporting
346                        // an error that multiple bounds are required.
347                        let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
348                            kind: type_test.generic_kind.to_string(),
349                            span: type_test_span,
350                        });
351
352                        // Add notes and suggestions for the case of 'static lifetime
353                        // implied but not specified when a generic associated types
354                        // are from higher-ranked trait bounds
355                        self.suggest_static_lifetime_for_gat_from_hrtb(
356                            &mut diag,
357                            type_test.lower_bound,
358                        );
359
360                        self.buffer_error(diag);
361                    }
362                }
363
364                RegionErrorKind::BoundUniversalRegionError {
365                    longer_fr,
366                    placeholder,
367                    error_element,
368                } => {
369                    let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
370
371                    // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
372                    let cause = self
373                        .regioncx
374                        .best_blame_constraint(
375                            longer_fr,
376                            NllRegionVariableOrigin::Placeholder(placeholder),
377                            error_vid,
378                        )
379                        .0
380                        .cause;
381
382                    let universe = placeholder.universe;
383                    let universe_info = self.regioncx.universe_info(universe);
384
385                    universe_info.report_erroneous_element(self, placeholder, error_element, cause);
386                }
387
388                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
389                    if is_reported {
390                        self.report_region_error(
391                            longer_fr,
392                            fr_origin,
393                            shorter_fr,
394                            &mut outlives_suggestion,
395                        );
396                    } else {
397                        // We only report the first error, so as not to overwhelm the user. See
398                        // `RegRegionErrorKind` docs.
399                        //
400                        // FIXME: currently we do nothing with these, but perhaps we can do better?
401                        // FIXME: try collecting these constraints on the outlives suggestion
402                        // builder. Does it make the suggestions any better?
403                        debug!(
404                            "Unreported region error: can't prove that {:?}: {:?}",
405                            longer_fr, shorter_fr
406                        );
407                    }
408                }
409            }
410        }
411
412        // Emit one outlives suggestions for each MIR def we borrowck
413        outlives_suggestion.add_suggestion(self);
414    }
415
416    /// Report an error because the universal region `fr` was required to outlive
417    /// `outlived_fr` but it is not known to do so. For example:
418    ///
419    /// ```compile_fail
420    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
421    /// ```
422    ///
423    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
424    // FIXME: make this translatable
425    #[allow(rustc::diagnostic_outside_of_impl)]
426    #[allow(rustc::untranslatable_diagnostic)]
427    pub(crate) fn report_region_error(
428        &mut self,
429        fr: RegionVid,
430        fr_origin: NllRegionVariableOrigin,
431        outlived_fr: RegionVid,
432        outlives_suggestion: &mut OutlivesSuggestionBuilder,
433    ) {
434        debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
435
436        let (blame_constraint, path) =
437            self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
438        let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
439
440        debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
441
442        // Check if we can use one of the "nice region errors".
443        if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
444            let infer_err = self.infcx.err_ctxt();
445            let nice =
446                NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), cause.span, o, f);
447            if let Some(diag) = nice.try_report_from_nll() {
448                self.buffer_error(diag);
449                return;
450            }
451        }
452
453        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
454            self.regioncx.universal_regions().is_local_free_region(fr),
455            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
456        );
457
458        debug!(
459            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
460            fr_is_local, outlived_fr_is_local, category
461        );
462
463        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span: cause.span };
464
465        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
466            (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
467                self.report_fnmut_error(&errci, kind)
468            }
469            (ConstraintCategory::Assignment, true, false)
470            | (ConstraintCategory::CallArgument(_), true, false) => {
471                let mut db = self.report_escaping_data_error(&errci);
472
473                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
474                outlives_suggestion.collect_constraint(fr, outlived_fr);
475
476                db
477            }
478            _ => {
479                let mut db = self.report_general_error(&errci);
480
481                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
482                outlives_suggestion.collect_constraint(fr, outlived_fr);
483
484                db
485            }
486        };
487
488        match variance_info {
489            ty::VarianceDiagInfo::None => {}
490            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
491                let (desc, note) = match ty.kind() {
492                    ty::RawPtr(ty, mutbl) => {
493                        assert_eq!(*mutbl, hir::Mutability::Mut);
494                        (
495                            format!("a mutable pointer to `{}`", ty),
496                            "mutable pointers are invariant over their type parameter".to_string(),
497                        )
498                    }
499                    ty::Ref(_, inner_ty, mutbl) => {
500                        assert_eq!(*mutbl, hir::Mutability::Mut);
501                        (
502                            format!("a mutable reference to `{inner_ty}`"),
503                            "mutable references are invariant over their type parameter"
504                                .to_string(),
505                        )
506                    }
507                    ty::Adt(adt, args) => {
508                        let generic_arg = args[param_index as usize];
509                        let identity_args =
510                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
511                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
512                        let base_generic_arg = identity_args[param_index as usize];
513                        let adt_desc = adt.descr();
514
515                        let desc = format!(
516                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
517                        );
518                        let note = format!(
519                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
520                        );
521                        (desc, note)
522                    }
523                    ty::FnDef(def_id, _) => {
524                        let name = self.infcx.tcx.item_name(*def_id);
525                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
526                        let desc = format!("a function pointer to `{name}`");
527                        let note = format!(
528                            "the function `{name}` is invariant over the parameter `{}`",
529                            identity_args[param_index as usize]
530                        );
531                        (desc, note)
532                    }
533                    _ => panic!("Unexpected type {ty:?}"),
534                };
535                diag.note(format!("requirement occurs because of {desc}",));
536                diag.note(note);
537                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
538            }
539        }
540
541        self.add_placeholder_from_predicate_note(&mut diag, &path);
542        self.add_sized_or_copy_bound_info(&mut diag, category, &path);
543
544        self.buffer_error(diag);
545    }
546
547    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
548    /// This function expects `fr` to be local and `outlived_fr` to not be local.
549    ///
550    /// ```text
551    /// error: captured variable cannot escape `FnMut` closure body
552    ///   --> $DIR/issue-53040.rs:15:8
553    ///    |
554    /// LL |     || &mut v;
555    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
556    ///    |     |
557    ///    |     inferred to be a `FnMut` closure
558    ///    |
559    ///    = note: `FnMut` closures only have access to their captured variables while they are
560    ///            executing...
561    ///    = note: ...therefore, returned references to captured variables will escape the closure
562    /// ```
563    #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
564    fn report_fnmut_error(
565        &self,
566        errci: &ErrorConstraintInfo<'tcx>,
567        kind: ReturnConstraint,
568    ) -> Diag<'infcx> {
569        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
570
571        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
572        if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() {
573            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
574        };
575
576        debug!("report_fnmut_error: output_ty={:?}", output_ty);
577
578        let err = FnMutError {
579            span: *span,
580            ty_err: match output_ty.kind() {
581                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
582                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
583                }
584                _ if output_ty.contains_closure() => {
585                    FnMutReturnTypeErr::ReturnClosure { span: *span }
586                }
587                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
588            },
589        };
590
591        let mut diag = self.dcx().create_err(err);
592
593        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
594            let def_id = match self.regioncx.universal_regions().defining_ty {
595                DefiningTy::Closure(def_id, _) => def_id,
596                ty => bug!("unexpected DefiningTy {:?}", ty),
597            };
598
599            let captured_place = &self.upvars[upvar_field.index()].place;
600            let defined_hir = match captured_place.base {
601                PlaceBase::Local(hirid) => Some(hirid),
602                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
603                _ => None,
604            };
605
606            if let Some(def_hir) = defined_hir {
607                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
608                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
609                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
610                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
611                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
612            }
613        }
614
615        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
616            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
617        }
618
619        self.suggest_move_on_borrowing_closure(&mut diag);
620
621        diag
622    }
623
624    /// Reports an error specifically for when data is escaping a closure.
625    ///
626    /// ```text
627    /// error: borrowed data escapes outside of function
628    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
629    ///    |
630    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
631    ///    |              - `x` is a reference that is only valid in the function body
632    /// LL |     // but ref_obj will not, so warn.
633    /// LL |     ref_obj(x)
634    ///    |     ^^^^^^^^^^ `x` escapes the function body here
635    /// ```
636    #[instrument(level = "debug", skip(self))]
637    fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
638        let ErrorConstraintInfo { span, category, .. } = errci;
639
640        let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
641            self.infcx.tcx,
642            self.body,
643            &self.local_names(),
644            &self.upvars,
645            errci.fr,
646        );
647        let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
648            self.infcx.tcx,
649            self.body,
650            &self.local_names(),
651            &self.upvars,
652            errci.outlived_fr,
653        );
654
655        let escapes_from =
656            self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
657
658        // Revert to the normal error in these cases.
659        // Assignments aren't "escapes" in function items.
660        if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
661            || (*category == ConstraintCategory::Assignment
662                && self.regioncx.universal_regions().defining_ty.is_fn_def())
663            || self.regioncx.universal_regions().defining_ty.is_const()
664        {
665            return self.report_general_error(errci);
666        }
667
668        let mut diag =
669            borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
670
671        if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
672            // FIXME: make this translatable
673            #[allow(rustc::diagnostic_outside_of_impl)]
674            #[allow(rustc::untranslatable_diagnostic)]
675            diag.span_label(
676                outlived_fr_span,
677                format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
678            );
679        }
680
681        // FIXME: make this translatable
682        #[allow(rustc::diagnostic_outside_of_impl)]
683        #[allow(rustc::untranslatable_diagnostic)]
684        if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
685            diag.span_label(
686                fr_span,
687                format!(
688                    "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
689                ),
690            );
691
692            diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
693        }
694
695        // Only show an extra note if we can find an 'error region' for both of the region
696        // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
697        // that don't help the user understand the error.
698        match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
699            (Some(f), Some(o)) => {
700                self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
701
702                let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
703                fr_region_name.highlight_region_name(&mut diag);
704                let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
705                outlived_fr_region_name.highlight_region_name(&mut diag);
706
707                // FIXME: make this translatable
708                #[allow(rustc::diagnostic_outside_of_impl)]
709                #[allow(rustc::untranslatable_diagnostic)]
710                diag.span_label(
711                    *span,
712                    format!(
713                        "{}requires that `{}` must outlive `{}`",
714                        category.description(),
715                        fr_region_name,
716                        outlived_fr_region_name,
717                    ),
718                );
719            }
720            _ => {}
721        }
722
723        diag
724    }
725
726    /// Reports a region inference error for the general case with named/synthesized lifetimes to
727    /// explain what is happening.
728    ///
729    /// ```text
730    /// error: unsatisfied lifetime constraints
731    ///   --> $DIR/regions-creating-enums3.rs:17:5
732    ///    |
733    /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
734    ///    |                -- -- lifetime `'b` defined here
735    ///    |                |
736    ///    |                lifetime `'a` defined here
737    /// LL |     ast::add(x, y)
738    ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
739    ///    |                    is returning data with lifetime `'b`
740    /// ```
741    #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
742    fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
743        let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
744
745        let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
746
747        let err = LifetimeOutliveErr { span: *span };
748        let mut diag = self.dcx().create_err(err);
749
750        // In certain scenarios, such as the one described in issue #118021,
751        // we might encounter a lifetime that cannot be named.
752        // These situations are bound to result in errors.
753        // To prevent an immediate ICE, we opt to create a dummy name instead.
754        let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
755            name: kw::UnderscoreLifetime,
756            source: RegionNameSource::Static,
757        });
758        fr_name.highlight_region_name(&mut diag);
759        let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
760        outlived_fr_name.highlight_region_name(&mut diag);
761
762        let err_category = if matches!(category, ConstraintCategory::Return(_))
763            && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
764        {
765            LifetimeReturnCategoryErr::WrongReturn {
766                span: *span,
767                mir_def_name,
768                outlived_fr_name,
769                fr_name: &fr_name,
770            }
771        } else {
772            LifetimeReturnCategoryErr::ShortReturn {
773                span: *span,
774                category_desc: category.description(),
775                free_region_name: &fr_name,
776                outlived_fr_name,
777            }
778        };
779
780        diag.subdiagnostic(err_category);
781
782        self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
783        self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
784        self.suggest_move_on_borrowing_closure(&mut diag);
785        self.suggest_deref_closure_return(&mut diag);
786
787        diag
788    }
789
790    /// Adds a suggestion to errors where an `impl Trait` is returned.
791    ///
792    /// ```text
793    /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
794    ///       a constraint
795    ///    |
796    /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
797    ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
798    /// ```
799    #[allow(rustc::diagnostic_outside_of_impl)]
800    #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
801    fn add_static_impl_trait_suggestion(
802        &self,
803        diag: &mut Diag<'_>,
804        fr: RegionVid,
805        // We need to pass `fr_name` - computing it again will label it twice.
806        fr_name: RegionName,
807        outlived_fr: RegionVid,
808    ) {
809        if let (Some(f), Some(outlived_f)) =
810            (self.to_error_region(fr), self.to_error_region(outlived_fr))
811        {
812            if outlived_f.kind() != ty::ReStatic {
813                return;
814            }
815            let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
816            let Some(suitable_region) = suitable_region else {
817                return;
818            };
819
820            let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
821
822            let param = if let Some(param) =
823                find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
824            {
825                param
826            } else {
827                return;
828            };
829
830            let lifetime =
831                if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
832
833            let arg = match param.param.pat.simple_ident() {
834                Some(simple_ident) => format!("argument `{simple_ident}`"),
835                None => "the argument".to_string(),
836            };
837            let captures = format!("captures data from {arg}");
838
839            if !fn_returns.is_empty() {
840                nice_region_error::suggest_new_region_bound(
841                    self.infcx.tcx,
842                    diag,
843                    fn_returns,
844                    lifetime.to_string(),
845                    Some(arg),
846                    captures,
847                    Some((param.param_ty_span, param.param_ty.to_string())),
848                    Some(suitable_region.scope),
849                );
850                return;
851            }
852
853            let Some((alias_tys, alias_span, lt_addition_span)) = self
854                .infcx
855                .tcx
856                .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
857            else {
858                return;
859            };
860
861            // in case the return type of the method is a type alias
862            let mut spans_suggs: Vec<_> = Vec::new();
863            for alias_ty in alias_tys {
864                if alias_ty.span.desugaring_kind().is_some() {
865                    // Skip `async` desugaring `impl Future`.
866                }
867                if let TyKind::TraitObject(_, lt) = alias_ty.kind {
868                    if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
869                        spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
870                    } else {
871                        spans_suggs.push((lt.ident.span, "'a".to_string()));
872                    }
873                }
874            }
875
876            if let Some(lt_addition_span) = lt_addition_span {
877                spans_suggs.push((lt_addition_span, "'a, ".to_string()));
878            } else {
879                spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
880            }
881
882            diag.multipart_suggestion_verbose(
883                format!(
884                    "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
885                ),
886                spans_suggs,
887                Applicability::MaybeIncorrect,
888            );
889        }
890    }
891
892    fn maybe_suggest_constrain_dyn_trait_impl(
893        &self,
894        diag: &mut Diag<'_>,
895        f: Region<'tcx>,
896        o: Region<'tcx>,
897        category: &ConstraintCategory<'tcx>,
898    ) {
899        if !o.is_static() {
900            return;
901        }
902
903        let tcx = self.infcx.tcx;
904
905        let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
906            let (fn_did, args) = match func_ty.kind() {
907                ty::FnDef(fn_did, args) => (fn_did, args),
908                _ => return,
909            };
910            debug!(?fn_did, ?args);
911
912            // Only suggest this on function calls, not closures
913            let ty = tcx.type_of(fn_did).instantiate_identity();
914            debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
915            if let ty::Closure(_, _) = ty.kind() {
916                return;
917            }
918
919            if let Ok(Some(instance)) = ty::Instance::try_resolve(
920                tcx,
921                self.infcx.typing_env(self.infcx.param_env),
922                *fn_did,
923                self.infcx.resolve_vars_if_possible(args),
924            ) {
925                instance
926            } else {
927                return;
928            }
929        } else {
930            return;
931        };
932
933        let param = match find_param_with_region(tcx, self.mir_def_id(), f, o) {
934            Some(param) => param,
935            None => return,
936        };
937        debug!(?param);
938
939        let mut visitor = TraitObjectVisitor(FxIndexSet::default());
940        visitor.visit_ty(param.param_ty);
941
942        let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
943            tcx,
944            instance.def_id(),
945            &visitor.0,
946        ) else {
947            return;
948        };
949
950        self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
951    }
952
953    #[allow(rustc::diagnostic_outside_of_impl)]
954    #[instrument(skip(self, err), level = "debug")]
955    fn suggest_constrain_dyn_trait_in_impl(
956        &self,
957        err: &mut Diag<'_>,
958        found_dids: &FxIndexSet<DefId>,
959        ident: Ident,
960        self_ty: &hir::Ty<'_>,
961    ) -> bool {
962        debug!("err: {:#?}", err);
963        let mut suggested = false;
964        for found_did in found_dids {
965            let mut traits = vec![];
966            let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
967            hir_v.visit_ty_unambig(self_ty);
968            debug!("trait spans found: {:?}", traits);
969            for span in &traits {
970                let mut multi_span: MultiSpan = vec![*span].into();
971                multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
972                multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
973                err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
974                err.span_suggestion_verbose(
975                    span.shrink_to_hi(),
976                    fluent::borrowck_implicit_static_relax,
977                    " + '_",
978                    Applicability::MaybeIncorrect,
979                );
980                suggested = true;
981            }
982        }
983        suggested
984    }
985
986    fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
987        let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
988            return;
989        };
990
991        let Some((ty_sub, _)) = self
992            .infcx
993            .tcx
994            .is_suitable_region(self.mir_def_id(), sub)
995            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
996        else {
997            return;
998        };
999
1000        let Some((ty_sup, _)) = self
1001            .infcx
1002            .tcx
1003            .is_suitable_region(self.mir_def_id(), sup)
1004            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1005        else {
1006            return;
1007        };
1008
1009        suggest_adding_lifetime_params(
1010            self.infcx.tcx,
1011            diag,
1012            self.mir_def_id(),
1013            sub,
1014            ty_sup,
1015            ty_sub,
1016        );
1017    }
1018
1019    #[allow(rustc::diagnostic_outside_of_impl)]
1020    /// When encountering a lifetime error caused by the return type of a closure, check the
1021    /// corresponding trait bound and see if dereferencing the closure return value would satisfy
1022    /// them. If so, we produce a structured suggestion.
1023    fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1024        let tcx = self.infcx.tcx;
1025
1026        // Get the closure return value and type.
1027        let closure_def_id = self.mir_def_id();
1028        let hir::Node::Expr(
1029            closure_expr @ hir::Expr {
1030                kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1031            },
1032        ) = tcx.hir_node_by_def_id(closure_def_id)
1033        else {
1034            return;
1035        };
1036        let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
1037        else {
1038            return;
1039        };
1040        let args = args.as_closure();
1041
1042        // Make sure that the parent expression is a method call.
1043        let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1044        let hir::Node::Expr(
1045            parent_expr @ hir::Expr {
1046                kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1047            },
1048        ) = tcx.hir_node(parent_expr_id)
1049        else {
1050            return;
1051        };
1052        let typeck_results = tcx.typeck(self.mir_def_id());
1053
1054        // We don't use `ty.peel_refs()` to get the number of `*`s needed to get the root type.
1055        let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1056        let mut peeled_ty = liberated_sig.output();
1057        let mut count = 0;
1058        while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1059            peeled_ty = ref_ty;
1060            count += 1;
1061        }
1062        if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1063            return;
1064        }
1065
1066        // Build a new closure where the return type is an owned value, instead of a ref.
1067        let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1068            tcx,
1069            ty::Binder::dummy(tcx.mk_fn_sig(
1070                liberated_sig.inputs().iter().copied(),
1071                peeled_ty,
1072                liberated_sig.c_variadic,
1073                hir::Safety::Safe,
1074                rustc_abi::ExternAbi::Rust,
1075            )),
1076        );
1077        let closure_ty = Ty::new_closure(
1078            tcx,
1079            closure_def_id.to_def_id(),
1080            ty::ClosureArgs::new(
1081                tcx,
1082                ty::ClosureArgsParts {
1083                    parent_args: args.parent_args(),
1084                    closure_kind_ty: args.kind_ty(),
1085                    tupled_upvars_ty: args.tupled_upvars_ty(),
1086                    closure_sig_as_fn_ptr_ty,
1087                },
1088            )
1089            .args,
1090        );
1091
1092        let Some((closure_arg_pos, _)) =
1093            call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1094        else {
1095            return;
1096        };
1097        // Get the type for the parameter corresponding to the argument the closure with the
1098        // lifetime error we had.
1099        let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1100            return;
1101        };
1102        let Some(input_arg) = tcx
1103            .fn_sig(method_def_id)
1104            .skip_binder()
1105            .inputs()
1106            .skip_binder()
1107            // Methods have a `self` arg, so `pos` is actually `+ 1` to match the method call arg.
1108            .get(closure_arg_pos + 1)
1109        else {
1110            return;
1111        };
1112        // If this isn't a param, then we can't substitute a new closure.
1113        let ty::Param(closure_param) = input_arg.kind() else { return };
1114
1115        // Get the arguments for the found method, only specifying that `Self` is the receiver type.
1116        let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1117        let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1118            if let ty::GenericParamDefKind::Lifetime = param.kind {
1119                tcx.lifetimes.re_erased.into()
1120            } else if param.index == 0 && param.name == kw::SelfUpper {
1121                possible_rcvr_ty.into()
1122            } else if param.index == closure_param.index {
1123                closure_ty.into()
1124            } else {
1125                self.infcx.var_for_def(parent_expr.span, param)
1126            }
1127        });
1128
1129        let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1130
1131        let ocx = ObligationCtxt::new(&self.infcx);
1132        ocx.register_obligations(preds.iter().map(|(pred, span)| {
1133            trace!(?pred);
1134            Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
1135        }));
1136
1137        if ocx.select_all_or_error().is_empty() && count > 0 {
1138            diag.span_suggestion_verbose(
1139                tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1140                fluent::borrowck_dereference_suggestion,
1141                "*".repeat(count),
1142                Applicability::MachineApplicable,
1143            );
1144        }
1145    }
1146
1147    #[allow(rustc::diagnostic_outside_of_impl)]
1148    fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1149        let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1150        let expr = &body.value.peel_blocks();
1151        let mut closure_span = None::<rustc_span::Span>;
1152        match expr.kind {
1153            hir::ExprKind::MethodCall(.., args, _) => {
1154                for arg in args {
1155                    if let hir::ExprKind::Closure(hir::Closure {
1156                        capture_clause: hir::CaptureBy::Ref,
1157                        ..
1158                    }) = arg.kind
1159                    {
1160                        closure_span = Some(arg.span.shrink_to_lo());
1161                        break;
1162                    }
1163                }
1164            }
1165            hir::ExprKind::Closure(hir::Closure {
1166                capture_clause: hir::CaptureBy::Ref,
1167                kind,
1168                ..
1169            }) => {
1170                if !matches!(
1171                    kind,
1172                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1173                        hir::CoroutineDesugaring::Async,
1174                        _
1175                    ),)
1176                ) {
1177                    closure_span = Some(expr.span.shrink_to_lo());
1178                }
1179            }
1180            _ => {}
1181        }
1182        if let Some(closure_span) = closure_span {
1183            diag.span_suggestion_verbose(
1184                closure_span,
1185                fluent::borrowck_move_closure_suggestion,
1186                "move ",
1187                Applicability::MaybeIncorrect,
1188            );
1189        }
1190    }
1191}