Skip to main content

rustc_trait_selection/error_reporting/infer/
region.rs

1use std::iter;
2
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{
5    Applicability, Diag, E0309, E0310, E0311, E0803, Subdiagnostic, msg, struct_span_code_err,
6};
7use rustc_hir::def::{DefKind, Namespace};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::intravisit::Visitor;
10use rustc_hir::{self as hir, ParamName};
11use rustc_middle::bug;
12use rustc_middle::traits::ObligationCauseCode;
13use rustc_middle::ty::error::TypeError;
14use rustc_middle::ty::print::RegionHighlightMode;
15use rustc_middle::ty::{
16    self, IsSuggestable, Region, Ty, TyCtxt, TypeVisitableExt as _, Upcast as _,
17};
18use rustc_span::{BytePos, ErrorGuaranteed, Span, Symbol, kw, sym};
19use tracing::{debug, instrument};
20
21use super::ObligationCauseAsDiagArg;
22use super::nice_region_error::find_anon_type;
23use crate::diagnostics::{
24    self, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent,
25    RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, note_and_explain,
26};
27use crate::error_reporting::TypeErrCtxt;
28use crate::error_reporting::infer::ObligationCauseExt;
29use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlighted;
30use crate::infer::region_constraints::GenericKind;
31use crate::infer::{
32    BoundRegionConversionTime, InferCtxt, RegionResolutionError, RegionVariableOrigin,
33    SubregionOrigin,
34};
35
36impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
37    pub fn report_region_errors(
38        &self,
39        generic_param_scope: LocalDefId,
40        errors: &[RegionResolutionError<'tcx>],
41    ) -> ErrorGuaranteed {
42        if !!errors.is_empty() {
    ::core::panicking::panic("assertion failed: !errors.is_empty()")
};assert!(!errors.is_empty());
43
44        if let Some(guaranteed) = self.infcx.tainted_by_errors() {
45            return guaranteed;
46        }
47
48        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:48",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(48u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors(): {0} errors to start",
                                                    errors.len()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_region_errors(): {} errors to start", errors.len());
49
50        // try to pre-process the errors, which will group some of them
51        // together into a `ProcessedErrors` group:
52        let errors = self.process_errors(errors);
53
54        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:54",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(54u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors: {0} errors after preprocessing",
                                                    errors.len()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_region_errors: {} errors after preprocessing", errors.len());
55
56        let mut guar = None;
57        for error in errors {
58            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:58",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(58u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_region_errors: error = {0:?}",
                                                    error) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_region_errors: error = {:?}", error);
59
60            let e = if let Some(guar) =
61                self.try_report_nice_region_error(generic_param_scope, &error)
62            {
63                guar
64            } else {
65                match error.clone() {
66                    // These errors could indicate all manner of different
67                    // problems with many different solutions. Rather
68                    // than generate a "one size fits all" error, what we
69                    // attempt to do is go through a number of specific
70                    // scenarios and try to find the best way to present
71                    // the error. If all of these fails, we fall back to a rather
72                    // general bit of code that displays the error information
73                    RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
74                        if sub.is_placeholder() || sup.is_placeholder() {
75                            self.report_placeholder_failure(generic_param_scope, origin, sub, sup)
76                                .emit()
77                        } else {
78                            self.report_concrete_failure(generic_param_scope, origin, sub, sup)
79                                .emit()
80                        }
81                    }
82
83                    RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => self
84                        .report_generic_bound_failure(
85                            generic_param_scope,
86                            origin.span(),
87                            Some(origin),
88                            param_ty,
89                            sub,
90                        ),
91
92                    RegionResolutionError::SubSupConflict(
93                        _,
94                        var_origin,
95                        sub_origin,
96                        sub_r,
97                        sup_origin,
98                        sup_r,
99                        _,
100                    ) => {
101                        if sub_r.is_placeholder() {
102                            self.report_placeholder_failure(
103                                generic_param_scope,
104                                sub_origin,
105                                sub_r,
106                                sup_r,
107                            )
108                            .emit()
109                        } else if sup_r.is_placeholder() {
110                            self.report_placeholder_failure(
111                                generic_param_scope,
112                                sup_origin,
113                                sub_r,
114                                sup_r,
115                            )
116                            .emit()
117                        } else {
118                            self.report_sub_sup_conflict(
119                                generic_param_scope,
120                                var_origin,
121                                sub_origin,
122                                sub_r,
123                                sup_origin,
124                                sup_r,
125                            )
126                        }
127                    }
128
129                    RegionResolutionError::UpperBoundUniverseConflict(
130                        _,
131                        _,
132                        _,
133                        sup_origin,
134                        sup_r,
135                    ) => {
136                        if !sup_r.is_placeholder() {
    ::core::panicking::panic("assertion failed: sup_r.is_placeholder()")
};assert!(sup_r.is_placeholder());
137
138                        // Make a dummy value for the "sub region" --
139                        // this is the initial value of the
140                        // placeholder. In practice, we expect more
141                        // tailored errors that don't really use this
142                        // value.
143                        let sub_r = self.tcx.lifetimes.re_erased;
144
145                        self.report_placeholder_failure(
146                            generic_param_scope,
147                            sup_origin,
148                            sub_r,
149                            sup_r,
150                        )
151                        .emit()
152                    }
153
154                    RegionResolutionError::CannotNormalize(clause, origin) => {
155                        let clause: ty::Clause<'tcx> =
156                            clause.map_bound(ty::ClauseKind::TypeOutlives).upcast(self.tcx);
157                        self.tcx
158                            .dcx()
159                            .struct_span_err(origin.span(), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot normalize `{0}`", clause))
    })format!("cannot normalize `{clause}`"))
160                            .emit()
161                    }
162                }
163            };
164
165            guar = Some(e)
166        }
167
168        guar.unwrap()
169    }
170
171    // This method goes through all the errors and try to group certain types
172    // of error together, for the purpose of suggesting explicit lifetime
173    // parameters to the user. This is done so that we can have a more
174    // complete view of what lifetimes should be the same.
175    // If the return value is an empty vector, it means that processing
176    // failed (so the return value of this method should not be used).
177    //
178    // The method also attempts to weed out messages that seem like
179    // duplicates that will be unhelpful to the end-user. But
180    // obviously it never weeds out ALL errors.
181    fn process_errors(
182        &self,
183        errors: &[RegionResolutionError<'tcx>],
184    ) -> Vec<RegionResolutionError<'tcx>> {
185        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:185",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(185u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("process_errors()")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("process_errors()");
186
187        // We want to avoid reporting generic-bound failures if we can
188        // avoid it: these have a very high rate of being unhelpful in
189        // practice. This is because they are basically secondary
190        // checks that test the state of the region graph after the
191        // rest of inference is done, and the other kinds of errors
192        // indicate that the region constraint graph is internally
193        // inconsistent, so these test results are likely to be
194        // meaningless.
195        //
196        // Therefore, we filter them out of the list unless they are
197        // the only thing in the list.
198
199        let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
200            RegionResolutionError::GenericBoundFailure(..) => true,
201            RegionResolutionError::ConcreteFailure(..)
202            | RegionResolutionError::SubSupConflict(..)
203            | RegionResolutionError::UpperBoundUniverseConflict(..)
204            | RegionResolutionError::CannotNormalize(..) => false,
205        };
206
207        let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
208            errors.to_owned()
209        } else {
210            errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
211        };
212
213        // sort the errors by span, for better error message stability.
214        errors.sort_by_key(|u| match *u {
215            RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
216            RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
217            RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
218            RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
219            RegionResolutionError::CannotNormalize(_, ref sro) => sro.span(),
220        });
221        errors
222    }
223
224    pub(super) fn note_region_origin(&self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>) {
225        match *origin {
226            SubregionOrigin::Subtype(ref trace) => RegionOriginNote::WithRequirement {
227                span: trace.cause.span,
228                requirement: ObligationCauseAsDiagArg(trace.cause.clone()),
229                expected_found: self.values_str(trace.values, &trace.cause, err.long_ty_path()),
230            }
231            .add_to_diag(err),
232            SubregionOrigin::Reborrow(span) => RegionOriginNote::Plain {
233                span,
234                msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that reference does not outlive borrowed content"))msg!("...so that reference does not outlive borrowed content"),
235            }
236            .add_to_diag(err),
237            SubregionOrigin::RelateObjectBound(span) => {
238                RegionOriginNote::Plain {
239                    span,
240                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that it can be closed over into an object"))msg!("...so that it can be closed over into an object"),
241                }
242                .add_to_diag(err);
243            }
244            SubregionOrigin::ReferenceOutlivesReferent(ty, span) => {
245                RegionOriginNote::WithName {
246                    span,
247                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the reference type `{$name}` does not outlive the data it points at"))msg!("...so that the reference type `{$name}` does not outlive the data it points at"),
248                    name: &self.ty_to_string(ty),
249                    continues: false,
250                }
251                .add_to_diag(err);
252            }
253            SubregionOrigin::RelateParamBound(span, ty, opt_span) => {
254                RegionOriginNote::WithName {
255                    span,
256                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the type `{$name}` will meet its required lifetime bounds{$continues ->\n                            [true] ...\n                            *[false] {\"\"}\n                        }"))msg!(
257                        "...so that the type `{$name}` will meet its required lifetime bounds{$continues ->
258                            [true] ...
259                            *[false] {\"\"}
260                        }"
261                    ),
262                    name: &self.ty_to_string(ty),
263                    continues: opt_span.is_some(),
264                }
265                .add_to_diag(err);
266                if let Some(span) = opt_span {
267                    RegionOriginNote::Plain {
268                        span,
269                        msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...that is required by this bound"))msg!("...that is required by this bound"),
270                    }
271                    .add_to_diag(err);
272                }
273            }
274            SubregionOrigin::RelateRegionParamBound(span, _) => {
275                RegionOriginNote::Plain {
276                    span,
277                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the declared lifetime parameter bounds are satisfied"))msg!("...so that the declared lifetime parameter bounds are satisfied"),
278                }
279                .add_to_diag(err);
280            }
281            SubregionOrigin::CompareImplItemObligation { span, .. } => {
282                RegionOriginNote::Plain {
283                    span,
284                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the definition in impl matches the definition from the trait"))msg!(
285                        "...so that the definition in impl matches the definition from the trait"
286                    ),
287                }
288                .add_to_diag(err);
289            }
290            SubregionOrigin::CheckAssociatedTypeBounds { ref parent, .. } => {
291                self.note_region_origin(err, parent);
292            }
293            SubregionOrigin::AscribeUserTypeProvePredicate(span) => {
294                RegionOriginNote::Plain { span, msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that the where clause holds"))msg!("...so that the where clause holds") }
295                    .add_to_diag(err);
296            }
297            SubregionOrigin::SolverRegionConstraint(span) => {
298                RegionOriginNote::Plain {
299                    span,
300                    msg: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...so that a higher-ranked lifetime bound can be satisfied"))msg!("...so that a higher-ranked lifetime bound can be satisfied"),
301                }
302                .add_to_diag(err);
303            }
304        }
305    }
306
307    pub(super) fn report_concrete_failure(
308        &self,
309        generic_param_scope: LocalDefId,
310        origin: SubregionOrigin<'tcx>,
311        sub: Region<'tcx>,
312        sup: Region<'tcx>,
313    ) -> Diag<'a> {
314        let mut err = match origin {
315            SubregionOrigin::Subtype(trace) => {
316                let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
317                let mut err = self.report_and_explain_type_error(
318                    *trace,
319                    self.tcx.param_env(generic_param_scope),
320                    terr,
321                );
322                match (sub.kind(), sup.kind()) {
323                    (ty::RePlaceholder(_), ty::RePlaceholder(_)) => {}
324                    (ty::RePlaceholder(_), _) => {
325                        note_and_explain_region(
326                            self.tcx,
327                            &mut err,
328                            generic_param_scope,
329                            "",
330                            sup,
331                            " doesn't meet the lifetime requirements",
332                            None,
333                        );
334                    }
335                    (_, ty::RePlaceholder(_)) => {
336                        note_and_explain_region(
337                            self.tcx,
338                            &mut err,
339                            generic_param_scope,
340                            "the required lifetime does not necessarily outlive ",
341                            sub,
342                            "",
343                            None,
344                        );
345                    }
346                    _ => {
347                        note_and_explain_region(
348                            self.tcx,
349                            &mut err,
350                            generic_param_scope,
351                            "",
352                            sup,
353                            "...",
354                            None,
355                        );
356                        note_and_explain_region(
357                            self.tcx,
358                            &mut err,
359                            generic_param_scope,
360                            "...does not necessarily outlive ",
361                            sub,
362                            "",
363                            None,
364                        );
365                    }
366                }
367                err
368            }
369            SubregionOrigin::Reborrow(span) => {
370                let reference_valid = note_and_explain::RegionExplanation::new(
371                    self.tcx,
372                    generic_param_scope,
373                    sub,
374                    None,
375                    note_and_explain::PrefixKind::RefValidFor,
376                    note_and_explain::SuffixKind::Continues,
377                );
378                let content_valid = note_and_explain::RegionExplanation::new(
379                    self.tcx,
380                    generic_param_scope,
381                    sup,
382                    None,
383                    note_and_explain::PrefixKind::ContentValidFor,
384                    note_and_explain::SuffixKind::Empty,
385                );
386                self.dcx().create_err(OutlivesContent {
387                    span,
388                    notes: reference_valid.into_iter().chain(content_valid).collect(),
389                })
390            }
391            SubregionOrigin::RelateObjectBound(span) => {
392                let object_valid = note_and_explain::RegionExplanation::new(
393                    self.tcx,
394                    generic_param_scope,
395                    sub,
396                    None,
397                    note_and_explain::PrefixKind::TypeObjValidFor,
398                    note_and_explain::SuffixKind::Empty,
399                );
400                let pointer_valid = note_and_explain::RegionExplanation::new(
401                    self.tcx,
402                    generic_param_scope,
403                    sup,
404                    None,
405                    note_and_explain::PrefixKind::SourcePointerValidFor,
406                    note_and_explain::SuffixKind::Empty,
407                );
408                self.dcx().create_err(OutlivesBound {
409                    span,
410                    notes: object_valid.into_iter().chain(pointer_valid).collect(),
411                })
412            }
413            SubregionOrigin::RelateParamBound(span, ty, opt_span) => {
414                let prefix = match sub.kind() {
415                    ty::ReStatic => note_and_explain::PrefixKind::TypeSatisfy,
416                    _ => note_and_explain::PrefixKind::TypeOutlive,
417                };
418                let suffix = if opt_span.is_some() {
419                    note_and_explain::SuffixKind::ReqByBinding
420                } else {
421                    note_and_explain::SuffixKind::Empty
422                };
423                let note = note_and_explain::RegionExplanation::new(
424                    self.tcx,
425                    generic_param_scope,
426                    sub,
427                    opt_span,
428                    prefix,
429                    suffix,
430                );
431                self.dcx().create_err(FulfillReqLifetime {
432                    span,
433                    ty: self.resolve_vars_if_possible(ty),
434                    note,
435                })
436            }
437            SubregionOrigin::RelateRegionParamBound(span, ty) => {
438                let param_instantiated = note_and_explain::RegionExplanation::new(
439                    self.tcx,
440                    generic_param_scope,
441                    sup,
442                    None,
443                    note_and_explain::PrefixKind::LfParamInstantiatedWith,
444                    note_and_explain::SuffixKind::Empty,
445                );
446                let mut alt_span = None;
447                if let Some(ty) = ty
448                    && sub.is_static()
449                    && let ty::Dynamic(preds, _) = ty.kind()
450                    && let Some(def_id) = preds.principal_def_id()
451                {
452                    for (clause, span) in
453                        self.tcx.clauses_of(def_id).instantiate_identity(self.tcx).into_iter()
454                    {
455                        if let ty::ClauseKind::TypeOutlives(ty::OutlivesClause(a, b)) =
456                            clause.kind().skip_binder()
457                            && let ty::Param(param) = a.kind()
458                            && param.name == kw::SelfUpper
459                            && b.is_static()
460                        {
461                            // Point at explicit `'static` bound on the trait (`trait T: 'static`).
462                            alt_span = Some(span);
463                        }
464                    }
465                }
466                let param_must_outlive = note_and_explain::RegionExplanation::new(
467                    self.tcx,
468                    generic_param_scope,
469                    sub,
470                    alt_span,
471                    note_and_explain::PrefixKind::LfParamMustOutlive,
472                    note_and_explain::SuffixKind::Empty,
473                );
474                self.dcx().create_err(LfBoundNotSatisfied {
475                    span,
476                    notes: param_instantiated.into_iter().chain(param_must_outlive).collect(),
477                })
478            }
479            SubregionOrigin::ReferenceOutlivesReferent(ty, span) => {
480                let pointer_valid = note_and_explain::RegionExplanation::new(
481                    self.tcx,
482                    generic_param_scope,
483                    sub,
484                    None,
485                    note_and_explain::PrefixKind::PointerValidFor,
486                    note_and_explain::SuffixKind::Empty,
487                );
488                let data_valid = note_and_explain::RegionExplanation::new(
489                    self.tcx,
490                    generic_param_scope,
491                    sup,
492                    None,
493                    note_and_explain::PrefixKind::DataValidFor,
494                    note_and_explain::SuffixKind::Empty,
495                );
496                self.dcx().create_err(RefLongerThanData {
497                    span,
498                    ty: self.resolve_vars_if_possible(ty),
499                    notes: pointer_valid.into_iter().chain(data_valid).collect(),
500                })
501            }
502            SubregionOrigin::CompareImplItemObligation {
503                span,
504                impl_item_def_id,
505                trait_item_def_id,
506            } => {
507                let mut err = self.report_extra_impl_obligation(
508                    span,
509                    impl_item_def_id,
510                    trait_item_def_id,
511                    &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}: {1}`", sup, sub))
    })format!("`{sup}: {sub}`"),
512                );
513                // We should only suggest rewriting the `where` clause if the predicate is within that `where` clause
514                if let Some(generics) = self.tcx.hir_get_generics(impl_item_def_id)
515                    && generics.where_clause_span.contains(span)
516                {
517                    self.suggest_copy_trait_method_bounds(
518                        trait_item_def_id,
519                        impl_item_def_id,
520                        &mut err,
521                    );
522                }
523                err
524            }
525            SubregionOrigin::CheckAssociatedTypeBounds {
526                impl_item_def_id,
527                trait_item_def_id,
528                parent,
529            } => {
530                let mut err = self.report_concrete_failure(generic_param_scope, *parent, sub, sup);
531
532                // Don't mention the item name if it's an RPITIT, since that'll just confuse
533                // folks.
534                if !self.tcx.is_impl_trait_in_trait(impl_item_def_id.to_def_id()) {
535                    let trait_item_span = self.tcx.def_span(trait_item_def_id);
536                    let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
537                    err.span_label(
538                        trait_item_span,
539                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("definition of `{0}` from trait",
                item_name))
    })format!("definition of `{item_name}` from trait"),
540                    );
541                }
542
543                self.suggest_copy_trait_method_bounds(
544                    trait_item_def_id,
545                    impl_item_def_id,
546                    &mut err,
547                );
548                err
549            }
550            SubregionOrigin::AscribeUserTypeProvePredicate(span) => {
551                let instantiated = note_and_explain::RegionExplanation::new(
552                    self.tcx,
553                    generic_param_scope,
554                    sup,
555                    None,
556                    note_and_explain::PrefixKind::LfInstantiatedWith,
557                    note_and_explain::SuffixKind::Empty,
558                );
559                let must_outlive = note_and_explain::RegionExplanation::new(
560                    self.tcx,
561                    generic_param_scope,
562                    sub,
563                    None,
564                    note_and_explain::PrefixKind::LfMustOutlive,
565                    note_and_explain::SuffixKind::Empty,
566                );
567                self.dcx().create_err(LfBoundNotSatisfied {
568                    span,
569                    notes: instantiated.into_iter().chain(must_outlive).collect(),
570                })
571            }
572            SubregionOrigin::SolverRegionConstraint(span) => self
573                .dcx()
574                .struct_span_err(span, "higher-ranked lifetime bound could not be satisfied"),
575        };
576        if sub.is_error() || sup.is_error() {
577            err.downgrade_to_delayed_bug();
578        }
579        err
580    }
581
582    pub fn suggest_copy_trait_method_bounds(
583        &self,
584        trait_item_def_id: DefId,
585        impl_item_def_id: LocalDefId,
586        err: &mut Diag<'_>,
587    ) {
588        // FIXME(compiler-errors): Right now this is only being used for region
589        // predicate mismatches. Ideally, we'd use it for *all* predicate mismatches,
590        // but right now it's not really very smart when it comes to implicit `Sized`
591        // predicates and bounds on the trait itself.
592
593        let Some(impl_def_id) = self.tcx.trait_impl_of_assoc(impl_item_def_id.to_def_id()) else {
594            return;
595        };
596        let trait_ref = self.tcx.impl_trait_ref(impl_def_id);
597        let trait_args = trait_ref
598            .instantiate_identity()
599            .skip_norm_wip()
600            // Replace the explicit self type with `Self` for better suggestion rendering
601            .with_replaced_self_ty(self.tcx, Ty::new_param(self.tcx, 0, kw::SelfUpper))
602            .args;
603        let trait_item_args = ty::GenericArgs::identity_for_item(self.tcx, impl_item_def_id)
604            .rebase_onto(self.tcx, impl_def_id, trait_args);
605
606        let Ok(trait_predicates) = self
607            .tcx
608            .explicit_clauses_of(trait_item_def_id)
609            .instantiate_own(self.tcx, trait_item_args)
610            .map(|(clause, _)| {
611                let clause = clause.skip_norm_wip();
612                if clause.is_suggestable(self.tcx, false) {
613                    Ok(clause.to_string())
614                } else {
615                    Err(())
616                }
617            })
618            .collect::<Result<Vec<_>, ()>>()
619        else {
620            return;
621        };
622
623        let Some(generics) = self.tcx.hir_get_generics(impl_item_def_id) else {
624            return;
625        };
626
627        let suggestion = if trait_predicates.is_empty() {
628            WhereClauseSuggestions::Remove { span: generics.where_clause_span }
629        } else {
630            let space = if generics.where_clause_span.is_empty() { " " } else { "" };
631            WhereClauseSuggestions::CopyPredicates {
632                span: generics.where_clause_span,
633                space,
634                trait_predicates: trait_predicates.join(", "),
635            }
636        };
637        err.subdiagnostic(suggestion);
638    }
639
640    pub(super) fn report_placeholder_failure(
641        &self,
642        generic_param_scope: LocalDefId,
643        placeholder_origin: SubregionOrigin<'tcx>,
644        sub: Region<'tcx>,
645        sup: Region<'tcx>,
646    ) -> Diag<'a> {
647        // I can't think how to do better than this right now. -nikomatsakis
648        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:648",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(648u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("placeholder_origin")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("placeholder_origin");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("sub")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("sub");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("sup")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("sup");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_placeholder_failure")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder_origin)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sup)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?placeholder_origin, ?sub, ?sup, "report_placeholder_failure");
649        match placeholder_origin {
650            SubregionOrigin::Subtype(ref trace)
651                if #[allow(non_exhaustive_omitted_patterns)] match &trace.cause.code().peel_derives()
    {
    ObligationCauseCode::WhereClause(..) |
        ObligationCauseCode::WhereClauseInExpr(..) => true,
    _ => false,
}matches!(
652                    &trace.cause.code().peel_derives(),
653                    ObligationCauseCode::WhereClause(..)
654                        | ObligationCauseCode::WhereClauseInExpr(..)
655                ) =>
656            {
657                // Hack to get around the borrow checker because trace.cause has an `Rc`.
658                if let ObligationCauseCode::WhereClause(_, span)
659                | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
660                    &trace.cause.code().peel_derives()
661                {
662                    let span = *span;
663                    let mut err = self.report_concrete_failure(
664                        generic_param_scope,
665                        placeholder_origin,
666                        sub,
667                        sup,
668                    );
669                    if !span.is_dummy() {
670                        err =
671                            err.with_span_note(span, "the lifetime requirement is introduced here");
672                    }
673                    err
674                } else {
675                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("control flow ensures we have a `BindingObligation` or `WhereClauseInExpr` here...")));
}unreachable!(
676                        "control flow ensures we have a `BindingObligation` or `WhereClauseInExpr` here..."
677                    )
678                }
679            }
680            SubregionOrigin::Subtype(trace) => {
681                let terr = TypeError::RegionsPlaceholderMismatch;
682                return self.report_and_explain_type_error(
683                    *trace,
684                    self.tcx.param_env(generic_param_scope),
685                    terr,
686                );
687            }
688            _ => {
689                return self.report_concrete_failure(
690                    generic_param_scope,
691                    placeholder_origin,
692                    sub,
693                    sup,
694                );
695            }
696        }
697    }
698
699    pub fn report_generic_bound_failure(
700        &self,
701        generic_param_scope: LocalDefId,
702        span: Span,
703        origin: Option<SubregionOrigin<'tcx>>,
704        bound_kind: GenericKind<'tcx>,
705        sub: Region<'tcx>,
706    ) -> ErrorGuaranteed {
707        self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
708            .emit()
709    }
710
711    pub fn construct_generic_bound_failure(
712        &self,
713        generic_param_scope: LocalDefId,
714        span: Span,
715        origin: Option<SubregionOrigin<'tcx>>,
716        bound_kind: GenericKind<'tcx>,
717        sub: Region<'tcx>,
718    ) -> Diag<'a> {
719        if let Some(SubregionOrigin::CompareImplItemObligation {
720            span,
721            impl_item_def_id,
722            trait_item_def_id,
723        }) = origin
724        {
725            return self.report_extra_impl_obligation(
726                span,
727                impl_item_def_id,
728                trait_item_def_id,
729                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}: {1}`", bound_kind, sub))
    })format!("`{bound_kind}: {sub}`"),
