Skip to main content

rustc_borrowck/diagnostics/
region_errors.rs

1//! Error reporting machinery for lifetime errors.
2
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
5use rustc_hir as hir;
6use rustc_hir::GenericBound::Trait;
7use rustc_hir::QPath::Resolved;
8use rustc_hir::WherePredicateKind::BoundPredicate;
9use rustc_hir::def::Res::Def;
10use rustc_hir::def_id::DefId;
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate};
13use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin};
14use rustc_middle::bug;
15use rustc_middle::hir::place::PlaceBase;
16use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
17use rustc_middle::ty::{
18    self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions,
19};
20use rustc_span::{Ident, Span, kw};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::error_reporting::infer::nice_region_error::{
23    self, HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, find_anon_type,
24    find_param_with_region, suggest_adding_lifetime_params,
25};
26use rustc_trait_selection::infer::InferCtxtExt;
27use rustc_trait_selection::traits::{Obligation, ObligationCtxt};
28use tracing::{debug, instrument, trace};
29
30use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource};
31use crate::nll::ConstraintDescription;
32use crate::region_infer::values::RegionElement;
33use crate::region_infer::{BlameConstraint, TypeTest};
34use crate::session_diagnostics::{
35    FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr,
36    LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
37};
38use crate::universal_regions::DefiningTy;
39use crate::{MirBorrowckCtxt, borrowck_errors, fluent_generated as fluent};
40
41impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
42    fn description(&self) -> &'static str {
43        // Must end with a space. Allows for empty names to be provided.
44        match self {
45            ConstraintCategory::Assignment => "assignment ",
46            ConstraintCategory::Return(_) => "returning this value ",
47            ConstraintCategory::Yield => "yielding this value ",
48            ConstraintCategory::UseAsConst => "using this value as a constant ",
49            ConstraintCategory::UseAsStatic => "using this value as a static ",
50            ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ",
51            ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ",
52            ConstraintCategory::CallArgument(_) => "argument ",
53            ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => "generic argument ",
54            ConstraintCategory::TypeAnnotation(_) => "type annotation ",
55            ConstraintCategory::SizedBound => "proving this value is `Sized` ",
56            ConstraintCategory::CopyBound => "copying this value ",
57            ConstraintCategory::OpaqueType => "opaque type ",
58            ConstraintCategory::ClosureUpvar(_) => "closure capture ",
59            ConstraintCategory::Usage => "this usage ",
60            ConstraintCategory::Predicate(_)
61            | ConstraintCategory::Boring
62            | ConstraintCategory::BoringNoLocation
63            | ConstraintCategory::Internal
64            | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
65        }
66    }
67}
68
69/// A collection of errors encountered during region inference. This is needed to efficiently
70/// report errors after borrow checking.
71///
72/// Usually we expect this to either be empty or contain a small number of items, so we can avoid
73/// allocation most of the time.
74pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
75
76impl<'tcx> RegionErrors<'tcx> {
77    pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
78        Self(::alloc::vec::Vec::new()vec![], tcx)
79    }
80    #[track_caller]
81    pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
82        let val = val.into();
83        let guar = self.1.sess.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", val))
    })format!("{val:?}"));
