Skip to main content

rustc_borrowck/diagnostics/
region_errors.rs

1//! Error reporting machinery for lifetime errors.
2
3use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, msg};
5use rustc_hir as hir;
6use rustc_hir::GenericBound::Trait;
7use rustc_hir::QPath::Resolved;
8use rustc_hir::WherePredicateKind::BoundPredicate;
9use rustc_hir::def::DefKind;
10use rustc_hir::def::Res::Def;
11use rustc_hir::def_id::DefId;
12use rustc_hir::intravisit::Visitor;
13use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate};
14use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin};
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, bug, 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::{LIMITATION_NOTE, OutlivesSuggestionBuilder, RegionName, RegionNameSource};
31use crate::consumers::OutlivesConstraint;
32use crate::nll::ConstraintDescription;
33use crate::region_infer::{RegionInferenceContext, 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};
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::SolverRegionConstraint(_)
61            | ConstraintCategory::Predicate(_, _)
62            | ConstraintCategory::Boring
63            | ConstraintCategory::BoringNoLocation
64            | ConstraintCategory::Internal
65            | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
66        }
67    }
68}
69
70/// A collection of errors encountered during region inference. This is needed to efficiently
71/// report errors after borrow checking.
72///
73/// Usually we expect this to either be empty or contain a small number of items, so we can avoid
74/// allocation most of the time.
75pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
76
77impl<'tcx> RegionErrors<'tcx> {
78    pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
79        Self(::alloc::vec::Vec::new()vec![], tcx)
80    }
81    #[track_caller]
82    pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
83        let val = val.into();
84        let guar = self.1.sess.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", val))
    })format!("{val:?}"));
