Skip to main content

rustc_borrowck/diagnostics/
region_errors.rs

1//! Error reporting machinery for lifetime errors.
2
3use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
4use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, msg};
5use rustc_hir as hir;
6use rustc_hir::GenericBound::Trait;
7use rustc_hir::QPath::Resolved;
8use rustc_hir::WherePredicateKind::BoundPredicate;
9use rustc_hir::def::DefKind;
10use rustc_hir::def::Res::Def;
11use rustc_hir::def_id::DefId;
12use rustc_hir::intravisit::Visitor;
13use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate};
14use rustc_infer::infer::{NllRegionVariableOrigin, SubregionOrigin};
15use rustc_middle::hir::place::PlaceBase;
16use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint};
17use rustc_middle::ty::{
18    self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions,
19};
20use rustc_span::{Ident, Span, Symbol, bug, kw};
21use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
22use rustc_trait_selection::error_reporting::infer::nice_region_error::{
23    self, HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, find_anon_type,
24    find_param_with_region, suggest_adding_lifetime_params,
25};
26use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor;
27use rustc_trait_selection::infer::InferCtxtExt;
28use rustc_trait_selection::traits::{Obligation, ObligationCtxt};
29use tracing::{debug, instrument, trace};
30
31use super::{LIMITATION_NOTE, OutlivesSuggestionBuilder, RegionName, RegionNameSource};
32use crate::consumers::OutlivesConstraint;
33use crate::nll::ConstraintDescription;
34use crate::region_infer::{RegionInferenceContext, TypeTest};
35use crate::session_diagnostics::{
36    FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr,
37    LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
38};
39use crate::universal_regions::DefiningTy;
40use crate::{MirBorrowckCtxt, borrowck_errors};
41
42impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
43    fn description(&self) -> &'static str {
44        // Must end with a space. Allows for empty names to be provided.
45        match self {
46            ConstraintCategory::Assignment => "assignment ",
47            ConstraintCategory::Return(_) => "returning this value ",
48            ConstraintCategory::Yield => "yielding this value ",
49            ConstraintCategory::UseAsConst => "using this value as a constant ",
50            ConstraintCategory::UseAsStatic => "using this value as a static ",
51            ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ",
52            ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ",
53            ConstraintCategory::CallArgument(_) => "argument ",
54            ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg) => "generic argument ",
55            ConstraintCategory::TypeAnnotation(_) => "type annotation ",
56            ConstraintCategory::SizedBound => "proving this value is `Sized` ",
57            ConstraintCategory::CopyBound => "copying this value ",
58            ConstraintCategory::OpaqueType => "opaque type ",
59            ConstraintCategory::ClosureUpvar(_) => "closure capture ",
60            ConstraintCategory::Usage => "this usage ",
61            ConstraintCategory::SolverRegionConstraint(_)
62            | ConstraintCategory::Predicate(_, _)
63            | ConstraintCategory::Boring
64            | ConstraintCategory::BoringNoLocation
65            | ConstraintCategory::Internal
66            | ConstraintCategory::OutlivesUnnameablePlaceholder(..) => "",
67        }
68    }
69}
70
71/// A collection of errors encountered during region inference. This is needed to efficiently
72/// report errors after borrow checking.
73///
74/// Usually we expect this to either be empty or contain a small number of items, so we can avoid
75/// allocation most of the time.
76pub(crate) struct RegionErrors<'tcx>(Vec<(RegionErrorKind<'tcx>, ErrorGuaranteed)>, TyCtxt<'tcx>);
77
78impl<'tcx> RegionErrors<'tcx> {
79    pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
80        Self(::alloc::vec::Vec::new()vec![], tcx)
81    }
82    #[track_caller]
83    pub(crate) fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
84        let val = val.into();
85        let guar = self.1.sess.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", val))
    })format!("{val:?}"));
