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