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/75a3786afbc93bbddf2c0259033b63957b45ace1/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/75a3786afbc93bbddf2c0259033b63957b45ace1/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/75a3786afbc93bbddf2c0259033b63957b45ace1/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/75a3786afbc93bbddf2c0259033b63957b45ace1/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/75a3786afbc93bbddf2c0259033b63957b45ace1/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/75a3786afbc93bbddf2c0259033b63957b45ace1/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
297        if !suggestions.is_empty() {
298            suggestions.dedup();
299            diag.multipart_suggestion(
300                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"),
301                suggestions,
302                Applicability::MaybeIncorrect,
303            );
304        }
305    }
306
307    /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
308    pub(crate) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
309        // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
310        // buffered in the `MirBorrowckCtxt`.
311        let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
312        for (nll_error, _) in nll_errors.into_iter() {
313            match nll_error {
314                RegionErrorKind::TypeTestError { type_test } => {
315                    // Try to convert the lower-bound region into something named we can print for
316                    // the user.
317                    let lower_bound_region = self.regioncx.to_error_region(type_test.lower_bound);
318
319                    let type_test_span = type_test.span;
320
321                    if let Some(lower_bound_region) = lower_bound_region {
322                        let generic_ty = self.regioncx.name_regions(
323                            self.infcx.tcx,
324                            type_test.generic_kind.to_ty(self.infcx.tcx),
325                        );
326                        let origin =
327                            SubregionOrigin::RelateParamBound(type_test_span, generic_ty, None);
328                        self.buffer_error(self.infcx.err_ctxt().construct_generic_bound_failure(
329                            self.body.source.def_id().expect_local(),
330                            type_test_span,
331                            Some(origin),
332                            self.regioncx.name_regions(self.infcx.tcx, type_test.generic_kind),
333                            lower_bound_region,
334                        ));
335                    } else {
336                        // FIXME. We should handle this case better. It
337                        // indicates that we have e.g., some region variable
338                        // whose value is like `'a+'b` where `'a` and `'b` are
339                        // distinct unrelated universal regions that are not
340                        // known to outlive one another. It'd be nice to have
341                        // some examples where this arises to decide how best
342                        // to report it; we could probably handle it by
343                        // iterating over the universal regions and reporting
344                        // an error that multiple bounds are required.
345                        let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
346                            kind: type_test.generic_kind.to_string(),
347                            span: type_test_span,
348                        });
349
350                        // Add notes and suggestions for the case of 'static lifetime
351                        // implied but not specified when a generic associated types
352                        // are from higher-ranked trait bounds
353                        self.suggest_static_lifetime_for_gat_from_hrtb(
354                            &mut diag,
355                            type_test.lower_bound,
356                        );
357
358                        self.buffer_error(diag);
359                    }
360                }
361
362                RegionErrorKind::PlaceholderOutlivesIllegalRegion {
363                    longer_fr,
364                    illegally_outlived_r,
365                } => {
366                    self.report_erroneous_rvid_reaches_placeholder(longer_fr, illegally_outlived_r)
367                }
368
369                RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
370                    if is_reported {
371                        self.report_region_error(
372                            longer_fr,
373                            fr_origin,
374                            shorter_fr,
375                            &mut outlives_suggestion,
376                        );
377                    } else {
378                        // We only report the first error, so as not to overwhelm the user. See
379                        // `RegRegionErrorKind` docs.
380                        //
381                        // FIXME: currently we do nothing with these, but perhaps we can do better?
382                        // FIXME: try collecting these constraints on the outlives suggestion
383                        // builder. Does it make the suggestions any better?
384                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:384",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(384u32),
                        ::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!(
385                            "Unreported region error: can't prove that {:?}: {:?}",
386                            longer_fr, shorter_fr
387                        );
388                    }
389                }
390            }
391        }
392
393        // Emit one outlives suggestions for each MIR def we borrowck
394        outlives_suggestion.add_suggestion(self);
395    }
396
397    /// Point at `'static` obligations from the item being called.
398    ///
399    /// ```text
400    /// error[E0521]: borrowed data escapes outside of function
401    ///   --> $DIR/static-impl-obligation.rs:163:9
402    ///    |
403    /// LL |     fn bar<'a>(x: &'a &'a u32) {
404    ///    |            --  - `x` is only valid in the function body
405    ///    |            |
406    ///    |            lifetime `'a` defined here
407    /// LL |         let y: &dyn Foo = x;
408    /// LL |         y.hello();
409    ///    |         ^^^^^^^^^
410    ///    |         |
411    ///    |         `x` escapes the function body here
412    ///    |         argument requires that `'a` must outlive `'static`
413    ///    |
414    /// note: `'static` lifetime requirement from `<(dyn o::Foo + 'static)>::hello` introduced here
415    ///   --> $DIR/static-impl-obligation.rs:158:20
416    ///    |
417    /// LL |     impl dyn Foo + 'static where Self: 'static {
418    ///    |                    ^^^^^^^             ^^^^^^^ lifetime requirement introduced here
419    ///    |                    |
420    ///    |                    lifetime requirement introduced here
421    /// LL |         fn hello(&'static self) where Self: 'static {}
422    ///    |                  ^^^^^^^^^^^^^              ^^^^^^^ lifetime requirement introduced here
423    ///    |                  |
424    ///    |                  lifetime requirement introduced here
425    /// ```
426    fn explain_impl_static_obligation(
427        &self,
428        diag: &mut Diag<'_>,
429        ty: Ty<'tcx>,
430        outlived_fr: RegionVid,
431    ) {
432        let tcx = self.infcx.tcx;
433        if self.regioncx.to_error_region(outlived_fr) != Some(tcx.lifetimes.re_static) {
434            return;
435        }
436        let ty::FnDef(def_id, args) = ty.kind() else {
437            return;
438        };
439        let typing_env = self.infcx.typing_env(self.infcx.param_env);
440        let Ok(Some(instance)) = ty::Instance::try_resolve(
441            tcx,
442            typing_env,
443            *def_id,
444            self.infcx.deeply_resolve_ignoring_regions(args.no_bound_vars().unwrap()),
445        ) else {
446            return;
447        };
448        let def_id = instance.def_id();
449        if tcx.is_closure_like(def_id) {
450            // Closures don't have a `fn_sig` query result and cannot introduce the `'static`
451            // obligations this function looks for
452            return;
453        }
454        let mut bounds =
455            tcx.clauses_of(def_id)
456                .instantiate(tcx, instance.args)
457                .into_iter()
458                .map(|(c, sp)| (c.skip_norm_wip().as_predicate(), sp))
459                .filter(|(pred, _)| match pred.kind().skip_binder() {
460                    ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
461                        ty::OutlivesClause(_, lt),
462                    ))
463                    | ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
464                        ty::OutlivesClause(_, lt),
465                    )) if lt.is_static() => true,
466                    _ => false,
467                })
468                .map(|(_, sp)| sp)
469                .collect::<Vec<Span>>();
470
471        let mut labels = FxHashMap::default();
472
473        let parent = tcx.parent(def_id);
474        if let Some(rcvr) =
475            tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().inputs().skip_binder().first()
476        {
477            // Look at the receiver for `&'static self`, which introduces a `'static` obligation.
478            // ```
479            // impl Foo {
480            //     fn foo(&'static self) {}
481            //            ^^^^^^^^^^^^^
482            // ```
483            if let ty::Ref(region, _, _) = rcvr.kind()
484                && *region == tcx.lifetimes.re_static
485                && let Some(assoc) = tcx.opt_associated_item(def_id)
486                && assoc.is_method()
487            {
488                let def_span = tcx.def_span(def_id);
489                // We have a `&'static self` receiver.
490                if let Some(def_id) = def_id.as_local()
491                    && let owner = tcx.expect_hir_owner_node(def_id)
492                    && let Some(decl) = owner.fn_decl()
493                    && let Some(ty) = decl.inputs.first()
494                {
495                    // Point at the `&'static self` receiver.
496                    bounds.push(ty.span);
497                } else if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
498                    // The method is not defined on the local crate, point at the signature instead of
499                    // just the receiver as an approximation. We don't add it if there are already
500                    // other spans with overlap with the def `Span`, as the other will be more specific.
501                    bounds.push(def_span)
502                }
503            }
504
505            if let DefKind::Impl { .. } = tcx.def_kind(parent)
506                && let ty = tcx.type_of(parent).instantiate_identity().skip_norm_wip()
507                && let ty::Dynamic(_, region) = ty.kind()
508                && *region == tcx.lifetimes.re_static
509            {
510                // We have a call into a method of either `impl dyn Trait {}` or
511                // `impl dyn Trait + 'static {}`.
512                if let Some(def_id) = parent.as_local()
513                    && let hir::OwnerNode::Item(item) = tcx.expect_hir_owner_node(def_id)
514                    && let hir::ItemKind::Impl(impl_) = item.kind
515                    && let hir::TyKind::TraitObject(_, tagged_ref) = impl_.self_ty.kind
516                {
517                    if tagged_ref.is_static() {
518                        // impl dyn Trait + 'static {
519                        //                  ^^^^^^^ lifetime requirement introduced here
520                        bounds.push(tagged_ref.pointer().ident.span);
521                    } else if tagged_ref.is_implicit() {
522                        // impl dyn Trait {
523                        //      ^^^^^^^^^ `dyn Trait` introduces an...
524                        bounds.push(impl_.self_ty.span);
525                        labels.insert(
526                            impl_.self_ty.span,
527                            "`dyn Trait` introduces an implicit `'static` lifetime requirement",
528                        );
529                    }
530                } else {
531                    // Non-local `impl`, we don't have a way to differentiate between `+ 'static`
532                    // and bare `dyn Trait`. We point at the whole def `Span` for now.
533                    let def_span = tcx.def_span(parent);
534                    if !bounds.iter().any(|sp| sp.overlaps(def_span)) {
535                        bounds.push(def_span);
536                    }
537                }
538            }
539        }
540
541        if !bounds.is_empty() {
542            let mut multispan: MultiSpan = bounds.clone().into();
543            for span in bounds {
544                let label = labels.get(&span).unwrap_or(&"lifetime requirement introduced here");
545                multispan.push_span_label(span, *label);
546            }
547            multispan.push_span_context(tcx.def_span(def_id).shrink_to_lo());
548            if let DefKind::Impl { .. } | DefKind::Trait = tcx.def_kind(parent) {
549                multispan.push_span_context(tcx.def_span(parent).shrink_to_lo());
550            }
551            diag.span_note(
552                multispan,
553                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`\'static` lifetime requirement from `{0}` introduced here",
                tcx.def_path_str(def_id)))
    })format!(
554                    "`'static` lifetime requirement from `{}` introduced here",
555                    tcx.def_path_str(def_id)
556                ),
557            );
558        }
559    }
560
561    /// Report that `longer_fr: error_vid`, which doesn't hold,
562    /// where `longer_fr` is a placeholder.
563    fn report_erroneous_rvid_reaches_placeholder(
564        &mut self,
565        longer_fr: RegionVid,
566        error_vid: RegionVid,
567    ) {
568        use NllRegionVariableOrigin::*;
569
570        let origin_longer = self.regioncx.definitions[longer_fr].origin;
571
572        let Placeholder(placeholder) = origin_longer else {
573            ::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!");
574        };
575
576        // FIXME: Is throwing away the existential region really the best here?
577        let error_region = match self.regioncx.definitions[error_vid].origin {
578            FreeRegion | Existential { .. } => None,
579            Placeholder(other_placeholder) => Some(other_placeholder),
580        };
581
582        // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
583        let best_blame = self.regioncx.best_blame_constraint(longer_fr, origin_longer, error_vid);
584        let cause = best_blame.to_obligation_cause();
585
586        // FIXME these methods should have better names, and also probably not be this generic.
587        // FIXME note that we *throw away* the error element here! We probably want to
588        // thread it through the computation further down and use it, but there currently isn't
589        // anything there to receive it.
590        self.regioncx.universe_info(placeholder.universe).report_erroneous_element(
591            self,
592            placeholder,
593            error_region,
594            cause,
595        );
596    }
597
598    /// Report an error because the universal region `fr` was required to outlive
599    /// `outlived_fr` but it is not known to do so. For example:
600    ///
601    /// ```compile_fail
602    /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
603    /// ```
604    ///
605    /// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
606    pub(crate) fn report_region_error(
607        &mut self,
608        fr: RegionVid,
609        fr_origin: NllRegionVariableOrigin<'tcx>,
610        outlived_fr: RegionVid,
611        outlives_suggestion: &mut OutlivesSuggestionBuilder,
612    ) {
613        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:613",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(613u32),
                        ::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);