730            );
731        }
732
733        let labeled_user_string = match bound_kind {
734            GenericKind::Param(_) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the parameter type `{0}`",
                bound_kind))
    })format!("the parameter type `{bound_kind}`"),
735            GenericKind::Placeholder(_) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the placeholder type `{0}`",
                bound_kind))
    })format!("the placeholder type `{bound_kind}`"),
736            GenericKind::Alias(p) => match p.kind {
737                ty::Projection { .. } | ty::Inherent { .. } => {
738                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the associated type `{0}`",
                bound_kind))
    })format!("the associated type `{bound_kind}`")
739                }
740                ty::Free { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the type alias `{0}`", bound_kind))
    })format!("the type alias `{bound_kind}`"),
741                ty::Opaque { .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the opaque type `{0}`",
                bound_kind))
    })format!("the opaque type `{bound_kind}`"),
742            },
743        };
744
745        let mut err = self
746            .tcx
747            .dcx()
748            .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} may not live long enough",
                labeled_user_string))
    })format!("{labeled_user_string} may not live long enough"));
749        err.code(match sub.kind() {
750            ty::ReEarlyParam(_) | ty::ReLateParam(_) if sub.is_named(self.tcx) => E0309,
751            ty::ReStatic => E0310,
752            _ => E0311,
753        });
754
755        '_explain: {
756            let (description, span) = match sub.kind() {
757                ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
758                    msg_span_from_named_region(self.tcx, generic_param_scope, sub, Some(span))
759                }
760                _ => (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}`", sub))
    })format!("lifetime `{sub}`"), Some(span)),
761            };
762            let prefix = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} must be valid for ",
                labeled_user_string))
    })format!("{labeled_user_string} must be valid for ");
763            label_msg_span(&mut err, &prefix, description, span, "...");
764            if let Some(origin) = origin {
765                self.note_region_origin(&mut err, &origin);
766            }
767        }
768
769        'suggestion: {
770            let msg = "consider adding an explicit lifetime bound";
771
772            if (bound_kind, sub).has_infer_regions()
773                || (bound_kind, sub).has_placeholders()
774                || !bound_kind.is_suggestable(self.tcx, false)
775            {
776                let lt_name = sub.get_name_or_anon(self.tcx).to_string();
777                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}: {2}`...", msg,
                bound_kind, lt_name))
    })format!("{msg} `{bound_kind}: {lt_name}`..."));
