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::IllegalUniverse => "",
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.regioncx.find_outlives_blame_span(
373                        longer_fr,
374                        NllRegionVariableOrigin::Placeholder(placeholder),
375                        error_vid,
376                    );
377
378                    let universe = placeholder.universe;
379                    let universe_info = self.regioncx.universe_info(universe);
380
381                    universe_info.report_erroneous_element(self, placeholder, error_element, cause);
382                }
383
384                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
385                    if is_reported {
386                        self.report_region_error(
387                            longer_fr,
388                            fr_origin,
389                            shorter_fr,
390                            &mut outlives_suggestion,
391                        );
392                    } else {
393                        // We only report the first error, so as not to overwhelm the user. See
394                        // `RegRegionErrorKind` docs.
395                        //
396                        // FIXME: currently we do nothing with these, but perhaps we can do better?
397                        // FIXME: try collecting these constraints on the outlives suggestion
398                        // builder. Does it make the suggestions any better?
399                        debug!(
400                            "Unreported region error: can't prove that {:?}: {:?}",
401                            longer_fr, shorter_fr
402                        );
403                    }
404                }
405            }
406        }
407
408        // Emit one outlives suggestions for each MIR def we borrowck
409        outlives_suggestion.add_suggestion(self);
410    }
411
412    /// Report an error because the universal region `fr` was required to outlive
413    /// `outlived_fr` but it is not known to do so. For example:
414    ///
415    /// ```compile_fail
416    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
417    /// ```
418    ///
419    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
420    // FIXME: make this translatable
421    #[allow(rustc::diagnostic_outside_of_impl)]
422    #[allow(rustc::untranslatable_diagnostic)]
423    pub(crate) fn report_region_error(
424        &mut self,
425        fr: RegionVid,
426        fr_origin: NllRegionVariableOrigin,
427        outlived_fr: RegionVid,
428        outlives_suggestion: &mut OutlivesSuggestionBuilder,
429    ) {
430        debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
431
432        let (blame_constraint, path) = self.regioncx.best_blame_constraint(fr, fr_origin, |r| {
433            self.regioncx.provides_universal_region(r, fr, outlived_fr)
434        });
435        let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
436
437        debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
438
439        // Check if we can use one of the "nice region errors".
440        if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
441            let infer_err = self.infcx.err_ctxt();
442            let nice =
443                NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), cause.span, o, f);
444            if let Some(diag) = nice.try_report_from_nll() {
445                self.buffer_error(diag);
446                return;
447            }
448        }
449
450        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
451            self.regioncx.universal_regions().is_local_free_region(fr),
452            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
453        );
454
455        debug!(
456            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
457            fr_is_local, outlived_fr_is_local, category
458        );
459
460        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span: cause.span };
461
462        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
463            (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
464                self.report_fnmut_error(&errci, kind)
465            }
466            (ConstraintCategory::Assignment, true, false)
467            | (ConstraintCategory::CallArgument(_), true, false) => {
468                let mut db = self.report_escaping_data_error(&errci);
469
470                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
471                outlives_suggestion.collect_constraint(fr, outlived_fr);
472
473                db
474            }
475            _ => {
476                let mut db = self.report_general_error(&errci);
477
478                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
479                outlives_suggestion.collect_constraint(fr, outlived_fr);
480
481                db
482            }
483        };
484
485        match variance_info {
486            ty::VarianceDiagInfo::None => {}
487            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
488                let (desc, note) = match ty.kind() {
489                    ty::RawPtr(ty, mutbl) => {
490                        assert_eq!(*mutbl, hir::Mutability::Mut);
491                        (
492                            format!("a mutable pointer to `{}`", ty),
493                            "mutable pointers are invariant over their type parameter".to_string(),
494                        )
495                    }
496                    ty::Ref(_, inner_ty, mutbl) => {
497                        assert_eq!(*mutbl, hir::Mutability::Mut);
498                        (
499                            format!("a mutable reference to `{inner_ty}`"),
500                            "mutable references are invariant over their type parameter"
501                                .to_string(),
502                        )
503                    }
504                    ty::Adt(adt, args) => {
505                        let generic_arg = args[param_index as usize];
506                        let identity_args =
507                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
508                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
509                        let base_generic_arg = identity_args[param_index as usize];
510                        let adt_desc = adt.descr();
511
512                        let desc = format!(
513                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
514                        );
515                        let note = format!(
516                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
517                        );
518                        (desc, note)
519                    }
520                    ty::FnDef(def_id, _) => {
521                        let name = self.infcx.tcx.item_name(*def_id);
522                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
523                        let desc = format!("a function pointer to `{name}`");
524                        let note = format!(
525                            "the function `{name}` is invariant over the parameter `{}`",
526                            identity_args[param_index as usize]
527                        );
528                        (desc, note)
529                    }
530                    _ => panic!("Unexpected type {ty:?}"),
531                };
532                diag.note(format!("requirement occurs because of {desc}",));
533                diag.note(note);
534                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
535            }
536        }
537
538        self.add_placeholder_from_predicate_note(&mut diag, &path);
539        self.add_sized_or_copy_bound_info(&mut diag, category, &path);
540
541        self.buffer_error(diag);
542    }
543
544    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
545    /// This function expects `fr` to be local and `outlived_fr` to not be local.
546    ///
547    /// ```text
548    /// error: captured variable cannot escape `FnMut` closure body
549    ///   --> $DIR/issue-53040.rs:15:8
550    ///    |
551    /// LL |     || &mut v;
552    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
553    ///    |     |
554    ///    |     inferred to be a `FnMut` closure
555    ///    |
556    ///    = note: `FnMut` closures only have access to their captured variables while they are
557    ///            executing...
558    ///    = note: ...therefore, returned references to captured variables will escape the closure
559    /// ```
560    #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
561    fn report_fnmut_error(
562        &self,
563        errci: &ErrorConstraintInfo<'tcx>,
564        kind: ReturnConstraint,
565    ) -> Diag<'infcx> {
566        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
567
568        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
569        if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() {
570            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
571        };
572
573        debug!("report_fnmut_error: output_ty={:?}", output_ty);
574
575        let err = FnMutError {
576            span: *span,
577            ty_err: match output_ty.kind() {
578                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
579                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
580                }
581                _ if output_ty.contains_closure() => {
582                    FnMutReturnTypeErr::ReturnClosure { span: *span }
583                }
584                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
585            },
586        };
587
588        let mut diag = self.dcx().create_err(err);
589
590        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
591            let def_id = match self.regioncx.universal_regions().defining_ty {
592                DefiningTy::Closure(def_id, _) => def_id,
593                ty => bug!("unexpected DefiningTy {:?}", ty),
594            };
595
596            let captured_place = &self.upvars[upvar_field.index()].place;
597            let defined_hir = match captured_place.base {
598                PlaceBase::Local(hirid) => Some(hirid),
599                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
600                _ => None,
601            };
602
603            if let Some(def_hir) = defined_hir {
604                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
605                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
606                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
607                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
608                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
609            }
610        }
611
612        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
613            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
614        }
615
616        self.suggest_move_on_borrowing_closure(&mut diag);
617
618        diag
619    }
620
621    /// Reports an error specifically for when data is escaping a closure.
622    ///
623    /// ```text
624    /// error: borrowed data escapes outside of function
625    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
626    ///    |
627    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
628    ///    |              - `x` is a reference that is only valid in the function body
629    /// LL |     // but ref_obj will not, so warn.
630    /// LL |     ref_obj(x)
631    ///    |     ^^^^^^^^^^ `x` escapes the function body here
632    /// ```
633    #[instrument(level = "debug", skip(self))]
634    fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
635        let ErrorConstraintInfo { span, category, .. } = errci;
636
637        let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
638            self.infcx.tcx,
639            self.body,
640            &self.local_names(),
641            &self.upvars,
642            errci.fr,
643        );
644        let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
645            self.infcx.tcx,
646            self.body,
647            &self.local_names(),
648            &self.upvars,
649            errci.outlived_fr,
650        );
651
652        let escapes_from =
653            self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
654
655        // Revert to the normal error in these cases.
656        // Assignments aren't "escapes" in function items.
657        if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
658            || (*category == ConstraintCategory::Assignment
659                && self.regioncx.universal_regions().defining_ty.is_fn_def())
660            || self.regioncx.universal_regions().defining_ty.is_const()
661        {
662            return self.report_general_error(errci);
663        }
664
665        let mut diag =
666            borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
667
668        if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
669            // FIXME: make this translatable
670            #[allow(rustc::diagnostic_outside_of_impl)]
671            #[allow(rustc::untranslatable_diagnostic)]
672            diag.span_label(
673                outlived_fr_span,
674                format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
675            );
676        }
677
678        // FIXME: make this translatable
679        #[allow(rustc::diagnostic_outside_of_impl)]
680        #[allow(rustc::untranslatable_diagnostic)]
681        if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
682            diag.span_label(
683                fr_span,
684                format!(
685                    "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
686                ),
687            );
688
689            diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
690        }
691
692        // Only show an extra note if we can find an 'error region' for both of the region
693        // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
694        // that don't help the user understand the error.
695        match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
696            (Some(f), Some(o)) => {
697                self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
698
699                let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
700                fr_region_name.highlight_region_name(&mut diag);
701                let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
702                outlived_fr_region_name.highlight_region_name(&mut diag);
703
704                // FIXME: make this translatable
705                #[allow(rustc::diagnostic_outside_of_impl)]
706                #[allow(rustc::untranslatable_diagnostic)]
707                diag.span_label(
708                    *span,
709                    format!(
710                        "{}requires that `{}` must outlive `{}`",
711                        category.description(),
712                        fr_region_name,
713                        outlived_fr_region_name,
714                    ),
715                );
716            }
717            _ => {}
718        }
719
720        diag
721    }
722
723    /// Reports a region inference error for the general case with named/synthesized lifetimes to
724    /// explain what is happening.
725    ///
726    /// ```text
727    /// error: unsatisfied lifetime constraints
728    ///   --> $DIR/regions-creating-enums3.rs:17:5
729    ///    |
730    /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
731    ///    |                -- -- lifetime `'b` defined here
732    ///    |                |
733    ///    |                lifetime `'a` defined here
734    /// LL |     ast::add(x, y)
735    ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
736    ///    |                    is returning data with lifetime `'b`
737    /// ```
738    #[allow(rustc::diagnostic_outside_of_impl)] // FIXME
739    fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
740        let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
741
742        let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
743
744        let err = LifetimeOutliveErr { span: *span };
745        let mut diag = self.dcx().create_err(err);
746
747        // In certain scenarios, such as the one described in issue #118021,
748        // we might encounter a lifetime that cannot be named.
749        // These situations are bound to result in errors.
750        // To prevent an immediate ICE, we opt to create a dummy name instead.
751        let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
752            name: kw::UnderscoreLifetime,
753            source: RegionNameSource::Static,
754        });
755        fr_name.highlight_region_name(&mut diag);
756        let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
757        outlived_fr_name.highlight_region_name(&mut diag);
758
759        let err_category = if matches!(category, ConstraintCategory::Return(_))
760            && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
761        {
762            LifetimeReturnCategoryErr::WrongReturn {
763                span: *span,
764                mir_def_name,
765                outlived_fr_name,
766                fr_name: &fr_name,
767            }
768        } else {
769            LifetimeReturnCategoryErr::ShortReturn {
770                span: *span,
771                category_desc: category.description(),
772                free_region_name: &fr_name,
773                outlived_fr_name,
774            }
775        };
776
777        diag.subdiagnostic(err_category);
778
779        self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
780        self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
781        self.suggest_move_on_borrowing_closure(&mut diag);
782        self.suggest_deref_closure_return(&mut diag);
783
784        diag
785    }
786
787    /// Adds a suggestion to errors where an `impl Trait` is returned.
788    ///
789    /// ```text
790    /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
791    ///       a constraint
792    ///    |
793    /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
794    ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
795    /// ```
796    #[allow(rustc::diagnostic_outside_of_impl)]
797    #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
798    fn add_static_impl_trait_suggestion(
799        &self,
800        diag: &mut Diag<'_>,
801        fr: RegionVid,
802        // We need to pass `fr_name` - computing it again will label it twice.
803        fr_name: RegionName,
804        outlived_fr: RegionVid,
805    ) {
806        if let (Some(f), Some(outlived_f)) =
807            (self.to_error_region(fr), self.to_error_region(outlived_fr))
808        {
809            if outlived_f.kind() != ty::ReStatic {
810                return;
811            }
812            let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
813            let Some(suitable_region) = suitable_region else {
814                return;
815            };
816
817            let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
818
819            let param = if let Some(param) =
820                find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
821            {
822                param
823            } else {
824                return;
825            };
826
827            let lifetime =
828                if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
829
830            let arg = match param.param.pat.simple_ident() {
831                Some(simple_ident) => format!("argument `{simple_ident}`"),
832                None => "the argument".to_string(),
833            };
834            let captures = format!("captures data from {arg}");
835
836            if !fn_returns.is_empty() {
837                nice_region_error::suggest_new_region_bound(
838                    self.infcx.tcx,
839                    diag,
840                    fn_returns,
841                    lifetime.to_string(),
842                    Some(arg),
843                    captures,
844                    Some((param.param_ty_span, param.param_ty.to_string())),
845                    Some(suitable_region.scope),
846                );
847                return;
848            }
849
850            let Some((alias_tys, alias_span, lt_addition_span)) = self
851                .infcx
852                .tcx
853                .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
854            else {
855                return;
856            };
857
858            // in case the return type of the method is a type alias
859            let mut spans_suggs: Vec<_> = Vec::new();
860            for alias_ty in alias_tys {
861                if alias_ty.span.desugaring_kind().is_some() {
862                    // Skip `async` desugaring `impl Future`.
863                }
864                if let TyKind::TraitObject(_, lt) = alias_ty.kind {
865                    if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
866                        spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
867                    } else {
868                        spans_suggs.push((lt.ident.span, "'a".to_string()));
869                    }
870                }
871            }
872
873            if let Some(lt_addition_span) = lt_addition_span {
874                spans_suggs.push((lt_addition_span, "'a, ".to_string()));
875            } else {
876                spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
877            }
878
879            diag.multipart_suggestion_verbose(
880                format!(
881                    "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
882                ),
883                spans_suggs,
884                Applicability::MaybeIncorrect,
885            );
886        }
887    }
888
889    fn maybe_suggest_constrain_dyn_trait_impl(
890        &self,
891        diag: &mut Diag<'_>,
892        f: Region<'tcx>,
893        o: Region<'tcx>,
894        category: &ConstraintCategory<'tcx>,
895    ) {
896        if !o.is_static() {
897            return;
898        }
899
900        let tcx = self.infcx.tcx;
901
902        let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category {
903            let (fn_did, args) = match func_ty.kind() {
904                ty::FnDef(fn_did, args) => (fn_did, args),
905                _ => return,
906            };
907            debug!(?fn_did, ?args);
908
909            // Only suggest this on function calls, not closures
910            let ty = tcx.type_of(fn_did).instantiate_identity();
911            debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
912            if let ty::Closure(_, _) = ty.kind() {
913                return;
914            }
915
916            if let Ok(Some(instance)) = ty::Instance::try_resolve(
917                tcx,
918                self.infcx.typing_env(self.infcx.param_env),
919                *fn_did,
920                self.infcx.resolve_vars_if_possible(args),
921            ) {
922                instance
923            } else {
924                return;
925            }
926        } else {
927            return;
928        };
929
930        let param = match find_param_with_region(tcx, self.mir_def_id(), f, o) {
931            Some(param) => param,
932            None => return,
933        };
934        debug!(?param);
935
936        let mut visitor = TraitObjectVisitor(FxIndexSet::default());
937        visitor.visit_ty(param.param_ty);
938
939        let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
940            tcx,
941            instance.def_id(),
942            &visitor.0,
943        ) else {
944            return;
945        };
946
947        self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
948    }
949
950    #[allow(rustc::diagnostic_outside_of_impl)]
951    #[instrument(skip(self, err), level = "debug")]
952    fn suggest_constrain_dyn_trait_in_impl(
953        &self,
954        err: &mut Diag<'_>,
955        found_dids: &FxIndexSet<DefId>,
956        ident: Ident,
957        self_ty: &hir::Ty<'_>,
958    ) -> bool {
959        debug!("err: {:#?}", err);
960        let mut suggested = false;
961        for found_did in found_dids {
962            let mut traits = vec![];
963            let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
964            hir_v.visit_ty_unambig(self_ty);
965            debug!("trait spans found: {:?}", traits);
966            for span in &traits {
967                let mut multi_span: MultiSpan = vec![*span].into();
968                multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
969                multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
970                err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
971                err.span_suggestion_verbose(
972                    span.shrink_to_hi(),
973                    fluent::borrowck_implicit_static_relax,
974                    " + '_",
975                    Applicability::MaybeIncorrect,
976                );
977                suggested = true;
978            }
979        }
980        suggested
981    }
982
983    fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
984        let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
985            return;
986        };
987
988        let Some((ty_sub, _)) = self
989            .infcx
990            .tcx
991            .is_suitable_region(self.mir_def_id(), sub)
992            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
993        else {
994            return;
995        };
996
997        let Some((ty_sup, _)) = self
998            .infcx
999            .tcx
1000            .is_suitable_region(self.mir_def_id(), sup)
1001            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1002        else {
1003            return;
1004        };
1005
1006        suggest_adding_lifetime_params(
1007            self.infcx.tcx,
1008            diag,
1009            self.mir_def_id(),
1010            sub,
1011            ty_sup,
1012            ty_sub,
1013        );
1014    }
1015
1016    #[allow(rustc::diagnostic_outside_of_impl)]
1017    /// When encountering a lifetime error caused by the return type of a closure, check the
1018    /// corresponding trait bound and see if dereferencing the closure return value would satisfy
1019    /// them. If so, we produce a structured suggestion.
1020    fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1021        let tcx = self.infcx.tcx;
1022
1023        // Get the closure return value and type.
1024        let closure_def_id = self.mir_def_id();
1025        let hir::Node::Expr(
1026            closure_expr @ hir::Expr {
1027                kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1028            },
1029        ) = tcx.hir_node_by_def_id(closure_def_id)
1030        else {
1031            return;
1032        };
1033        let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
1034        else {
1035            return;
1036        };
1037        let args = args.as_closure();
1038
1039        // Make sure that the parent expression is a method call.
1040        let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1041        let hir::Node::Expr(
1042            parent_expr @ hir::Expr {
1043                kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1044            },
1045        ) = tcx.hir_node(parent_expr_id)
1046        else {
1047            return;
1048        };
1049        let typeck_results = tcx.typeck(self.mir_def_id());
1050
1051        // We don't use `ty.peel_refs()` to get the number of `*`s needed to get the root type.
1052        let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1053        let mut peeled_ty = liberated_sig.output();
1054        let mut count = 0;
1055        while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1056            peeled_ty = ref_ty;
1057            count += 1;
1058        }
1059        if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1060            return;
1061        }
1062
1063        // Build a new closure where the return type is an owned value, instead of a ref.
1064        let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1065            tcx,
1066            ty::Binder::dummy(tcx.mk_fn_sig(
1067                liberated_sig.inputs().iter().copied(),
1068                peeled_ty,
1069                liberated_sig.c_variadic,
1070                hir::Safety::Safe,
1071                rustc_abi::ExternAbi::Rust,
1072            )),
1073        );
1074        let closure_ty = Ty::new_closure(
1075            tcx,
1076            closure_def_id.to_def_id(),
1077            ty::ClosureArgs::new(
1078                tcx,
1079                ty::ClosureArgsParts {
1080                    parent_args: args.parent_args(),
1081                    closure_kind_ty: args.kind_ty(),
1082                    tupled_upvars_ty: args.tupled_upvars_ty(),
1083                    closure_sig_as_fn_ptr_ty,
1084                },
1085            )
1086            .args,
1087        );
1088
1089        let Some((closure_arg_pos, _)) =
1090            call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1091        else {
1092            return;
1093        };
1094        // Get the type for the parameter corresponding to the argument the closure with the
1095        // lifetime error we had.
1096        let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1097            return;
1098        };
1099        let Some(input_arg) = tcx
1100            .fn_sig(method_def_id)
1101            .skip_binder()
1102            .inputs()
1103            .skip_binder()
1104            // Methods have a `self` arg, so `pos` is actually `+ 1` to match the method call arg.
1105            .get(closure_arg_pos + 1)
1106        else {
1107            return;
1108        };
1109        // If this isn't a param, then we can't substitute a new closure.
1110        let ty::Param(closure_param) = input_arg.kind() else { return };
1111
1112        // Get the arguments for the found method, only specifying that `Self` is the receiver type.
1113        let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1114        let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1115            if let ty::GenericParamDefKind::Lifetime = param.kind {
1116                tcx.lifetimes.re_erased.into()
1117            } else if param.index == 0 && param.name == kw::SelfUpper {
1118                possible_rcvr_ty.into()
1119            } else if param.index == closure_param.index {
1120                closure_ty.into()
1121            } else {
1122                self.infcx.var_for_def(parent_expr.span, param)
1123            }
1124        });
1125
1126        let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1127
1128        let ocx = ObligationCtxt::new(&self.infcx);
1129        ocx.register_obligations(preds.iter().map(|(pred, span)| {
1130            trace!(?pred);
1131            Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
1132        }));
1133
1134        if ocx.select_all_or_error().is_empty() && count > 0 {
1135            diag.span_suggestion_verbose(
1136                tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1137                fluent::borrowck_dereference_suggestion,
1138                "*".repeat(count),
1139                Applicability::MachineApplicable,
1140            );
1141        }
1142    }
1143
1144    #[allow(rustc::diagnostic_outside_of_impl)]
1145    fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1146        let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1147        let expr = &body.value.peel_blocks();
1148        let mut closure_span = None::<rustc_span::Span>;
1149        match expr.kind {
1150            hir::ExprKind::MethodCall(.., args, _) => {
1151                for arg in args {
1152                    if let hir::ExprKind::Closure(hir::Closure {
1153                        capture_clause: hir::CaptureBy::Ref,
1154                        ..
1155                    }) = arg.kind
1156                    {
1157                        closure_span = Some(arg.span.shrink_to_lo());
1158                        break;
1159                    }
1160                }
1161            }
1162            hir::ExprKind::Closure(hir::Closure {
1163                capture_clause: hir::CaptureBy::Ref,
1164                kind,
1165                ..
1166            }) => {
1167                if !matches!(
1168                    kind,
1169                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1170                        hir::CoroutineDesugaring::Async,
1171                        _
1172                    ),)
1173                ) {
1174                    closure_span = Some(expr.span.shrink_to_lo());
1175                }
1176            }
1177            _ => {}
1178        }
1179        if let Some(closure_span) = closure_span {
1180            diag.span_suggestion_verbose(
1181                closure_span,
1182                fluent::borrowck_move_closure_suggestion,
1183                "move ",
1184                Applicability::MaybeIncorrect,
1185            );
1186        }
1187    }
1188}