86        self.0.push((val, guar));
87    }
88    pub(crate) fn is_empty(&self) -> bool {
89        self.0.is_empty()
90    }
91    pub(crate) fn into_iter(
92        self,
93    ) -> impl Iterator<Item = (RegionErrorKind<'tcx>, ErrorGuaranteed)> {
94        self.0.into_iter()
95    }
96}
97
98impl std::fmt::Debug for RegionErrors<'_> {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.debug_tuple("RegionErrors").field(&self.0).finish()
101    }
102}
103
104#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    RegionErrorKind<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::TypeTestError { type_test: __self_0 } =>
                RegionErrorKind::TypeTestError {
                    type_test: ::core::clone::Clone::clone(__self_0),
                },
            Self::PlaceholderOutlivesIllegalRegion {
                longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
                RegionErrorKind::PlaceholderOutlivesIllegalRegion {
                    longer_fr: ::core::clone::Clone::clone(__self_0),
                    illegally_outlived_r: ::core::clone::Clone::clone(__self_1),
                },
            Self::RegionError {
                fr_origin: __self_0,
                longer_fr: __self_1,
                shorter_fr: __self_2,
                is_reported: __self_3 } =>
                RegionErrorKind::RegionError {
                    fr_origin: ::core::clone::Clone::clone(__self_0),
                    longer_fr: ::core::clone::Clone::clone(__self_1),
                    shorter_fr: ::core::clone::Clone::clone(__self_2),
                    is_reported: ::core::clone::Clone::clone(__self_3),
                },
        }
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
    RegionErrorKind<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::TypeTestError { type_test: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TypeTestError type_test", &__self_0),
            Self::PlaceholderOutlivesIllegalRegion {
                longer_fr: __self_0, illegally_outlived_r: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "PlaceholderOutlivesIllegalRegion longer_fr illegally_outlived_r",
                    __self_0, &__self_1),
            Self::RegionError {
                fr_origin: __self_0,
                longer_fr: __self_1,
                shorter_fr: __self_2,
                is_reported: __self_3 } =>
                ::core::fmt::Formatter::debug_struct_field4_finish(f,
                    "RegionError fr_origin longer_fr shorter_fr is_reported",
                    __self_0, __self_1, __self_2, &__self_3),
        }
    }
}Debug)]
105pub(crate) enum RegionErrorKind<'tcx> {
106    /// A generic bound failure for a type test (`T: 'a`).
107    TypeTestError { type_test: TypeTest<'tcx> },
108
109    /// 'p outlives 'r, which does not hold. 'p is always a placeholder
110    /// and 'r is some other region.
111    PlaceholderOutlivesIllegalRegion { longer_fr: RegionVid, illegally_outlived_r: RegionVid },
112
113    /// Any other lifetime error.
114    RegionError {
115        /// The origin of the region.
116        fr_origin: NllRegionVariableOrigin<'tcx>,
117        /// The region that should outlive `shorter_fr`.
118        longer_fr: RegionVid,
119        /// The region that should be shorter, but we can't prove it.
120        shorter_fr: RegionVid,
121        /// Indicates whether this is a reported error. We currently only report the first error
122        /// encountered and leave the rest unreported so as not to overwhelm the user.
123        is_reported: bool,
124    },
125}
126
127/// Information about the various region constraints involved in a borrow checker error.
128#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
    ErrorConstraintInfo<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        ErrorConstraintInfo {
            fr: ::core::clone::Clone::clone(&self.fr),
            outlived_fr: ::core::clone::Clone::clone(&self.outlived_fr),
            category: ::core::clone::Clone::clone(&self.category),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
    ErrorConstraintInfo<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "ErrorConstraintInfo fr outlived_fr category span", &self.fr,
            &self.outlived_fr, &self.category, &&self.span)
    }
}Debug)]
129pub(crate) struct ErrorConstraintInfo<'tcx> {
130    // fr: outlived_fr
131    pub(super) fr: RegionVid,
132    pub(super) outlived_fr: RegionVid,
133
134    // Category and span for best blame constraint
135    pub(super) category: ConstraintCategory<'tcx>,
136    pub(super) span: Span,
137}
138
139impl<'tcx> RegionInferenceContext<'tcx> {
140    /// Converts a region inference variable into a `ty::Region` that
141    /// we can use for error reporting. If `r` is universally bound,
142    /// then we use the name that we have on record for it. If `r` is
143    /// existentially bound, then we check its inferred value and try
144    /// to find a good name from that. Returns `None` if we can't find
145    /// one (e.g., this is just some random part of the CFG).
146    pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
147        self.to_error_region_vid(r).and_then(|r| self.region_definition(r).external_name)
148    }
149
150    /// Returns the `RegionVid` corresponding to the region returned by
151    /// `to_error_region`.
152    pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
153        if self.universal_regions().is_universal_region(r) {
154            Some(r)
155        } else {
156            // We just want something nameable, even if it's not
157            // actually an upper bound.
158            let upper_bound = self.approx_universal_upper_bound(r);
159
160            if self.upper_bound_in_region_scc(r, upper_bound) {
161                self.to_error_region_vid(upper_bound)
162            } else {
163                None
164            }
165        }
166    }
167
168    /// Map the regions in the type to named regions, where possible.
169    fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
170    where
171        T: TypeFoldable<TyCtxt<'tcx>>,
172    {
173        fold_regions(tcx, ty, |region, _| match region.kind() {
174            ty::ReVar(vid) => self.to_error_region(vid).unwrap_or(region),
175            _ => region,
176        })
177    }
178
179    /// Returns `true` if a closure is inferred to be an `FnMut` closure.
180    fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
181        if let Some(r) = self.to_error_region(fr)
182            && let ty::ReLateParam(late_param) = r.kind()
183            && let ty::LateParamRegionKind::ClosureEnv = late_param.kind
184            && let DefiningTy::Closure(_, args) = self.universal_regions().defining_ty
185        {
186            return args.as_closure().kind() == ty::ClosureKind::FnMut;
187        }
188
189        false
190    }
191}
192
193impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> {
194    // For generic associated types (GATs) which implied 'static requirement
195    // from higher-ranked trait bounds (HRTB). Try to locate span of the trait
196    // and the span which bounded to the trait for adding 'static lifetime suggestion
197    fn suggest_static_lifetime_for_gat_from_hrtb(
198        &self,
199        diag: &mut Diag<'_>,
200        lower_bound: RegionVid,
201    ) {
202        let tcx = self.infcx.tcx;
203
204        // find generic associated types in the given region 'lower_bound'
205        let gat_id_and_generics = self
206            .regioncx
207            .placeholders_contained_in(lower_bound)
208            .map(|placeholder| {
209                if let Some(id) = placeholder.bound.kind.get_id()
210                    && let Some(placeholder_id) = id.as_local()
211                    && let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
212                    && let Some(generics_impl) =
213                        tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
214                {
215                    Some((gat_hir_id, generics_impl))
216                } else {
217                    None
218                }
219            })
220            .collect::<Vec<_>>();
221        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:221",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(221u32),
                        ::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);
222
223        // Look for the where-bound which introduces the placeholder.
224        // As we're using the HIR, we need to handle both `for<'a> T: Trait<'a>`
225        // and `T: for<'a> Trait`<'a>.
226        let mut hrtb_bounds = ::alloc::vec::Vec::new()vec![];
227        gat_id_and_generics.iter().flatten().for_each(|&(gat_hir_id, generics)| {
228            for pred in generics.predicates {
229                let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) =
230                    pred.kind
231                else {
232                    continue;
233                };
234                if bound_generic_params
235                    .iter()
236                    .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
237                    .is_some()
238                {
239                    for bound in *bounds {
240                        hrtb_bounds.push(bound);
241                    }
242                } else {
243                    for bound in *bounds {
244                        if let Trait(trait_bound) = bound {
245                            if trait_bound
246                                .bound_generic_params
247                                .iter()
248                                .rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == gat_hir_id)
249                                .is_some()
250                            {
251                                hrtb_bounds.push(bound);
252                                return;
253                            }
254                        }
255                    }
256                }
257            }
258        });
259        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:259",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(259u32),
                        ::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);
260
261        let mut suggestions = ::alloc::vec::Vec::new()vec![];
262        hrtb_bounds.iter().for_each(|bound| {
263            let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }) = bound else {
264                return;
265            };
266            diag.span_note(*trait_span, LIMITATION_NOTE);
267            let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
268            else {
269                return;
270            };
271            let Def(_, trait_res_defid) = trait_ref.path.res else {
272                return;
273            };
274            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:274",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(274u32),
                        ::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);