778                break 'suggestion;
779            }
780
781            let mut generic_param_scope = generic_param_scope;
782            while self.tcx.def_kind(generic_param_scope) == DefKind::OpaqueTy {
783                generic_param_scope = self.tcx.local_parent(generic_param_scope);
784            }
785
786            // type_param_sugg_span is (span, has_bounds, needs_parentheses)
787            let (type_scope, type_param_sugg_span) = match bound_kind {
788                GenericKind::Param(param) => {
789                    let generics = self.tcx.generics_of(generic_param_scope);
790                    let type_param = generics.type_param(param, self.tcx);
791                    let def_id = type_param.def_id.expect_local();
792                    let scope = self.tcx.local_def_id_to_hir_id(def_id).owner.def_id;
793                    // Get the `hir::Param` to verify whether it already has any bounds.
794                    // We do this to avoid suggesting code that ends up as `T: 'a'b`,
795                    // instead we suggest `T: 'a + 'b` in that case.
796                    let hir_generics = self.tcx.hir_get_generics(scope).unwrap();
797                    let sugg_span = match hir_generics.bounds_span_for_suggestions(def_id) {
798                        Some((span, open_paren_sp)) => {
799                            Some((span, LifetimeSuggestion::NeedsPlus(open_paren_sp)))
800                        }
801                        // If `param` corresponds to `Self`, no usable suggestion span.
802                        None if generics.has_self && param.index == 0 => None,
803                        None => {
804                            let mut colon_flag = false;
805                            let span = if let Some(param) =
806                                hir_generics.params.iter().find(|param| param.def_id == def_id)
807                                && let ParamName::Plain(ident) = param.name
808                            {
809                                if let Some(sp) = param.colon_span {
810                                    colon_flag = true;
811                                    sp.shrink_to_hi()
812                                } else {
813                                    ident.span.shrink_to_hi()
814                                }
815                            } else {
816                                let span = self.tcx.def_span(def_id);
817                                span.shrink_to_hi()
818                            };
819                            match colon_flag {
820                                true => Some((span, LifetimeSuggestion::HasColon)),
821                                false => Some((span, LifetimeSuggestion::NeedsColon)),
822                            }
823                        }
824                    };
825                    (scope, sugg_span)
826                }
827                _ => (generic_param_scope, None),
828            };
829            let suggestion_scope = {
830                let lifetime_scope = match sub.kind() {
831                    ty::ReStatic => hir::def_id::CRATE_DEF_ID,
832                    _ => match self.tcx.is_suitable_region(generic_param_scope, sub) {
833                        Some(info) => info.scope,
834                        None => generic_param_scope,
835                    },
836                };
837                match self.tcx.is_descendant_of(type_scope, lifetime_scope) {
838                    true => type_scope,
839                    false => lifetime_scope,
840                }
841            };
842
843            let mut suggs = ::alloc::vec::Vec::new()vec![];
844            let lt_name = self.suggest_name_region(generic_param_scope, sub, &mut suggs);
845
846            if let Some((sp, suggestion_type)) = type_param_sugg_span
847                && suggestion_scope == type_scope
848            {
849                match suggestion_type {
850                    LifetimeSuggestion::NeedsPlus(open_paren_sp) => {
851                        let suggestion = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + {0}", lt_name))
    })format!(" + {lt_name}");
852                        if let Some(open_paren_sp) = open_paren_sp {
853                            suggs.push((open_paren_sp, "(".to_string()));
854                            suggs.push((sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("){0}", suggestion))
    })format!("){suggestion}")));
