Skip to main content

rustc_borrowck/diagnostics/
region_errors.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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