85        self.0.push((val, guar));
86    }
87    pub(crate) fn is_empty(&self) -> bool {
88        self.0.is_empty()
89    }
90    pub(crate) fn into_iter(
91        self,
92    ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
93        self.0.into_iter()
94    }
95}
96
97impl std::fmt::Debug for RegionErrors<'_> {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_tuple("RegionErrors").field(&self.0).finish()
100    }
101}
102
103#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for RegionErrorKind<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::TypeTestError { type_test: __self_0 } =>
                RegionErrorKind::TypeTestError {
                    type_test: ::core::clone::Clone::clone(__self_0),
                },
            Self::PlaceholderOutlivesIllegalRegion {
                longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
                RegionErrorKind::PlaceholderOutlivesIllegalRegion {
                    longer_fr: ::core::clone::Clone::clone(__self_0),
                    illegally_outlived_r: ::core::clone::Clone::clone(__self_1),
                },
            Self::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 {
            Self::TypeTestError { type_test: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TypeTestError", "type_test", &__self_0),
            Self::PlaceholderOutlivesIllegalRegion {
                longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "PlaceholderOutlivesIllegalRegion", "longer_fr", __self_0,
                    "illegally_outlived_r", &__self_1),
            Self::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)]
104pub(crate) enum RegionErrorKind<'tcx> {
105    /// A generic bound failure for a type test (`T: 'a`).
106    TypeTestError { type_test: TypeTest<'tcx> },
107
108    /// 'p outlives 'r, which does not hold. 'p is always a placeholder
109    /// and 'r is some other region.
110    PlaceholderOutlivesIllegalRegion { longer_fr: RegionVid, illegally_outlived_r: RegionVid },
111
112    /// Any other lifetime error.
113    RegionError {
114        /// The origin of the region.
115        fr_origin: NllRegionVariableOrigin<'tcx>,
116        /// The region that should outlive `shorter_fr`.
117        longer_fr: RegionVid,
118        /// The region that should be shorter, but we can't prove it.
119        shorter_fr: RegionVid,
120        /// Indicates whether this is a reported error. We currently only report the first error
121        /// encountered and leave the rest unreported so as not to overwhelm the user.
122        is_reported: bool,
123    },
124}
125
126/// Information about the various region constraints involved in a borrow checker error.
127#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ErrorConstraintInfo<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        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)]
128pub(crate) struct ErrorConstraintInfo<'tcx> {
129    // fr: outlived_fr
130    pub(super) fr: RegionVid,
131    pub(super) outlived_fr: RegionVid,
132
133    // Category and span for best blame constraint
134    pub(super) category: ConstraintCategory<'tcx>,
135    pub(super) span: Span,
136}
137
138impl<'tcx> RegionInferenceContext<'tcx> {
139    /// Converts a region inference variable into a `ty::Region` that
140    /// we can use for error reporting. If `r` is universally bound,
141    /// then we use the name that we have on record for it. If `r` is
142    /// existentially bound, then we check its inferred value and try
143    /// to find a good name from that. Returns `None` if we can't find
144    /// one (e.g., this is just some random part of the CFG).
145    pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
146        self.to_error_region_vid(r).and_then(|r| self.region_definition(r).external_name)
147    }
148
149    /// Returns the `RegionVid` corresponding to the region returned by
150    /// `to_error_region`.
151    pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
152        if self.universal_regions().is_universal_region(r) {
153            Some(r)
154        } else {
155            // We just want something nameable, even if it's not
156            // actually an upper bound.
157            let upper_bound = self.approx_universal_upper_bound(r);
158
159            if self.upper_bound_in_region_scc(r, upper_bound) {
160                self.to_error_region_vid(upper_bound)
161            } else {
162                None
163            }
164        }
165    }
166
167    /// Map the regions in the type to named regions, where possible.
168    fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
169    where
170        T: TypeFoldable<TyCtxt<'tcx>>,
171    {
172        fold_regions(tcx, ty, |region, _| match region.kind() {
173            ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
174            _ => region,
175        })
176    }
177
178    /// Returns `true` if a closure is inferred to be an `FnMut` closure.
179    fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
180        if let Some(r) = self.to_error_region(fr)
181            && let ty::ReLateParam(late_param) = r.kind()
182            && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
183            && let DefiningTy::Closure(_, args) = self.universal_regions().defining_ty
184        {
185            return args.as_closure().kind() == ty::ClosureKind::FnMut;
186        }
187
188        false
189    }
190}
191
192impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
193    // For generic associated types (GATs) which implied 'static requirement
194    // from higher-ranked trait bounds (HRTB). Try to locate span of the trait
195    // and the span which bounded to the trait for adding 'static lifetime suggestion
196    fn suggest_static_lifetime_for_gat_from_hrtb(
197        &self,
198        diag: &mut Diag<'_>,
199        lower_bound: RegionVid,
200    ) {
201        let tcx = self.infcx.tcx;
202
203        // find generic associated types in the given region 'lower_bound'
204        let gat_id_and_generics = self
205            .regioncx
206            .placeholders_contained_in(lower_bound)
207            .map(|placeholder| {
208                if let Some(id) = placeholder.bound.kind.get_id()
209                    && let Some(placeholder_id) = id.as_local()
210                    && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
211                    && let Some(generics_impl) =
212                        tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
213                {
214                    Some((gat_hir_id, generics_impl))
215                } else {
216                    None
217                }
218            })
219            .collect::<Vec<_>>();
220        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:220",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(220u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("gat_id_and_generics")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("gat_id_and_generics");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&gat_id_and_generics)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?gat_id_and_generics);
221
222        // Look for the where-bound which introduces the placeholder.
223        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
224        // and `T: for<'a> Trait`<'a>.
225        let mut hrtb_bounds = ::alloc::vec::Vec::new()vec![];
226        gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
227            for pred in generics.predicates {
228                let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
229                    pred.kind
230                else {
231                    continue;
232                };
233                if bound_generic_params
234                    .iter()
235                    .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
236                    .is_some()
237                {
238                    for bound in *bounds {
239                        hrtb_bounds.push(bound);
240                    }
241                } else {
242                    for bound in *bounds {
243                        if let Trait(trait_bound) = bound {
244                            if trait_bound
245                                .bound_generic_params
246                                .iter()
247                                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
248                                .is_some()
249                            {
250                                hrtb_bounds.push(bound);
251                                return;
252                            }
253                        }
254                    }
255                }
256            }
257        });
258        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:258",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(258u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("hrtb_bounds")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("hrtb_bounds");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hrtb_bounds)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?hrtb_bounds);
259
260        let mut suggestions = ::alloc::vec::Vec::new()vec![];
261        hrtb_bounds.iter().for_each(|bound| {
262            let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
263                return;
264            };
265            diag.span_note(*trait_span, LIMITATION_NOTE);
266            let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
267            else {
268                return;
269            };
270            let Def(_, trait_res_defid) = trait_ref.path.res else {
271                return;
272            };
273            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:273",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(273u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("generics_fn")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("generics_fn");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics_fn)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?generics_fn);
274            generics_fn.predicates.iter().for_each(|predicate| {
275                let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
276                else {
277                    return;
278                };
279                bounds.iter().for_each(|bd| {
280                    if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
281                        && let Def(_, res_defid) = tr_ref.path.res
282                        && res_defid == trait_res_defid // trait id matches
283                        && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
284                        && let Def(_, defid) = path.res
285                        && generics_fn.params
286                            .iter()
287                            .rfind(|param| param.def_id.to_def_id() == defid)
288                            .is_some()
289                    {
290                        suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
291                    }
292                });
293            });
294        });
295        if suggestions.len() > 0 {
296            suggestions.dedup();
297            diag.multipart_suggestion(
298                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider restricting the type parameter to the `'static` lifetime"))msg!("consider restricting the type parameter to the `'static` lifetime"),
299                suggestions,
300                Applicability::MaybeIncorrect,
301            );
302        }
303    }
304
305    /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
306    pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
307        // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
308        // buffered in the `MirBorrowckCtxt`.
309        let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
310        for (nll_error, _) in nll_errors.into_iter() {
311            match nll_error {
312                RegionErrorKind::TypeTestError { type_test } => {
313                    // Try to convert the lower-bound region into something named we can print for
314                    // the user.
315                    let lower_bound_region = self.regioncx.to_error_region(type_test.lower_bound);
316
317                    let type_test_span = type_test.span;
318
319                    if let Some(lower_bound_region) = lower_bound_region {
320                        let generic_ty = self.regioncx.name_regions(
321                            self.infcx.tcx,
322                            type_test.generic_kind.to_ty(self.infcx.tcx),
323                        );
324                        let origin =
325                            SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
326                        self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
327                            self.body.source.def_id().expect_local(),
328                            type_test_span,
329                            Some(origin),
330                            self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
331                            lower_bound_region,
332                        ));
333                    } else {
334                        // FIXME. We should handle this case better. It
335                        // indicates that we have e.g., some region variable
336                        // whose value is like `'a+'b` where `'a` and `'b` are
337                        // distinct unrelated universal regions that are not
338                        // known to outlive one another. It'd be nice to have
339                        // some examples where this arises to decide how best
340                        // to report it; we could probably handle it by
341                        // iterating over the universal regions and reporting
342                        // an error that multiple bounds are required.
343                        let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
344                            kind: type_test.generic_kind.to_string(),
345                            span: type_test_span,
346                        });
347
348                        // Add notes and suggestions for the case of 'static lifetime
349                        // implied but not specified when a generic associated types
350                        // are from higher-ranked trait bounds
351                        self.suggest_static_lifetime_for_gat_from_hrtb(
352                            &mut diag,
353                            type_test.lower_bound,
354                        );
355
356                        self.buffer_error(diag);
357                    }
358                }
359
360                RegionErrorKind::PlaceholderOutlivesIllegalRegion {
361                    longer_fr,
362                    illegally_outlived_r,
363                } => {
364                    self.report_erroneous_rvid_reaches_placeholder(longer_fr, illegally_outlived_r)
365                }
366
367                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
368                    if is_reported {
369                        self.report_region_error(
370                            longer_fr,
371                            fr_origin,
372                            shorter_fr,
373                            &mut outlives_suggestion,
374                        );
375                    } else {
376                        // We only report the first error, so as not to overwhelm the user. See
377                        // `RegRegionErrorKind` docs.
378                        //
379                        // FIXME: currently we do nothing with these, but perhaps we can do better?
380                        // FIXME: try collecting these constraints on the outlives suggestion
381                        // builder. Does it make the suggestions any better?
382                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:382",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(382u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Unreported region error: can\'t prove that {0:?}: {1:?}",
                                                    longer_fr, shorter_fr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
383                            "Unreported region error: can't prove that {:?}: {:?}",
384                            longer_fr, shorter_fr
385                        );
386                    }
387                }
388            }
389        }
390
391        // Emit one outlives suggestions for each MIR def we borrowck
392        outlives_suggestion.add_suggestion(self);
393    }
394
395    /// Point at `'static` obligations from the item being called.
396    ///
397    /// ```text
398    /// error[E0521]: borrowed data escapes outside of function
399    ///   --> $DIR/static-impl-obligation.rs:163:9
400    ///    |
401    /// LL |     fn bar<'a>(x: &'a &'a u32) {
402    ///    |            --  - `x` is only valid in the function body
403    ///    |            |
404    ///    |            lifetime `'a` defined here
405    /// LL |         let y: &dyn Foo = x;
406    /// LL |         y.hello();
407    ///    |         ^^^^^^^^^
408    ///    |         |
409    ///    |         `x` escapes the function body here
410    ///    |         argument requires that `'a` must outlive `'static`
411    ///    |
412    /// note: `'static` lifetime requirement from `<(dyn o::Foo + 'static)>::hello` introduced here
413    ///   --> $DIR/static-impl-obligation.rs:158:20
414    ///    |
415    /// LL |     impl dyn Foo + 'static where Self: 'static {
416    ///    |                    ^^^^^^^             ^^^^^^^ lifetime requirement introduced here
417    ///    |                    |
418    ///    |                    lifetime requirement introduced here
419    /// LL |         fn hello(&'static self) where Self: 'static {}
420    ///    |                  ^^^^^^^^^^^^^              ^^^^^^^ lifetime requirement introduced here
421    ///    |                  |
422    ///    |                  lifetime requirement introduced here
423    /// ```
424    fn explain_impl_static_obligation(
425        &self,
426        diag: &mut Diag<'_>,
427        ty: Ty<'tcx>,
428        outlived_fr: RegionVid,
429    ) {
430        let tcx = self.infcx.tcx;
431        if self.regioncx.to_error_region(outlived_fr) != Some(tcx.lifetimes.re_static) {
432            return;
433        }
434        let ty::FnDef(def_id, args) = ty.kind() else {
435            return;
436        };
437        let typing_env = self.infcx.typing_env(self.infcx.param_env);
438        let Ok(Some(instance)) = ty::Instance::try_resolve(
439            tcx,
440            typing_env,
441            *def_id,
442            self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
443        ) else {
444            return;
445        };
446        let def_id = instance.def_id();
447        if tcx.is_closure_like(def_id) {
448            // Closures don't have a `fn_sig` query result and cannot introduce the `'static`
449            // obligations this function looks for
450            return;
451        }
452        let mut bounds =
453            tcx.clauses_of(def_id)
454                .instantiate(tcx, instance.args)
455                .into_iter()
456                .map(|(c, sp)| (c.skip_norm_wip().as_predicate(), sp))
457                .filter(|(pred, _)| match pred.kind().skip_binder() {
458                    ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
459                        ty::OutlivesClause(_, lt),
460                    ))
461                    | ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
462                        ty::OutlivesClause(_, lt),
463                    )) if lt.is_static() => true,
464                    _ => false,
465                })
466                .map(|(_, sp)| sp)
467                .collect::<Vec<Span>>();
468
469        let mut labels = FxHashMap::default();
470
471        let parent = tcx.parent(def_id);
472        if let Some(rcvr) =
473            tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
474        {
475            // Look at the receiver for `&'static self`, which introduces a `'static` obligation.
476            // ```
477            // impl Foo {
478            //     fn foo(&'static self) {}
479            //            ^^^^^^^^^^^^^
480            // ```
481            if let ty::Ref(region, _, _) = rcvr.kind()
482                && *region == tcx.lifetimes.re_static
483                && let Some(assoc) = tcx.opt_associated_item(def_id)
484                && assoc.is_method()
485            {
486                let def_span = tcx.def_span(def_id);
487                // We have a `&'static self` receiver.
488                if let Some(def_id) = def_id.as_local()
489                    && let owner = tcx.expect_hir_owner_node(def_id)
490                    && let Some(decl) = owner.fn_decl()
491                    && let Some(ty) = decl.inputs.get(0)
492                {
493                    // Point at the `&'static self` receiver.
494                    bounds.push(ty.span);
495                } else if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
496                    // The method is not defined on the local crate, point at the signature instead of
497                    // just the receiver as an approximation. We don't add it if there are already
498                    // other spans with overlap with the def `Span`, as the other will be more specific.
499                    bounds.push(def_span)
500                }
501            }
502
503            if let DefKind::Impl { .. } = tcx.def_kind(parent)
504                && let ty = tcx.type_of(parent).instantiate_identity().skip_norm_wip()
505                && let ty::Dynamic(_, region) = ty.kind()
506                && *region == tcx.lifetimes.re_static
507            {
508                // We have a call into a method of either `impl dyn Trait {}` or
509                // `impl dyn Trait + 'static {}`.
510                if let Some(def_id) = parent.as_local()
511                    && let hir::OwnerNode::Item(item) = tcx.expect_hir_owner_node(def_id)
512                    && let hir::ItemKind::Impl(impl_) = item.kind
513                    && let hir::TyKind::TraitObject(_, tagged_ref) = impl_.self_ty.kind
514                {
515                    if tagged_ref.is_static() {
516                        // impl dyn Trait + 'static {
517                        //                  ^^^^^^^ lifetime requirement introduced here
518                        bounds.push(tagged_ref.pointer().ident.span);
519                    } else if tagged_ref.is_implicit() {
520                        // impl dyn Trait {
521                        //      ^^^^^^^^^ `dyn Trait` introduces an...
522                        bounds.push(impl_.self_ty.span);
523                        labels.insert(
524                            impl_.self_ty.span,
525                            "`dyn Trait` introduces an implicit `'static` lifetime requirement",
526                        );
527                    }
528                } else {
529                    // Non-local `impl`, we don't have a way to differentiate between `+ 'static`
530                    // and bare `dyn Trait`. We point at the whole def `Span` for now.
531                    let def_span = tcx.def_span(parent);
532                    if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
533                        bounds.push(def_span);
534                    }
535                }
536            }
537        }
538
539        if !bounds.is_empty() {
540            let mut multispan: MultiSpan = bounds.clone().into();
541            for span in bounds {
542                let label = labels.get(&span).unwrap_or(&"lifetime requirement introduced here");
543                multispan.push_span_label(span, *label);
544            }
545            multispan.push_span_context(tcx.def_span(def_id).shrink_to_lo());
546            if let DefKind::Impl { .. } | DefKind::Trait = tcx.def_kind(parent) {
547                multispan.push_span_context(tcx.def_span(parent).shrink_to_lo());
548            }
549            diag.span_note(
550                multispan,
551                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`\'static` lifetime requirement from `{0}` introduced here",
                tcx.def_path_str(def_id)))
    })format!(
552                    "`'static` lifetime requirement from `{}` introduced here",
553                    tcx.def_path_str(def_id)
554                ),
555            );
556        }
557    }
558
559    /// Report that `longer_fr: error_vid`, which doesn't hold,
560    /// where `longer_fr` is a placeholder.
561    fn report_erroneous_rvid_reaches_placeholder(
562        &mut self,
563        longer_fr: RegionVid,
564        error_vid: RegionVid,
565    ) {
566        use NllRegionVariableOrigin::*;
567
568        let origin_longer = self.regioncx.definitions[longer_fr].origin;
569
570        let Placeholder(placeholder) = origin_longer else {
571            ::rustc_span::macros::bug_impl(None,
    format_args!("Expected {0:?} to come from placeholder!", longer_fr),
    Location::caller());bug!("Expected {longer_fr:?} to come from placeholder!");
572        };
573
574        // FIXME: Is throwing away the existential region really the best here?
575        let error_region = match self.regioncx.definitions[error_vid].origin {
576            FreeRegion | Existential { .. } => None,
577            Placeholder(other_placeholder) => Some(other_placeholder),
578        };
579
580        // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
581        let best_blame = self.regioncx.best_blame_constraint(longer_fr, origin_longer, error_vid);
582        let cause = best_blame.to_obligation_cause();
583
584        // FIXME these methods should have better names, and also probably not be this generic.
585        // FIXME note that we *throw away* the error element here! We probably want to
586        // thread it through the computation further down and use it, but there currently isn't
587        // anything there to receive it.
588        self.regioncx.universe_info(placeholder.universe).report_erroneous_element(
589            self,
590            placeholder,
591            error_region,
592            cause,
593        );
594    }
595
596    /// Report an error because the universal region `fr` was required to outlive
597    /// `outlived_fr` but it is not known to do so. For example:
598    ///
599    /// ```compile_fail
600    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
601    /// ```
602    ///
603    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
604    pub(crate) fn report_region_error(
605        &mut self,
606        fr: RegionVid,
607        fr_origin: NllRegionVariableOrigin<'tcx>,
608        outlived_fr: RegionVid,
609        outlives_suggestion: &mut OutlivesSuggestionBuilder,
610    ) {
611        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:611",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(611u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_error(fr={0:?}, outlived_fr={1:?})",
                                                    fr, outlived_fr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
612
613        let best_blame = self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
614        let OutlivesConstraint { category, span, variance_info, .. } = *best_blame.constraint();
615        let path = best_blame.path();
616
617        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:617",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(617u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_error: category={0:?} {1:?} {2:?}",
                                                    category, span, variance_info) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_region_error: category={:?} {:?} {:?}", category, span, variance_info);
