Skip to main content

rustc_trait_selection/
regions.rs

1use rustc_data_structures::fx::FxIndexSet;
2use rustc_hir::def_id::LocalDefId;
3use rustc_infer::infer::outlives::env::OutlivesEnvironment;
4use rustc_infer::infer::{
5    InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt, TypeOutlivesConstraint,
6};
7use rustc_macros::extension;
8use rustc_middle::traits::ObligationCause;
9use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, elaborate};
10use rustc_span::DUMMY_SP;
11
12use crate::traits::ScrubbedTraitError;
13use crate::traits::outlives_bounds::InferCtxtExt;
14
15pub trait OutlivesEnvironmentBuildExt<'tcx> {
    fn new(infcx: &InferCtxt<'tcx>, body_def_id: LocalDefId,
    param_env: ty::ParamEnv<'tcx>,
    assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>)
    -> Self;
    fn new_with_implied_bounds_compat(infcx: &InferCtxt<'tcx>,
    body_def_id: LocalDefId, param_env: ty::ParamEnv<'tcx>,
    assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>,
    disable_implied_bounds_hack: bool)
    -> Self;
}
impl<'tcx> OutlivesEnvironmentBuildExt<'tcx> for OutlivesEnvironment<'tcx> {
    fn new(infcx: &InferCtxt<'tcx>, body_def_id: LocalDefId,
        param_env: ty::ParamEnv<'tcx>,
        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>) -> Self {
        Self::new_with_implied_bounds_compat(infcx, body_def_id, param_env,
            assumed_wf_tys, false)
    }
    fn new_with_implied_bounds_compat(infcx: &InferCtxt<'tcx>,
        body_def_id: LocalDefId, param_env: ty::ParamEnv<'tcx>,
        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>,
        disable_implied_bounds_hack: bool) -> Self {
        let mut bounds = ::alloc::vec::Vec::new();
        for bound in param_env.caller_bounds() {
            if let Some(type_outlives) = bound.as_type_outlives_clause() {
                if true {
                    if !(!infcx.next_trait_solver() ||
                                !type_outlives.has_non_rigid_aliases()) {
                        ::core::panicking::panic("assertion failed: !infcx.next_trait_solver() || !type_outlives.has_non_rigid_aliases()")
                    };
                };
                bounds.push(type_outlives);
            }
        }
        let higher_ranked_assumptions =
            infcx.take_registered_region_assumptions();
        let higher_ranked_assumptions =
            elaborate::elaborate_outlives_assumptions(infcx.tcx,
                higher_ranked_assumptions);
        OutlivesEnvironment::from_normalized_bounds(param_env, bounds,
            infcx.implied_bounds_tys(body_def_id, param_env, assumed_wf_tys,
                disable_implied_bounds_hack), higher_ranked_assumptions)
    }
}#[extension(pub trait OutlivesEnvironmentBuildExt<'tcx>)]
16impl<'tcx> OutlivesEnvironment<'tcx> {
17    fn new(
18        infcx: &InferCtxt<'tcx>,
19        body_def_id: LocalDefId,
20        param_env: ty::ParamEnv<'tcx>,
21        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>,
22    ) -> Self {
23        Self::new_with_implied_bounds_compat(infcx, body_def_id, param_env, assumed_wf_tys, false)
24    }
25
26    fn new_with_implied_bounds_compat(
27        infcx: &InferCtxt<'tcx>,
28        body_def_id: LocalDefId,
29        param_env: ty::ParamEnv<'tcx>,
30        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>,
31        disable_implied_bounds_hack: bool,
32    ) -> Self {
33        let mut bounds = vec![];
34
35        for bound in param_env.caller_bounds() {
36            if let Some(type_outlives) = bound.as_type_outlives_clause() {
37                debug_assert!(!infcx.next_trait_solver() || !type_outlives.has_non_rigid_aliases());
38                bounds.push(type_outlives);
39            }
40        }
41
42        // FIXME(-Znext-trait-solver): Normalize these.
43        let higher_ranked_assumptions = infcx.take_registered_region_assumptions();
44        let higher_ranked_assumptions =
45            elaborate::elaborate_outlives_assumptions(infcx.tcx, higher_ranked_assumptions);
46
47        // FIXME: This needs to be modified so that we normalize the known type
48        // outlives obligations then elaborate them into their region/type components.
49        // Otherwise, `<W<'a> as Mirror>::Assoc: 'b` will not imply `'a: 'b` even
50        // if we can normalize `'a`.
51        OutlivesEnvironment::from_normalized_bounds(
52            param_env,
53            bounds,
54            infcx.implied_bounds_tys(
55                body_def_id,
56                param_env,
57                assumed_wf_tys,
58                disable_implied_bounds_hack,
59            ),
60            higher_ranked_assumptions,
61        )
62    }
63}
64
65pub trait InferCtxtRegionExt<'tcx> {
    #[doc = " Resolve regions lexically."]
    #[doc = ""]
    #[doc =
    " This function assumes that all infer variables are already constrained."]
    #[doc = ""]
    #[doc =
    " FIXME(#155345): this can probably be moved back to `rustc_infer` now that normalization is"]
    #[doc =
    " no longer required. These two extension traits won\'t be needed then."]
    fn resolve_regions(&self, body_def_id: LocalDefId,
    param_env: ty::ParamEnv<'tcx>,
    assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>)
    -> Vec<RegionResolutionError<'tcx>>;
}
impl<'tcx> InferCtxtRegionExt<'tcx> for InferCtxt<'tcx> {
    #[doc = " Resolve regions lexically."]
    #[doc = ""]
    #[doc =
    " This function assumes that all infer variables are already constrained."]
    #[doc = ""]
    #[doc =
    " FIXME(#155345): this can probably be moved back to `rustc_infer` now that normalization is"]
    #[doc =
    " no longer required. These two extension traits won\'t be needed then."]
    fn resolve_regions(&self, body_def_id: LocalDefId,
        param_env: ty::ParamEnv<'tcx>,
        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>)
        -> Vec<RegionResolutionError<'tcx>> {
        self.resolve_regions_with_outlives_env(&OutlivesEnvironment::new(self,
                    body_def_id, param_env, assumed_wf_tys))
    }
}#[extension(pub trait InferCtxtRegionExt<'tcx>)]
66impl<'tcx> InferCtxt<'tcx> {
67    /// Resolve regions lexically.
68    ///
69    /// This function assumes that all infer variables are already constrained.
70    ///
71    /// FIXME(#155345): this can probably be moved back to `rustc_infer` now that normalization is
72    /// no longer required. These two extension traits won't be needed then.
73    fn resolve_regions(
74        &self,
75        body_def_id: LocalDefId,
76        param_env: ty::ParamEnv<'tcx>,
77        assumed_wf_tys: impl IntoIterator<Item = Ty<'tcx>>,
78    ) -> Vec<RegionResolutionError<'tcx>> {
79        self.resolve_regions_with_outlives_env(&OutlivesEnvironment::new(
80            self,
81            body_def_id,
82            param_env,
83            assumed_wf_tys,
84        ))
85    }
86}
87
88/// Given a known `param_env` and a set of well formed types, can we prove that
89/// `ty` outlives `region`.
90pub fn ty_known_to_outlive<'tcx>(
91    tcx: TyCtxt<'tcx>,
92    id: LocalDefId,
93    param_env: ty::ParamEnv<'tcx>,
94    wf_tys: &FxIndexSet<Ty<'tcx>>,
95    ty: Unnormalized<'tcx, Ty<'tcx>>,
96    region: ty::Region<'tcx>,
97) -> bool {
98    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
99        // Types in region obligations should be normalized.
100        let ty = if infcx.next_trait_solver() {
101            let Ok(ty) = crate::solve::deeply_normalize::<_, ScrubbedTraitError<'tcx>>(
102                infcx.at(&ObligationCause::dummy_with_span(DUMMY_SP), param_env),
103                ty,
104            ) else {
105                return Err(());
106            };
107            ty
108        } else {
109            ty.skip_norm_wip()
110        };
111
112        infcx.register_type_outlives_constraint_inner(TypeOutlivesConstraint {
113            sub_region: region,
114            sup_type: ty,
115            origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
116        });
117
118        Ok(())
119    })
120}
121
122/// Given a known `param_env` and a set of well formed types, can we prove that
123/// `region_a` outlives `region_b`
124pub fn region_known_to_outlive<'tcx>(
125    tcx: TyCtxt<'tcx>,
126    id: LocalDefId,
127    param_env: ty::ParamEnv<'tcx>,
128    wf_tys: &FxIndexSet<Ty<'tcx>>,
129    region_a: ty::Region<'tcx>,
130    region_b: ty::Region<'tcx>,
131) -> bool {
132    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
133        infcx.sub_regions(
134            SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
135            region_b,
136            region_a,
137            ty::VisibleForLeakCheck::Unreachable,
138        );
139        Ok(())
140    })
141}
142
143/// Given a known `param_env` and a set of well formed types, set up an
144/// `InferCtxt`, call the passed function (to e.g. set up region constraints
145/// to be tested), then resolve region and return errors
146pub fn test_region_obligations<'tcx>(
147    tcx: TyCtxt<'tcx>,
148    id: LocalDefId,
149    param_env: ty::ParamEnv<'tcx>,
150    wf_tys: &FxIndexSet<Ty<'tcx>>,
151    add_constraints: impl FnOnce(&InferCtxt<'tcx>) -> Result<(), ()>,
152) -> bool {
153    // Unfortunately, we have to use a new `InferCtxt` each call, because
154    // region constraints get added and solved there and we need to test each
155    // call individually.
156    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
157
158    if add_constraints(&infcx).is_err() {
159        return false;
160    }
161
162    let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
163    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/regions.rs:163",
                        "rustc_trait_selection::regions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/regions.rs"),
                        ::tracing_core::__macro_support::Option::Some(163u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::regions"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("errors")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("errors");
                                            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!("errors")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errors)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};tracing::debug!(?errors, "errors");
164
165    // If we were able to prove that the type outlives the region without
166    // an error, it must be because of the implied or explicit bounds...
167    errors.is_empty()
168}