275            generics_fn.predicates.iter().for_each(|predicate| {
276                let BoundPredicate(WhereBoundPredicate { bounded_ty, bounds, .. }) = predicate.kind
277                else {
278                    return;
279                };
280                bounds.iter().for_each(|bd| {
281                    if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }) = bd
282                        && let Def(_, res_defid) = tr_ref.path.res
283                        && res_defid == trait_res_defid // trait id matches
284                        && let TyKind::Path(Resolved(_, path)) = bounded_ty.kind
285                        && let Def(_, defid) = path.res
286                        && generics_fn.params
287                            .iter()
288                            .rfind(|param| param.def_id.to_def_id() == defid)
289                            .is_some()
290                    {
291                        suggestions.push((predicate.span.shrink_to_hi(), " + 'static".to_string()));
292                    }
293                });
294            });
295        });
296        if suggestions.len() > 0 {
297            suggestions.dedup();
298            diag.multipart_suggestion(
299                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"),
300                suggestions,
301                Applicability::MaybeIncorrect,
302            );
303        }
304    }
305
306    /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
307    pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
308        // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
309        // buffered in the `MirBorrowckCtxt`.
310        let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
311        for (nll_error, _) in nll_errors.into_iter() {
312            match nll_error {
313                RegionErrorKind::TypeTestError { type_test } => {
314                    // Try to convert the lower-bound region into something named we can print for
315                    // the user.
316                    let lower_bound_region = self.regioncx.to_error_region(type_test.lower_bound);
317
318                    let type_test_span = type_test.span;
319
320                    if let Some(lower_bound_region) = lower_bound_region {
321                        let generic_ty = self.regioncx.name_regions(
322                            self.infcx.tcx,
323                            type_test.generic_kind.to_ty(self.infcx.tcx),
324                        );
325                        let origin =
326                            SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
327                        self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
328                            self.body.source.def_id().expect_local(),
329                            type_test_span,
330                            Some(origin),
331                            self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
332                            lower_bound_region,
333                        ));
334                    } else {
335                        // FIXME. We should handle this case better. It
336                        // indicates that we have e.g., some region variable
337                        // whose value is like `'a+'b` where `'a` and `'b` are
338                        // distinct unrelated universal regions that are not
339                        // known to outlive one another. It'd be nice to have
340                        // some examples where this arises to decide how best
341                        // to report it; we could probably handle it by
342                        // iterating over the universal regions and reporting
343                        // an error that multiple bounds are required.
344                        let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
345                            kind: type_test.generic_kind.to_string(),
346                            span: type_test_span,
347                        });
348
349                        // Add notes and suggestions for the case of 'static lifetime
350                        // implied but not specified when a generic associated types
351                        // are from higher-ranked trait bounds
352                        self.suggest_static_lifetime_for_gat_from_hrtb(
353                            &mut diag,
354                            type_test.lower_bound,
355                        );
356
357                        self.buffer_error(diag);
358                    }
359                }
360
361                RegionErrorKind::PlaceholderOutlivesIllegalRegion {
362                    longer_fr,
363                    illegally_outlived_r,
364                } => {
365                    self.report_erroneous_rvid_reaches_placeholder(longer_fr, illegally_outlived_r)
366                }
367
368                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
369                    if is_reported {
370                        self.report_region_error(
371                            longer_fr,
372                            fr_origin,
373                            shorter_fr,
374                            &mut outlives_suggestion,
375                        );
376                    } else {
377                        // We only report the first error, so as not to overwhelm the user. See
378                        // `RegRegionErrorKind` docs.
379                        //
380                        // FIXME: currently we do nothing with these, but perhaps we can do better?
381                        // FIXME: try collecting these constraints on the outlives suggestion
382                        // builder. Does it make the suggestions any better?
383                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:383",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(383u32),
                        ::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!(
384                            "Unreported region error: can't prove that {:?}: {:?}",
385                            longer_fr, shorter_fr
386                        );
387                    }
388                }
389            }
390        }
391
392        // Emit one outlives suggestions for each MIR def we borrowck
393        outlives_suggestion.add_suggestion(self);
394    }
395
396    /// Point at `'static` obligations from the item being called.
397    ///
398    /// ```text
399    /// error[E0521]: borrowed data escapes outside of function
400    ///   --> $DIR/static-impl-obligation.rs:163:9
401    ///    |
402    /// LL |     fn bar<'a>(x: &'a &'a u32) {
403    ///    |            --  - `x` is only valid in the function body
404    ///    |            |
405    ///    |            lifetime `'a` defined here
406    /// LL |         let y: &dyn Foo = x;
407    /// LL |         y.hello();
408    ///    |         ^^^^^^^^^
409    ///    |         |
410    ///    |         `x` escapes the function body here
411    ///    |         argument requires that `'a` must outlive `'static`
412    ///    |
413    /// note: `'static` lifetime requirement from `<(dyn o::Foo + 'static)>::hello` introduced here
414    ///   --> $DIR/static-impl-obligation.rs:158:20
415    ///    |
416    /// LL |     impl dyn Foo + 'static where Self: 'static {
417    ///    |                    ^^^^^^^             ^^^^^^^ lifetime requirement introduced here
418    ///    |                    |
419    ///    |                    lifetime requirement introduced here
420    /// LL |         fn hello(&'static self) where Self: 'static {}
421    ///    |                  ^^^^^^^^^^^^^              ^^^^^^^ lifetime requirement introduced here
422    ///    |                  |
423    ///    |                  lifetime requirement introduced here
424    /// ```
425    fn explain_impl_static_obligation(
426        &self,
427        diag: &mut Diag<'_>,
428        ty: Ty<'tcx>,
429        outlived_fr: RegionVid,
430    ) {
431        let tcx = self.infcx.tcx;
432        if self.regioncx.to_error_region(outlived_fr) != Some(tcx.lifetimes.re_static) {
433            return;
434        }
435        let ty::FnDef(def_id, args) = ty.kind() else {
436            return;
437        };
438        let typing_env = self.infcx.typing_env(self.infcx.param_env);
439        let Ok(Some(instance)) = ty::Instance::try_resolve(
440            tcx,
441            typing_env,
442            *def_id,
443            self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
444        ) else {
445            return;
446        };
447        let def_id = instance.def_id();
448        if tcx.is_closure_like(def_id) {
449            // Closures don't have a `fn_sig` query result and cannot introduce the `'static`
450            // obligations this function looks for
451            return;
452        }
453        let mut bounds =
454            tcx.clauses_of(def_id)
455                .instantiate(tcx, instance.args)
456                .into_iter()
457                .map(|(c, sp)| (c.skip_norm_wip().as_predicate(), sp))
458                .filter(|(pred, _)| match pred.kind().skip_binder() {
459                    ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
460                        ty::OutlivesClause(_, lt),
461                    ))
462                    | ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
463                        ty::OutlivesClause(_, lt),
464                    )) if lt.is_static() => true,
465                    _ => false,
466                })
467                .map(|(_, sp)| sp)
468                .collect::<Vec<Span>>();
469
470        let mut labels = FxHashMap::default();
471
472        let parent = tcx.parent(def_id);
473        if let Some(rcvr) =
474            tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().get(0)
475        {
476            // Look at the receiver for `&'static self`, which introduces a `'static` obligation.
477            // ```
478            // impl Foo {
479            //     fn foo(&'static self) {}
480            //            ^^^^^^^^^^^^^
481            // ```
482            if let ty::Ref(region, _, _) = rcvr.kind()
483                && *region == tcx.lifetimes.re_static
484                && let Some(assoc) = tcx.opt_associated_item(def_id)
485                && assoc.is_method()
486            {
487                let def_span = tcx.def_span(def_id);
488                // We have a `&'static self` receiver.
489                if let Some(def_id) = def_id.as_local()
490                    && let owner = tcx.expect_hir_owner_node(def_id)
491                    && let Some(decl) = owner.fn_decl()
492                    && let Some(ty) = decl.inputs.get(0)
493                {
494                    // Point at the `&'static self` receiver.
495                    bounds.push(ty.span);
496                } else if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
497                    // The method is not defined on the local crate, point at the signature instead of
498                    // just the receiver as an approximation. We don't add it if there are already
499                    // other spans with overlap with the def `Span`, as the other will be more specific.
500                    bounds.push(def_span)
501                }
502            }
503
504            if let DefKind::Impl { .. } = tcx.def_kind(parent)
505                && let ty = tcx.type_of(parent).instantiate_identity().skip_norm_wip()
506                && let ty::Dynamic(_, region) = ty.kind()
507                && *region == tcx.lifetimes.re_static
508            {
509                // We have a call into a method of either `impl dyn Trait {}` or
510                // `impl dyn Trait + 'static {}`.
511                if let Some(def_id) = parent.as_local()
512                    && let hir::OwnerNode::Item(item) = tcx.expect_hir_owner_node(def_id)
513                    && let hir::ItemKind::Impl(impl_) = item.kind
514                    && let hir::TyKind::TraitObject(_, tagged_ref) = impl_.self_ty.kind
515                {
516                    if tagged_ref.is_static() {
517                        // impl dyn Trait + 'static {
518                        //                  ^^^^^^^ lifetime requirement introduced here
519                        bounds.push(tagged_ref.pointer().ident.span);
520                    } else if tagged_ref.is_implicit() {
521                        // impl dyn Trait {
522                        //      ^^^^^^^^^ `dyn Trait` introduces an...
523                        bounds.push(impl_.self_ty.span);
524                        labels.insert(
525                            impl_.self_ty.span,
526                            "`dyn Trait` introduces an implicit `'static` lifetime requirement",
527                        );
528                    }
529                } else {
530                    // Non-local `impl`, we don't have a way to differentiate between `+ 'static`
531                    // and bare `dyn Trait`. We point at the whole def `Span` for now.
532                    let def_span = tcx.def_span(parent);
533                    if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
534                        bounds.push(def_span);
535                    }
536                }
537            }
538        }
539
540        if !bounds.is_empty() {
541            let mut multispan: MultiSpan = bounds.clone().into();
542            for span in bounds {
543                let label = labels.get(&span).unwrap_or(&"lifetime requirement introduced here");
544                multispan.push_span_label(span, *label);
545            }
546            multispan.push_span_context(tcx.def_span(def_id).shrink_to_lo());
547            if let DefKind::Impl { .. } | DefKind::Trait = tcx.def_kind(parent) {
548                multispan.push_span_context(tcx.def_span(parent).shrink_to_lo());
549            }
550            diag.span_note(
551                multispan,
552                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`\'static` lifetime requirement from `{0}` introduced here",
                tcx.def_path_str(def_id)))
    })format!(
553                    "`'static` lifetime requirement from `{}` introduced here",
554                    tcx.def_path_str(def_id)
555                ),
556            );
557        }
558    }
559
560    /// Report that `longer_fr: error_vid`, which doesn't hold,
561    /// where `longer_fr` is a placeholder.
562    fn report_erroneous_rvid_reaches_placeholder(
563        &mut self,
564        longer_fr: RegionVid,
565        error_vid: RegionVid,
566    ) {
567        use NllRegionVariableOrigin::*;
568
569        let origin_longer = self.regioncx.definitions[longer_fr].origin;
570
571        let Placeholder(placeholder) = origin_longer else {
572            ::rustc_span::macros::bug_impl(None,
    format_args!("Expected {0:?} to come from placeholder!", longer_fr),
    Location::caller());bug!("Expected {longer_fr:?} to come from placeholder!");
573        };
574
575        // FIXME: Is throwing away the existential region really the best here?
576        let error_region = match self.regioncx.definitions[error_vid].origin {
577            FreeRegion | Existential { .. } => None,
578            Placeholder(other_placeholder) => Some(other_placeholder),
579        };
580
581        // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
582        let best_blame = self.regioncx.best_blame_constraint(longer_fr, origin_longer, error_vid);
583        let cause = best_blame.to_obligation_cause();
584
585        // FIXME these methods should have better names, and also probably not be this generic.
586        // FIXME note that we *throw away* the error element here! We probably want to
587        // thread it through the computation further down and use it, but there currently isn't
588        // anything there to receive it.
589        self.regioncx.universe_info(placeholder.universe).report_erroneous_element(
590            self,
591            placeholder,
592            error_region,
593            cause,
594        );
595    }
596
597    /// Report an error because the universal region `fr` was required to outlive
598    /// `outlived_fr` but it is not known to do so. For example:
599    ///
600    /// ```compile_fail
601    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
602    /// ```
603    ///
604    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
605    pub(crate) fn report_region_error(
606        &mut self,
607        fr: RegionVid,
608        fr_origin: NllRegionVariableOrigin<'tcx>,
609        outlived_fr: RegionVid,
610        outlives_suggestion: &mut OutlivesSuggestionBuilder,
611    ) {
612        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:612",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(612u32),
                        ::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);
