rustc_trait_selection/traits/query/type_op/
implied_outlives_bounds.rs

1use std::ops::ControlFlow;
2
3use rustc_infer::infer::RegionObligation;
4use rustc_infer::infer::canonical::CanonicalQueryInput;
5use rustc_infer::traits::query::OutlivesBound;
6use rustc_infer::traits::query::type_op::ImpliedOutlivesBounds;
7use rustc_middle::infer::canonical::CanonicalQueryResponse;
8use rustc_middle::traits::ObligationCause;
9use rustc_middle::ty::outlives::{Component, push_outlives_components};
10use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeVisitable, TypeVisitor};
11use rustc_span::def_id::CRATE_DEF_ID;
12use rustc_span::{DUMMY_SP, Span, sym};
13use smallvec::{SmallVec, smallvec};
14
15use crate::traits::query::NoSolution;
16use crate::traits::{ObligationCtxt, wf};
17
18impl<'tcx> super::QueryTypeOp<'tcx> for ImpliedOutlivesBounds<'tcx> {
19    type QueryResponse = Vec<OutlivesBound<'tcx>>;
20
21    fn try_fast_path(
22        _tcx: TyCtxt<'tcx>,
23        key: &ParamEnvAnd<'tcx, Self>,
24    ) -> Option<Self::QueryResponse> {
25        // Don't go into the query for things that can't possibly have lifetimes.
26        match key.value.ty.kind() {
27            ty::Tuple(elems) if elems.is_empty() => Some(vec![]),
28            ty::Never | ty::Str | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
29                Some(vec![])
30            }
31            _ => None,
32        }
33    }
34
35    fn perform_query(
36        tcx: TyCtxt<'tcx>,
37        canonicalized: CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>,
38    ) -> Result<CanonicalQueryResponse<'tcx, Self::QueryResponse>, NoSolution> {
39        tcx.implied_outlives_bounds((canonicalized, false))
40    }
41
42    fn perform_locally_with_next_solver(
43        ocx: &ObligationCtxt<'_, 'tcx>,
44        key: ParamEnvAnd<'tcx, Self>,
45        span: Span,
46    ) -> Result<Self::QueryResponse, NoSolution> {
47        compute_implied_outlives_bounds_inner(ocx, key.param_env, key.value.ty, span, false)
48    }
49}
50
51pub fn compute_implied_outlives_bounds_inner<'tcx>(
52    ocx: &ObligationCtxt<'_, 'tcx>,
53    param_env: ty::ParamEnv<'tcx>,
54    ty: Ty<'tcx>,
55    span: Span,
56    disable_implied_bounds_hack: bool,
57) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
58    let normalize_ty = |ty| -> Result<_, NoSolution> {
59        // We must normalize the type so we can compute the right outlives components.
60        // for example, if we have some constrained param type like `T: Trait<Out = U>`,
61        // and we know that `&'a T::Out` is WF, then we want to imply `U: 'a`.
62        let ty = ocx
63            .deeply_normalize(&ObligationCause::dummy_with_span(span), param_env, ty)
64            .map_err(|_| NoSolution)?;
65        Ok(ty)
66    };
67
68    // Sometimes when we ask what it takes for T: WF, we get back that
69    // U: WF is required; in that case, we push U onto this stack and
70    // process it next. Because the resulting predicates aren't always
71    // guaranteed to be a subset of the original type, so we need to store the
72    // WF args we've computed in a set.
73    let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
74    let mut wf_args = vec![ty.into(), normalize_ty(ty)?.into()];
75
76    let mut outlives_bounds: Vec<OutlivesBound<'tcx>> = vec![];
77
78    while let Some(arg) = wf_args.pop() {
79        if !checked_wf_args.insert(arg) {
80            continue;
81        }
82
83        // From the full set of obligations, just filter down to the region relationships.
84        for obligation in
85            wf::unnormalized_obligations(ocx.infcx, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
86                .into_iter()
87                .flatten()
88        {
89            let pred = ocx
90                .deeply_normalize(
91                    &ObligationCause::dummy_with_span(span),
92                    param_env,
93                    obligation.predicate,
94                )
95                .map_err(|_| NoSolution)?;
96            let Some(pred) = pred.kind().no_bound_vars() else {
97                continue;
98            };
99            match pred {
100                // FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound
101                // if we ever support that
102                ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
103                | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
104                | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
105                | ty::PredicateKind::Subtype(..)
106                | ty::PredicateKind::Coerce(..)
107                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
108                | ty::PredicateKind::DynCompatible(..)
109                | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
110                | ty::PredicateKind::ConstEquate(..)
111                | ty::PredicateKind::Ambiguous
112                | ty::PredicateKind::NormalizesTo(..)
113                | ty::PredicateKind::AliasRelate(..) => {}
114
115                // We need to search through *all* WellFormed predicates
116                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
117                    wf_args.push(term);
118                }
119
120                // We need to register region relationships
121                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
122                    ty::OutlivesPredicate(r_a, r_b),
123                )) => outlives_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a)),
124
125                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
126                    ty_a,
127                    r_b,
128                ))) => {
129                    let mut components = smallvec![];
130                    push_outlives_components(ocx.infcx.tcx, ty_a, &mut components);
131                    outlives_bounds.extend(implied_bounds_from_components(r_b, components))
132                }
133            }
134        }
135    }
136
137    // If we detect `bevy_ecs::*::ParamSet` in the WF args list (and `disable_implied_bounds_hack`
138    // or `-Zno-implied-bounds-compat` are not set), then use the registered outlives obligations
139    // as implied bounds.
140    if !disable_implied_bounds_hack
141        && !ocx.infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat
142        && ty.visit_with(&mut ContainsBevyParamSet { tcx: ocx.infcx.tcx }).is_break()
143    {
144        for RegionObligation { sup_type, sub_region, .. } in
145            ocx.infcx.take_registered_region_obligations()
146        {
147            let mut components = smallvec![];
148            push_outlives_components(ocx.infcx.tcx, sup_type, &mut components);
149            outlives_bounds.extend(implied_bounds_from_components(sub_region, components));
150        }
151    }
152
153    Ok(outlives_bounds)
154}
155
156struct ContainsBevyParamSet<'tcx> {
157    tcx: TyCtxt<'tcx>,
158}
159
160impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsBevyParamSet<'tcx> {
161    type Result = ControlFlow<()>;
162
163    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
164        // We only care to match `ParamSet<T>` or `&ParamSet<T>`.
165        match t.kind() {
166            ty::Adt(def, _) => {
167                if self.tcx.item_name(def.did()) == sym::ParamSet
168                    && self.tcx.crate_name(def.did().krate) == sym::bevy_ecs
169                {
170                    return ControlFlow::Break(());
171                }
172            }
173            ty::Ref(_, ty, _) => ty.visit_with(self)?,
174            _ => {}
175        }
176
177        ControlFlow::Continue(())
178    }
179}
180
181/// When we have an implied bound that `T: 'a`, we can further break
182/// this down to determine what relationships would have to hold for
183/// `T: 'a` to hold. We get to assume that the caller has validated
184/// those relationships.
185fn implied_bounds_from_components<'tcx>(
186    sub_region: ty::Region<'tcx>,
187    sup_components: SmallVec<[Component<TyCtxt<'tcx>>; 4]>,
188) -> Vec<OutlivesBound<'tcx>> {
189    sup_components
190        .into_iter()
191        .filter_map(|component| {
192            match component {
193                Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
194                Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
195                Component::Alias(p) => Some(OutlivesBound::RegionSubAlias(sub_region, p)),
196                Component::Placeholder(_p) => {
197                    // FIXME(non_lifetime_binders): Placeholders don't currently
198                    // imply anything for outlives, though they could easily.
199                    None
200                }
201                Component::EscapingAlias(_) =>
202                // If the projection has escaping regions, don't
203                // try to infer any implied bounds even for its
204                // free components. This is conservative, because
205                // the caller will still have to prove that those
206                // free components outlive `sub_region`. But the
207                // idea is that the WAY that the caller proves
208                // that may change in the future and we want to
209                // give ourselves room to get smarter here.
210                {
211                    None
212                }
213                Component::UnresolvedInferenceVariable(..) => None,
214            }
215        })
216        .collect()
217}