618
619        // Check if we can use one of the "nice region errors".
620        if let (Some(f), Some(o)) =
621            (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
622        {
623            let infer_err = self.infcx.err_ctxt();
624            let nice = NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), span, o, f);
625            if let Some(diag) = nice.try_report_from_nll() {
626                self.buffer_error(diag);
627                return;
628            }
629        }
630
631        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
632            self.regioncx.universal_regions().is_local_free_region(fr),
633            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
634        );
635
636        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:636",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(636u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
637            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
638            fr_is_local, outlived_fr_is_local, category
639        );
640
641        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span };
642
643        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
644            (ConstraintCategory::SolverRegionConstraint(span), _, _) => self
645                .dcx()
646                .struct_span_err(span, "higher-ranked lifetime bound could not be satisfied"),
647            (ConstraintCategory::Return(kind), true, false)
648                if self.regioncx.is_closure_fn_mut(fr) =>
649            {
650                self.report_fnmut_error(&errci, kind)
651            }
652            (ConstraintCategory::Assignment, true, false)
653            | (ConstraintCategory::CallArgument(_), true, false) => {
654                let mut db = self.report_escaping_data_error(&errci);
655
656                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
657                outlives_suggestion.collect_constraint(fr, outlived_fr);
658
659                db
660            }
661            _ => {
662                let mut db = self.report_general_error(&errci);
663
664                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
665                outlives_suggestion.collect_constraint(fr, outlived_fr);
666
667                db
668            }
669        };
670
671        if let ConstraintCategory::CallArgument(Some(ty)) = category {
672            self.explain_impl_static_obligation(&mut diag, ty, outlived_fr);
673        }
674
675        match variance_info {
676            ty::VarianceDiagInfo::None => {}
677            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
678                let (desc, note) = match ty.kind() {
679                    ty::RawPtr(ty, mutbl) => {
680                        {
    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);
681                        (
682                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable pointer to `{0}`", ty))
    })format!("a mutable pointer to `{}`", ty),
683                            "mutable pointers are invariant over their type parameter".to_string(),
684                        )
685                    }
686                    ty::Ref(_, inner_ty, mutbl) => {
687                        {
    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);
688                        (
689                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable reference to `{0}`",
                inner_ty))
    })format!("a mutable reference to `{inner_ty}`"),