84        self.0.push((val, guar));
85    }
86    pub(crate) fn is_empty(&self) -> bool {
87        self.0.is_empty()
88    }
89    pub(crate) fn into_iter(
90        self,
91    ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
92        self.0.into_iter()
93    }
94}
95
96impl std::fmt::Debug for RegionErrors<'_> {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_tuple("RegionErrors").field(&self.0).finish()
99    }
100}
101
102#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionErrorKind<'tcx> {
    #[inline]
    fn clone(&self) -> RegionErrorKind<'tcx> {
        match self {
            RegionErrorKind::TypeTestError { type_test: __self_0 } =>
                RegionErrorKind::TypeTestError {
                    type_test: ::core::clone::Clone::clone(__self_0),
                },
            RegionErrorKind::BoundUniversalRegionError {
                longer_fr: __self_0,
                error_element: __self_1,
                placeholder: __self_2 } =>
                RegionErrorKind::BoundUniversalRegionError {
                    longer_fr: ::core::clone::Clone::clone(__self_0),
                    error_element: ::core::clone::Clone::clone(__self_1),
                    placeholder: ::core::clone::Clone::clone(__self_2),
                },
            RegionErrorKind::RegionError {
                fr_origin: __self_0,
                longer_fr: __self_1,
                shorter_fr: __self_2,
                is_reported: __self_3 } =>
                RegionErrorKind::RegionError {
                    fr_origin: ::core::clone::Clone::clone(__self_0),
                    longer_fr: ::core::clone::Clone::clone(__self_1),
                    shorter_fr: ::core::clone::Clone::clone(__self_2),
                    is_reported: ::core::clone::Clone::clone(__self_3),
                },
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for RegionErrorKind<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RegionErrorKind::TypeTestError { type_test: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TypeTestError", "type_test", &__self_0),
            RegionErrorKind::BoundUniversalRegionError {
                longer_fr: __self_0,
                error_element: __self_1,
                placeholder: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "BoundUniversalRegionError", "longer_fr", __self_0,
                    "error_element", __self_1, "placeholder", &__self_2),
            RegionErrorKind::RegionError {
                fr_origin: __self_0,
                longer_fr: __self_1,
                shorter_fr: __self_2,
                is_reported: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "RegionError", "fr_origin", __self_0, "longer_fr", __self_1,
                    "shorter_fr", __self_2, "is_reported", &__self_3),
        }
    }
}Debug)]
103pub(crate) enum RegionErrorKind<'tcx> {
104    /// A generic bound failure for a type test (`T: 'a`).
105    TypeTestError { type_test: TypeTest<'tcx> },
106
107    /// Higher-ranked subtyping error.
108    BoundUniversalRegionError {
109        /// The placeholder free region.
110        longer_fr: RegionVid,
111        /// The region element that erroneously must be outlived by `longer_fr`.
112        error_element: RegionElement<'tcx>,
113        /// The placeholder region.
114        placeholder: ty::PlaceholderRegion<'tcx>,
115    },
116
117    /// Any other lifetime error.
118    RegionError {
119        /// The origin of the region.
120        fr_origin: NllRegionVariableOrigin<'tcx>,
121        /// The region that should outlive `shorter_fr`.
122        longer_fr: RegionVid,
123        /// The region that should be shorter, but we can't prove it.
124        shorter_fr: RegionVid,
125        /// Indicates whether this is a reported error. We currently only report the first error
126        /// encountered and leave the rest unreported so as not to overwhelm the user.
127        is_reported: bool,
128    },
129}
130
131/// Information about the various region constraints involved in a borrow checker error.
132#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ErrorConstraintInfo<'tcx> {
    #[inline]
    fn clone(&self) -> ErrorConstraintInfo<'tcx> {
        ErrorConstraintInfo {
            fr: ::core::clone::Clone::clone(&self.fr),
            outlived_fr: ::core::clone::Clone::clone(&self.outlived_fr),
            category: ::core::clone::Clone::clone(&self.category),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ErrorConstraintInfo<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ErrorConstraintInfo", "fr", &self.fr, "outlived_fr",
            &self.outlived_fr, "category", &self.category, "span",
            &&self.span)
    }
}Debug)]
133pub(crate) struct ErrorConstraintInfo<'tcx> {
134    // fr: outlived_fr
135    pub(super) fr: RegionVid,
136    pub(super) outlived_fr: RegionVid,
137
138    // Category and span for best blame constraint
139    pub(super) category: ConstraintCategory<'tcx>,
140    pub(super) span: Span,
141}
142
143impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
144    /// Converts a region inference variable into a `ty::Region` that
145    /// we can use for error reporting. If `r` is universally bound,
146    /// then we use the name that we have on record for it. If `r` is
147    /// existentially bound, then we check its inferred value and try
148    /// to find a good name from that. Returns `None` if we can't find
149    /// one (e.g., this is just some random part of the CFG).
150    pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
151        self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
152    }
153
154    /// Returns the `RegionVid` corresponding to the region returned by
155    /// `to_error_region`.
156    pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
157        if self.regioncx.universal_regions().is_universal_region(r) {
158            Some(r)
159        } else {
160            // We just want something nameable, even if it's not
161            // actually an upper bound.
162            let upper_bound = self.regioncx.approx_universal_upper_bound(r);
163
164            if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
165                self.to_error_region_vid(upper_bound)
166            } else {
167                None
168            }
169        }
170    }
171
172    /// Map the regions in the type to named regions, where possible.
173    fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
174    where
175        T: TypeFoldable<TyCtxt<'tcx>>,
176    {
177        fold_regions(tcx, ty, |region, _| match region.kind() {
178            ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
179            _ => region,
180        })
181    }
182
183    /// Returns `true` if a closure is inferred to be an `FnMut` closure.
184    fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
185        if let Some(r) = self.to_error_region(fr)
186            && let ty::ReLateParam(late_param) = r.kind()
187            && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
188            && let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty
189        {
190            return args.as_closure().kind() == ty::ClosureKind::FnMut;
191        }
192
193        false
194    }
195
196    // For generic associated types (GATs) which implied 'static requirement
197    // from higher-ranked trait bounds (HRTB). Try to locate span of the trait
198    // and the span which bounded to the trait for adding 'static lifetime suggestion
199    fn suggest_static_lifetime_for_gat_from_hrtb(
200        &self,
201        diag: &mut Diag<'_>,
202        lower_bound: RegionVid,
203    ) {
204        let tcx = self.infcx.tcx;
205
206        // find generic associated types in the given region 'lower_bound'
207        let gat_id_and_generics = self
208            .regioncx
209            .placeholders_contained_in(lower_bound)
210            .map(|placeholder| {
211                if let Some(id) = placeholder.bound.kind.get_id()
212                    && let Some(placeholder_id) = id.as_local()
213                    && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
214                    && let Some(generics_impl) =
215                        tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
216                {
217                    Some((gat_hir_id, generics_impl))
218                } else {
219                    None
220                }
221            })
222            .collect::<Vec<_>>();
223        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:223",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(223u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["gat_id_and_generics"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&gat_id_and_generics)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?gat_id_and_generics);
224
225        // Look for the where-bound which introduces the placeholder.
226        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
227        // and `T: for<'a> Trait`<'a>.
228        let mut hrtb_bounds = ::alloc::vec::Vec::new()vec![];
229        gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
230            for pred in generics.predicates {
231                let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
232                    pred.kind
233                else {
234                    continue;
235                };
236                if bound_generic_params
237                    .iter()
238                    .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
239                    .is_some()
240                {
241                    for bound in *bounds {
242                        hrtb_bounds.push(bound);
243                    }
244                } else {
245                    for bound in *bounds {
246                        if let Trait(trait_bound) = bound {
247                            if trait_bound
248                                .bound_generic_params
249                                .iter()
250                                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
251                                .is_some()
252                            {
253                                hrtb_bounds.push(bound);
254                                return;
255                            }
256                        }
257                    }
258                }
259            }
260        });
261        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:261",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(261u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["hrtb_bounds"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&hrtb_bounds)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?hrtb_bounds);
262
263        let mut suggestions = ::alloc::vec::Vec::new()vec![];
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            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:276",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(276u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["generics_fn"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&generics_fn)
                                            as &dyn Value))])
            });
    } else { ; }
};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        let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
313        for (nll_error, _) in nll_errors.into_iter() {
314            match nll_error {
315                RegionErrorKind::TypeTestError { type_test } => {
316                    // Try to convert the lower-bound region into something named we can print for
317                    // the user.
318                    let lower_bound_region = self.to_error_region(type_test.lower_bound);
319
320                    let type_test_span = type_test.span;
321
322                    if let Some(lower_bound_region) = lower_bound_region {
323                        let generic_ty = self.name_regions(
324                            self.infcx.tcx,
325                            type_test.generic_kind.to_ty(self.infcx.tcx),
326                        );
327                        let origin =
328                            SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
329                        self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
330                            self.body.source.def_id().expect_local(),
331                            type_test_span,
332                            Some(origin),
333                            self.name_regions(self.infcx.tcx, type_test.generic_kind),
334                            lower_bound_region,
335                        ));
336                    } else {
337                        // FIXME. We should handle this case better. It
338                        // indicates that we have e.g., some region variable
339                        // whose value is like `'a+'b` where `'a` and `'b` are
340                        // distinct unrelated universal regions that are not
341                        // known to outlive one another. It'd be nice to have
342                        // some examples where this arises to decide how best
343                        // to report it; we could probably handle it by
344                        // iterating over the universal regions and reporting
345                        // an error that multiple bounds are required.
346                        let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
347                            kind: type_test.generic_kind.to_string(),
348                            span: type_test_span,
349                        });
350
351                        // Add notes and suggestions for the case of 'static lifetime
352                        // implied but not specified when a generic associated types
353                        // are from higher-ranked trait bounds
354                        self.suggest_static_lifetime_for_gat_from_hrtb(
355                            &mut diag,
356                            type_test.lower_bound,
357                        );
358
359                        self.buffer_error(diag);
360                    }
361                }
362
363                RegionErrorKind::BoundUniversalRegionError {
364                    longer_fr,
365                    placeholder,
366                    error_element,
367                } => {
368                    let error_vid = self.regioncx.region_from_element(longer_fr, &error_element);
369
370                    // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
371                    let cause = self
372                        .regioncx
373                        .best_blame_constraint(
374                            longer_fr,
375                            NllRegionVariableOrigin::Placeholder(placeholder),
376                            error_vid,
377                        )
378                        .0
379                        .cause;
380
381                    let universe = placeholder.universe;
382                    let universe_info = self.regioncx.universe_info(universe);
383
384                    universe_info.report_erroneous_element(self, placeholder, error_element, cause);
385                }
386
387                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
388                    if is_reported {
389                        self.report_region_error(
390                            longer_fr,
391                            fr_origin,
392                            shorter_fr,
393                            &mut outlives_suggestion,
394                        );
395                    } else {
396                        // We only report the first error, so as not to overwhelm the user. See
397                        // `RegRegionErrorKind` docs.
398                        //
399                        // FIXME: currently we do nothing with these, but perhaps we can do better?
400                        // FIXME: try collecting these constraints on the outlives suggestion
401                        // builder. Does it make the suggestions any better?
402                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:402",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(402u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Unreported region error: can\'t prove that {0:?}: {1:?}",
                                                    longer_fr, shorter_fr) as &dyn Value))])
            });
    } else { ; }
};debug!(
403                            "Unreported region error: can't prove that {:?}: {:?}",
404                            longer_fr, shorter_fr
405                        );
406                    }
407                }
408            }
409        }
410
411        // Emit one outlives suggestions for each MIR def we borrowck
412        outlives_suggestion.add_suggestion(self);
413    }
414
415    /// Report an error because the universal region `fr` was required to outlive
416    /// `outlived_fr` but it is not known to do so. For example:
417    ///
418    /// ```compile_fail
419    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
420    /// ```
421    ///
422    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
423    pub(crate) fn report_region_error(
424        &mut self,
425        fr: RegionVid,
426        fr_origin: NllRegionVariableOrigin<'tcx>,
427        outlived_fr: RegionVid,
428        outlives_suggestion: &mut OutlivesSuggestionBuilder,
429    ) {
430        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:430",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(430u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_region_error(fr={0:?}, outlived_fr={1:?})",
                                                    fr, outlived_fr) as &dyn Value))])
            });
    } else { ; }
};debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
431
432        let (blame_constraint, path) =
433            self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
434        let BlameConstraint { category, cause, variance_info, .. } = blame_constraint;
435
436        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:436",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(436u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_region_error: category={0:?} {1:?} {2:?}",
                                                    category, cause, variance_info) as &dyn Value))])
            });
    } else { ; }
};debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);
437
438        // Check if we can use one of the "nice region errors".
439        if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
440            let infer_err = self.infcx.err_ctxt();
441            let nice =
442                NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), cause.span, o, f);
443            if let Some(diag) = nice.try_report_from_nll() {
444                self.buffer_error(diag);
445                return;
446            }
447        }
448
449        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
450            self.regioncx.universal_regions().is_local_free_region(fr),
451            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
452        );
453
454        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:454",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(454u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_region_error: fr_is_local={0:?} outlived_fr_is_local={1:?} category={2:?}",
                                                    fr_is_local, outlived_fr_is_local, category) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