613
614        let best_blame = self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
615        let OutlivesConstraint { category, span, variance_info, .. } = *best_blame.constraint();
616        let path = best_blame.path();
617
618        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:618",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(618u32),
                        ::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);
619
620        // Check if we can use one of the "nice region errors".
621        if let (Some(f), Some(o)) =
622            (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
623        {
624            let infer_err = self.infcx.err_ctxt();
625            let nice = NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), span, o, f);
626            if let Some(diag) = nice.try_report_from_nll() {
627                self.buffer_error(diag);
628                return;
629            }
630        }
631
632        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
633            self.regioncx.universal_regions().is_local_free_region(fr),
634            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
635        );
636
637        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:637",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(637u32),
                        ::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!(
638            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
639            fr_is_local, outlived_fr_is_local, category
640        );
641
642        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span };
643
644        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
645            (ConstraintCategory::SolverRegionConstraint(span), _, _) => self
646                .dcx()
647                .struct_span_err(span, "higher-ranked lifetime bound could not be satisfied"),
648            (ConstraintCategory::Return(kind), true, false)
649                if self.regioncx.is_closure_fn_mut(fr) =>
650            {
651                self.report_fnmut_error(&errci, kind)
652            }
653            (ConstraintCategory::Assignment, true, false)
654            | (ConstraintCategory::CallArgument(_), true, false) => {
655                let mut db = self.report_escaping_data_error(&errci);
656
657                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
658                outlives_suggestion.collect_constraint(fr, outlived_fr);
659
660                db
661            }
662            _ => {
663                let mut db = self.report_general_error(&errci);
664
665                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
666                outlives_suggestion.collect_constraint(fr, outlived_fr);
667
668                db
669            }
670        };
671
672        if let ConstraintCategory::CallArgument(Some(ty)) = category {
673            self.explain_impl_static_obligation(&mut diag, ty, outlived_fr);
674        }
675
676        match variance_info {
677            ty::VarianceDiagInfo::None => {}
678            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
679                let (desc, note) = match ty.kind() {
680                    ty::RawPtr(ty, mutbl) => {
681                        {
    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);
682                        (
683                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable pointer to `{0}`", ty))
    })format!("a mutable pointer to `{}`", ty),
684                            "mutable pointers are invariant over their type parameter".to_string(),
685                        )
686                    }
687                    ty::Ref(_, inner_ty, mutbl) => {
688                        {
    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);
689                        (
690                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable reference to `{0}`",
                inner_ty))
    })format!("a mutable reference to `{inner_ty}`"),
691                            "mutable references are invariant over their type parameter"
692                                .to_string(),
693                        )
694                    }
695                    ty::Adt(adt, args) => {
696                        let generic_arg = args[param_index as usize];
697                        let identity_args =
698                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
699                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
700                        let base_generic_arg = identity_args[param_index as usize];
701                        let adt_desc = adt.descr();
702
703                        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!(
704                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
705                        );
706                        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!(
707                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
708                        );
709                        (desc, note)
710                    }
711                    ty::FnDef(def_id, _) => {
712                        let name = self.infcx.tcx.item_name(*def_id);
713                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
714                        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}`");
715                        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!(
716                            "the function `{name}` is invariant over the parameter `{}`",
717                            identity_args[param_index as usize]
718                        );
719                        (desc, note)
720                    }
721                    _ => { ::core::panicking::panic_fmt(format_args!("Unexpected type {0:?}", ty)); }panic!("Unexpected type {ty:?}"),
722                };
723                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs because of {0}",
                desc))
    })format!("requirement occurs because of {desc}",));
724                diag.note(note);
725                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
726            }
727        }
728
729        self.add_placeholder_from_predicate_note(&mut diag, path);
730        self.add_sized_or_copy_bound_info(&mut diag, category, path);
731
732        for constraint in path {
733            if let ConstraintCategory::Cast { is_raw_ptr_dyn_type_cast: true, .. } =
734                constraint.category
735            {
736                diag.span_note(
737                    constraint.span,
738                    ::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"),
739                );
740                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this was previously accepted by the compiler but was changed recently"))
    })format!(
741                    "this was previously accepted by the compiler but was changed recently"
742                ));
743                diag.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("see <https://github.com/rust-lang/rust/issues/141402> for more information"))
    })format!(
744                    "see <https://github.com/rust-lang/rust/issues/141402> for more information"
745                ));
746            }
747        }
748
749        self.buffer_error(diag);
750    }
751
752    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
753    /// This function expects `fr` to be local and `outlived_fr` to not be local.
754    ///
755    /// ```text
756    /// error: captured variable cannot escape `FnMut` closure body
757    ///   --> $DIR/issue-53040.rs:15:8
758    ///    |
759    /// LL |     || &mut v;
760    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
761    ///    |     |
762    ///    |     inferred to be a `FnMut` closure
763    ///    |
764    ///    = note: `FnMut` closures only have access to their captured variables while they are
765    ///            executing...
766    ///    = note: ...therefore, returned references to captured variables will escape the closure
767    /// ```
768    fn report_fnmut_error(
769        &self,
770        errci: &ErrorConstraintInfo<'tcx>,
771        kind: ReturnConstraint,
772    ) -> Diag<'diag> {
773        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
774
775        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
776        if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *output_ty.kind() {
777            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
778        };
779
780        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:780",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(780u32),
                        ::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);