690                            "mutable references are invariant over their type parameter"
691                                .to_string(),
692                        )
693                    }
694                    ty::Adt(adt, args) => {
695                        let generic_arg = args[param_index as usize];
696                        let identity_args =
697                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
698                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
699                        let base_generic_arg = identity_args[param_index as usize];
700                        let adt_desc = adt.descr();
701
702                        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!(
703                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
704                        );
705                        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!(
706                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
707                        );
708                        (desc, note)
709                    }
710                    ty::FnDef(def_id, _) => {
711                        let name = self.infcx.tcx.item_name(*def_id);
712                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
713                        let desc = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the function item type defined by `{0}`",
                name))
    })format!("the function item type defined by `{name}`");
714                        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!(
715                            "the function `{name}` is invariant over the parameter `{}`",
716                            identity_args[param_index as usize]
717                        );
718                        (desc, note)
719                    }
720                    _ => { ::core::panicking::panic_fmt(format_args!("Unexpected type {0:?}", ty)); }panic!("Unexpected type {ty:?}"),
721                };
722                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs because of {0}",
                desc))
    })format!("requirement occurs because of {desc}",));
723                diag.note(note);
724                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
725            }
726        }
727
728        self.add_placeholder_from_predicate_note(&mut diag, path);
729        self.add_sized_or_copy_bound_info(&mut diag, category, path);
730
731        for constraint in path {
732            if let ConstraintCategory::Cast { is_raw_ptr_dyn_type_cast: true, .. } =
733                constraint.category
734            {
735                diag.span_note(
736                    constraint.span,
737                    ::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"),
738                );
739                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this was previously accepted by the compiler but was changed recently"))
    })format!(
740                    "this was previously accepted by the compiler but was changed recently"
741                ));
742                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("see <https://github.com/rust-lang/rust/issues/141402> for more information"))
    })format!(
743                    "see <https://github.com/rust-lang/rust/issues/141402> for more information"
744                ));
745            }
746        }
747
748        self.buffer_error(diag);
749    }
750
751    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
752    /// This function expects `fr` to be local and `outlived_fr` to not be local.
753    ///
754    /// ```text
755    /// error: captured variable cannot escape `FnMut` closure body
756    ///   --> $DIR/issue-53040.rs:15:8
757    ///    |
758    /// LL |     || &mut v;
759    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
760    ///    |     |
761    ///    |     inferred to be a `FnMut` closure
762    ///    |
763    ///    = note: `FnMut` closures only have access to their captured variables while they are
764    ///            executing...
765    ///    = note: ...therefore, returned references to captured variables will escape the closure
766    /// ```
767    fn report_fnmut_error(
768        &self,
769        errci: &ErrorConstraintInfo<'tcx>,
770        kind: ReturnConstraint,
771    ) -> Diag<'diag> {
772        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
773
774        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
775        if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *output_ty.kind() {
776            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
777        };
778
779        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:779",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(779u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_fnmut_error: output_ty={0:?}",
                                                    output_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_fnmut_error: output_ty={:?}", output_ty);
