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