781
782        let err = FnMutError {
783            span: *span,
784            ty_err: match output_ty.kind() {
785                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
786                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
787                }
788                _ if output_ty.contains_closure() => {
789                    FnMutReturnTypeErr::ReturnClosure { span: *span }
790                }
791                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
792            },
793        };
794
795        let mut diag = self.dcx().create_err(err);
796
797        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
798            let def_id = match self.regioncx.universal_regions().defining_ty {
799                DefiningTy::Closure(def_id, _) => def_id,
800                ty => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected DefiningTy {0:?}", ty), Location::caller())bug!("unexpected DefiningTy {:?}", ty),
801            };
802
803            let captured_place = &self.upvars[upvar_field.index()].place;
804            let defined_hir = match captured_place.base {
805                PlaceBase::Local(hirid) => Some(hirid),
806                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
807                _ => None,
808            };
809
810            if let Some(def_hir) = defined_hir {
811                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
812                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
813                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
814                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
815                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
816            }
817        }
818
819        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
820            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
821        }
822
823        self.suggest_move_on_borrowing_closure(&mut diag);
824
825        diag
826    }
827
828    /// Reports an error specifically for when data is escaping a closure.
829    ///
830    /// ```text
831    /// error: borrowed data escapes outside of function
832    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
833    ///    |
834    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
835    ///    |              - `x` is only valid in the function body
836    /// LL |     // but ref_obj will not, so warn.
837    /// LL |     ref_obj(x)
838    ///    |     ^^^^^^^^^^ `x` escapes the function body here
839    /// ```
840    {}
#[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/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(840u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("errci")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("errci");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errci)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'diag> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ErrorConstraintInfo { span, category, .. } = errci;
            let fr_name_and_span =
                self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
                    self.body, &self.local_names(), &self.upvars, errci.fr);
            let outlived_fr_name_and_span =
                self.regioncx.get_var_name_and_span_for_region(self.infcx.tcx,
                    self.body, &self.local_names(), &self.upvars,
                    errci.outlived_fr);
            let escapes_from =
                self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
            if (fr_name_and_span.is_none() &&
                                    outlived_fr_name_and_span.is_none()) ||
                            (*category == ConstraintCategory::Assignment &&
                                    self.regioncx.universal_regions().defining_ty.is_fn_def())
                        || self.regioncx.universal_regions().defining_ty.is_const()
                    ||
                    (fr_name_and_span.is_none() &&
                            self.regioncx.universal_regions().defining_ty.is_fn_def()) {
                return self.report_general_error(errci);
            }
            let mut diag =
                borrowck_errors::borrowed_data_escapes_closure(self.dcx(),
                    *span, escapes_from);
            if let Some((Some(outlived_fr_name), outlived_fr_span)) =
                    outlived_fr_name_and_span {
                diag.span_label(outlived_fr_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` declared here, outside of the {1} body",
                                    outlived_fr_name, escapes_from))
                        }));
            }
            if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
                diag.span_label(fr_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` is only valid in the {1} body",
                                    fr_name, escapes_from))
                        }));
                diag.span_label(*span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` escapes the {1} body here",
                                    fr_name, escapes_from))
                        }));
            } else {
                diag.span_label(*span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("a temporary borrow escapes the {0} body here",
                                    escapes_from))
                        }));
                if let Some((Some(outlived_name), _)) =
                        outlived_fr_name_and_span {
                    diag.help(::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("`{0}` is declared outside the {1}, so any data borrowed inside the {1} cannot be stored into it",
                                        outlived_name, escapes_from))
                            }));
                }
            }
            match (self.regioncx.to_error_region(errci.fr),
                    self.regioncx.to_error_region(errci.outlived_fr)) {
                (Some(f), Some(o)) => {
                    self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o,
                        category);
                    let fr_region_name =
                        self.give_region_a_name(errci.fr).unwrap();
                    fr_region_name.highlight_region_name(&mut diag);
                    let outlived_fr_region_name =
                        self.give_region_a_name(errci.outlived_fr).unwrap();
                    outlived_fr_region_name.highlight_region_name(&mut diag);
                    diag.span_label(*span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}requires that `{1}` must outlive `{2}`",
                                        category.description(), fr_region_name,
                                        outlived_fr_region_name))
                            }));
                }
                _ => {}
            }
            diag
        }
    }
}#[instrument(level = "debug", skip(self))]
841    fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'diag> {
842        let ErrorConstraintInfo { span, category, .. } = errci;
843
844        let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
845            self.infcx.tcx,
846            self.body,
847            &self.local_names(),
848            &self.upvars,
849            errci.fr,
850        );
851        let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
852            self.infcx.tcx,
853            self.body,
854            &self.local_names(),
855            &self.upvars,
856            errci.outlived_fr,
857        );
858
859        let escapes_from =
860            self.infcx.tcx.def_descr(self.regioncx.universal_regions().defining_ty.def_id());
861
862        // Revert to the normal error in these cases.
863        // Assignments aren't "escapes" in function items.
864        if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
865            || (*category == ConstraintCategory::Assignment
866                && self.regioncx.universal_regions().defining_ty.is_fn_def())
867            || self.regioncx.universal_regions().defining_ty.is_const()
868            || (fr_name_and_span.is_none()
869                && self.regioncx.universal_regions().defining_ty.is_fn_def())
870        {
871            return self.report_general_error(errci);
872        }
873
874        let mut diag =
875            borrowck_errors::borrowed_data_escapes_closure(self.dcx(), *span, escapes_from);
876
877        if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
878            diag.span_label(
879                outlived_fr_span,
880                format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
881            );
882        }
883
884        if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
885            diag.span_label(
886                fr_span,
887                format!("`{fr_name}` is only valid in the {escapes_from} body"),
888            );
889
890            diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
891        } else {
892            diag.span_label(
893                *span,
894                format!("a temporary borrow escapes the {escapes_from} body here"),
895            );
896            if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
897                diag.help(format!(
898                    "`{outlived_name}` is declared outside the {escapes_from}, \
899                     so any data borrowed inside the {escapes_from} cannot be stored into it"
900                ));
901            }
902        }
903
904        // Only show an extra note if we can find an 'error region' for both of the region
905        // variables. This avoids showing a noisy note that just mentions 'synthetic' regions
906        // that don't help the user understand the error.
907        match (
908            self.regioncx.to_error_region(errci.fr),
909            self.regioncx.to_error_region(errci.outlived_fr),
910        ) {
911            (Some(f), Some(o)) => {
912                self.maybe_suggest_constrain_dyn_trait_impl(&mut diag, f, o, category);
913
914                let fr_region_name = self.give_region_a_name(errci.fr).unwrap();
915                fr_region_name.highlight_region_name(&mut diag);
916                let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
917                outlived_fr_region_name.highlight_region_name(&mut diag);
918
919                diag.span_label(
920                    *span,
921                    format!(
922                        "{}requires that `{}` must outlive `{}`",
923                        category.description(),
924                        fr_region_name,
925                        outlived_fr_region_name,
926                    ),
927                );
928            }
929            _ => {}
930        }
931
932        diag
933    }
934
935    /// Reports a region inference error for the general case with named/synthesized lifetimes to
936    /// explain what is happening.
937    ///
938    /// ```text
939    /// error: unsatisfied lifetime constraints
940    ///   --> $DIR/regions-creating-enums3.rs:17:5
941    ///    |
942    /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
943    ///    |                -- -- lifetime `'b` defined here
944    ///    |                |
945    ///    |                lifetime `'a` defined here
946    /// LL |     ast::add(x, y)
947    ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
948    ///    |                    is returning data with lifetime `'b`
949    /// ```
950    fn report_general_error(&self, errci: &ErrorConstraintInfo<'tcx>) -> Diag<'diag> {
951        let ErrorConstraintInfo { fr, outlived_fr, span, category } = errci;
952
953        let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
954
955        let err = LifetimeOutliveErr { span: *span };
956        let mut diag = self.dcx().create_err(err);
957
958        // In certain scenarios, such as the one described in issue #118021,
959        // we might encounter a lifetime that cannot be named.
960        // These situations are bound to result in errors.
961        // To prevent an immediate ICE, we opt to create a dummy name instead.
962        let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName {
963            name: kw::UnderscoreLifetime,
964            source: RegionNameSource::Static,
965        });
966        fr_name.highlight_region_name(&mut diag);
967        let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
968        outlived_fr_name.highlight_region_name(&mut diag);
969
970        let err_category = if #[allow(non_exhaustive_omitted_patterns)] match category {
    ConstraintCategory::Return(_) => true,
    _ => false,
}matches!(category, ConstraintCategory::Return(_))
971            && self.regioncx.universal_regions().is_local_free_region(*outlived_fr)
972        {
973            LifetimeReturnCategoryErr::WrongReturn {
974                span: *span,
975                mir_def_name,
976                outlived_fr_name,
977                fr_name: &fr_name,
978            }
979        } else {
980            LifetimeReturnCategoryErr::ShortReturn {
981                span: *span,
982                category_desc: category.description(),
983                free_region_name: &fr_name,
984                outlived_fr_name,
985            }
986        };
987
988        diag.subdiagnostic(err_category);
989
990        self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
991        self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
992        self.suggest_move_on_borrowing_closure(&mut diag);
993        self.suggest_deref_closure_return(&mut diag);
994        self.point_at_dyn_trait_in_field_def(&mut diag, *span, *outlived_fr);
995
996        diag
997    }
998
999    /// When a returned value has a field with a lifetime that isn't `'static`, and the requirement
1000    /// comes from a `dyn Trait` with an implicit `'static` in the given field, point at the trait
1001    /// object in the definition and suggest constraining it with a lifetime.
1002    fn point_at_dyn_trait_in_field_def(
1003        &self,
1004        diag: &mut Diag<'_>,
1005        span: Span,
1006        outlived_fr: RegionVid,
1007    ) {
1008        let Some(outlived_f) = self.regioncx.to_error_region(outlived_fr) else { return };
1009        if outlived_f.kind() != ty::ReStatic {
1010            return;
1011        }
1012        let Some(body_id) = self.infcx.tcx.hir_node_by_def_id(self.mir_def_id()).body_id() else {
1013            return;
1014        };
1015        let mut visitor = ReturnsVisitor::default();
1016        visitor.visit_body(&self.infcx.tcx.hir_body(body_id));
1017        if visitor.returns.is_empty() {
1018            return;
1019        }
1020
1021        enum NameOrPos {
1022            Name(Symbol),
1023            Pos(usize),
1024        }
1025
1026        for ret in visitor.returns {
1027            let (def_id, lit_field) = match ret.kind {
1028                hir::ExprKind::Struct(hir::QPath::Resolved(_, path), fields, _tail) => {
1029                    let Def(_, def_id) = path.res else { continue };
1030                    let Some(def_id) = def_id.as_local() else { continue };
1031                    let Some(field) = fields.iter().find(|f| f.expr.span.contains(span)) else {
1032                        continue;
1033                    };
1034                    (def_id, NameOrPos::Name(field.ident.name))
1035                }
1036                hir::ExprKind::Call(callee, args)
1037                    if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = callee.kind =>
1038                {
1039                    let Def(_, def_id) = path.res else { continue };
1040                    let Some(def_id) = def_id.as_local() else { continue };
1041                    let Some((pos, _)) =
1042                        args.iter().enumerate().find(|(_, a)| a.span.contains(span))
1043                    else {
1044                        continue;
1045                    };
1046                    (def_id, NameOrPos::Pos(pos))
1047                }
1048                _ => continue,
1049            };
1050            let (def_spans, fields, generics) = match self.infcx.tcx.hir_node_by_def_id(def_id) {
1051                hir::Node::Item(item) => match item.kind {
1052                    hir::ItemKind::Struct(name, generics, data) => {
1053                        let (hir::VariantData::Struct { fields, .. }
1054                        | hir::VariantData::Tuple(fields, ..)) = data
1055                        else {
1056                            continue;
1057                        };
1058                        (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [name.span]))vec![name.span], fields, generics)
1059                    }
1060                    _ => continue,
1061                },
1062                hir::Node::Variant(variant) => {
1063                    let hir::VariantData::Struct { fields, .. } = variant.data else { continue };
1064                    let parent = self.infcx.tcx.parent(def_id.into());
1065                    let mut def_spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.infcx.tcx.def_span(parent).shrink_to_lo()]))vec![self.infcx.tcx.def_span(parent).shrink_to_lo()];
1066                    let generics = if let DefKind::Variant = self.infcx.tcx.def_kind(parent) {
1067                        let parent = self.infcx.tcx.parent(parent);
1068                        def_spans.push(self.infcx.tcx.def_span(parent).shrink_to_lo());
1069                        self.infcx
1070                            .tcx
1071                            .hir_get_generics(parent.expect_local())
1072                            .expect("item with no generics?")
1073                    } else {
1074                        self.infcx
1075                            .tcx
1076                            .hir_get_generics(parent.expect_local())
1077                            .expect("item with no generics?")
1078                    };
1079                    (def_spans, fields, generics)
1080                }
1081                hir::Node::Ctor(data) => {
1082                    let hir::VariantData::Tuple(fields, ..) = data else { continue };
1083                    let parent = self.infcx.tcx.parent(def_id.into());
1084                    let mut def_spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.infcx.tcx.def_span(parent).shrink_to_lo()]))vec![self.infcx.tcx.def_span(parent).shrink_to_lo()];
1085                    let generics = if let DefKind::Variant = self.infcx.tcx.def_kind(parent) {
1086                        let parent = self.infcx.tcx.parent(parent);
1087                        def_spans.push(self.infcx.tcx.def_span(parent).shrink_to_lo());
1088                        self.infcx
1089                            .tcx
1090                            .hir_get_generics(parent.expect_local())
1091                            .expect("item with no generics?")
1092                    } else {
1093                        self.infcx
1094                            .tcx
1095                            .hir_get_generics(parent.expect_local())
1096                            .expect("item with no generics?")
1097                    };
1098                    (def_spans, *fields, generics)
1099                }
1100                _ => continue,
1101            };
1102
1103            let Some((_, f)) = fields.iter().enumerate().find(|(i, f)| match lit_field {
1104                NameOrPos::Name(name) => f.ident.name == name,
1105                NameOrPos::Pos(pos) => *i == pos,
1106            }) else {
1107                continue;
1108            };
1109
1110            let mut v = ty::TraitObjectVisitor(::alloc::vec::Vec::new()vec![]);
1111            v.visit_ty_unambig(f.ty);
1112
1113            if v.0.is_empty() {
1114                // No trait object found in this return
1115                continue;
1116            }
1117
1118            let mut span: MultiSpan = v.0.iter().map(|x| x.span).collect::<Vec<_>>().into();
1119            // Display the item and variant lines.
1120            for def_span in def_spans {
1121                span.push_span_context(def_span);
1122            }
1123            // Display the field's line (even if different to its type's).
1124            span.push_span_context(f.ident.span);
1125            // Display the type's start line (even if different to its type's).
1126            span.push_span_context(f.ty.span.shrink_to_lo());
1127            let (these, s, introduce) = if v.0.len() == 1 {
1128                ("this", "", "introduces")
1129            } else {
1130                ("these", "s", "introduce")
1131            };
1132            diag.span_note(
1133                span,
1134                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `dyn Trait`{1} {2} an implicit `\'static` obligation",
                these, s, introduce))
    })format!("{these} `dyn Trait`{s} {introduce} an implicit `'static` obligation"),