780
781        let err = FnMutError {
782            span: *span,
783            ty_err: match output_ty.kind() {
784                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
785                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
786                }
787                _ if output_ty.contains_closure() => {
788                    FnMutReturnTypeErr::ReturnClosure { span: *span }
789                }
790                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
791            },
792        };
793
794        let mut diag = self.dcx().create_err(err);
795
796        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
797            let def_id = match self.regioncx.universal_regions().defining_ty {
798                DefiningTy::Closure(def_id, _) => def_id,
799                ty => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected DefiningTy {0:?}", ty), Location::caller())bug!("unexpected DefiningTy {:?}", ty),
800            };
801
802            let captured_place = &self.upvars[upvar_field.index()].place;
803            let defined_hir = match captured_place.base {
804                PlaceBase::Local(hirid) => Some(hirid),
805                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
806                _ => None,
807            };
808
809            if let Some(def_hir) = defined_hir {
810                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
811                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
812                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
813                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
814                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
815            }
816        }
817
818        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
819            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
820        }
821
822        self.suggest_move_on_borrowing_closure(&mut diag);
823
824        diag
825    }
826
827    /// Reports an error specifically for when data is escaping a closure.
828    ///
829    /// ```text
830    /// error: borrowed data escapes outside of function
831    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
832    ///    |
833    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
834    ///    |              - `x` is only valid in the function body
835    /// LL |     // but ref_obj will not, so warn.
836    /// LL |     ref_obj(x)
837    ///    |     ^^^^^^^^^^ `x` escapes the function body here
838    /// ```
839    {}
#[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("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(839u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("errci")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("errci");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errci)
                                                            as &dyn ::tracing::field::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<'diag> = 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()
                    ||
                    (fr_name_and_span.is_none() &&
                            self.regioncx.universal_regions().defining_ty.is_fn_def()) {
                return self.report_general_error(errci);
            }
            let mut diag =
                borrowck_errors::borrowed_data_escapes_closure(self.dcx(),
                    *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 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.regioncx.to_error_region(errci.fr),
                    self.regioncx.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))]