614
615        let best_blame = self.regioncx.best_blame_constraint(fr, fr_origin, outlived_fr);
616        let OutlivesConstraint { category, span, variance_info, .. } = *best_blame.constraint();
617        let path = best_blame.path();
618
619        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:619",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(619u32),
                        ::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);
620
621        // Check if we can use one of the "nice region errors".
622        if let (Some(f), Some(o)) =
623            (self.regioncx.to_error_region(fr), self.regioncx.to_error_region(outlived_fr))
624        {
625            let infer_err = self.infcx.err_ctxt();
626            let nice = NiceRegionError::new_from_span(&infer_err, self.mir_def_id(), span, o, f);
627            if let Some(diag) = nice.try_report_from_nll() {
628                self.buffer_error(diag);
629                return;
630            }
631        }
632
633        let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
634            self.regioncx.universal_regions().is_local_free_region(fr),
635            self.regioncx.universal_regions().is_local_free_region(outlived_fr),
636        );
637
638        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:638",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(638u32),
                        ::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!(
639            "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
640            fr_is_local, outlived_fr_is_local, category
641        );
642
643        let errci = ErrorConstraintInfo { fr, outlived_fr, category, span };
644
645        let mut diag = match (category, fr_is_local, outlived_fr_is_local) {
646            (ConstraintCategory::SolverRegionConstraint(span), _, _) => self
647                .dcx()
648                .struct_span_err(span, "higher-ranked lifetime bound could not be satisfied"),
649            (ConstraintCategory::Return(kind), true, false)
650                if self.regioncx.is_closure_fn_mut(fr) =>
651            {
652                self.report_fnmut_error(&errci, kind)
653            }
654            (ConstraintCategory::Assignment, true, false)
655            | (ConstraintCategory::CallArgument(_), true, false) => {
656                let mut db = self.report_escaping_data_error(&errci);
657
658                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
659                outlives_suggestion.collect_constraint(fr, outlived_fr);
660
661                db
662            }
663            _ => {
664                let mut db = self.report_general_error(&errci);
665
666                outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
667                outlives_suggestion.collect_constraint(fr, outlived_fr);
668
669                db
670            }
671        };
672
673        if let ConstraintCategory::CallArgument(Some(ty)) = category {
674            self.explain_impl_static_obligation(&mut diag, ty, outlived_fr);
675        }
676
677        match variance_info {
678            ty::VarianceDiagInfo::None => {}
679            ty::VarianceDiagInfo::Invariant { ty, param_index } => {
680                let (desc, note) = match ty.kind() {
681                    ty::RawPtr(ty, mutbl) => {
682                        {
    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);
683                        (
684                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable pointer to `{0}`", ty))
    })format!("a mutable pointer to `{}`", ty),
685                            "mutable pointers are invariant over their type parameter".to_string(),
686                        )
687                    }
688                    ty::Ref(_, inner_ty, mutbl) => {
689                        {
    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);
690                        (
691                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a mutable reference to `{0}`",
                inner_ty))
    })format!("a mutable reference to `{inner_ty}`"),