855                        } else {
856                            suggs.push((sp, suggestion));
857                        }
858                    }
859                    LifetimeSuggestion::NeedsColon => suggs.push((sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(": {0}", lt_name))
    })format!(": {lt_name}"))),
860                    LifetimeSuggestion::HasColon => suggs.push((sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", lt_name))
    })format!(" {lt_name}"))),
861                }
862            } else if let GenericKind::Alias(ref p) = bound_kind
863                && let ty::Projection { def_id } = p.kind
864                && let DefKind::AssocTy = self.tcx.def_kind(def_id)
865                && let Some(ty::ImplTraitInTraitData::Trait { .. }) =
866                    self.tcx.opt_rpitit_info(def_id)
867            {
868                // The lifetime found in the `impl` is longer than the one on the RPITIT.
869                // Do not suggest `<Type as Trait>::{opaque}: 'static`.
870            } else if let Some(generics) = self.tcx.hir_get_generics(suggestion_scope) {
871                let pred = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", bound_kind, lt_name))
    })format!("{bound_kind}: {lt_name}");
872                let suggestion = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}",
                generics.add_where_or_trailing_comma(), pred))
    })format!("{} {}", generics.add_where_or_trailing_comma(), pred);
873                suggs.push((generics.tail_span_for_predicate_suggestion(), suggestion))
874            } else {
875                let consider = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} `{1}: {2}`...", msg,
                bound_kind, sub))
    })format!("{msg} `{bound_kind}: {sub}`...");
