Skip to main content

rustc_borrowck/diagnostics/
bound_region_errors.rs

1use std::fmt;
2use std::rc::Rc;
3
4use rustc_errors::Diag;
5use rustc_hir::def_id::LocalDefId;
6use rustc_infer::infer::region_constraints::{Constraint, ConstraintKind, RegionConstraintData};
7use rustc_infer::infer::{
8    InferCtxt, RegionResolutionError, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt as _,
9};
10use rustc_infer::traits::ObligationCause;
11use rustc_infer::traits::query::{
12    CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpNormalizeGoal,
13    CanonicalTypeOpProvePredicateGoal,
14};
15use rustc_middle::ty::error::TypeError;
16use rustc_middle::ty::{
17    self, RePlaceholder, Region, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex,
18};
19use rustc_span::Span;
20use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
21use rustc_trait_selection::error_reporting::infer::nice_region_error::NiceRegionError;
22use rustc_trait_selection::traits::ObligationCtxt;
23use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause};
24use tracing::{debug, instrument};
25
26use crate::MirBorrowckCtxt;
27use crate::session_diagnostics::{
28    HigherRankedErrorCause, HigherRankedLifetimeError, HigherRankedSubtypeError,
29};
30
31/// What operation a universe was created for.
32#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniverseInfo<'tcx> {
    #[inline]
    fn clone(&self) -> UniverseInfo<'tcx> {
        match self {
            UniverseInfo::RelateTys { expected: __self_0, found: __self_1 } =>
                UniverseInfo::RelateTys {
                    expected: ::core::clone::Clone::clone(__self_0),
                    found: ::core::clone::Clone::clone(__self_1),
                },
            UniverseInfo::TypeOp(__self_0) =>
                UniverseInfo::TypeOp(::core::clone::Clone::clone(__self_0)),
            UniverseInfo::Other => UniverseInfo::Other,
        }
    }
}Clone)]
33pub(crate) enum UniverseInfo<'tcx> {
34    /// Relating two types which have binders.
35    RelateTys { expected: Ty<'tcx>, found: Ty<'tcx> },
36    /// Created from performing a `TypeOp`.
37    TypeOp(Rc<dyn TypeOpInfo<'tcx> + 'tcx>),
38    /// Any other reason.
39    Other,
40}
41
42impl<'tcx> UniverseInfo<'tcx> {
43    pub(crate) fn other() -> UniverseInfo<'tcx> {
44        UniverseInfo::Other
45    }
46
47    pub(crate) fn relate(expected: Ty<'tcx>, found: Ty<'tcx>) -> UniverseInfo<'tcx> {
48        UniverseInfo::RelateTys { expected, found }
49    }
50
51    /// Report an error where an element erroneously made its way into `placeholder`.
52    pub(crate) fn report_erroneous_element(
53        &self,
54        mbcx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
55        placeholder: ty::PlaceholderRegion<'tcx>,
56        error_element: Option<ty::PlaceholderRegion<'tcx>>,
57        cause: ObligationCause<'tcx>,
58    ) {
59        match *self {
60            UniverseInfo::RelateTys { expected, found } => {
61                let err = mbcx.infcx.err_ctxt().report_mismatched_types(
62                    &cause,
63                    mbcx.infcx.param_env,
64                    expected,
65                    found,
66                    TypeError::RegionsPlaceholderMismatch,
67                );
68                mbcx.buffer_error(err);
69            }
70            UniverseInfo::TypeOp(ref type_op_info) => {
71                type_op_info.report_erroneous_element(mbcx, placeholder, error_element, cause);
72            }
73            UniverseInfo::Other => {
74                // FIXME: This error message isn't great, but it doesn't show
75                // up in the existing UI tests. Consider investigating this
76                // some more.
77                mbcx.buffer_error(
78                    mbcx.dcx().create_err(HigherRankedSubtypeError { span: cause.span }),
79                );
80            }
81        }
82    }
83}
84
85pub(crate) trait ToUniverseInfo<'tcx> {
86    fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx>;
87}
88
89impl<'tcx> ToUniverseInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
90    fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
91        UniverseInfo::TypeOp(Rc::new(crate::type_check::InstantiateOpaqueType {
92            base_universe: Some(base_universe),
93            ..self
94        }))
95    }
96}
97
98impl<'tcx> ToUniverseInfo<'tcx> for CanonicalTypeOpProvePredicateGoal<'tcx> {
99    fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
100        UniverseInfo::TypeOp(Rc::new(PredicateQuery { canonical_query: self, base_universe }))
101    }
102}
103
104impl<'tcx, T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx> ToUniverseInfo<'tcx>
105    for CanonicalTypeOpNormalizeGoal<'tcx, T>
106{
107    fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
108        UniverseInfo::TypeOp(Rc::new(NormalizeQuery { canonical_query: self, base_universe }))
109    }
110}
111
112impl<'tcx> ToUniverseInfo<'tcx> for CanonicalTypeOpAscribeUserTypeGoal<'tcx> {
113    fn to_universe_info(self, base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
114        UniverseInfo::TypeOp(Rc::new(AscribeUserTypeQuery { canonical_query: self, base_universe }))
115    }
116}
117
118impl<'tcx> ToUniverseInfo<'tcx> for ! {
119    fn to_universe_info(self, _base_universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
120        self
121    }
122}
123
124#[allow(unused_lifetimes)]
125pub(crate) trait TypeOpInfo<'tcx> {
126    /// Returns an error to be reported if rerunning the type op fails to
127    /// recover the error's cause.
128    fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx>;
129
130    fn base_universe(&self) -> ty::UniverseIndex;
131
132    fn nice_error<'infcx>(
133        &self,
134        mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
135        cause: ObligationCause<'tcx>,
136        placeholder_region: ty::Region<'tcx>,
137        error_region: Option<ty::Region<'tcx>>,
138    ) -> Option<Diag<'infcx>>;
139
140    /// Constraints require that `error_element` appear in the
141    /// values of `placeholder`, but this cannot be proven to
142    /// hold. Report an error.
143    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("report_erroneous_element",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(143u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("placeholder")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("placeholder");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("error_element")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("error_element");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cause");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error_element)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = mbcx.infcx.tcx;
            let base_universe = self.base_universe();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs:153",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(153u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("base_universe")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("base_universe");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&base_universe)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let Some(adjusted_universe) =
                placeholder.universe.as_u32().checked_sub(base_universe.as_u32()) else {
                    mbcx.buffer_error(self.fallback_error(tcx, cause.span));
                    return;
                };
            let placeholder_region =
                ty::Region::new_placeholder(tcx,
                    ty::PlaceholderRegion::new(adjusted_universe.into(),
                        placeholder.bound));
            let error_region =
                error_element.and_then(|e|
                        {
                            let adjusted_universe =
                                e.universe.as_u32().checked_sub(base_universe.as_u32());
                            adjusted_universe.map(|adjusted|
                                    {
                                        ty::Region::new_placeholder(tcx,
                                            ty::PlaceholderRegion::new(adjusted.into(), e.bound))
                                    })
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs:179",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(179u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("placeholder_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("placeholder_region");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder_region)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let span = cause.span;
            let nice_error =
                self.nice_error(mbcx, cause, placeholder_region,
                    error_region);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs:184",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(184u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("nice_error")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("nice_error");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&nice_error)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            mbcx.buffer_error(nice_error.unwrap_or_else(||
                        self.fallback_error(tcx, span)));
        }
    }
}#[instrument(level = "debug", skip(self, mbcx))]
144    fn report_erroneous_element(
145        &self,
146        mbcx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
147        placeholder: ty::PlaceholderRegion<'tcx>,
148        error_element: Option<ty::PlaceholderRegion<'tcx>>,
149        cause: ObligationCause<'tcx>,
150    ) {
151        let tcx = mbcx.infcx.tcx;
152        let base_universe = self.base_universe();
153        debug!(?base_universe);
154
155        let Some(adjusted_universe) =
156            placeholder.universe.as_u32().checked_sub(base_universe.as_u32())
157        else {
158            mbcx.buffer_error(self.fallback_error(tcx, cause.span));
159            return;
160        };
161
162        let placeholder_region = ty::Region::new_placeholder(
163            tcx,
164            ty::PlaceholderRegion::new(adjusted_universe.into(), placeholder.bound),
165        );
166
167        // FIXME: one day this should just be error_element,
168        // and this method shouldn't do anything.
169        let error_region = error_element.and_then(|e| {
170            let adjusted_universe = e.universe.as_u32().checked_sub(base_universe.as_u32());
171            adjusted_universe.map(|adjusted| {
172                ty::Region::new_placeholder(
173                    tcx,
174                    ty::PlaceholderRegion::new(adjusted.into(), e.bound),
175                )
176            })
177        });
178
179        debug!(?placeholder_region);
180
181        let span = cause.span;
182        let nice_error = self.nice_error(mbcx, cause, placeholder_region, error_region);
183
184        debug!(?nice_error);
185        mbcx.buffer_error(nice_error.unwrap_or_else(|| self.fallback_error(tcx, span)));
186    }
187}
188
189struct PredicateQuery<'tcx> {
190    canonical_query: CanonicalTypeOpProvePredicateGoal<'tcx>,
191    base_universe: ty::UniverseIndex,
192}
193
194impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
195    fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
196        tcx.dcx().create_err(HigherRankedLifetimeError {
197            cause: Some(HigherRankedErrorCause::CouldNotProve {
198                predicate: self.canonical_query.canonical.value.value.predicate.to_string(),
199            }),
200            span,
201        })
202    }
203
204    fn base_universe(&self) -> ty::UniverseIndex {
205        self.base_universe
206    }
207
208    fn nice_error<'infcx>(
209        &self,
210        mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
211        cause: ObligationCause<'tcx>,
212        placeholder_region: ty::Region<'tcx>,
213        error_region: Option<ty::Region<'tcx>>,
214    ) -> Option<Diag<'infcx>> {
215        let (infcx, key, _) =
216            mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
217        let ocx = ObligationCtxt::new(&infcx);
218        type_op_prove_predicate_with_cause(&ocx, key, cause);
219        let diag = try_extract_error_from_fulfill_cx(
220            &ocx,
221            mbcx.mir_def_id(),
222            placeholder_region,
223            error_region,
224        )?
225        .with_dcx(mbcx.dcx());
226        Some(diag)
227    }
228}
229
230struct NormalizeQuery<'tcx, T> {
231    canonical_query: CanonicalTypeOpNormalizeGoal<'tcx, T>,
232    base_universe: ty::UniverseIndex,
233}
234
235impl<'tcx, T> TypeOpInfo<'tcx> for NormalizeQuery<'tcx, T>
236where
237    T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx,
238{
239    fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
240        tcx.dcx().create_err(HigherRankedLifetimeError {
241            cause: Some(HigherRankedErrorCause::CouldNotNormalize {
242                value: self
243                    .canonical_query
244                    .canonical
245                    .value
246                    .value
247                    .value
248                    .skip_normalization()
249                    .to_string(),
250            }),
251            span,
252        })
253    }
254
255    fn base_universe(&self) -> ty::UniverseIndex {
256        self.base_universe
257    }
258
259    fn nice_error<'infcx>(
260        &self,
261        mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
262        cause: ObligationCause<'tcx>,
263        placeholder_region: ty::Region<'tcx>,
264        error_region: Option<ty::Region<'tcx>>,
265    ) -> Option<Diag<'infcx>> {
266        let (infcx, key, _) =
267            mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
268        let ocx = ObligationCtxt::new(&infcx);
269
270        // FIXME(lqd): Unify and de-duplicate the following with the actual
271        // `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the
272        // `ObligationCause`. The normalization results are currently different between
273        // `QueryNormalizeExt::query_normalize` used in the query and `normalize` called below:
274        // the former fails to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs`
275        // test. Check after #85499 lands to see if its fixes have erased this difference.
276        let ty::ParamEnvAnd { param_env, value } = key;
277        let _ = ocx.normalize(&cause, param_env, value.value);
278
279        let diag = try_extract_error_from_fulfill_cx(
280            &ocx,
281            mbcx.mir_def_id(),
282            placeholder_region,
283            error_region,
284        )?
285        .with_dcx(mbcx.dcx());
286        Some(diag)
287    }
288}
289
290struct AscribeUserTypeQuery<'tcx> {
291    canonical_query: CanonicalTypeOpAscribeUserTypeGoal<'tcx>,
292    base_universe: ty::UniverseIndex,
293}
294
295impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
296    fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
297        // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
298        // and is only the fallback when the nice error fails. Consider improving this some more.
299        tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
300    }
301
302    fn base_universe(&self) -> ty::UniverseIndex {
303        self.base_universe
304    }
305
306    fn nice_error<'infcx>(
307        &self,
308        mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
309        cause: ObligationCause<'tcx>,
310        placeholder_region: ty::Region<'tcx>,
311        error_region: Option<ty::Region<'tcx>>,
312    ) -> Option<Diag<'infcx>> {
313        let (infcx, key, _) =
314            mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
315        let ocx = ObligationCtxt::new(&infcx);
316        type_op_ascribe_user_type_with_span(&ocx, key, cause.span).ok()?;
317        let diag = try_extract_error_from_fulfill_cx(
318            &ocx,
319            mbcx.mir_def_id(),
320            placeholder_region,
321            error_region,
322        )?
323        .with_dcx(mbcx.dcx());
324        Some(diag)
325    }
326}
327
328impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
329    fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> Diag<'tcx> {
330        // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
331        // and is only the fallback when the nice error fails. Consider improving this some more.
332        tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
333    }
334
335    fn base_universe(&self) -> ty::UniverseIndex {
336        self.base_universe.unwrap()
337    }
338
339    fn nice_error<'infcx>(
340        &self,
341        mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
342        _cause: ObligationCause<'tcx>,
343        placeholder_region: ty::Region<'tcx>,
344        error_region: Option<ty::Region<'tcx>>,
345    ) -> Option<Diag<'infcx>> {
346        try_extract_error_from_region_constraints(
347            mbcx.infcx,
348            mbcx.mir_def_id(),
349            placeholder_region,
350            error_region,
351            self.region_constraints.as_ref().unwrap(),
352            // We're using the original `InferCtxt` that we
353            // started MIR borrowchecking with, so the region
354            // constraints have already been taken. Use the data from
355            // our `mbcx` instead.
356            |vid| RegionVariableOrigin::Nll(mbcx.regioncx.definitions[vid].origin),
357            |vid| mbcx.regioncx.definitions[vid].universe,
358        )
359    }
360}
361
362#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("try_extract_error_from_fulfill_cx",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(362u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::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("placeholder_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("placeholder_region");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("error_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("error_region");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_param_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder_region)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error_region)
                                                            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: Option<Diag<'a>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let _errors = ocx.evaluate_obligations_error_on_ambiguity();
            let region_constraints =
                ocx.infcx.with_region_constraints(|r| r.clone());
            try_extract_error_from_region_constraints(ocx.infcx,
                generic_param_scope, placeholder_region, error_region,
                &region_constraints, |vid| ocx.infcx.region_var_origin(vid),
                |vid|
                    ocx.infcx.universe_of_region(ty::Region::new_var(ocx.infcx.tcx,
                            vid)))
        }
    }
}#[instrument(skip(ocx), level = "debug")]
363fn try_extract_error_from_fulfill_cx<'a, 'tcx>(
364    ocx: &ObligationCtxt<'a, 'tcx>,
365    generic_param_scope: LocalDefId,
366    placeholder_region: ty::Region<'tcx>,
367    error_region: Option<ty::Region<'tcx>>,
368) -> Option<Diag<'a>> {
369    // We generally shouldn't have errors here because the query was
370    // already run, but there's no point using `span_delayed_bug`
371    // when we're going to emit an error here anyway.
372    let _errors = ocx.evaluate_obligations_error_on_ambiguity();
373    let region_constraints = ocx.infcx.with_region_constraints(|r| r.clone());
374    try_extract_error_from_region_constraints(
375        ocx.infcx,
376        generic_param_scope,
377        placeholder_region,
378        error_region,
379        &region_constraints,
380        |vid| ocx.infcx.region_var_origin(vid),
381        |vid| ocx.infcx.universe_of_region(ty::Region::new_var(ocx.infcx.tcx, vid)),
382    )
383}
384
385#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("try_extract_error_from_region_constraints",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(385u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::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("placeholder_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("placeholder_region");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("error_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("error_region");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("region_constraints")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_constraints");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_param_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&placeholder_region)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error_region)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_constraints)
                                                            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: Option<Diag<'a>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let placeholder_universe =
                match placeholder_region.kind() {
                    ty::RePlaceholder(p) => p.universe,
                    ty::ReVar(vid) => universe_of_region(vid),
                    _ => ty::UniverseIndex::ROOT,
                };
            let regions_the_same =
                |a_region: Region<'tcx>, b_region: Region<'tcx>|
                    match (a_region.kind(), b_region.kind()) {
                        (RePlaceholder(a_p), RePlaceholder(b_p)) =>
                            a_p.bound == b_p.bound,
                        _ => a_region == b_region,
                    };
            let mut check =
                |c: Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact|
                    match c.kind {
                        ConstraintKind::RegSubReg if
                            ((exact && c.sup == placeholder_region) ||
                                        (!exact && regions_the_same(c.sup, placeholder_region))) &&
                                c.sup != c.sub => {
                            Some((c.sub, cause.clone()))
                        }
                        ConstraintKind::VarSubReg if
                            (exact && c.sup == placeholder_region &&
                                        !universe_of_region(c.sub.as_var()).can_name(placeholder_universe))
                                || (!exact && regions_the_same(c.sup, placeholder_region))
                            => {
                            Some((c.sub, cause.clone()))
                        }
                        ConstraintKind::VarSubVar | ConstraintKind::RegSubVar |
                            ConstraintKind::VarSubReg | ConstraintKind::RegSubReg =>
                            None,
                        ConstraintKind::VarEqVar | ConstraintKind::VarEqReg |
                            ConstraintKind::RegEqReg => {
                            ::core::panicking::panic("internal error: entered unreachable code")
                        }
                    };
            let mut find_culprit =
                |exact_match: bool|
                    {
                        region_constraints.constraints.iter().flat_map(|(constraint,
                                        cause)|
                                    {
                                        constraint.iter_outlives().map(move |constraint|
                                                (constraint, cause))
                                    }).find_map(|(constraint, cause)|
                                check(constraint, cause, exact_match))
                    };
            let (sub_region, cause) =
                find_culprit(true).or_else(|| find_culprit(false))?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs:444",
                                    "rustc_borrowck::diagnostics::bound_region_errors",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs"),
                                    ::tracing_core::__macro_support::Option::Some(444u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::diagnostics::bound_region_errors"),
                                    ::tracing_core::field::FieldSet::new(&["message",
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sub_region")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sub_region");
                                                        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!("cause = {0:#?}",
                                                                cause) as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub_region)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let error =
                match (error_region, sub_region.kind()) {
                    (Some(error_region), ty::ReVar(vid)) =>
                        RegionResolutionError::SubSupConflict(vid,
                            region_var_origin(vid), cause.clone(), error_region,
                            cause.clone(), placeholder_region,
                            ::alloc::vec::Vec::new()),
                    (Some(error_region), _) => {
                        RegionResolutionError::ConcreteFailure(cause.clone(),
                            error_region, placeholder_region)
                    }
                    (None, ty::ReVar(vid)) =>
                        RegionResolutionError::UpperBoundUniverseConflict(vid,
                            region_var_origin(vid), universe_of_region(vid),
                            cause.clone(), placeholder_region),
                    (None, _) => {
                        RegionResolutionError::ConcreteFailure(cause.clone(),
                            sub_region, placeholder_region)
                    }
                };
            NiceRegionError::new(&infcx.err_ctxt(), generic_param_scope,
                        error).try_report_from_nll().or_else(||
                    {
                        if let SubregionOrigin::Subtype(trace) = cause {
                            Some(infcx.err_ctxt().report_and_explain_type_error(*trace,
                                    infcx.tcx.param_env(generic_param_scope),
                                    TypeError::RegionsPlaceholderMismatch))
                        } else { None }
                    })
        }
    }
}#[instrument(level = "debug", skip(infcx, region_var_origin, universe_of_region))]
386fn try_extract_error_from_region_constraints<'a, 'tcx>(
387    infcx: &'a InferCtxt<'tcx>,
388    generic_param_scope: LocalDefId,
389    placeholder_region: ty::Region<'tcx>,
390    error_region: Option<ty::Region<'tcx>>,
391    region_constraints: &RegionConstraintData<'tcx>,
392    mut region_var_origin: impl FnMut(RegionVid) -> RegionVariableOrigin<'tcx>,
393    mut universe_of_region: impl FnMut(RegionVid) -> UniverseIndex,
394) -> Option<Diag<'a>> {
395    let placeholder_universe = match placeholder_region.kind() {
396        ty::RePlaceholder(p) => p.universe,
397        ty::ReVar(vid) => universe_of_region(vid),
398        _ => ty::UniverseIndex::ROOT,
399    };
400    // Are the two regions the same?
401    let regions_the_same =
402        |a_region: Region<'tcx>, b_region: Region<'tcx>| match (a_region.kind(), b_region.kind()) {
403            (RePlaceholder(a_p), RePlaceholder(b_p)) => a_p.bound == b_p.bound,
404            _ => a_region == b_region,
405        };
406    let mut check = |c: Constraint<'tcx>, cause: &SubregionOrigin<'tcx>, exact| match c.kind {
407        ConstraintKind::RegSubReg
408            if ((exact && c.sup == placeholder_region)
409                || (!exact && regions_the_same(c.sup, placeholder_region)))
410                && c.sup != c.sub =>
411        {
412            Some((c.sub, cause.clone()))
413        }
414        ConstraintKind::VarSubReg
415            if (exact
416                && c.sup == placeholder_region
417                && !universe_of_region(c.sub.as_var()).can_name(placeholder_universe))
418                || (!exact && regions_the_same(c.sup, placeholder_region)) =>
419        {
420            Some((c.sub, cause.clone()))
421        }
422        ConstraintKind::VarSubVar
423        | ConstraintKind::RegSubVar
424        | ConstraintKind::VarSubReg
425        | ConstraintKind::RegSubReg => None,
426
427        ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => {
428            unreachable!()
429        }
430    };
431
432    let mut find_culprit = |exact_match: bool| {
433        region_constraints
434            .constraints
435            .iter()
436            .flat_map(|(constraint, cause)| {
437                constraint.iter_outlives().map(move |constraint| (constraint, cause))
438            })
439            .find_map(|(constraint, cause)| check(constraint, cause, exact_match))
440    };
441
442    let (sub_region, cause) = find_culprit(true).or_else(|| find_culprit(false))?;
443
444    debug!(?sub_region, "cause = {:#?}", cause);
445    let error = match (error_region, sub_region.kind()) {
446        (Some(error_region), ty::ReVar(vid)) => RegionResolutionError::SubSupConflict(
447            vid,
448            region_var_origin(vid),
449            cause.clone(),
450            error_region,
451            cause.clone(),
452            placeholder_region,
453            vec![],
454        ),
455        (Some(error_region), _) => {
456            RegionResolutionError::ConcreteFailure(cause.clone(), error_region, placeholder_region)
457        }
458        // Note universe here is wrong...
459        (None, ty::ReVar(vid)) => RegionResolutionError::UpperBoundUniverseConflict(
460            vid,
461            region_var_origin(vid),
462            universe_of_region(vid),
463            cause.clone(),
464            placeholder_region,
465        ),
466        (None, _) => {
467            RegionResolutionError::ConcreteFailure(cause.clone(), sub_region, placeholder_region)
468        }
469    };
470    NiceRegionError::new(&infcx.err_ctxt(), generic_param_scope, error)
471        .try_report_from_nll()
472        .or_else(|| {
473            if let SubregionOrigin::Subtype(trace) = cause {
474                Some(infcx.err_ctxt().report_and_explain_type_error(
475                    *trace,
476                    infcx.tcx.param_env(generic_param_scope),
477                    TypeError::RegionsPlaceholderMismatch,
478                ))
479            } else {
480                None
481            }
482        })
483}