692                            "mutable references are invariant over their type parameter"
693                                .to_string(),
694                        )
695                    }
696                    ty::Adt(adt, args) => {
697                        let generic_arg = args[param_index as usize];
698                        let identity_args =
699                            GenericArgs::identity_for_item(self.infcx.tcx, adt.did());
700                        let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args);
701                        let base_generic_arg = identity_args[param_index as usize];
702                        let adt_desc = adt.descr();
703
704                        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!(
705                            "the type `{ty}`, which makes the generic argument `{generic_arg}` invariant"
706                        );
707                        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!(
708                            "the {adt_desc} `{base_ty}` is invariant over the parameter `{base_generic_arg}`"
709                        );
710                        (desc, note)
711                    }
712                    ty::FnDef(def_id, _) => {
713                        let name = self.infcx.tcx.item_name(*def_id);
714                        let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id);
715                        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}`");
716                        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!(
717                            "the function `{name}` is invariant over the parameter `{}`",
718                            identity_args[param_index as usize]
719                        );
720                        (desc, note)
721                    }
722                    _ => { ::core::panicking::panic_fmt(format_args!("Unexpected type {0:?}", ty)); }panic!("Unexpected type {ty:?}"),
723                };
724                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("requirement occurs because of {0}",
                desc))
    })format!("requirement occurs because of {desc}",));
725                diag.note(note);
726                diag.help("see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance");
727            }
728        }
729
730        self.add_placeholder_from_predicate_note(&mut diag, path);
731        self.add_sized_or_copy_bound_info(&mut diag, category, path);
732
733        for constraint in path {
734            if let ConstraintCategory::Cast { is_raw_ptr_dyn_type_cast: true, .. } =
735                constraint.category
736            {
737                diag.span_note(
738                    constraint.span,
739                    "raw pointer casts of trait objects cannot extend lifetimes",
740                );
741                diag.note("this was previously accepted by the compiler but was changed recently");
742                diag.help(
743                    "see <https://github.com/rust-lang/rust/issues/141402> for more information",
744                );
745            }
746        }
747
748        self.buffer_error(diag);
749    }
750
751    /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
752    /// This function expects `fr` to be local and `outlived_fr` to not be local.
753    ///
754    /// ```text
755    /// error: captured variable cannot escape `FnMut` closure body
756    ///   --> $DIR/issue-53040.rs:15:8
757    ///    |
758    /// LL |     || &mut v;
759    ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
760    ///    |     |
761    ///    |     inferred to be a `FnMut` closure
762    ///    |
763    ///    = note: `FnMut` closures only have access to their captured variables while they are
764    ///            executing...
765    ///    = note: ...therefore, returned references to captured variables will escape the closure
766    /// ```
767    fn report_fnmut_error(
768        &self,
769        errci: &ErrorConstraintInfo<'tcx>,
770        kind: ReturnConstraint,
771    ) -> Diag<'diag> {
772        let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
773
774        let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
775        if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) = *output_ty.kind() {
776            output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
777        };
778
779        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs:779",
                        "rustc_borrowck::diagnostics::region_errors",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                        ::tracing_core::__macro_support::Option::Some(779u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_fnmut_error: output_ty={0:?}",
                                                    output_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_fnmut_error: output_ty={:?}", output_ty);
780
781        let err = FnMutError {
782            span: *span,
783            ty_err: match output_ty.kind() {
784                ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => {
785                    FnMutReturnTypeErr::ReturnAsyncBlock { span: *span }
786                }
787                _ if output_ty.contains_closure() => {
788                    FnMutReturnTypeErr::ReturnClosure { span: *span }
789                }
790                _ => FnMutReturnTypeErr::ReturnRef { span: *span },
791            },
792        };
793
794        let mut diag = self.dcx().create_err(err);
795
796        if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
797            let def_id = match self.regioncx.universal_regions().defining_ty {
798                DefiningTy::Closure(def_id, _) => def_id,
799                ty => ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected DefiningTy {0:?}", ty), Location::caller())bug!("unexpected DefiningTy {:?}", ty),
800            };
801
802            let captured_place = &self.upvars[upvar_field.index()].place;
803            let defined_hir = match captured_place.base {
804                PlaceBase::Local(hirid) => Some(hirid),
805                PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
806                _ => None,
807            };
808
809            if let Some(def_hir) = defined_hir {
810                let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
811                let upvar_def_span = self.infcx.tcx.hir_span(def_hir);
812                let upvar_span = upvars_map.get(&def_hir).unwrap().span;
813                diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
814                diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
815            }
816        }
817
818        if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
819            diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
820        }
821
822        self.suggest_move_on_borrowing_closure(&mut diag);
823
824        diag
825    }
826
827    /// Reports an error specifically for when data is escaping a closure.
828    ///
829    /// ```text
830    /// error: borrowed data escapes outside of function
831    ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
832    ///    |
833    /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
834    ///    |              - `x` is only valid in the function body
835    /// LL |     // but ref_obj will not, so warn.
836    /// LL |     ref_obj(x)
837    ///    |     ^^^^^^^^^^ `x` escapes the function body here
838    /// ```
839    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_escaping_data_error",
                                    "rustc_borrowck::diagnostics::region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_borrowck/src/diagnostics/region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(839u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("errci")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("errci");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errci)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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