876                err.help(consider);
877            }
878
879            if !suggs.is_empty() {
880                err.multipart_suggestion(
881                    msg,
882                    suggs,
883                    Applicability::MaybeIncorrect, // Issue #41966
884                );
885            }
886        }
887
888        if sub.kind() == ty::ReStatic
889            && let Some(node) = self.tcx.hir_get_if_local(generic_param_scope.into())
890            && let hir::Node::Item(hir::Item {
891                kind: hir::ItemKind::Fn { sig, body, has_body: true, .. },
892                ..
893            })
894            | hir::Node::TraitItem(hir::TraitItem {
895                kind: hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body)),
896                ..
897            })
898            | hir::Node::ImplItem(hir::ImplItem {
899                kind: hir::ImplItemKind::Fn(sig, body), ..
900            }) = node
901            && let hir::Node::Expr(expr) = self.tcx.hir_node(body.hir_id)
902            && let hir::ExprKind::Block(block, _) = expr.kind
903            && let Some(tail) = block.expr
904            && tail.span == span
905            && let hir::FnRetTy::Return(ty) = sig.decl.output
906            && let hir::TyKind::Path(path) = ty.kind
907            && let hir::QPath::Resolved(None, path) = path
908            && let hir::def::Res::Def(_, def_id) = path.res
909            && Some(def_id) == self.tcx.lang_items().owned_box()
910            && let [segment] = path.segments
911            && let Some(args) = segment.args
912            && let [hir::GenericArg::Type(ty)] = args.args
913            && let hir::TyKind::TraitObject(_, tagged_ref) = ty.kind
914            && let hir::LifetimeKind::ImplicitObjectLifetimeDefault = tagged_ref.pointer().kind
915        {
916            // Explicitly look for `-> Box<dyn Trait>` to point at it as the *likely* source of
917            // the `'static` lifetime requirement.
918            err.span_label(
919                ty.span,
920                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `dyn Trait` has an implicit `\'static` lifetime bound"))
    })format!("this `dyn Trait` has an implicit `'static` lifetime bound"),
921            );
922        }
923
924        err
925    }
926
927    pub fn suggest_name_region(
928        &self,
929        generic_param_scope: LocalDefId,
930        lifetime: Region<'tcx>,
931        add_lt_suggs: &mut Vec<(Span, String)>,
932    ) -> String {
933        struct LifetimeReplaceVisitor<'a> {
934            needle: hir::LifetimeKind,
935            new_lt: &'a str,
936            add_lt_suggs: &'a mut Vec<(Span, String)>,
937        }
938
939        impl<'hir> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'_> {
940            fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
941                if lt.kind == self.needle {
942                    self.add_lt_suggs.push(lt.suggestion(self.new_lt));
943                }
944            }
945        }
946
947        let (lifetime_def_id, lifetime_scope) =
948            match self.tcx.is_suitable_region(generic_param_scope, lifetime) {
949                Some(info) if !lifetime.is_named(self.tcx) => {
950                    (info.region_def_id.expect_local(), info.scope)
951                }
952                _ => return lifetime.get_name_or_anon(self.tcx).to_string(),
953            };
954
955        let new_lt = {
956            let generics = self.tcx.generics_of(lifetime_scope);
957            let mut used_names =
958                iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
959                    .flat_map(|g| &g.own_params)
960                    .filter(|p| #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    ty::GenericParamDefKind::Lifetime => true,
    _ => false,
}matches!(p.kind, ty::GenericParamDefKind::Lifetime))
961                    .map(|p| p.name)
962                    .collect::<Vec<_>>();
963            let hir_id = self.tcx.local_def_id_to_hir_id(lifetime_scope);
964            // consider late-bound lifetimes ...
965            used_names.extend(self.tcx.late_bound_vars(hir_id).into_iter().filter_map(
966                |p| match p {
967                    ty::BoundVariableKind::Region(lt) => lt.get_name(self.tcx),
968                    _ => None,
969                },
970            ));
971            (b'a'..=b'z')
972                .map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\'{0}", c as char))
    })format!("'{}", c as char))
973                .find(|candidate| !used_names.iter().any(|e| e.as_str() == candidate))
974                .unwrap_or_else(|| "'lt".to_string())
975        };
976
977        let mut visitor = LifetimeReplaceVisitor {
978            needle: hir::LifetimeKind::Param(lifetime_def_id),
979            add_lt_suggs,
980            new_lt: &new_lt,
981        };
982        match self.tcx.expect_hir_owner_node(lifetime_scope) {
983            hir::OwnerNode::Item(i) => visitor.visit_item(i),
984            hir::OwnerNode::ForeignItem(i) => visitor.visit_foreign_item(i),
985            hir::OwnerNode::ImplItem(i) => visitor.visit_impl_item(i),
986            hir::OwnerNode::TraitItem(i) => visitor.visit_trait_item(i),
987            hir::OwnerNode::Crate(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("OwnerNode::Crate doesn\'t not have generics"))bug!("OwnerNode::Crate doesn't not have generics"),
988            hir::OwnerNode::Synthetic => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
989        }
990
991        let ast_generics = self.tcx.hir_get_generics(lifetime_scope).unwrap();
992        let sugg = ast_generics
993            .span_for_lifetime_suggestion()
994            .map(|span| (span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", new_lt))
    })format!("{new_lt}, ")))