455            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
456            fr_is_local, outlived_fr_is_local, category
457        );
458
459        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span: cause.span };
460
461        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
462            (ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
463                self.report_fnmut_error(&errci, kind)
464            }
465            (ConstraintCategory::Assignment, true, false)
466            | (ConstraintCategory::CallArgument(_), true, false) => {
467                let mut db = self.report_escaping_data_error(&errci);
468
469                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
470                outlives_suggestion.collect_constraint(fr, outlived_fr);
471
472                db
473            }
474            _ => {
475                let mut db = self.report_general_error(&errci);
476
477                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
478                outlives_suggestion.collect_constraint(fr, outlived_fr);
479
480                db
481            }
482        };
483
484        match variance_info {
485            ty::VarianceDiagInfo::None => {}
486            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
487                let (desc, note) = match ty.kind() {
488                    ty::RawPtr(ty, mutbl) => {
489                        match (&*mutbl, &hir::Mutability::Mut) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(*mutbl, hir::Mutability::Mut);
490                        (
491                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable pointer to `{0}`", ty))
    })format!("a mutable pointer to `{}`", ty),
492                            "mutable pointers are invariant over their type parameter".to_string(),
493                        )
494                    }
495                    ty::Ref(_, inner_ty, mutbl) => {
496                        match (&*mutbl, &hir::Mutability::Mut) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(*mutbl, hir::Mutability::Mut);
497                        (
498                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable reference to `{0}`",
                inner_ty))
    })format!("a mutable reference to `{inner_ty}`"),
