Skip to main content

rustc_borrowck/type_check/
free_region_relations.rs

1use rustc_data_structures::frozen::Frozen;
2use rustc_data_structures::transitive_relation::{TransitiveRelation, TransitiveRelationBuilder};
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::LocalDefId;
5use rustc_infer::infer::canonical::{OriginalQueryValues, QueryRegionConstraints};
6use rustc_infer::infer::outlives::env::RegionBoundPairs;
7use rustc_infer::infer::region_constraints::GenericKind;
8use rustc_infer::infer::{InferOk, outlives};
9use rustc_infer::traits::ObligationCause;
10use rustc_infer::traits::query::MirBorrowckImpliedOutlivesBounds;
11use rustc_infer::traits::query::type_op::Normalize;
12use rustc_middle::mir::ConstraintCategory;
13use rustc_middle::traits::query::OutlivesBound;
14use rustc_middle::ty::{self, RegionVid, Ty, TypeVisitableExt};
15use rustc_span::{ErrorGuaranteed, Span};
16use rustc_trait_selection::solve::NoSolution;
17use rustc_trait_selection::traits::query::type_op;
18use tracing::{debug, instrument};
19use type_op::TypeOpOutput;
20
21use crate::BorrowckInferCtxt;
22use crate::implied_bounds::implied_bounds_query_var_values;
23use crate::type_check::{Locations, MirTypeckRegionConstraints, constraint_conversion};
24use crate::universal_regions::UniversalRegions;
25
26#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UniversalRegionRelations<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "UniversalRegionRelations", "universal_regions",
            &self.universal_regions, "outlives", &self.outlives,
            "inverse_outlives", &&self.inverse_outlives)
    }
}Debug)]
27#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniversalRegionRelations<'tcx> {
    #[inline]
    fn clone(&self) -> UniversalRegionRelations<'tcx> {
        UniversalRegionRelations {
            universal_regions: ::core::clone::Clone::clone(&self.universal_regions),
            outlives: ::core::clone::Clone::clone(&self.outlives),
            inverse_outlives: ::core::clone::Clone::clone(&self.inverse_outlives),
        }
    }
}Clone)] // FIXME(#146079)
28pub(crate) struct UniversalRegionRelations<'tcx> {
29    pub(crate) universal_regions: UniversalRegions<'tcx>,
30
31    /// Stores the outlives relations that are known to hold from the
32    /// implied bounds, in-scope where-clauses, and that sort of
33    /// thing.
34    pub(crate) outlives: TransitiveRelation<RegionVid>,
35
36    /// This is the `<=` relation; that is, if `a: b`, then `b <= a`,
37    /// and we store that here. This is useful when figuring out how
38    /// to express some local region in terms of external regions our
39    /// caller will understand.
40    inverse_outlives: TransitiveRelation<RegionVid>,
41}
42
43/// As part of computing the free region relations, we also have to
44/// normalize the input-output types, which we then need later. So we
45/// return those. This vector consists of first the input types and
46/// then the output type as the last element.
47type NormalizedInputsAndOutput<'tcx> = Vec<Ty<'tcx>>;
48
49pub(crate) struct CreateResult<'tcx> {
50    pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
51    pub(crate) region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
52    pub(crate) known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesClause<'tcx>>>,
53    pub(crate) normalized_inputs_and_output: NormalizedInputsAndOutput<'tcx>,
54}
55
56pub(crate) fn create<'tcx>(
57    infcx: &BorrowckInferCtxt<'tcx>,
58    universal_regions: UniversalRegions<'tcx>,
59    constraints: &mut MirTypeckRegionConstraints<'tcx>,
60) -> CreateResult<'tcx> {
61    UniversalRegionRelationsBuilder {
62        infcx,
63        constraints,
64        universal_regions,
65        region_bound_pairs: Default::default(),
66        outlives: Default::default(),
67        inverse_outlives: Default::default(),
68    }
69    .create()
70}
71
72impl UniversalRegionRelations<'_> {
73    /// Given two universal regions, returns the postdominating
74    /// upper-bound (effectively the least upper bound).
75    ///
76    /// (See `TransitiveRelation::postdom_upper_bound` for details on
77    /// the postdominating upper bound in general.)
78    pub(crate) fn postdom_upper_bound(&self, fr1: RegionVid, fr2: RegionVid) -> RegionVid {
79        if !self.universal_regions.is_universal_region(fr1) {
    ::core::panicking::panic("assertion failed: self.universal_regions.is_universal_region(fr1)")
};assert!(self.universal_regions.is_universal_region(fr1));
80        if !self.universal_regions.is_universal_region(fr2) {
    ::core::panicking::panic("assertion failed: self.universal_regions.is_universal_region(fr2)")
};assert!(self.universal_regions.is_universal_region(fr2));
81        self.inverse_outlives
82            .postdom_upper_bound(fr1, fr2)
83            .unwrap_or(self.universal_regions.fr_static)
84    }
85
86    /// Finds an "upper bound" for `fr` that is not local. In other
87    /// words, returns the smallest (*) known region `fr1` that (a)
88    /// outlives `fr` and (b) is not local.
89    ///
90    /// (*) If there are multiple competing choices, we return all of them.
91    pub(crate) fn non_local_upper_bounds(&self, fr: RegionVid) -> Vec<RegionVid> {
92        {
    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/type_check/free_region_relations.rs:92",
                        "rustc_borrowck::type_check::free_region_relations",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                        ::tracing_core::__macro_support::Option::Some(92u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                        ::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!("non_local_upper_bound(fr={0:?})",
                                                    fr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("non_local_upper_bound(fr={:?})", fr);
93        let res = self.non_local_bounds(&self.inverse_outlives, fr);
94        if !!res.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("can\'t find an upper bound!?"));
    }
};assert!(!res.is_empty(), "can't find an upper bound!?");
95        res
96    }
97
98    /// Finds a "lower bound" for `fr` that is not local. In other
99    /// words, returns the largest (*) known region `fr1` that (a) is
100    /// outlived by `fr` and (b) is not local.
101    ///
102    /// (*) If there are multiple competing choices, we return all of them.
103    pub(crate) fn non_local_lower_bounds(&self, fr: RegionVid) -> Vec<RegionVid> {
104        {
    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/type_check/free_region_relations.rs:104",
                        "rustc_borrowck::type_check::free_region_relations",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                        ::tracing_core::__macro_support::Option::Some(104u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                        ::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!("non_local_lower_bound(fr={0:?})",
                                                    fr) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("non_local_lower_bound(fr={:?})", fr);
105        self.non_local_bounds(&self.outlives, fr)
106    }
107
108    /// Helper for `non_local_upper_bounds` and `non_local_lower_bounds`.
109    /// Repeatedly invokes `postdom_parent` until we find something that is not
110    /// local. Returns `None` if we never do so.
111    fn non_local_bounds(
112        &self,
113        relation: &TransitiveRelation<RegionVid>,
114        fr0: RegionVid,
115    ) -> Vec<RegionVid> {
116        // This method assumes that `fr0` is one of the universally
117        // quantified region variables.
118        if !self.universal_regions.is_universal_region(fr0) {
    ::core::panicking::panic("assertion failed: self.universal_regions.is_universal_region(fr0)")
};assert!(self.universal_regions.is_universal_region(fr0));
119
120        let mut external_parents = ::alloc::vec::Vec::new()vec![];
121
122        let mut queue = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [relation.minimal_scc_representative(fr0)]))vec![relation.minimal_scc_representative(fr0)];
123
124        // Keep expanding `fr` into its parents until we reach
125        // non-local regions.
126        while let Some(fr) = queue.pop() {
127            if !self.universal_regions.is_local_free_region(fr) {
128                external_parents.push(fr);
129                continue;
130            }
131
132            queue.extend(relation.parents(fr));
133        }
134
135        {
    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/type_check/free_region_relations.rs:135",
                        "rustc_borrowck::type_check::free_region_relations",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                        ::tracing_core::__macro_support::Option::Some(135u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                        ::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!("non_local_bound: external_parents={0:?}",
                                                    external_parents) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("non_local_bound: external_parents={:?}", external_parents);
136
137        external_parents
138    }
139
140    /// Returns `true` if fr1 is known to outlive fr2.
141    ///
142    /// This will only ever be true for universally quantified regions.
143    pub(crate) fn outlives(&self, fr1: RegionVid, fr2: RegionVid) -> bool {
144        self.outlives.contains(fr1, fr2)
145    }
146
147    /// Returns `true` if fr1 is known to equal fr2.
148    ///
149    /// This will only ever be true for universally quantified regions.
150    pub(crate) fn equal(&self, fr1: RegionVid, fr2: RegionVid) -> bool {
151        self.outlives.contains(fr1, fr2) && self.outlives.contains(fr2, fr1)
152    }
153
154    /// Returns a vector of free regions `x` such that `fr1: x` is
155    /// known to hold.
156    pub(crate) fn regions_outlived_by(&self, fr1: RegionVid) -> Vec<RegionVid> {
157        self.outlives.reachable_from(fr1)
158    }
159
160    /// Returns the _non-transitive_ set of known `outlives` constraints between free regions.
161    pub(crate) fn known_outlives(&self) -> impl Iterator<Item = (RegionVid, RegionVid)> {
162        self.outlives.base_edges()
163    }
164}
165
166struct UniversalRegionRelationsBuilder<'a, 'tcx> {
167    infcx: &'a BorrowckInferCtxt<'tcx>,
168    universal_regions: UniversalRegions<'tcx>,
169    constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
170
171    // outputs:
172    outlives: TransitiveRelationBuilder<RegionVid>,
173    inverse_outlives: TransitiveRelationBuilder<RegionVid>,
174    region_bound_pairs: RegionBoundPairs<'tcx>,
175}
176
177impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
178    /// Records in the `outlives_relation` (and
179    /// `inverse_outlives_relation`) that `fr_a: fr_b`.
180    fn relate_universal_regions(&mut self, fr_a: RegionVid, fr_b: RegionVid) {
181        {
    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/type_check/free_region_relations.rs:181",
                        "rustc_borrowck::type_check::free_region_relations",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                        ::tracing_core::__macro_support::Option::Some(181u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                        ::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!("relate_universal_regions: fr_a={0:?} outlives fr_b={1:?}",
                                                    fr_a, fr_b) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("relate_universal_regions: fr_a={:?} outlives fr_b={:?}", fr_a, fr_b);
182        self.outlives.add(fr_a, fr_b);
183        self.inverse_outlives.add(fr_b, fr_a);
184    }
185
186    // FIXME(#160491): Remove this once the new implied bounds impl is through FCP.
187    #[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("create_old",
                                    "rustc_borrowck::type_check::free_region_relations",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                    ::tracing_core::__macro_support::Option::Some(187u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: CreateResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.infcx.tcx;
            let defining_ty_def_id =
                self.universal_regions.defining_ty.def_id().expect_local();
            let span = tcx.def_span(defining_ty_def_id);
            let param_env = self.infcx.param_env;
            self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
            let fr_static = self.universal_regions.fr_static;
            let fr_fn_body = self.universal_regions.fr_fn_body;
            for fr in self.universal_regions.universal_regions_iter() {
                {
                    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/type_check/free_region_relations.rs:205",
                                        "rustc_borrowck::type_check::free_region_relations",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                        ::tracing_core::__macro_support::Option::Some(205u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                        ::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!("build: relating free region {0:?} to itself and to \'static",
                                                                    fr) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                self.relate_universal_regions(fr, fr);
                self.relate_universal_regions(fr_static, fr);
                self.relate_universal_regions(fr, fr_fn_body);
            }
            let mut constraints = ::alloc::vec::Vec::new();
            let mut known_type_outlives_obligations =
                ::alloc::vec::Vec::new();
            for bound in param_env.caller_bounds() {
                if let Some(outlives) = bound.as_type_outlives_clause() {
                    known_type_outlives_obligations.push(outlives);
                };
            }
            let unnormalized_input_output_tys =
                self.universal_regions.unnormalized_input_tys.iter().cloned().chain(Some(self.universal_regions.unnormalized_output_ty));
            let mut normalized_inputs_and_output =
                Vec::with_capacity(self.universal_regions.unnormalized_input_tys.len()
                        + 1);
            for ty in unnormalized_input_output_tys {
                {
                    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/type_check/free_region_relations.rs:239",
                                        "rustc_borrowck::type_check::free_region_relations",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                        ::tracing_core::__macro_support::Option::Some(239u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                        ::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!("build: input_or_output={0:?}",
                                                                    ty) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                let constraints_unnorm = self.add_implied_bounds(ty, span);
                if let Some(c) = constraints_unnorm { constraints.push(c) }
                let TypeOpOutput {
                        output: norm_ty, constraints: constraints_normalize, .. } =
                    self.infcx.fully_perform(Normalize {
                                value: ty::Unnormalized::new_wip(ty),
                            },
                            span).unwrap_or_else(|guar|
                            TypeOpOutput {
                                output: Ty::new_error(self.infcx.tcx, guar),
                                constraints: None,
                                error_info: None,
                            });
                if let Some(c) = constraints_normalize { constraints.push(c) }
                if ty != norm_ty {
                    let constraints_norm =
                        self.add_implied_bounds(norm_ty, span);
                    if let Some(c) = constraints_norm { constraints.push(c) }
                }
                normalized_inputs_and_output.push(norm_ty);
            }
            if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(defining_ty_def_id)
                    {
                    DefKind::AssocFn | DefKind::AssocConst { .. } => true,
                    _ => false,
                } {
                for &(ty, _) in
                    tcx.assumed_wf_types(tcx.local_parent(defining_ty_def_id)) {
                    let result: Result<_, ErrorGuaranteed> =
                        self.infcx.fully_perform(Normalize {
                                value: ty::Unnormalized::new_wip(ty),
                            }, span);
                    let Ok(TypeOpOutput { output: norm_ty, constraints: c, ..
                            }) = result else { continue; };
                    constraints.extend(c);
                    let c = self.add_implied_bounds(norm_ty, span);
                    constraints.extend(c);
                }
            }
            for c in constraints {
                constraint_conversion::ConstraintConversion::new(self.infcx,
                        &self.universal_regions, &self.region_bound_pairs,
                        &known_type_outlives_obligations, Locations::All(span),
                        span, ConstraintCategory::Internal,
                        self.constraints).convert_all(c);
            }
            CreateResult {
                universal_region_relations: Frozen::freeze(UniversalRegionRelations {
                        universal_regions: self.universal_regions,
                        outlives: self.outlives.freeze(),
                        inverse_outlives: self.inverse_outlives.freeze(),
                    }),
                known_type_outlives_obligations: Frozen::freeze(known_type_outlives_obligations),
                region_bound_pairs: Frozen::freeze(self.region_bound_pairs),
                normalized_inputs_and_output,
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
188    pub(crate) fn create_old(mut self) -> CreateResult<'tcx> {
189        let tcx = self.infcx.tcx;
190        let defining_ty_def_id = self.universal_regions.defining_ty.def_id().expect_local();
191        let span = tcx.def_span(defining_ty_def_id);
192
193        // Insert the `'a: 'b` we know from the predicates.
194        // This does not consider the type-outlives.
195        let param_env = self.infcx.param_env;
196        self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
197
198        // - outlives is reflexive, so `'r: 'r` for every region `'r`
199        // - `'static: 'r` for every region `'r`
200        // - `'r: 'fn_body` for every (other) universally quantified
201        //   region `'r`, all of which are provided by our caller
202        let fr_static = self.universal_regions.fr_static;
203        let fr_fn_body = self.universal_regions.fr_fn_body;
204        for fr in self.universal_regions.universal_regions_iter() {
205            debug!("build: relating free region {:?} to itself and to 'static", fr);
206            self.relate_universal_regions(fr, fr);
207            self.relate_universal_regions(fr_static, fr);
208            self.relate_universal_regions(fr, fr_fn_body);
209        }
210
211        // Normalize the assumptions we use to borrowck the program.
212        let mut constraints = vec![];
213        let mut known_type_outlives_obligations = vec![];
214        for bound in param_env.caller_bounds() {
215            if let Some(outlives) = bound.as_type_outlives_clause() {
216                known_type_outlives_obligations.push(outlives);
217            };
218        }
219
220        let unnormalized_input_output_tys = self
221            .universal_regions
222            .unnormalized_input_tys
223            .iter()
224            .cloned()
225            .chain(Some(self.universal_regions.unnormalized_output_ty));
226
227        // For each of the input/output types:
228        // - Normalize the type. This will create some region
229        //   constraints, which we buffer up because we are
230        //   not ready to process them yet.
231        // - Then compute the implied bounds. This will adjust
232        //   the `region_bound_pairs` and so forth.
233        // - After this is done, we'll register the constraints in
234        //   the `BorrowckInferCtxt`. Checking these constraints is
235        //   handled later by actual borrow checking.
236        let mut normalized_inputs_and_output =
237            Vec::with_capacity(self.universal_regions.unnormalized_input_tys.len() + 1);
238        for ty in unnormalized_input_output_tys {
239            debug!("build: input_or_output={:?}", ty);
240            // We add implied bounds from both the unnormalized and normalized ty.
241            // See issue #87748
242            let constraints_unnorm = self.add_implied_bounds(ty, span);
243            if let Some(c) = constraints_unnorm {
244                constraints.push(c)
245            }
246            let TypeOpOutput { output: norm_ty, constraints: constraints_normalize, .. } = self
247                .infcx
248                .fully_perform(Normalize { value: ty::Unnormalized::new_wip(ty) }, span)
249                .unwrap_or_else(|guar| TypeOpOutput {
250                    output: Ty::new_error(self.infcx.tcx, guar),
251                    constraints: None,
252                    error_info: None,
253                });
254            if let Some(c) = constraints_normalize {
255                constraints.push(c)
256            }
257
258            // Currently `implied_outlives_bounds` will normalize the provided
259            // `Ty`, despite this it's still important to normalize the ty ourselves
260            // as normalization may introduce new region variables (#136547).
261            //
262            // If we do not add implied bounds for the type involving these new
263            // region variables then we'll wind up with the normalized form of
264            // the signature having not-wf types due to unsatisfied region
265            // constraints.
266            //
267            // Note: we need this in examples like
268            // ```
269            // trait Foo {
270            //   type Bar;
271            //   fn foo(&self) -> &Self::Bar;
272            // }
273            // impl Foo for () {
274            //   type Bar = ();
275            //   fn foo(&self) -> &() {}
276            // }
277            // ```
278            // Both &Self::Bar and &() are WF
279            if ty != norm_ty {
280                let constraints_norm = self.add_implied_bounds(norm_ty, span);
281                if let Some(c) = constraints_norm {
282                    constraints.push(c)
283                }
284            }
285
286            normalized_inputs_and_output.push(norm_ty);
287        }
288
289        // Add implied bounds from impl header.
290        //
291        // We don't use `assumed_wf_types` to source the entire set of implied bounds for
292        // a few reasons:
293        // - `DefiningTy` for closure has the `&'env Self` type while `assumed_wf_types` doesn't
294        // - We compute implied bounds from the unnormalized types in the `DefiningTy` but do not
295        //   do so for types in impl headers
296        // - We must compute the normalized signature and then compute implied bounds from that
297        //   in order to connect any unconstrained region vars created during normalization to
298        //   the types of the locals corresponding to the inputs and outputs of the item. (#136547)
299        if matches!(tcx.def_kind(defining_ty_def_id), DefKind::AssocFn | DefKind::AssocConst { .. })
300        {
301            for &(ty, _) in tcx.assumed_wf_types(tcx.local_parent(defining_ty_def_id)) {
302                let result: Result<_, ErrorGuaranteed> = self
303                    .infcx
304                    .fully_perform(Normalize { value: ty::Unnormalized::new_wip(ty) }, span);
305                let Ok(TypeOpOutput { output: norm_ty, constraints: c, .. }) = result else {
306                    continue;
307                };
308
309                constraints.extend(c);
310
311                // We currently add implied bounds from the normalized ty only.
312                // This is more conservative and matches wfcheck behavior.
313                let c = self.add_implied_bounds(norm_ty, span);
314                constraints.extend(c);
315            }
316        }
317
318        for c in constraints {
319            constraint_conversion::ConstraintConversion::new(
320                self.infcx,
321                &self.universal_regions,
322                &self.region_bound_pairs,
323                &known_type_outlives_obligations,
324                Locations::All(span),
325                span,
326                ConstraintCategory::Internal,
327                self.constraints,
328            )
329            .convert_all(c);
330        }
331
332        CreateResult {
333            universal_region_relations: Frozen::freeze(UniversalRegionRelations {
334                universal_regions: self.universal_regions,
335                outlives: self.outlives.freeze(),
336                inverse_outlives: self.inverse_outlives.freeze(),
337            }),
338            known_type_outlives_obligations: Frozen::freeze(known_type_outlives_obligations),
339            region_bound_pairs: Frozen::freeze(self.region_bound_pairs),
340            normalized_inputs_and_output,
341        }
342    }
343
344    #[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("create",
                                    "rustc_borrowck::type_check::free_region_relations",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                    ::tracing_core::__macro_support::Option::Some(344u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: CreateResult<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.infcx.next_trait_solver() { return self.create_old(); }
            let tcx = self.infcx.tcx;
            let body_def_id =
                self.universal_regions.defining_ty.def_id().expect_local();
            let span = tcx.def_span(body_def_id);
            let param_env = self.infcx.param_env;
            self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
            let fr_static = self.universal_regions.fr_static;
            let fr_fn_body = self.universal_regions.fr_fn_body;
            for fr in self.universal_regions.universal_regions_iter() {
                {
                    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/type_check/free_region_relations.rs:366",
                                        "rustc_borrowck::type_check::free_region_relations",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                        ::tracing_core::__macro_support::Option::Some(366u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                        ::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!("build: relating free region {0:?} to itself and to \'static",
                                                                    fr) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                self.relate_universal_regions(fr, fr);
                self.relate_universal_regions(fr_static, fr);
                self.relate_universal_regions(fr, fr_fn_body);
            }
            let mut constraints = ::alloc::vec::Vec::new();
            let mut known_type_outlives_obligations =
                ::alloc::vec::Vec::new();
            for bound in param_env.caller_bounds() {
                if let Some(outlives) = bound.as_type_outlives_clause() {
                    known_type_outlives_obligations.push(outlives);
                };
            }
            let unnormalized_input_output_tys: Vec<_> =
                self.universal_regions.unnormalized_input_tys.iter().cloned().chain(Some(self.universal_regions.unnormalized_output_ty)).collect();
            let query_normalized_inputs_and_output =
                self.compute_implied_bounds(body_def_id, span,
                    unnormalized_input_output_tys, &mut constraints);
            let mut normalized_inputs_and_output =
                Vec::with_capacity(self.universal_regions.unnormalized_input_tys.len()
                        + 1);
            for ty in query_normalized_inputs_and_output {
                let ty = ty::set_aliases_to_non_rigid(tcx, ty);
                let TypeOpOutput {
                        output: norm_ty, constraints: constraints_normalize, .. } =
                    self.infcx.fully_perform(Normalize { value: ty },
                            span).unwrap_or_else(|guar|
                            TypeOpOutput {
                                output: Ty::new_error(self.infcx.tcx, guar),
                                constraints: None,
                                error_info: None,
                            });
                if let Some(c) = constraints_normalize { constraints.push(c) }
                normalized_inputs_and_output.push(norm_ty);
            }
            for c in constraints {
                constraint_conversion::ConstraintConversion::new(self.infcx,
                        &self.universal_regions, &self.region_bound_pairs,
                        &known_type_outlives_obligations, Locations::All(span),
                        span, ConstraintCategory::Internal,
                        self.constraints).convert_all(c);
            }
            CreateResult {
                universal_region_relations: Frozen::freeze(UniversalRegionRelations {
                        universal_regions: self.universal_regions,
                        outlives: self.outlives.freeze(),
                        inverse_outlives: self.inverse_outlives.freeze(),
                    }),
                known_type_outlives_obligations: Frozen::freeze(known_type_outlives_obligations),
                region_bound_pairs: Frozen::freeze(self.region_bound_pairs),
                normalized_inputs_and_output,
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
345    pub(crate) fn create(mut self) -> CreateResult<'tcx> {
346        if !self.infcx.next_trait_solver() {
347            return self.create_old();
348        }
349
350        let tcx = self.infcx.tcx;
351        let body_def_id = self.universal_regions.defining_ty.def_id().expect_local();
352        let span = tcx.def_span(body_def_id);
353
354        // Insert the `'a: 'b` we know from the predicates.
355        // This does not consider the type-outlives.
356        let param_env = self.infcx.param_env;
357        self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
358
359        // - outlives is reflexive, so `'r: 'r` for every region `'r`
360        // - `'static: 'r` for every region `'r`
361        // - `'r: 'fn_body` for every (other) universally quantified
362        //   region `'r`, all of which are provided by our caller
363        let fr_static = self.universal_regions.fr_static;
364        let fr_fn_body = self.universal_regions.fr_fn_body;
365        for fr in self.universal_regions.universal_regions_iter() {
366            debug!("build: relating free region {:?} to itself and to 'static", fr);
367            self.relate_universal_regions(fr, fr);
368            self.relate_universal_regions(fr_static, fr);
369            self.relate_universal_regions(fr, fr_fn_body);
370        }
371
372        // Normalize the assumptions we use to borrowck the program.
373        let mut constraints = vec![];
374        let mut known_type_outlives_obligations = vec![];
375        for bound in param_env.caller_bounds() {
376            if let Some(outlives) = bound.as_type_outlives_clause() {
377                known_type_outlives_obligations.push(outlives);
378            };
379        }
380
381        let unnormalized_input_output_tys: Vec<_> = self
382            .universal_regions
383            .unnormalized_input_tys
384            .iter()
385            .cloned()
386            .chain(Some(self.universal_regions.unnormalized_output_ty))
387            .collect();
388
389        // Compute the implied bounds of the current function based on its signature.
390        let query_normalized_inputs_and_output = self.compute_implied_bounds(
391            body_def_id,
392            span,
393            unnormalized_input_output_tys,
394            &mut constraints,
395        );
396
397        // We need to renormalize the signature returned by the implied bounds query. This
398        // query normalizes the signature in a context which does not define any opaque types
399        // while this current function does actually reveal opaque types.
400        //
401        // We will later equate this signature with the type of the arguments and return local
402        // of this MIR body, so we need to normalize again.
403        //
404        // This does assume that `unnormalized_input_output_tys` would normalize to the same
405        // thing as `query_normalized_inputs_and_output`.
406        let mut normalized_inputs_and_output =
407            Vec::with_capacity(self.universal_regions.unnormalized_input_tys.len() + 1);
408        for ty in query_normalized_inputs_and_output {
409            let ty = ty::set_aliases_to_non_rigid(tcx, ty);
410            let TypeOpOutput { output: norm_ty, constraints: constraints_normalize, .. } = self
411                .infcx
412                .fully_perform(Normalize { value: ty }, span)
413                .unwrap_or_else(|guar| TypeOpOutput {
414                    output: Ty::new_error(self.infcx.tcx, guar),
415                    constraints: None,
416                    error_info: None,
417                });
418            if let Some(c) = constraints_normalize {
419                constraints.push(c)
420            }
421
422            normalized_inputs_and_output.push(norm_ty);
423        }
424
425        for c in constraints {
426            constraint_conversion::ConstraintConversion::new(
427                self.infcx,
428                &self.universal_regions,
429                &self.region_bound_pairs,
430                &known_type_outlives_obligations,
431                Locations::All(span),
432                span,
433                ConstraintCategory::Internal,
434                self.constraints,
435            )
436            .convert_all(c);
437        }
438
439        CreateResult {
440            universal_region_relations: Frozen::freeze(UniversalRegionRelations {
441                universal_regions: self.universal_regions,
442                outlives: self.outlives.freeze(),
443                inverse_outlives: self.inverse_outlives.freeze(),
444            }),
445            known_type_outlives_obligations: Frozen::freeze(known_type_outlives_obligations),
446            region_bound_pairs: Frozen::freeze(self.region_bound_pairs),
447            normalized_inputs_and_output,
448        }
449    }
450
451    /// Computes the implied bounds for the current body by using a separate query.
452    /// This is necessary as we need to make sure that all implied bounds are checked
453    /// by the user of this item.
454    ///
455    /// If we're a defining scope but can be used by caller which does not define the
456    /// same opaques, we must not get any assumptions from the hidden type of an opaque
457    /// type in our signature. We avoid this by computing implied bounds in a different
458    /// context which cannot normalize opaque types if we're in a typeck root.
459    ///
460    /// This also returns the function signature as normalized in that separate environment
461    /// which we then renormalize. This is necessary to correctly handle implied bounds
462    /// involving unconstrained regions due to #136547.
463    fn compute_implied_bounds(
464        &mut self,
465        body_def_id: LocalDefId,
466        span: Span,
467        unnormalized_inputs_and_output: Vec<Ty<'tcx>>,
468        constraints: &mut Vec<&QueryRegionConstraints<'tcx>>,
469    ) -> Vec<Ty<'tcx>> {
470        let infcx = self.infcx;
471        let tcx = infcx.tcx;
472        let var_values =
473            implied_bounds_query_var_values(tcx, &unnormalized_inputs_and_output, |region| {
474                self.universal_regions.is_external_free_region(region.as_var())
475            });
476        let original_query_values = OriginalQueryValues { var_values, ..Default::default() };
477        match tcx.mir_borrowck_implied_outlives_bounds(body_def_id) {
478            Ok(canonical_result) => {
479                // `instantiate_nll_query_response_and_region_obligations` should never fail
480                // here as all our `var_values` are unique generic parameters.
481                let mut query_constraints = QueryRegionConstraints::default();
482                let InferOk { value, obligations } = self
483                    .infcx
484                    .instantiate_nll_query_response_and_region_obligations(
485                        &ObligationCause::dummy_with_span(span),
486                        infcx.param_env,
487                        &original_query_values,
488                        canonical_result,
489                        &mut query_constraints,
490                    )
491                    .unwrap();
492                if !query_constraints.is_empty() {
493                    constraints.push(infcx.tcx.arena.alloc(query_constraints));
494                };
495
496                // `mir_borrowck_implied_outlives_bounds` for nested bodies can result in
497                // defining uses of opaques.
498                for obligation in obligations {
499                    let predicate = obligation.predicate;
500                    match infcx
501                        .fully_perform(type_op::prove_predicate::ProvePredicate { predicate }, span)
502                    {
503                        Ok(TypeOpOutput { constraints: obligation_constraints, .. }) => {
504                            if let Some(c) = obligation_constraints {
505                                constraints.push(c);
506                            }
507                        }
508                        Err(guar) => self.infcx.set_tainted_by_errors(guar),
509                    }
510                }
511
512                let MirBorrowckImpliedOutlivesBounds {
513                    outlives_bounds,
514                    normalized_inputs_and_output,
515                } = value;
516
517                // Because of #109628, we may have unexpected placeholders. Ignore them!
518                // FIXME(#109628): panic in this case once the issue is fixed.
519                let bounds = outlives_bounds.into_iter().filter(|bound| !bound.has_placeholders());
520
521                // We intentionally do not renormalize `bounds` while in the defining scope.
522                // While we must not look into opaque types for implied bounds, we must also not
523                // treat an `impl Sized + static: 'static` implied bound as a way to prove that
524                // the underlying hidden type is `'static`. Doing so would be unsound. This is
525                // not an ideal way as it results in assumptions which are unusable as aliases
526                // are incorrectly marked as rigid, but it's the easiest way to get the desired
527                // behavior.
528                //
529                // See tests/ui/traits/next-solver/opaques/implied-bounds-cyclic-reasoning.rs.
530                self.add_outlives_bounds(bounds);
531
532                normalized_inputs_and_output
533            }
534            Err(NoSolution) => {
535                self.infcx.dcx().span_delayed_bug(
536                    span,
537                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("error computing implied bounds {0:?}",
                body_def_id))
    })format!("error computing implied bounds {body_def_id:?}"),
538                );
539                unnormalized_inputs_and_output
540            }
541        }
542    }
543
544    // FIXME(#160491): Remove this once the new implied bounds impl is through FCP.
545    #[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("add_implied_bounds",
                                    "rustc_borrowck::type_check::free_region_relations",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                    ::tracing_core::__macro_support::Option::Some(545u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        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(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            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<&'tcx QueryRegionConstraints<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let TypeOpOutput { output: bounds, constraints, .. } =
                self.infcx.fully_perform(type_op::ImpliedOutlivesBounds {
                                    ty,
                                },
                                span).map_err(|_: ErrorGuaranteed|
                                {
                                    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/type_check/free_region_relations.rs:554",
                                                        "rustc_borrowck::type_check::free_region_relations",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(554u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                                        ::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!("failed to compute implied bounds {0:?}",
                                                                                    ty) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                }).ok()?;
            {
                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/type_check/free_region_relations.rs:556",
                                    "rustc_borrowck::type_check::free_region_relations",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                                    ::tracing_core::__macro_support::Option::Some(556u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("bounds")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("bounds");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constraints")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constraints");
                                                        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(&bounds)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraints)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let bounds =
                bounds.into_iter().filter(|bound| !bound.has_placeholders());
            self.add_outlives_bounds(bounds);
            constraints
        }
    }
}#[instrument(level = "debug", skip(self))]
546    fn add_implied_bounds(
547        &mut self,
548        ty: Ty<'tcx>,
549        span: Span,
550    ) -> Option<&'tcx QueryRegionConstraints<'tcx>> {
551        let TypeOpOutput { output: bounds, constraints, .. } = self
552            .infcx
553            .fully_perform(type_op::ImpliedOutlivesBounds { ty }, span)
554            .map_err(|_: ErrorGuaranteed| debug!("failed to compute implied bounds {:?}", ty))
555            .ok()?;
556        debug!(?bounds, ?constraints);
557        // Because of #109628, we may have unexpected placeholders. Ignore them!
558        // FIXME(#109628): panic in this case once the issue is fixed.
559        let bounds = bounds.into_iter().filter(|bound| !bound.has_placeholders());
560        self.add_outlives_bounds(bounds);
561        constraints
562    }
563
564    /// Registers the `OutlivesBound` items from `outlives_bounds` in
565    /// the outlives relation as well as the region-bound pairs
566    /// listing.
567    fn add_outlives_bounds<I>(&mut self, outlives_bounds: I)
568    where
569        I: IntoIterator<Item = OutlivesBound<'tcx>>,
570    {
571        for outlives_bound in outlives_bounds {
572            {
    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/type_check/free_region_relations.rs:572",
                        "rustc_borrowck::type_check::free_region_relations",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/free_region_relations.rs"),
                        ::tracing_core::__macro_support::Option::Some(572u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::free_region_relations"),
                        ::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!("add_outlives_bounds(bound={0:?})",
                                                    outlives_bound) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_outlives_bounds(bound={:?})", outlives_bound);
573
574            match outlives_bound {
575                OutlivesBound::RegionSubRegion(r1, r2) => {
576                    // The bound says that `r1 <= r2`; we store `r2: r1`.
577                    let r1 = self.universal_regions.to_region_vid(r1);
578                    let r2 = self.universal_regions.to_region_vid(r2);
579                    self.relate_universal_regions(r2, r1);
580                }
581
582                OutlivesBound::RegionSubParam(r_a, param_b) => {
583                    self.region_bound_pairs
584                        .insert(ty::OutlivesClause(GenericKind::Param(param_b), r_a));
585                }
586
587                OutlivesBound::RegionSubAlias(r_a, alias_b) => {
588                    self.region_bound_pairs
589                        .insert(ty::OutlivesClause(GenericKind::Alias(alias_b), r_a));
590                }
591            }
592        }
593    }
594}