840    fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'diag> {
841        let ErrorConstraintInfo { span, category, .. } = errci;
842
843        let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
844            self.infcx.tcx,
845            self.body,
846            &self.local_names(),
847            &self.upvars,
848            errci.fr,
849        );
850        let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
851            self.infcx.tcx,
852            self.body,
853            &self.local_names(),
854            &self.upvars,
855            errci.outlived_fr,
856        );
857
858        let escapes_from =
859            self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
860
861        // Revert to the normal error in these cases.
862        // Assignments aren't "escapes" in function items.
863        if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
864            || (*category == ConstraintCategory::Assignment
865                && self.regioncx.universal_regions().defining_ty.is_fn_def())
866            || self.regioncx.universal_regions().defining_ty.is_const()
867            || (fr_name_and_span.is_none()
868                && self.regioncx.universal_regions().defining_ty.is_fn_def())
869        {
870            return self.report_general_error(errci);
871        }
872
873        let mut diag =
874            borrowck_errors::borrowed_data_escapes_closure(self.dcx(), *span, escapes_from);
875
876        if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
877            diag.span_label(
878                outlived_fr_span,
879                format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
880            );
881        }
882
883        if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
884            diag.span_label(
885                fr_span,
886                format!("`{fr_name}` is only valid in the {escapes_from} body"),
887            );
888
889            diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
890        } else {
891            diag.span_label(
892                *span,
893                format!("a temporary borrow escapes the {escapes_from} body here"),
894            );
895            if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
896                diag.help(format!(
897                    "`{outlived_name}` is declared outside the {escapes_from}, \
898                     so any data borrowed inside the {escapes_from} cannot be stored into it"
899                ));
900            }
901        }
902
903        // Only show an extra note if we can find an 'error region' for both of the region
904        // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
905        // that don't help the user understand the error.
906        match (
907            self.regioncx.to_error_region(errci.fr),
908            self.regioncx.to_error_region(errci.outlived_fr),
909        ) {
910            (Some(f), Some(o)) => {
911                self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
912
913                let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
914                fr_region_name.highlight_region_name(&mut diag);
915                let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
916                outlived_fr_region_name.highlight_region_name(&mut diag);
917
918                diag.span_label(
919                    *span,
920                    format!(
921                        "{}requires that `{}` must outlive `{}`",
922                        category.description(),
923                        fr_region_name,
924                        outlived_fr_region_name,
925                    ),
926                );
927            }
928            _ => {}
929        }
930
931        diag
932    }
933
934    /// Reports a region inference error for the general case with named/synthesized lifetimes to
935    /// explain what is happening.
936    ///
937    /// ```text
938    /// error: unsatisfied lifetime constraints
939    ///   --> $DIR/regions-creating-enums3.rs:17:5
940    ///    |
941    /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
942    ///    |                -- -- lifetime `'b` defined here
943    ///    |                |
944    ///    |                lifetime `'a` defined here
945    /// LL |     ast::add(x, y)
946    ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
947    ///    |                    is returning data with lifetime `'b`
948    /// ```
949    fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'diag> {
950        let ErrorConstraintInfo { fr, outlived_fr, span, category, .. } = errci;
951
952        let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
953
954        let err = LifetimeOutliveErr { span: *span };
955        let mut diag = self.dcx().create_err(err);
956
957        // In certain scenarios, such as the one described in issue #118021,
958        // we might encounter a lifetime that cannot be named.
959        // These situations are bound to result in errors.
960        // To prevent an immediate ICE, we opt to create a dummy name instead.
961        let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
962            name: kw::UnderscoreLifetime,
963            source: RegionNameSource::Static,
964        });
965        fr_name.highlight_region_name(&mut diag);
966        let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
967        outlived_fr_name.highlight_region_name(&mut diag);
968
969        let err_category = if #[allow(non_exhaustive_omitted_patterns)] match category {
    ConstraintCategory::Return(_) => true,
    _ => false,
}matches!(category, ConstraintCategory::Return(_))
970            && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
971        {
972            LifetimeReturnCategoryErr::WrongReturn {
973                span: *span,
974                mir_def_name,
975                outlived_fr_name,
976                fr_name: &fr_name,
977            }
978        } else {
979            LifetimeReturnCategoryErr::ShortReturn {
980                span: *span,
981                category_desc: category.description(),
982                free_region_name: &fr_name,
983                outlived_fr_name,
984            }
985        };
986
987        diag.subdiagnostic(err_category);
988
989        self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
990        self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
991        self.suggest_move_on_borrowing_closure(&mut diag);
992        self.suggest_deref_closure_return(&mut diag);
993
994        diag
995    }
996
997    /// Adds a suggestion to errors where an `impl Trait` is returned.
998    ///
999    /// ```text
1000    /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
1001    ///       a constraint
1002    ///    |
1003    /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
1004    ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1005    /// ```
1006    fn add_static_impl_trait_suggestion(
1007        &self,
1008        diag: &mut Diag<'_>,
1009        fr: RegionVid,
1010        // We need to pass `fr_name` - computing it again will label it twice.
1011        fr_name: RegionName,
1012        outlived_fr: RegionVid,
1013    ) {
1014        if let (Some(f), Some(outlived_f)) =
1015            (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
1016        {
1017            if outlived_f.kind() != ty::ReStatic {
1018                return;
1019            }
1020            let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
1021            let Some(suitable_region) = suitable_region else {
1022                return;
1023            };
1024
1025            let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
1026
1027            let Some(param) =
1028                find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
1029            else {
1030                return;
1031            };
1032
1033            let lifetime =
1034                if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
1035
1036            let arg = match param.param.pat.simple_ident() {
1037                Some(simple_ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument `{0}`", simple_ident))
    })format!("argument `{simple_ident}`"),
1038                None => "the argument".to_string(),
1039            };
1040            let captures = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("captures data from {0}", arg))
    })format!("captures data from {arg}");
