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