499                            "mutable references are invariant over their type parameter"
500                                .to_string(),
501                        )
502                    }
503                    ty::Adt(adt, args) => {
504                        let generic_arg = args[param_index as usize];
505                        let identity_args =
506                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
507                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
508                        let base_generic_arg = identity_args[param_index as usize];
509                        let adt_desc = adt.descr();
510
511                        let desc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the type `{0}`, which makes the generic argument `{1}` invariant",
                ty, generic_arg))
    })format!(
512                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
513                        );
514                        let note = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the {0} `{1}` is invariant over the parameter `{2}`",
                adt_desc, base_ty, base_generic_arg))
    })format!(
515                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
516                        );
517                        (desc, note)
518                    }
519                    ty::FnDef(def_id, _) => {
520                        let name = self.infcx.tcx.item_name(*def_id);
521                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
522                        let desc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a function pointer to `{0}`",
                name))
    })format!("a function pointer to `{name}`");
523                        let note = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the function `{1}` is invariant over the parameter `{0}`",
                identity_args[param_index as usize], name))
    })format!(
524                            "the function `{name}` is invariant over the parameter `{}`",
525                            identity_args[param_index as usize]
526                        );
527                        (desc, note)
528                    }
529                    _ => { ::core::panicking::panic_fmt(format_args!("Unexpected type {0:?}", ty)); }panic!("Unexpected type {ty:?}"),
530                };
531                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs because of {0}",
                desc))
    })format!("requirement occurs because of {desc}",));
532                diag.note(note);
533                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
534            }
535        }
536
537        self.add_placeholder_from_predicate_note(&mut diag, &path);
538        self.add_sized_or_copy_bound_info(&mut diag, category, &path);
539
540        for constraint in &path {
541            if let ConstraintCategory::Cast { is_raw_ptr_dyn_type_cast: true, .. } =
542                constraint.category
543            {
544                diag.span_note(
545                    constraint.span,
546                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("raw pointer casts of trait objects cannot extend lifetimes"))
    })format!("raw pointer casts of trait objects cannot extend lifetimes"),
547                );
548                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this was previously accepted by the compiler but was changed recently"))
    })format!(
549                    "this was previously accepted by the compiler but was changed recently"
550                ));
551                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("see <https://github.com/rust-lang/rust/issues/141402> for more information"))
    })format!(
552                    "see <https://github.com/rust-lang/rust/issues/141402> for more information"
553                ));
554            }
555        }
556
557        self.buffer_error(diag);
558    }
559
560    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
561    /// This function expects `fr` to be local and `outlived_fr` to not be local.
562    ///
563    /// ```text
564    /// error: captured variable cannot escape `FnMut` closure body
565    ///   --> $DIR/issue-53040.rs:15:8
566    ///    |
567    /// LL |     || &mut v;
568    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
569    ///    |     |
570    ///    |     inferred to be a `FnMut` closure
571    ///    |
572    ///    = note: `FnMut` closures only have access to their captured variables while they are
573    ///            executing...
574    ///    = note: ...therefore, returned references to captured variables will escape the closure
575    /// ```
576    fn report_fnmut_error(
577        &self,
578        errci: &ErrorConstraintInfo<'tcx>,
579        kind: ReturnConstraint,
580    ) -> Diag<'infcx> {
581        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
582
583        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
584        if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() {
585            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity()
586        };
587
588        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:588",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(588u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("report_fnmut_error: output_ty={0:?}",
                                                    output_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("report_fnmut_error: output_ty={:?}", output_ty);