1041
1042            if !fn_returns.is_empty() {
1043                nice_region_error::suggest_new_region_bound(
1044                    self.infcx.tcx,
1045                    diag,
1046                    fn_returns,
1047                    lifetime.to_string(),
1048                    Some(arg),
1049                    captures,
1050                    Some((param.param_ty_span, param.param_ty.to_string())),
1051                    Some(suitable_region.scope),
1052                );
1053                return;
1054            }
1055
1056            let Some((alias_tys, alias_span, lt_addition_span)) = self
1057                .infcx
1058                .tcx
1059                .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
1060            else {
1061                return;
1062            };
1063
1064            // in case the return type of the method is a type alias
1065            let mut spans_suggs: Vec<_> = Vec::new();
1066            for alias_ty in alias_tys {
1067                if alias_ty.span.desugaring_kind().is_some() {
1068                    // Skip `async` desugaring `impl Future`.
1069                    continue;
1070                }
1071                if let TyKind::TraitObject(_, lt) = alias_ty.kind {
1072                    if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
1073                        spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
1074                    } else {
1075                        spans_suggs.push((lt.ident.span, "'a".to_string()));
1076                    }
1077                }
1078            }
1079
1080            if let Some(lt_addition_span) = lt_addition_span {
1081                spans_suggs.push((lt_addition_span, "'a, ".to_string()));
1082            } else {
1083                spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
1084            }
1085
1086            diag.multipart_suggestion(
1087                ::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!(
1088                    "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
1089                ),
1090                spans_suggs,
1091                Applicability::MaybeIncorrect,
1092            );
1093        }
1094    }
1095
1096    fn maybe_suggest_constrain_dyn_trait_impl(
1097        &self,
1098        diag: &mut Diag<'_>,
1099        f: Region<'tcx>,
1100        o: Region<'tcx>,
1101        category: &ConstraintCategory<'tcx>,
1102    ) {
1103        if !o.is_static() {
1104            return;
1105        }
1106
1107        let tcx = self.infcx.tcx;
1108
1109        let ConstraintCategory::CallArgument(Some(func_ty)) = category else { return };
1110        let ty::FnDef(fn_did, args) = *func_ty.kind() else { return };
1111        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1111",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1111u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("fn_did")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("fn_did");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("args")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("args");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_did)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?fn_did, ?args);
1112
1113        // Only suggest this on function calls, not closures
1114        let ty = tcx.type_of(fn_did).instantiate_identity().skip_norm_wip();
1115        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1115",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1115u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ty: {0:?}, ty.kind: {1:?}",
                                                    ty, ty.kind()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind());
