Skip to main content

rustc_borrowck/diagnostics/
region_errors.rs

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