1135            );
1136            let suggestion_param_name = generics
1137                .params
1138                .iter()
1139                .filter(|p| #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    hir::GenericParamKind::Lifetime { .. } => true,
    _ => false,
}matches!(p.kind, hir::GenericParamKind::Lifetime { .. }))
1140                .map(|p| p.name.ident().name)
1141                .find(|i| *i != kw::UnderscoreLifetime);
1142            if let Some(name) = suggestion_param_name {
1143                let msg = "consider using an explicit lifetime";
1144                let mut sugg = ::alloc::vec::Vec::new()vec![];
1145                for ty in v.0 {
1146                    sugg.push((ty.span.shrink_to_hi(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", name))
    })format!(" + {name}")));
1147                }
1148                diag.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1149            } else {
1150                let msg = "consider introducing an explicit lifetime";
1151                let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [match generics.span_for_lifetime_suggestion() {
                    Some(span) => (span, "'a, ".to_string()),
                    None => (generics.span, "<'a>".to_string()),
                }]))vec![match generics.span_for_lifetime_suggestion() {
1152                    Some(span) => (span, "'a, ".to_string()),
1153                    None => (generics.span, "<'a>".to_string()),
1154                }];
1155                for ty in v.0 {
1156                    sugg.push((ty.span.shrink_to_hi(), " + 'a".to_string()));
1157                }
1158                diag.multipart_suggestion(msg, sugg, Applicability::MachineApplicable);
1159            }
1160            return;
1161        }
1162    }
1163
1164    /// Adds a suggestion to errors where an `impl Trait` is returned.
1165    ///
1166    /// ```text
1167    /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
1168    ///       a constraint
1169    ///    |
1170    /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
1171    ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1172    /// ```
1173    fn add_static_impl_trait_suggestion(
1174        &self,
1175        diag: &mut Diag<'_>,
1176        fr: RegionVid,
1177        // We need to pass `fr_name` - computing it again will label it twice.
1178        fr_name: RegionName,
1179        outlived_fr: RegionVid,
1180    ) {
1181        if let (Some(f), Some(outlived_f)) =
1182            (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
1183        {
1184            if outlived_f.kind() != ty::ReStatic {
1185                return;
1186            }
1187            let suitable_region = self.infcx.tcx.is_suitable_region(self.mir_def_id(), f);
1188            let Some(suitable_region) = suitable_region else {
1189                return;
1190            };
1191
1192            let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.scope);
1193
1194            let Some(param) =
1195                find_param_with_region(self.infcx.tcx, self.mir_def_id(), f, outlived_f)
1196            else {
1197                return;
1198            };
1199
1200            let lifetime =
1201                if f.is_named(self.infcx.tcx) { fr_name.name } else { kw::UnderscoreLifetime };
1202
1203            let arg = match param.param.pat.simple_ident() {
1204                Some(simple_ident) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument `{0}`", simple_ident))
    })format!("argument `{simple_ident}`"),
1205                None => "the argument".to_string(),
1206            };
1207            let captures = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("captures data from {0}", arg))
    })format!("captures data from {arg}");