589
590        let err = FnMutError {
591            span: *span,
592            ty_err: match output_ty.kind() {
593                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
594                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
595                }
596                _ if output_ty.contains_closure() => {
597                    FnMutReturnTypeErr::ReturnClosure { span: *span }
598                }
599                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
600            },
601        };
602
603        let mut diag = self.dcx().create_err(err);
604
605        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
606            let def_id = match self.regioncx.universal_regions().defining_ty {
607                DefiningTy::Closure(def_id, _) => def_id,
608                ty => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected DefiningTy {0:?}",
        ty))bug!("unexpected DefiningTy {:?}", ty),
609            };
610
611            let captured_place = &self.upvars[upvar_field.index()].place;
612            let defined_hir = match captured_place.base {
613                PlaceBase::Local(hirid) => Some(hirid),
614                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
615                _ => None,
616            };
617
618            if let Some(def_hir) = defined_hir {
619                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
620                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
621                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
622                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
623                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
624            }
625        }
626
627        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
628            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
629        }
630
631        self.suggest_move_on_borrowing_closure(&mut diag);
632
633        diag
634    }
635
636    /// Reports an error specifically for when data is escaping a closure.
637    ///
638    /// ```text
639    /// error: borrowed data escapes outside of function
640    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
641    ///    |
642    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
643    ///    |              - `x` is a reference that is only valid in the function body
644    /// LL |     // but ref_obj will not, so warn.
645    /// LL |     ref_obj(x)
646    ///    |     ^^^^^^^^^^ `x` escapes the function body here
647    /// ```
648    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_escaping_data_error",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(648u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&["errci"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errci)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'infcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ErrorConstraintInfo { span, category, .. } = errci;
            let fr_name_and_span =
                self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
                    self.body, &self.local_names(), &self.upvars, errci.fr);
            let outlived_fr_name_and_span =
                self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
                    self.body, &self.local_names(), &self.upvars,
                    errci.outlived_fr);
            let escapes_from =
                self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
            if (fr_name_and_span.is_none() &&
                                outlived_fr_name_and_span.is_none()) ||
                        (*category == ConstraintCategory::Assignment &&
                                self.regioncx.universal_regions().defining_ty.is_fn_def())
                    || self.regioncx.universal_regions().defining_ty.is_const()
                {
                return self.report_general_error(errci);
            }
            let mut diag =
                borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx,
                    *span, escapes_from);
            if let Some((Some(outlived_fr_name), outlived_fr_span)) =
                    outlived_fr_name_and_span {
                diag.span_label(outlived_fr_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` declared here, outside of the {1} body",
                                    outlived_fr_name, escapes_from))
                        }));
            }
            if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
                diag.span_label(fr_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` is a reference that is only valid in the {1} body",
                                    fr_name, escapes_from))
                        }));
                diag.span_label(*span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` escapes the {1} body here",
                                    fr_name, escapes_from))
                        }));
            } else {
                diag.span_label(*span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("a temporary borrow escapes the {0} body here",
                                    escapes_from))
                        }));
                if let Some((Some(outlived_name), _)) =
                        outlived_fr_name_and_span {
                    diag.help(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("`{0}` is declared outside the {1}, so any data borrowed inside the {1} cannot be stored into it",
                                        outlived_name, escapes_from))
                            }));
                }
            }
            match (self.to_error_region(errci.fr),
                    self.to_error_region(errci.outlived_fr)) {
                (Some(f), Some(o)) => {
                    self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o,
                        category);
                    let fr_region_name =
                        self.give_region_a_name(errci.fr).unwrap();
                    fr_region_name.highlight_region_name(&mut diag);
                    let outlived_fr_region_name =
                        self.give_region_a_name(errci.outlived_fr).unwrap();
                    outlived_fr_region_name.highlight_region_name(&mut diag);
                    diag.span_label(*span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}requires that `{1}` must outlive `{2}`",
                                        category.description(), fr_region_name,
                                        outlived_fr_region_name))
                            }));
                }
                _ => {}
            }
            diag
        }
    }
}#[instrument(level = "debug", skip(self))]
649    fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
650        let ErrorConstraintInfo { span, category, .. } = errci;
651
652        let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
653            self.infcx.tcx,
654            self.body,
655            &self.local_names(),
656            &self.upvars,
657            errci.fr,
658        );
659        let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
660            self.infcx.tcx,
661            self.body,
662            &self.local_names(),
663            &self.upvars,
664            errci.outlived_fr,
665        );
666
667        let escapes_from =
668            self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
669
670        // Revert to the normal error in these cases.
671        // Assignments aren't "escapes" in function items.
672        if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
673            || (*category == ConstraintCategory::Assignment
674                && self.regioncx.universal_regions().defining_ty.is_fn_def())
675            || self.regioncx.universal_regions().defining_ty.is_const()
676        {
677            return self.report_general_error(errci);
678        }
679
680        let mut diag =
681            borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
682
683        if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
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        if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
691            diag.span_label(
692                fr_span,
693                format!(
694                    "`{fr_name}` is a reference that is only valid in the {escapes_from} body",
695                ),
696            );
697
698            diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
699        } else {
700            diag.span_label(
701                *span,
702                format!("a temporary borrow escapes the {escapes_from} body here"),
703            );
704            if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
705                diag.help(format!(
706                    "`{outlived_name}` is declared outside the {escapes_from}, \
707                     so any data borrowed inside the {escapes_from} cannot be stored into it"
708                ));
709            }
710        }
711
712        // Only show an extra note if we can find an 'error region' for both of the region
713        // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
714        // that don't help the user understand the error.
715        match (self.to_error_region(errci.fr), self.to_error_region(errci.outlived_fr)) {
716            (Some(f), Some(o)) => {
717                self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
718
719                let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
720                fr_region_name.highlight_region_name(&mut diag);
721                let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
722                outlived_fr_region_name.highlight_region_name(&mut diag);
723
724                diag.span_label(
725                    *span,
726                    format!(
727                        "{}requires that `{}` must outlive `{}`",
728                        category.description(),
729                        fr_region_name,
730                        outlived_fr_region_name,
731                    ),
732                );
733            }
734            _ => {}
735        }
736
737        diag
738    }
739
740    /// Reports a region inference error for the general case with named/synthesized lifetimes to
741    /// explain what is happening.
742    ///
743    /// ```text
744    /// error: unsatisfied lifetime constraints
745    ///   --> $DIR/regions-creating-enums3.rs:17:5
746    ///    |
747    /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
748    ///    |                -- -- lifetime `'b` defined here
749    ///    |                |
750    ///    |                lifetime `'a` defined here
751    /// LL |     ast::add(x, y)
752    ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
753    ///    |                    is returning data with lifetime `'b`
754    /// ```
755    fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'infcx> {
756        let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
757
758        let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
759
760        let err = LifetimeOutliveErr { span: *span };
761        let mut diag = self.dcx().create_err(err);
762
763        // In certain scenarios, such as the one described in issue #118021,
764        // we might encounter a lifetime that cannot be named.
765        // These situations are bound to result in errors.
766        // To prevent an immediate ICE, we opt to create a dummy name instead.
767        let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
768            name: kw::UnderscoreLifetime,
769            source: RegionNameSource::Static,
770        });
771        fr_name.highlight_region_name(&mut diag);
772        let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
773        outlived_fr_name.highlight_region_name(&mut diag);
774
775        let err_category = if #[allow(non_exhaustive_omitted_patterns)] match category {
    ConstraintCategory::Return(_) => true,
    _ => false,
}matches!(category, ConstraintCategory::Return(_))
776            && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
777        {
778            LifetimeReturnCategoryErr::WrongReturn {
779                span: *span,
780                mir_def_name,
781                outlived_fr_name,
782                fr_name: &fr_name,
783            }
784        } else {
785            LifetimeReturnCategoryErr::ShortReturn {
786                span: *span,
787                category_desc: category.description(),
788                free_region_name: &fr_name,
789                outlived_fr_name,
790            }
791        };
792
793        diag.subdiagnostic(err_category);
794
795        self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
796        self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
797        self.suggest_move_on_borrowing_closure(&mut diag);
798        self.suggest_deref_closure_return(&mut diag);
799
800        diag
801    }
802
803    /// Adds a suggestion to errors where an `impl Trait` is returned.
804    ///
805    /// ```text
806    /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
807    ///       a constraint
808    ///    |
809    /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
810    ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
811    /// ```
812    fn add_static_impl_trait_suggestion(
813        &self,
814        diag: &mut Diag<'_>,
815        fr: RegionVid,
816        // We need to pass `fr_name` - computing it again will label it twice.
817        fr_name: RegionName,
818        outlived_fr: RegionVid,
819    ) {
820        if let (Some(f), Some(outlived_f)) =
821            (self.to_error_region(fr), self.to_error_region(outlived_fr))
822        {
823            if outlived_f.kind() != ty::ReStatic {
824                return;
825            }
826            let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
827            let Some(suitable_region) = suitable_region else {
828                return;
829            };
830
831            let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
832
833            let Some(param) =
834                find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
835            else {
836                return;
837            };
838
839            let lifetime =
840                if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
841
842            let arg = match param.param.pat.simple_ident() {
843                Some(simple_ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument `{0}`", simple_ident))
    })format!("argument `{simple_ident}`"),
844                None => "the argument".to_string(),
845            };
846            let captures = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("captures data from {0}", arg))
    })format!("captures data from {arg}");