995            .unwrap_or_else(|| (ast_generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", new_lt))
    })format!("<{new_lt}>")));
996        add_lt_suggs.push(sugg);
997
998        new_lt
999    }
1000
1001    fn report_sub_sup_conflict(
1002        &self,
1003        generic_param_scope: LocalDefId,
1004        var_origin: RegionVariableOrigin<'tcx>,
1005        sub_origin: SubregionOrigin<'tcx>,
1006        sub_region: Region<'tcx>,
1007        sup_origin: SubregionOrigin<'tcx>,
1008        sup_region: Region<'tcx>,
1009    ) -> ErrorGuaranteed {
1010        let mut err = self.report_inference_failure(var_origin);
1011
1012        note_and_explain_region(
1013            self.tcx,
1014            &mut err,
1015            generic_param_scope,
1016            "first, the lifetime cannot outlive ",
1017            sup_region,
1018            "...",
1019            None,
1020        );
1021
1022        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1022",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(1022u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: var_origin={0:?}",
                                                    var_origin) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1023        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1023",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(1023u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sub_region={0:?}",
                                                    sub_region) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1024        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1024",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(1024u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sub_origin={0:?}",
                                                    sub_origin) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1025        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1025",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(1025u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sup_region={0:?}",
                                                    sup_region) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1026        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs:1026",
                        "rustc_trait_selection::error_reporting::infer::region",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                        ::tracing_core::__macro_support::Option::Some(1026u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_sub_sup_conflict: sup_origin={0:?}",
                                                    sup_origin) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1027
1028        if let SubregionOrigin::Subtype(ref sup_trace) = sup_origin
1029            && let SubregionOrigin::Subtype(ref sub_trace) = sub_origin
1030            && let Some((sup_expected, sup_found)) =
1031                self.values_str(sup_trace.values, &sup_trace.cause, err.long_ty_path())
1032            && let Some((sub_expected, sub_found)) =
1033                self.values_str(sub_trace.values, &sub_trace.cause, err.long_ty_path())
1034            && sub_expected == sup_expected
1035            && sub_found == sup_found
1036        {
1037            note_and_explain_region(
1038                self.tcx,
1039                &mut err,
1040                generic_param_scope,
1041                "...but the lifetime must also be valid for ",
1042                sub_region,
1043                "...",
1044                None,
1045            );
1046            err.span_note(
1047                sup_trace.cause.span,
1048                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("...so that the {0}",
                sup_trace.cause.as_requirement_str()))
    })format!("...so that the {}", sup_trace.cause.as_requirement_str()),
1049            );
1050
1051            err.note_expected_found("", sup_expected, "", sup_found);
1052            return if sub_region.is_error() | sup_region.is_error() {
1053                err.delay_as_bug()
1054            } else {
1055                err.emit()
1056            };
1057        }
1058
1059        self.note_region_origin(&mut err, &sup_origin);
1060
1061        note_and_explain_region(
1062            self.tcx,
1063            &mut err,
1064            generic_param_scope,
1065            "but, the lifetime must be valid for ",
1066            sub_region,
1067            "...",
1068            None,
1069        );
1070
1071        self.note_region_origin(&mut err, &sub_origin);
1072        if sub_region.is_error() | sup_region.is_error() { err.delay_as_bug() } else { err.emit() }
1073    }
1074
1075    fn report_inference_failure(&self, var_origin: RegionVariableOrigin<'tcx>) -> Diag<'_> {
1076        let br_string = |br: ty::BoundRegionKind<'tcx>| {
1077            let mut s = match br {
1078                ty::BoundRegionKind::Named(def_id) => self.tcx.item_name(def_id).to_string(),
1079                _ => String::new(),
1080            };
1081            if !s.is_empty() {
1082                s.push(' ');
1083            }
1084            s
1085        };
1086        let var_description = match var_origin {
1087            RegionVariableOrigin::Misc(_) => String::new(),
1088            RegionVariableOrigin::PatternRegion(_) => " for pattern".to_string(),
1089            RegionVariableOrigin::BorrowRegion(_) => " for borrow expression".to_string(),
1090            RegionVariableOrigin::Autoref(_) => " for autoref".to_string(),
1091            RegionVariableOrigin::Coercion(_) => " for automatic coercion".to_string(),
1092            RegionVariableOrigin::BoundRegion(_, br, BoundRegionConversionTime::FnCall) => {
1093                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for lifetime parameter {0}in function call",
                br_string(br)))
    })format!(" for lifetime parameter {}in function call", br_string(br))
1094            }
1095            RegionVariableOrigin::BoundRegion(
1096                _,
1097                br,
1098                BoundRegionConversionTime::HigherRankedType,
1099            ) => {
1100                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for lifetime parameter {0}in generic type",
                br_string(br)))
    })format!(" for lifetime parameter {}in generic type", br_string(br))
1101            }
1102            RegionVariableOrigin::BoundRegion(
1103                _,
1104                br,
1105                BoundRegionConversionTime::AssocTypeProjection(def_id),
1106            ) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for lifetime parameter {0}in trait containing associated type `{1}`",
                br_string(br), self.tcx.associated_item(def_id).name()))
    })format!(
1107                " for lifetime parameter {}in trait containing associated type `{}`",
1108                br_string(br),
1109                self.tcx.associated_item(def_id).name()
1110            ),
1111            RegionVariableOrigin::RegionParameterDefinition(_, name) => {
1112                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for lifetime parameter `{0}`",
                name))
    })format!(" for lifetime parameter `{name}`")
1113            }
1114            RegionVariableOrigin::UpvarRegion(ref upvar_id, _) => {
1115                let var_name = self.tcx.hir_name(upvar_id.var_path.hir_id);
1116                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" for capture of `{0}` by closure",
                var_name))
    })format!(" for capture of `{var_name}` by closure")