1208
1209            if !fn_returns.is_empty() {
1210                nice_region_error::suggest_new_region_bound(
1211                    self.infcx.tcx,
1212                    diag,
1213                    fn_returns,
1214                    lifetime.to_string(),
1215                    Some(arg),
1216                    captures,
1217                    Some((param.param_ty_span, param.param_ty.to_string())),
1218                    Some(suitable_region.scope),
1219                );
1220                return;
1221            }
1222
1223            let Some((alias_tys, alias_span, lt_addition_span)) = self
1224                .infcx
1225                .tcx
1226                .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.scope)
1227            else {
1228                return;
1229            };
1230
1231            // in case the return type of the method is a type alias
1232            let mut spans_suggs: Vec<_> = Vec::new();
1233            for alias_ty in alias_tys {
1234                if alias_ty.span.desugaring_kind().is_some() {
1235                    // Skip `async` desugaring `impl Future`.
1236                    continue;
1237                }
1238                if let TyKind::TraitObject(_, lt) = alias_ty.kind {
1239                    if lt.kind == hir::LifetimeKind::ImplicitObjectLifetimeDefault {
1240                        spans_suggs.push((lt.ident.span.shrink_to_hi(), " + 'a".to_string()));
1241                    } else {
1242                        spans_suggs.push((lt.ident.span, "'a".to_string()));
1243                    }
1244                }
1245            }
1246
1247            if let Some(lt_addition_span) = lt_addition_span {
1248                spans_suggs.push((lt_addition_span, "'a, ".to_string()));
1249            } else {
1250                spans_suggs.push((alias_span.shrink_to_hi(), "<'a>".to_string()));
1251            }
1252
1253            diag.multipart_suggestion(
1254                ::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!(
1255                    "to declare that the trait object {captures}, you can add a lifetime parameter `'a` in the type alias"
1256                ),
1257                spans_suggs,
1258                Applicability::MaybeIncorrect,
1259            );
1260        }
1261    }
1262
1263    fn maybe_suggest_constrain_dyn_trait_impl(
1264        &self,
1265        diag: &mut Diag<'_>,
1266        f: Region<'tcx>,
1267        o: Region<'tcx>,
1268        category: &ConstraintCategory<'tcx>,
1269    ) {
1270        if !o.is_static() {
1271            return;
1272        }
1273
1274        let tcx = self.infcx.tcx;
1275
1276        let ConstraintCategory::CallArgument(Some(func_ty)) = category else { return };
1277        let ty::FnDef(fn_did, args) = *func_ty.kind() else { return };
1278        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1278",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1278u32),
                        ::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);
1279
1280        // Only suggest this on function calls, not closures
1281        let ty = tcx.type_of(fn_did).instantiate_identity().skip_norm_wip();
1282        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1282",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1282u32),
                        ::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());
1283        if let ty::Closure(_, _) = ty.kind() {
1284            return;
1285        }
1286        let Ok(Some(instance)) = ty::Instance::try_resolve(
1287            tcx,
1288            self.infcx.typing_env(self.infcx.param_env),
1289            fn_did,
1290            self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
1291        ) else {
1292            return;
1293        };
1294
1295        let Some(param) = find_param_with_region(tcx, self.mir_def_id(), f, o) else {
1296            return;
1297        };
1298        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1298",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1298u32),
                        ::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);
1299
1300        let mut visitor = TraitObjectVisitor(FxIndexSet::default());
1301        visitor.visit_ty(param.param_ty);
1302
1303        let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(
1304            tcx,
1305            instance.def_id(),
1306            &visitor.0,
1307        ) else {
1308            return;
1309        };
1310
1311        self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty);
1312    }
1313
1314    {}
#[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/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1314u32),
                                    ::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/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1322",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1322u32),
                                    ::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/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1328",
                                        "rustc_borrowck::diagnostics::region_errors",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1328u32),
                                        ::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")]