1116        if let ty::Closure(_, _) = ty.kind() {
1117            return;
1118        }
1119        let Ok(Some(instance)) = ty::Instance::try_resolve(
1120            tcx,
1121            self.infcx.typing_env(self.infcx.param_env),
1122            fn_did,
1123            self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
1124        ) else {
1125            return;
1126        };
1127
1128        let Some(param) = find_param_with_region(tcx, self.mir_def_id(), f, o) else {
1129            return;
1130        };
1131        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1131",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1131u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("param")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("param");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&param)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?param);
1132
1133        let mut visitor = TraitObjectVisitor(FxIndexSet::default());
1134        visitor.visit_ty(param.param_ty);
1135
1136        let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
1137            tcx,
1138            instance.def_id(),
1139            &visitor.0,
1140        ) else {
1141            return;
1142        };
1143
1144        self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
1145    }
1146
1147    {}
#[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("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1147u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("found_dids")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("found_dids");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ident");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self_ty");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found_dids)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ident)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                            as &dyn ::tracing::field::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 /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1155",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1155u32),
                                    ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("err: {0:#?}",
                                                                err) as &dyn ::tracing::field::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 /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1161",
                                        "rustc_borrowck::diagnostics::region_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1161u32),
                                        ::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};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("trait spans found: {0:?}",
                                                                    traits) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                for span in &traits {
                    let mut multi_span: MultiSpan =
                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                    [*span])).into();
                    multi_span.push_span_label(*span,
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this has an implicit `'static` lifetime requirement")));
                    multi_span.push_span_label(ident.span,
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("calling this method introduces the `impl`'s `'static` requirement")));
                    err.subdiagnostic(RequireStaticErr::UsedImpl {
                            multi_span,
                        });
                    err.span_suggestion_verbose(span.shrink_to_hi(),
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider relaxing the implicit `'static` requirement")),
                        " + '_", Applicability::MaybeIncorrect);
                    suggested = true;
                }
            }
            suggested
        }
    }
}#[instrument(skip(self, err), level = "debug")]
1148    fn suggest_constrain_dyn_trait_in_impl(
1149        &self,
1150        err: &mut Diag<'_>,
1151        found_dids: &FxIndexSet<DefId>,
1152        ident: Ident,
1153        self_ty: &hir::Ty<'_>,
1154    ) -> bool {
1155        debug!("err: {:#?}", err);
1156        let mut suggested = false;
1157        for found_did in found_dids {
1158            let mut traits = vec![];
1159            let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
1160            hir_v.visit_ty_unambig(self_ty);
1161            debug!("trait spans found: {:?}", traits);
1162            for span in &traits {
1163                let mut multi_span: MultiSpan = vec![*span].into();
1164                multi_span.push_span_label(
1165                    *span,
1166                    msg!("this has an implicit `'static` lifetime requirement"),
1167                );
1168                multi_span.push_span_label(
1169                    ident.span,
1170                    msg!("calling this method introduces the `impl`'s `'static` requirement"),
1171                );
1172                err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
1173                err.span_suggestion_verbose(
1174                    span.shrink_to_hi(),
1175                    msg!("consider relaxing the implicit `'static` requirement"),
1176                    " + '_",
1177                    Applicability::MaybeIncorrect,
1178                );
1179                suggested = true;
1180            }
1181        }
1182        suggested
1183    }
1184
1185    fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
1186        let (Some(sub), Some(sup)) =
1187            (self.regioncx.to_error_region(sub), self.regioncx.to_error_region(sup))
1188        else {
1189            return;
1190        };
1191
1192        let Some((ty_sub, _)) = self
1193            .infcx
1194            .tcx
1195            .is_suitable_region(self.mir_def_id(), sub)
1196            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
1197        else {
1198            return;
1199        };
1200
1201        let Some((ty_sup, _)) = self
1202            .infcx
1203            .tcx
1204            .is_suitable_region(self.mir_def_id(), sup)
1205            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1206        else {
1207            return;
1208        };
1209
1210        suggest_adding_lifetime_params(
1211            self.infcx.tcx,
1212            diag,
1213            self.mir_def_id(),
1214            sub,
1215            ty_sup,
1216            ty_sub,
1217        );
1218    }
1219
1220    /// When encountering a lifetime error caused by the return type of a closure, check the
1221    /// corresponding trait bound and see if dereferencing the closure return value would satisfy
1222    /// them. If so, we produce a structured suggestion.
1223    fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1224        let tcx = self.infcx.tcx;
1225
1226        // Get the closure return value and type.
1227        let closure_def_id = self.mir_def_id();
1228        let hir::Node::Expr(
1229            closure_expr @ hir::Expr {
1230                kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1231            },
1232        ) = tcx.hir_node_by_def_id(closure_def_id)
1233        else {
1234            return;
1235        };
1236        let ty::Closure(_, args) =
1237            *tcx.type_of(closure_def_id).instantiate_identity().skip_norm_wip().kind()
1238        else {
1239            return;
1240        };
1241        let args = args.as_closure();
1242
1243        // Make sure that the parent expression is a method call.
1244        let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1245        let hir::Node::Expr(
1246            parent_expr @ hir::Expr {
1247                kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1248            },
1249        ) = tcx.hir_node(parent_expr_id)
1250        else {
1251            return;
1252        };
1253        let typeck_results = tcx.typeck(self.mir_def_id());
1254
1255        // We don't use `ty.peel_refs()` to get the number of `*`s needed to get the root type.
1256        let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1257        let mut peeled_ty = liberated_sig.output();
1258        let mut count = 0;
1259        while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1260            peeled_ty = ref_ty;
1261            count += 1;
1262        }
1263        if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1264            return;
1265        }
1266
1267        // Build a new closure where the return type is an owned value, instead of a ref.
1268        // The new closure is safe, but otherwise has the same ABI, splat, and c-variadic.
1269        let fn_sig_kind = liberated_sig.fn_sig_kind.set_safety(hir::Safety::Safe);
1270        let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1271            tcx,
1272            ty::Binder::dummy(tcx.mk_fn_sig(
1273                liberated_sig.inputs().iter().copied(),
1274                peeled_ty,
1275                fn_sig_kind,
1276            )),
1277        );
1278        let closure_ty = Ty::new_closure(
1279            tcx,
1280            closure_def_id.to_def_id(),
1281            ty::ClosureArgs::new(
1282                tcx,
1283                ty::ClosureArgsParts {
1284                    parent_args: args.parent_args(),
1285                    closure_kind_ty: args.kind_ty(),
1286                    tupled_upvars_ty: args.tupled_upvars_ty(),
1287                    closure_sig_as_fn_ptr_ty,
1288                },
1289            )
1290            .args,
1291        );
1292
1293        let Some((closure_arg_pos, _)) =
1294            call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1295        else {
1296            return;
1297        };
1298        // Get the type for the parameter corresponding to the argument the closure with the
1299        // lifetime error we had.
1300        let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1301            return;
1302        };
1303        let Some(input_arg) = tcx
1304            .fn_sig(method_def_id)
1305            .skip_binder()
1306            .inputs()
1307            .skip_binder()
1308            // Methods have a `self` arg, so `pos` is actually `+ 1` to match the method call arg.
1309            .get(closure_arg_pos + 1)
1310        else {
1311            return;
1312        };
1313        // If this isn't a param, then we can't substitute a new closure.
1314        let ty::Param(closure_param) = input_arg.kind() else { return };
1315
1316        // Get the arguments for the found method, only specifying that `Self` is the receiver type.
1317        let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1318        let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1319            if let ty::GenericParamDefKind::Lifetime = param.kind {
1320                tcx.lifetimes.re_erased.into()
1321            } else if param.index == 0 && param.name == kw::SelfUpper {
1322                possible_rcvr_ty.into()
1323            } else if param.index == closure_param.index {
1324                closure_ty.into()
1325            } else {
1326                self.infcx.var_for_def(parent_expr.span, param)
1327            }
1328        });
1329
1330        let clauses = tcx.clauses_of(method_def_id).instantiate(tcx, args);
1331
1332        let ocx = ObligationCtxt::new(&self.infcx);
1333        ocx.register_obligations(clauses.iter().map(|(clause, span)| {
1334            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1334",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/19833af7224424e8b53e288097d56b6af43d5bcf/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1334u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("clause")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("clause");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?clause);
1335            Obligation::misc(
1336                tcx,
1337                span,
1338                self.mir_def_id(),
1339                self.infcx.param_env,
1340                clause.skip_norm_wip(),
1341            )
1342        }));
1343
1344        if ocx.evaluate_obligations_error_on_ambiguity().no_errors() && count > 0 {
1345            diag.span_suggestion_verbose(
1346                tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1347                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("dereference the return value"))msg!("dereference the return value"),
1348                "*".repeat(count),
1349                Applicability::MachineApplicable,
1350            );
1351        }
1352    }
1353
1354    fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1355        let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1356        let expr = &body.value.peel_blocks();
1357        let mut closure_span = None::<rustc_span::Span>;
1358        match expr.kind {
1359            hir::ExprKind::MethodCall(.., args, _) => {
1360                for arg in args {
1361                    if let hir::ExprKind::Closure(hir::Closure {
1362                        capture_clause: hir::CaptureBy::Ref,
1363                        ..
1364                    }) = arg.kind
1365                    {
1366                        closure_span = Some(arg.span.shrink_to_lo());
1367                        break;
1368                    }
1369                }
1370            }
1371            hir::ExprKind::Closure(hir::Closure {
1372                capture_clause: hir::CaptureBy::Ref,
1373                kind,
1374                ..
1375            }) => {
1376                if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
        _)) => true,
    _ => false,
}matches!(
1377                    kind,
1378                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1379                        hir::CoroutineDesugaring::Async,
1380                        _
1381                    ),)
1382                ) {
1383                    closure_span = Some(expr.span.shrink_to_lo());
1384                }
1385            }
1386            _ => {}
1387        }
1388        if let Some(closure_span) = closure_span {
1389            diag.span_suggestion_verbose(
1390                closure_span,
1391                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding 'move' keyword before the nested closure"))msg!("consider adding 'move' keyword before the nested closure"),
1392                "move ",
1393                Applicability::MaybeIncorrect,
1394            );
1395        }
1396    }
1397}