1117            }
1118            RegionVariableOrigin::Nll(..) => ::rustc_middle::util::bug::bug_fmt(format_args!("NLL variable found in lexical phase"))bug!("NLL variable found in lexical phase"),
1119        };
1120
1121        {
    self.dcx().struct_span_err(var_origin.span(),
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("cannot infer an appropriate lifetime{0} due to conflicting requirements",
                            var_description))
                })).with_code(E0803)
}struct_span_code_err!(
1122            self.dcx(),
1123            var_origin.span(),
1124            E0803,
1125            "cannot infer an appropriate lifetime{} due to conflicting requirements",
1126            var_description
1127        )
1128    }
1129}
1130
1131enum LifetimeSuggestion {
1132    NeedsPlus(Option<Span>),
1133    NeedsColon,
1134    HasColon,
1135}
1136
1137pub(super) fn note_and_explain_region<'tcx>(
1138    tcx: TyCtxt<'tcx>,
1139    err: &mut Diag<'_>,
1140    generic_param_scope: LocalDefId,
1141    prefix: &str,
1142    region: ty::Region<'tcx>,
1143    suffix: &str,
1144    alt_span: Option<Span>,
1145) {
1146    let (description, span) = match region.kind() {
1147        ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::RePlaceholder(_) | ty::ReStatic => {
1148            msg_span_from_named_region(tcx, generic_param_scope, region, alt_span)
1149        }
1150
1151        ty::ReError(_) => return,
1152
1153        // FIXME(#125431): `ReVar` shouldn't reach here.
1154        ty::ReVar(_) => (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}`", region))
    })format!("lifetime `{region}`"), alt_span),
1155
1156        ty::ReBound(..) | ty::ReErased => {
1157            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected region for note_and_explain_region: {0:?}",
        region));bug!("unexpected region for note_and_explain_region: {:?}", region);
1158        }
1159    };
1160
1161    emit_msg_span(err, prefix, description, span, suffix);
1162}
1163
1164fn explain_free_region<'tcx>(
1165    tcx: TyCtxt<'tcx>,
1166    err: &mut Diag<'_>,
1167    generic_param_scope: LocalDefId,
1168    prefix: &str,
1169    region: ty::Region<'tcx>,
1170    suffix: &str,
1171) {
1172    let (description, span) = msg_span_from_named_region(tcx, generic_param_scope, region, None);
1173
1174    label_msg_span(err, prefix, description, span, suffix);
1175}
1176
1177fn msg_span_from_named_region<'tcx>(
1178    tcx: TyCtxt<'tcx>,
1179    generic_param_scope: LocalDefId,
1180    region: ty::Region<'tcx>,
1181    alt_span: Option<Span>,
1182) -> (String, Option<Span>) {
1183    match region.kind() {
1184        ty::ReEarlyParam(br) => {
1185            let param_def_id = tcx.generics_of(generic_param_scope).region_param(br, tcx).def_id;
1186            let span = tcx.def_span(param_def_id);
1187            let text = if br.is_named() {
1188                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
                br.name))
    })format!("the lifetime `{}` as defined here", br.name)
1189            } else {
1190                "the anonymous lifetime as defined here".to_string()
1191            };
1192            (text, Some(span))
1193        }
1194        ty::ReLateParam(ref fr) => {
1195            if !fr.kind.is_named(tcx)
1196                && let Some((ty, _)) = find_anon_type(tcx, generic_param_scope, region)
1197            {
1198                ("the anonymous lifetime defined here".to_string(), Some(ty.span))
1199            } else {
1200                match fr.kind {
1201                    ty::LateParamRegionKind::Named(param_def_id) => {
1202                        let name = tcx.item_name(param_def_id);
1203                        let span = tcx.def_span(param_def_id);
1204                        let text = if name == kw::UnderscoreLifetime {
1205                            "the anonymous lifetime as defined here".to_string()
1206                        } else {
1207                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
                name))
    })format!("the lifetime `{name}` as defined here")
1208                        };
1209                        (text, Some(span))
1210                    }
1211                    ty::LateParamRegionKind::Anon(_) => (
1212                        "the anonymous lifetime as defined here".to_string(),
1213                        Some(tcx.def_span(generic_param_scope)),
1214                    ),
1215                    _ => (
1216                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
                region))
    })format!("the lifetime `{region}` as defined here"),
1217                        Some(tcx.def_span(generic_param_scope)),
1218                    ),
1219                }
1220            }
1221        }
1222        ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
1223        ty::RePlaceholder(ty::PlaceholderRegion {
1224            bound: ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. },
1225            ..
1226        }) => (
1227            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the lifetime `{0}` as defined here",
                tcx.item_name(def_id)))
    })format!("the lifetime `{}` as defined here", tcx.item_name(def_id)),
1228            Some(tcx.def_span(def_id)),
1229        ),
1230        ty::RePlaceholder(ty::PlaceholderRegion {
1231            bound: ty::BoundRegion { kind: ty::BoundRegionKind::Anon, .. },
1232            ..
1233        }) => ("an anonymous lifetime".to_owned(), None),
1234        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?}", region))bug!("{:?}", region),
1235    }
1236}
1237
1238fn emit_msg_span(
1239    err: &mut Diag<'_>,
1240    prefix: &str,
1241    description: String,
1242    span: Option<Span>,
1243    suffix: &str,
1244) {
1245    let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, description,
                suffix))
    })format!("{prefix}{description}{suffix}");
1246
1247    if let Some(span) = span {
1248        err.span_note(span, message);
1249    } else {
1250        err.note(message);
1251    }
1252}
1253
1254fn label_msg_span(
1255    err: &mut Diag<'_>,
1256    prefix: &str,
1257    description: String,
1258    span: Option<Span>,
1259    suffix: &str,
1260) {
1261    let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, description,
                suffix))
    })format!("{prefix}{description}{suffix}");
1262
1263    if let Some(span) = span {
1264        err.span_label(span, message);
1265    } else {
1266        err.note(message);
1267    }
1268}
1269
1270{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("unexpected_hidden_region_diagnostic",
                                    "rustc_trait_selection::error_reporting::infer::region",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1270u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::region"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("generic_param_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("generic_param_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hidden_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hidden_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hidden_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hidden_region");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("opaque_ty_key")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("opaque_ty_key");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_param_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hidden_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hidden_region)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opaque_ty_key)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Diag<'a> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = infcx.tcx;
            let mut err =
                infcx.dcx().create_err(diagnostics::OpaqueCapturesLifetime {
                        span,
                        opaque_ty: Ty::new_opaque(tcx, ty::IsRigid::No,
                            opaque_ty_key.def_id.to_def_id(), opaque_ty_key.args),
                        opaque_ty_span: tcx.def_span(opaque_ty_key.def_id),
                    });
            let mut highlight = RegionHighlightMode::default();
            highlight.keep_regions = true;
            let hidden_ty =
                Highlighted {
                    highlight,
                    ns: Namespace::TypeNS,
                    tcx,
                    value: hidden_ty,
                };
            match hidden_region.kind() {
                ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
                    explain_free_region(tcx, &mut err, generic_param_scope,
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
                                            hidden_ty))
                                }), hidden_region, "");
                    if let Some(_) =
                            tcx.is_suitable_region(generic_param_scope, hidden_region) {
                        suggest_precise_capturing(tcx, opaque_ty_key.def_id,
                            hidden_region, &mut err);
                    }
                }
                ty::RePlaceholder(_) => {
                    explain_free_region(tcx, &mut err, generic_param_scope,
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
                                            hidden_ty))
                                }), hidden_region, "");
                }
                ty::ReError(_) => { err.downgrade_to_delayed_bug(); }
                _ => {
                    note_and_explain_region(tcx, &mut err, generic_param_scope,
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("hidden type `{0}` captures ",
                                            hidden_ty))
                                }), hidden_region, "", None);
                }
            }
            err
        }
    }
}#[instrument(level = "trace", skip(infcx))]
1271pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>(
1272    infcx: &'a InferCtxt<'tcx>,
1273    generic_param_scope: LocalDefId,
1274    span: Span,
1275    hidden_ty: Ty<'tcx>,
1276    hidden_region: ty::Region<'tcx>,
1277    opaque_ty_key: ty::OpaqueTypeKey<'tcx>,
1278) -> Diag<'a> {
1279    let tcx = infcx.tcx;
1280    let mut err = infcx.dcx().create_err(diagnostics::OpaqueCapturesLifetime {
1281        span,
1282        opaque_ty: Ty::new_opaque(
1283            tcx,
1284            ty::IsRigid::No,
1285            opaque_ty_key.def_id.to_def_id(),
1286            opaque_ty_key.args,
1287        ),
1288        opaque_ty_span: tcx.def_span(opaque_ty_key.def_id),
1289    });
1290    let mut highlight = RegionHighlightMode::default();
1291    highlight.keep_regions = true;
1292    let hidden_ty = Highlighted { highlight, ns: Namespace::TypeNS, tcx, value: hidden_ty };
1293
1294    // Explain the region we are capturing.
1295    match hidden_region.kind() {
1296        ty::ReEarlyParam(_) | ty::ReLateParam(_) | ty::ReStatic => {
1297            // Assuming regionck succeeded (*), we ought to always be
1298            // capturing *some* region from the fn header, and hence it
1299            // ought to be free. So under normal circumstances, we will go
1300            // down this path which gives a decent human readable
1301            // explanation.
1302            //
1303            // (*) if not, the `tainted_by_errors` field would be set to
1304            // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
1305            explain_free_region(
1306                tcx,
1307                &mut err,
1308                generic_param_scope,
1309                &format!("hidden type `{hidden_ty}` captures "),
1310                hidden_region,
1311                "",
1312            );
1313            if let Some(_) = tcx.is_suitable_region(generic_param_scope, hidden_region) {
1314                suggest_precise_capturing(tcx, opaque_ty_key.def_id, hidden_region, &mut err);
1315            }
1316        }
1317        ty::RePlaceholder(_) => {
1318            explain_free_region(
1319                tcx,
1320                &mut err,
1321                generic_param_scope,
1322                &format!("hidden type `{}` captures ", hidden_ty),
1323                hidden_region,
1324                "",
1325            );
1326        }
1327        ty::ReError(_) => {
1328            err.downgrade_to_delayed_bug();
1329        }
1330        _ => {
1331            // Ugh. This is a painful case: the hidden region is not one
1332            // that we can easily summarize or explain. This can happen
1333            // in a case like
1334            // `tests/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
1335            //
1336            // ```
1337            // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
1338            //   if condition() { a } else { b }
1339            // }
1340            // ```
1341            //
1342            // Here the captured lifetime is the intersection of `'a` and
1343            // `'b`, which we can't quite express.
1344
1345            // We can at least report a really cryptic error for now.
1346            note_and_explain_region(
1347                tcx,
1348                &mut err,
1349                generic_param_scope,
1350                &format!("hidden type `{hidden_ty}` captures "),
1351                hidden_region,
1352                "",
1353                None,
1354            );
1355        }
1356    }
1357
1358    err
1359}
1360
1361fn suggest_precise_capturing<'tcx>(
1362    tcx: TyCtxt<'tcx>,
1363    opaque_def_id: LocalDefId,
1364    captured_lifetime: ty::Region<'tcx>,
1365    diag: &mut Diag<'_>,
1366) {
1367    let hir::OpaqueTy { bounds, origin, .. } =
1368        tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
1369
1370    let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. } = *origin else {
1371        return;
1372    };
1373
1374    let new_lifetime = Symbol::intern(&captured_lifetime.to_string());
1375
1376    if let Some((args, span)) = bounds.iter().find_map(|bound| match bound {
1377        hir::GenericBound::Use(args, span) => Some((args, span)),
1378        _ => None,
1379    }) {
1380        let last_lifetime_span = args.iter().rev().find_map(|arg| match arg {
1381            hir::PreciseCapturingArg::Lifetime(lt) => Some(lt.ident.span),
1382            _ => None,
1383        });
1384
1385        let first_param_span = args.iter().find_map(|arg| match arg {
1386            hir::PreciseCapturingArg::Param(p) => Some(p.ident.span),
1387            _ => None,
1388        });
1389
1390        let (span, pre, post) = if let Some(last_lifetime_span) = last_lifetime_span {
1391            (last_lifetime_span.shrink_to_hi(), ", ", "")
1392        } else if let Some(first_param_span) = first_param_span {
1393            (first_param_span.shrink_to_lo(), "", ", ")
1394        } else {
1395            // If we have no args, then have `use<>` and need to fall back to using
1396            // span math. This sucks, but should be reliable due to the construction
1397            // of the `use<>` span.
1398            (span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(), "", "")
1399        };
1400
1401        diag.subdiagnostic(diagnostics::AddPreciseCapturing::Existing {
1402            span,
1403            new_lifetime,
1404            pre,
1405            post,
1406        });
1407    } else {
1408        let mut captured_lifetimes = FxIndexSet::default();
1409        let mut captured_non_lifetimes = FxIndexSet::default();
1410
1411        let variances = tcx.variances_of(opaque_def_id);
1412        let mut generics = tcx.generics_of(opaque_def_id);
1413        let mut synthetics = ::alloc::vec::Vec::new()vec![];
1414        loop {
1415            for param in &generics.own_params {
1416                if variances[param.index as usize] == ty::Bivariant {
1417                    continue;
1418                }
1419
1420                match param.kind {
1421                    ty::GenericParamDefKind::Lifetime => {
1422                        captured_lifetimes.insert(param.name);
1423                    }
1424                    ty::GenericParamDefKind::Type { synthetic: true, .. } => {
1425                        synthetics.push((tcx.def_span(param.def_id), param.name));
1426                    }
1427                    ty::GenericParamDefKind::Type { .. }
1428                    | ty::GenericParamDefKind::Const { .. } => {
1429                        captured_non_lifetimes.insert(param.name);
1430                    }
1431                }
1432            }
1433
1434            if let Some(parent) = generics.parent {
1435                generics = tcx.generics_of(parent);
1436            } else {
1437                break;
1438            }
1439        }
1440
1441        if !captured_lifetimes.insert(new_lifetime) {
1442            // Uh, strange. This lifetime appears to already be captured...
1443            return;
1444        }
1445
1446        if synthetics.is_empty() {
1447            let concatenated_bounds = captured_lifetimes
1448                .into_iter()
1449                .chain(captured_non_lifetimes)
1450                .map(|sym| sym.to_string())
1451                .collect::<Vec<_>>()
1452                .join(", ");
1453
1454            diag.subdiagnostic(diagnostics::AddPreciseCapturing::New {
1455                span: tcx.def_span(opaque_def_id).shrink_to_hi(),
1456                new_lifetime,
1457                concatenated_bounds,
1458            });
1459        } else {
1460            let mut next_fresh_param = || {
1461                ['T', 'U', 'V', 'W', 'X', 'Y', 'A', 'B', 'C']
1462                    .into_iter()
1463                    .map(sym::character)
1464                    .chain((0..).map(|i| Symbol::intern(&::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("T{0}", i)) })format!("T{i}"))))
1465                    .find(|s| captured_non_lifetimes.insert(*s))
1466                    .unwrap()
1467            };
1468
1469            let mut new_params = String::new();
1470            let mut suggs = ::alloc::vec::Vec::new()vec![];
1471            let mut apit_spans = ::alloc::vec::Vec::new()vec![];
1472
1473            for (i, (span, name)) in synthetics.into_iter().enumerate() {
1474                apit_spans.push(span);
1475
1476                let fresh_param = next_fresh_param();
1477
1478                // Suggest renaming.
1479                suggs.push((span, fresh_param.to_string()));
1480
1481                // Super jank. Turn `impl Trait` into `T: Trait`.
1482                //
1483                // This currently involves stripping the `impl` from the name of
1484                // the parameter, since APITs are always named after how they are
1485                // rendered in the AST. This sucks! But to recreate the bound list
1486                // from the APIT itself would be miserable, so we're stuck with
1487                // this for now!
1488                if i > 0 {
1489                    new_params += ", ";
1490                }
1491                let name_as_bounds = name.as_str().trim_start_matches("impl").trim_start();
1492                new_params += fresh_param.as_str();
1493                new_params += ": ";
1494                new_params += name_as_bounds;
1495            }
1496
1497            let Some(generics) = tcx.hir_get_generics(fn_def_id) else {
1498                // This shouldn't happen, but don't ICE.
1499                return;
1500            };
1501
1502            // Add generics or concatenate to the end of the list.
1503            suggs.push(if let Some(params_span) = generics.span_for_param_suggestion() {
1504                (params_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", new_params))
    })format!(", {new_params}"))
1505            } else {
1506                (generics.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", new_params))
    })format!("<{new_params}>"))
1507            });
1508
1509            let concatenated_bounds = captured_lifetimes
1510                .into_iter()
1511                .chain(captured_non_lifetimes)
1512                .map(|sym| sym.to_string())
1513                .collect::<Vec<_>>()
1514                .join(", ");
1515
1516            suggs.push((
1517                tcx.def_span(opaque_def_id).shrink_to_hi(),
1518                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" + use<{0}>", concatenated_bounds))
    })format!(" + use<{concatenated_bounds}>"),
1519            ));
1520
1521            diag.subdiagnostic(diagnostics::AddPreciseCapturingAndParams {
1522                suggs,
1523                new_lifetime,
1524                apit_spans,
1525            });
1526        }
1527    }
1528}