847
848            if !fn_returns.is_empty() {
849                nice_region_error::suggest_new_region_bound(
850                    self.infcx.tcx,
851                    diag,
852                    fn_returns,
853                    lifetime.to_string(),
854                    Some(arg),
855                    captures,
856                    Some((param.param_ty_span, param.param_ty.to_string())),
857                    Some(suitable_region.scope),
858                );
859                return;
860            }
861
862            let Some((alias_tys, alias_span, lt_addition_span)) = self
863                .infcx
864                .tcx
865                .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
866            else {
867                return;
868            };
869
870            // in case the return type of the method is a type alias
871            let mut spans_suggs: Vec<_> = Vec::new();
872            for alias_ty in alias_tys {
873                if alias_ty.span.desugaring_kind().is_some() {
874                    // Skip `async` desugaring `impl Future`.
875                }
876                if let TyKind::TraitObject(_, lt) = alias_ty.kind {
877                    if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
878                        spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
879                    } else {
880                        spans_suggs.push((lt.ident.span, "'a".to_string()));
881                    }
882                }
883            }
884
885            if let Some(lt_addition_span) = lt_addition_span {
886                spans_suggs.push((lt_addition_span, "'a, ".to_string()));
887            } else {
888                spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
889            }
890
891            diag.multipart_suggestion_verbose(
892                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to declare that the trait object {0}, you can add a lifetime parameter `\'a` in the type alias",
                captures))
    })format!(
893                    "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
894                ),
895                spans_suggs,
896                Applicability::MaybeIncorrect,
897            );
898        }
899    }
900
901    fn maybe_suggest_constrain_dyn_trait_impl(
902        &self,
903        diag: &mut Diag<'_>,
904        f: Region<'tcx>,
905        o: Region<'tcx>,
906        category: &ConstraintCategory<'tcx>,
907    ) {
908        if !o.is_static() {
909            return;
910        }
911
912        let tcx = self.infcx.tcx;
913
914        let ConstraintCategory::CallArgument(Some(func_ty)) = category else { return };
915        let ty::FnDef(fn_did, args) = func_ty.kind() else { return };
916        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:916",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(916u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["fn_did", "args"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&fn_did) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&args) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?fn_did, ?args);
917
918        // Only suggest this on function calls, not closures
919        let ty = tcx.type_of(fn_did).instantiate_identity();
920        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:920",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(920u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ty: {0:?}, ty.kind: {1:?}",
                                                    ty, ty.kind()) as &dyn Value))])
            });
    } else { ; }
};debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
921        if let ty::Closure(_, _) = ty.kind() {
922            return;
923        }
924        let Ok(Some(instance)) = ty::Instance::try_resolve(
925            tcx,
926            self.infcx.typing_env(self.infcx.param_env),
927            *fn_did,
928            self.infcx.resolve_vars_if_possible(args),
929        ) else {
930            return;
931        };
932
933        let Some(param) = find_param_with_region(tcx, self.mir_def_id(), f, o) else {
934            return;
935        };
936        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:936",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(936u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["param"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&param) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?param);
937
938        let mut visitor = TraitObjectVisitor(FxIndexSet::default());
939        visitor.visit_ty(param.param_ty);
940
941        let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
942            tcx,
943            instance.def_id(),
944            &visitor.0,
945        ) else {
946            return;
947        };
948
949        self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
950    }
951
952    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("suggest_constrain_dyn_trait_in_impl",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(952u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&["found_dids",
                                                    "ident", "self_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found_dids)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:960",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(960u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("err: {0:#?}",
                                                                err) as &dyn Value))])
                        });
                } else { ; }
            };
            let mut suggested = false;
            for found_did in found_dids {
                let mut traits = ::alloc::vec::Vec::new();
                let mut hir_v =
                    HirTraitObjectVisitor(&mut traits, *found_did);
                hir_v.visit_ty_unambig(self_ty);
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:966",
                                        "rustc_borrowck::diagnostics::region_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(966u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("trait spans found: {0:?}",
                                                                    traits) as &dyn Value))])
                            });
                    } else { ; }
                };
                for span in &traits {
                    let mut multi_span: MultiSpan =
                        <[_]>::into_vec(::alloc::boxed::box_new([*span])).into();
                    multi_span.push_span_label(*span,
                        fluent::borrowck_implicit_static);
                    multi_span.push_span_label(ident.span,
                        fluent::borrowck_implicit_static_introduced);
                    err.subdiagnostic(RequireStaticErr::UsedImpl {
                            multi_span,
                        });
                    err.span_suggestion_verbose(span.shrink_to_hi(),
                        fluent::borrowck_implicit_static_relax, " + '_",
                        Applicability::MaybeIncorrect);
                    suggested = true;
                }
            }
            suggested
        }
    }
}#[instrument(skip(self, err), level = "debug")]
953    fn suggest_constrain_dyn_trait_in_impl(
954        &self,
955        err: &mut Diag<'_>,
956        found_dids: &FxIndexSet<DefId>,
957        ident: Ident,
958        self_ty: &hir::Ty<'_>,
959    ) -> bool {
960        debug!("err: {:#?}", err);
961        let mut suggested = false;
962        for found_did in found_dids {
963            let mut traits = vec![];
964            let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
965            hir_v.visit_ty_unambig(self_ty);
966            debug!("trait spans found: {:?}", traits);
967            for span in &traits {
968                let mut multi_span: MultiSpan = vec![*span].into();
969                multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
970                multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
971                err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
972                err.span_suggestion_verbose(
973                    span.shrink_to_hi(),
974                    fluent::borrowck_implicit_static_relax,
975                    " + '_",
976                    Applicability::MaybeIncorrect,
977                );
978                suggested = true;
979            }
980        }
981        suggested
982    }
983
984    fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
985        let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
986            return;
987        };
988
989        let Some((ty_sub, _)) = self
990            .infcx
991            .tcx
992            .is_suitable_region(self.mir_def_id(), sub)
993            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
994        else {
995            return;
996        };
997
998        let Some((ty_sup, _)) = self
999            .infcx
1000            .tcx
1001            .is_suitable_region(self.mir_def_id(), sup)
1002            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1003        else {
1004            return;
1005        };
1006
1007        suggest_adding_lifetime_params(
1008            self.infcx.tcx,
1009            diag,
1010            self.mir_def_id(),
1011            sub,
1012            ty_sup,
1013            ty_sub,
1014        );
1015    }
1016
1017    /// When encountering a lifetime error caused by the return type of a closure, check the
1018    /// corresponding trait bound and see if dereferencing the closure return value would satisfy
1019    /// them. If so, we produce a structured suggestion.
1020    fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1021        let tcx = self.infcx.tcx;
1022
1023        // Get the closure return value and type.
1024        let closure_def_id = self.mir_def_id();
1025        let hir::Node::Expr(
1026            closure_expr @ hir::Expr {
1027                kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1028            },
1029        ) = tcx.hir_node_by_def_id(closure_def_id)
1030        else {
1031            return;
1032        };
1033        let ty::Closure(_, args) = *tcx.type_of(closure_def_id).instantiate_identity().kind()
1034        else {
1035            return;
1036        };
1037        let args = args.as_closure();
1038
1039        // Make sure that the parent expression is a method call.
1040        let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1041        let hir::Node::Expr(
1042            parent_expr @ hir::Expr {
1043                kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1044            },
1045        ) = tcx.hir_node(parent_expr_id)
1046        else {
1047            return;
1048        };
1049        let typeck_results = tcx.typeck(self.mir_def_id());
1050
1051        // We don't use `ty.peel_refs()` to get the number of `*`s needed to get the root type.
1052        let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1053        let mut peeled_ty = liberated_sig.output();
1054        let mut count = 0;
1055        while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1056            peeled_ty = ref_ty;
1057            count += 1;
1058        }
1059        if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1060            return;
1061        }
1062
1063        // Build a new closure where the return type is an owned value, instead of a ref.
1064        let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1065            tcx,
1066            ty::Binder::dummy(tcx.mk_fn_sig(
1067                liberated_sig.inputs().iter().copied(),
1068                peeled_ty,
1069                liberated_sig.c_variadic,
1070                hir::Safety::Safe,
1071                rustc_abi::ExternAbi::Rust,
1072            )),
1073        );
1074        let closure_ty = Ty::new_closure(
1075            tcx,
1076            closure_def_id.to_def_id(),
1077            ty::ClosureArgs::new(
1078                tcx,
1079                ty::ClosureArgsParts {
1080                    parent_args: args.parent_args(),
1081                    closure_kind_ty: args.kind_ty(),
1082                    tupled_upvars_ty: args.tupled_upvars_ty(),
1083                    closure_sig_as_fn_ptr_ty,
1084                },
1085            )
1086            .args,
1087        );
1088
1089        let Some((closure_arg_pos, _)) =
1090            call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1091        else {
1092            return;
1093        };
1094        // Get the type for the parameter corresponding to the argument the closure with the
1095        // lifetime error we had.
1096        let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1097            return;
1098        };
1099        let Some(input_arg) = tcx
1100            .fn_sig(method_def_id)
1101            .skip_binder()
1102            .inputs()
1103            .skip_binder()
1104            // Methods have a `self` arg, so `pos` is actually `+ 1` to match the method call arg.
1105            .get(closure_arg_pos + 1)
1106        else {
1107            return;
1108        };
1109        // If this isn't a param, then we can't substitute a new closure.
1110        let ty::Param(closure_param) = input_arg.kind() else { return };
1111
1112        // Get the arguments for the found method, only specifying that `Self` is the receiver type.
1113        let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1114        let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1115            if let ty::GenericParamDefKind::Lifetime = param.kind {
1116                tcx.lifetimes.re_erased.into()
1117            } else if param.index == 0 && param.name == kw::SelfUpper {
1118                possible_rcvr_ty.into()
1119            } else if param.index == closure_param.index {
1120                closure_ty.into()
1121            } else {
1122                self.infcx.var_for_def(parent_expr.span, param)
1123            }
1124        });
1125
1126        let preds = tcx.predicates_of(method_def_id).instantiate(tcx, args);
1127
1128        let ocx = ObligationCtxt::new(&self.infcx);
1129        ocx.register_obligations(preds.iter().map(|(pred, span)| {
1130            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1130",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1130u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["pred"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&pred) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!(?pred);
1131            Obligation::misc(tcx, span, self.mir_def_id(), self.infcx.param_env, pred)
1132        }));
1133
1134        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() && count > 0 {
1135            diag.span_suggestion_verbose(
1136                tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1137                fluent::borrowck_dereference_suggestion,
1138                "*".repeat(count),
1139                Applicability::MachineApplicable,
1140            );
1141        }
1142    }
1143
1144    fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1145        let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1146        let expr = &body.value.peel_blocks();
1147        let mut closure_span = None::<rustc_span::Span>;
1148        match expr.kind {
1149            hir::ExprKind::MethodCall(.., args, _) => {
1150                for arg in args {
1151                    if let hir::ExprKind::Closure(hir::Closure {
1152                        capture_clause: hir::CaptureBy::Ref,
1153                        ..
1154                    }) = arg.kind
1155                    {
1156                        closure_span = Some(arg.span.shrink_to_lo());
1157                        break;
1158                    }
1159                }
1160            }
1161            hir::ExprKind::Closure(hir::Closure {
1162                capture_clause: hir::CaptureBy::Ref,
1163                kind,
1164                ..
1165            }) => {
1166                if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
        _)) => true,
    _ => false,
}matches!(
1167                    kind,
1168                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1169                        hir::CoroutineDesugaring::Async,
1170                        _
1171                    ),)
1172                ) {
1173                    closure_span = Some(expr.span.shrink_to_lo());
1174                }
1175            }
1176            _ => {}
1177        }
1178        if let Some(closure_span) = closure_span {
1179            diag.span_suggestion_verbose(
1180                closure_span,
1181                fluent::borrowck_move_closure_suggestion,
1182                "move ",
1183                Applicability::MaybeIncorrect,
1184            );
1185        }
1186    }
1187}