1315    fn suggest_constrain_dyn_trait_in_impl(
1316        &self,
1317        err: &mut Diag<'_>,
1318        found_dids: &FxIndexSet<DefId>,
1319        ident: Ident,
1320        self_ty: &hir::Ty<'_>,
1321    ) -> bool {
1322        debug!("err: {:#?}", err);
1323        let mut suggested = false;
1324        for found_did in found_dids {
1325            let mut traits = vec![];
1326            let mut hir_v = HirTraitObjectVisitor(&mut traits, *found_did);
1327            hir_v.visit_ty_unambig(self_ty);
1328            debug!("trait spans found: {:?}", traits);
1329            for span in &traits {
1330                let mut multi_span: MultiSpan = vec![*span].into();
1331                multi_span.push_span_label(
1332                    *span,
1333                    msg!("this has an implicit `'static` lifetime requirement"),
1334                );
1335                multi_span.push_span_label(
1336                    ident.span,
1337                    msg!("calling this method introduces the `impl`'s `'static` requirement"),
1338                );
1339                err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
1340                err.span_suggestion_verbose(
1341                    span.shrink_to_hi(),
1342                    msg!("consider relaxing the implicit `'static` requirement"),
1343                    " + '_",
1344                    Applicability::MaybeIncorrect,
1345                );
1346                suggested = true;
1347            }
1348        }
1349        suggested
1350    }
1351
1352    fn suggest_adding_lifetime_params(&self, diag: &mut Diag<'_>, sub: RegionVid, sup: RegionVid) {
1353        let (Some(sub), Some(sup)) =
1354            (self.regioncx.to_error_region(sub), self.regioncx.to_error_region(sup))
1355        else {
1356            return;
1357        };
1358
1359        let Some((ty_sub, _)) = self
1360            .infcx
1361            .tcx
1362            .is_suitable_region(self.mir_def_id(), sub)
1363            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sub))
1364        else {
1365            return;
1366        };
1367
1368        let Some((ty_sup, _)) = self
1369            .infcx
1370            .tcx
1371            .is_suitable_region(self.mir_def_id(), sup)
1372            .and_then(|_| find_anon_type(self.infcx.tcx, self.mir_def_id(), sup))
1373        else {
1374            return;
1375        };
1376
1377        suggest_adding_lifetime_params(
1378            self.infcx.tcx,
1379            diag,
1380            self.mir_def_id(),
1381            sub,
1382            ty_sup,
1383            ty_sub,
1384        );
1385    }
1386
1387    /// When encountering a lifetime error caused by the return type of a closure, check the
1388    /// corresponding trait bound and see if dereferencing the closure return value would satisfy
1389    /// them. If so, we produce a structured suggestion.
1390    fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) {
1391        let tcx = self.infcx.tcx;
1392
1393        // Get the closure return value and type.
1394        let closure_def_id = self.mir_def_id();
1395        let hir::Node::Expr(
1396            closure_expr @ hir::Expr {
1397                kind: hir::ExprKind::Closure(hir::Closure { body, .. }), ..
1398            },
1399        ) = tcx.hir_node_by_def_id(closure_def_id)
1400        else {
1401            return;
1402        };
1403        let ty::Closure(_, args) =
1404            *tcx.type_of(closure_def_id).instantiate_identity().skip_norm_wip().kind()
1405        else {
1406            return;
1407        };
1408        let args = args.as_closure();
1409
1410        // Make sure that the parent expression is a method call.
1411        let parent_expr_id = tcx.parent_hir_id(self.mir_hir_id());
1412        let hir::Node::Expr(
1413            parent_expr @ hir::Expr {
1414                kind: hir::ExprKind::MethodCall(_, rcvr, call_args, _), ..
1415            },
1416        ) = tcx.hir_node(parent_expr_id)
1417        else {
1418            return;
1419        };
1420        let typeck_results = tcx.typeck(self.mir_def_id());
1421
1422        // We don't use `ty.peel_refs()` to get the number of `*`s needed to get the root type.
1423        let liberated_sig = tcx.liberate_late_bound_regions(closure_def_id.to_def_id(), args.sig());
1424        let mut peeled_ty = liberated_sig.output();
1425        let mut count = 0;
1426        while let ty::Ref(_, ref_ty, _) = *peeled_ty.kind() {
1427            peeled_ty = ref_ty;
1428            count += 1;
1429        }
1430        if !self.infcx.type_is_copy_modulo_regions(self.infcx.param_env, peeled_ty) {
1431            return;
1432        }
1433
1434        // Build a new closure where the return type is an owned value, instead of a ref.
1435        // The new closure is safe, but otherwise has the same ABI, splat, and c-variadic.
1436        let fn_sig_kind = liberated_sig.fn_sig_kind.set_safety(hir::Safety::Safe);
1437        let closure_sig_as_fn_ptr_ty = Ty::new_fn_ptr(
1438            tcx,
1439            ty::Binder::dummy(tcx.mk_fn_sig(
1440                liberated_sig.inputs().iter().copied(),
1441                peeled_ty,
1442                fn_sig_kind,
1443            )),
1444        );
1445        let closure_ty = Ty::new_closure(
1446            tcx,
1447            closure_def_id.to_def_id(),
1448            ty::ClosureArgs::new(
1449                tcx,
1450                ty::ClosureArgsParts {
1451                    parent_args: args.parent_args(),
1452                    closure_kind_ty: args.kind_ty(),
1453                    tupled_upvars_ty: args.tupled_upvars_ty(),
1454                    closure_sig_as_fn_ptr_ty,
1455                },
1456            )
1457            .args,
1458        );
1459
1460        let Some((closure_arg_pos, _)) =
1461            call_args.iter().enumerate().find(|(_, arg)| arg.hir_id == closure_expr.hir_id)
1462        else {
1463            return;
1464        };
1465        // Get the type for the parameter corresponding to the argument the closure with the
1466        // lifetime error we had.
1467        let Some(method_def_id) = typeck_results.type_dependent_def_id(parent_expr.hir_id) else {
1468            return;
1469        };
1470        let Some(input_arg) = tcx
1471            .fn_sig(method_def_id)
1472            .skip_binder()
1473            .inputs()
1474            .skip_binder()
1475            // Methods have a `self` arg, so `pos` is actually `+ 1` to match the method call arg.
1476            .get(closure_arg_pos + 1)
1477        else {
1478            return;
1479        };
1480        // If this isn't a param, then we can't substitute a new closure.
1481        let ty::Param(closure_param) = input_arg.kind() else { return };
1482
1483        // Get the arguments for the found method, only specifying that `Self` is the receiver type.
1484        let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return };
1485        let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
1486            if let ty::GenericParamDefKind::Lifetime = param.kind {
1487                tcx.lifetimes.re_erased.into()
1488            } else if param.index == 0 && param.name == kw::SelfUpper {
1489                possible_rcvr_ty.into()
1490            } else if param.index == closure_param.index {
1491                closure_ty.into()
1492            } else {
1493                self.infcx.var_for_def(parent_expr.span, param)
1494            }
1495        });
1496
1497        let clauses = tcx.clauses_of(method_def_id).instantiate(tcx, args);
1498
1499        let ocx = ObligationCtxt::new(&self.infcx);
1500        ocx.register_obligations(clauses.iter().map(|(clause, span)| {
1501            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:1501",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/9c5648833e5ceb667a708d53c00b83ecc9e610d5/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(1501u32),
                        ::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);
1502            Obligation::misc(
1503                tcx,
1504                span,
1505                self.mir_def_id(),
1506                self.infcx.param_env,
1507                clause.skip_norm_wip(),
1508            )
1509        }));
1510
1511        if ocx.evaluate_obligations_error_on_ambiguity().no_errors() && count > 0 {
1512            diag.span_suggestion_verbose(
1513                tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
1514                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("dereference the return value"))msg!("dereference the return value"),
1515                "*".repeat(count),
1516                Applicability::MachineApplicable,
1517            );
1518        }
1519    }
1520
1521    fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
1522        let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
1523        let expr = &body.value.peel_blocks();
1524        let mut closure_span = None::<rustc_span::Span>;
1525        match expr.kind {
1526            hir::ExprKind::MethodCall(.., args, _) => {
1527                for arg in args {
1528                    if let hir::ExprKind::Closure(hir::Closure {
1529                        capture_clause: hir::CaptureBy::Ref,
1530                        ..
1531                    }) = arg.kind
1532                    {
1533                        closure_span = Some(arg.span.shrink_to_lo());
1534                        break;
1535                    }
1536                }
1537            }
1538            hir::ExprKind::Closure(hir::Closure {
1539                capture_clause: hir::CaptureBy::Ref,
1540                kind,
1541                ..
1542            }) => {
1543                if !#[allow(non_exhaustive_omitted_patterns)] match kind {
    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
        _)) => true,
    _ => false,
}matches!(
1544                    kind,
1545                    hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1546                        hir::CoroutineDesugaring::Async,
1547                        _
1548                    ),)
1549                ) {
1550                    closure_span = Some(expr.span.shrink_to_lo());
1551                }
1552            }
1553            _ => {}
1554        }
1555        if let Some(closure_span) = closure_span {
1556            diag.span_suggestion_verbose(
1557                closure_span,
1558                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"),
1559                "move ",
1560                Applicability::MaybeIncorrect,
1561            );
1562        }
1563    }
1564}