rustc_trait_selection/traits/query/type_op/
implied_outlives_bounds.rs

1use rustc_infer::infer::canonical::CanonicalQueryInput;
2use rustc_infer::infer::resolve::OpportunisticRegionResolver;
3use rustc_infer::traits::query::OutlivesBound;
4use rustc_infer::traits::query::type_op::ImpliedOutlivesBounds;
5use rustc_middle::infer::canonical::CanonicalQueryResponse;
6use rustc_middle::traits::ObligationCause;
7use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFolder, TypeVisitableExt};
8use rustc_span::def_id::CRATE_DEF_ID;
9use rustc_span::{DUMMY_SP, Span};
10use rustc_type_ir::outlives::{Component, push_outlives_components};
11use smallvec::{SmallVec, smallvec};
12use tracing::debug;
13
14use crate::traits::query::NoSolution;
15use crate::traits::{ObligationCtxt, wf};
16
17impl<'tcx> super::QueryTypeOp<'tcx> for ImpliedOutlivesBounds<'tcx> {
18    type QueryResponse = Vec<OutlivesBound<'tcx>>;
19
20    fn try_fast_path(
21        _tcx: TyCtxt<'tcx>,
22        key: &ParamEnvAnd<'tcx, Self>,
23    ) -> Option<Self::QueryResponse> {
24        // Don't go into the query for things that can't possibly have lifetimes.
25        match key.value.ty.kind() {
26            ty::Tuple(elems) if elems.is_empty() => Some(vec![]),
27            ty::Never | ty::Str | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
28                Some(vec![])
29            }
30            _ => None,
31        }
32    }
33
34    fn perform_query(
35        tcx: TyCtxt<'tcx>,
36        canonicalized: CanonicalQueryInput<'tcx, ParamEnvAnd<'tcx, Self>>,
37    ) -> Result<CanonicalQueryResponse<'tcx, Self::QueryResponse>, NoSolution> {
38        if tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
39            tcx.implied_outlives_bounds(canonicalized)
40        } else {
41            tcx.implied_outlives_bounds_compat(canonicalized)
42        }
43    }
44
45    fn perform_locally_with_next_solver(
46        ocx: &ObligationCtxt<'_, 'tcx>,
47        key: ParamEnvAnd<'tcx, Self>,
48        span: Span,
49    ) -> Result<Self::QueryResponse, NoSolution> {
50        if ocx.infcx.tcx.sess.opts.unstable_opts.no_implied_bounds_compat {
51            compute_implied_outlives_bounds_inner(ocx, key.param_env, key.value.ty, span)
52        } else {
53            compute_implied_outlives_bounds_compat_inner(ocx, key.param_env, key.value.ty, span)
54        }
55    }
56}
57
58pub fn compute_implied_outlives_bounds_inner<'tcx>(
59    ocx: &ObligationCtxt<'_, 'tcx>,
60    param_env: ty::ParamEnv<'tcx>,
61    ty: Ty<'tcx>,
62    span: Span,
63) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
64    let normalize_op = |ty| -> Result<_, NoSolution> {
65        // We must normalize the type so we can compute the right outlives components.
66        // for example, if we have some constrained param type like `T: Trait<Out = U>`,
67        // and we know that `&'a T::Out` is WF, then we want to imply `U: 'a`.
68        let ty = ocx
69            .deeply_normalize(&ObligationCause::dummy_with_span(span), param_env, ty)
70            .map_err(|_| NoSolution)?;
71        if !ocx.select_all_or_error().is_empty() {
72            return Err(NoSolution);
73        }
74        let ty = OpportunisticRegionResolver::new(&ocx.infcx).fold_ty(ty);
75        Ok(ty)
76    };
77
78    // Sometimes when we ask what it takes for T: WF, we get back that
79    // U: WF is required; in that case, we push U onto this stack and
80    // process it next. Because the resulting predicates aren't always
81    // guaranteed to be a subset of the original type, so we need to store the
82    // WF args we've computed in a set.
83    let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
84    let mut wf_args = vec![ty.into(), normalize_op(ty)?.into()];
85
86    let mut outlives_bounds: Vec<OutlivesBound<'tcx>> = vec![];
87
88    while let Some(arg) = wf_args.pop() {
89        if !checked_wf_args.insert(arg) {
90            continue;
91        }
92
93        // From the full set of obligations, just filter down to the region relationships.
94        for obligation in
95            wf::unnormalized_obligations(ocx.infcx, param_env, arg, DUMMY_SP, CRATE_DEF_ID)
96                .into_iter()
97                .flatten()
98        {
99            assert!(!obligation.has_escaping_bound_vars());
100            let Some(pred) = obligation.predicate.kind().no_bound_vars() else {
101                continue;
102            };
103            match pred {
104                // FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound
105                // if we ever support that
106                ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
107                | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
108                | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
109                | ty::PredicateKind::Subtype(..)
110                | ty::PredicateKind::Coerce(..)
111                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
112                | ty::PredicateKind::DynCompatible(..)
113                | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
114                | ty::PredicateKind::ConstEquate(..)
115                | ty::PredicateKind::Ambiguous
116                | ty::PredicateKind::NormalizesTo(..)
117                | ty::PredicateKind::AliasRelate(..) => {}
118
119                // We need to search through *all* WellFormed predicates
120                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
121                    wf_args.push(arg);
122                }
123
124                // We need to register region relationships
125                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
126                    ty::OutlivesPredicate(r_a, r_b),
127                )) => outlives_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a)),
128
129                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
130                    ty_a,
131                    r_b,
132                ))) => {
133                    let ty_a = normalize_op(ty_a)?;
134                    let mut components = smallvec![];
135                    push_outlives_components(ocx.infcx.tcx, ty_a, &mut components);
136                    outlives_bounds.extend(implied_bounds_from_components(r_b, components))
137                }
138            }
139        }
140    }
141
142    Ok(outlives_bounds)
143}
144
145pub fn compute_implied_outlives_bounds_compat_inner<'tcx>(
146    ocx: &ObligationCtxt<'_, 'tcx>,
147    param_env: ty::ParamEnv<'tcx>,
148    ty: Ty<'tcx>,
149    span: Span,
150) -> Result<Vec<OutlivesBound<'tcx>>, NoSolution> {
151    let tcx = ocx.infcx.tcx;
152
153    // Sometimes when we ask what it takes for T: WF, we get back that
154    // U: WF is required; in that case, we push U onto this stack and
155    // process it next. Because the resulting predicates aren't always
156    // guaranteed to be a subset of the original type, so we need to store the
157    // WF args we've computed in a set.
158    let mut checked_wf_args = rustc_data_structures::fx::FxHashSet::default();
159    let mut wf_args = vec![ty.into()];
160
161    let mut outlives_bounds: Vec<ty::OutlivesPredicate<'tcx, ty::GenericArg<'tcx>>> = vec![];
162
163    while let Some(arg) = wf_args.pop() {
164        if !checked_wf_args.insert(arg) {
165            continue;
166        }
167
168        // Compute the obligations for `arg` to be well-formed. If `arg` is
169        // an unresolved inference variable, just instantiated an empty set
170        // -- because the return type here is going to be things we *add*
171        // to the environment, it's always ok for this set to be smaller
172        // than the ultimate set. (Note: normally there won't be
173        // unresolved inference variables here anyway, but there might be
174        // during typeck under some circumstances.)
175        //
176        // FIXME(@lcnr): It's not really "always fine", having fewer implied
177        // bounds can be backward incompatible, e.g. #101951 was caused by
178        // us not dealing with inference vars in `TypeOutlives` predicates.
179        let obligations =
180            wf::obligations(ocx.infcx, param_env, CRATE_DEF_ID, 0, arg, span).unwrap_or_default();
181
182        for obligation in obligations {
183            debug!(?obligation);
184            assert!(!obligation.has_escaping_bound_vars());
185
186            // While these predicates should all be implied by other parts of
187            // the program, they are still relevant as they may constrain
188            // inference variables, which is necessary to add the correct
189            // implied bounds in some cases, mostly when dealing with projections.
190            //
191            // Another important point here: we only register `Projection`
192            // predicates, since otherwise we might register outlives
193            // predicates containing inference variables, and we don't
194            // learn anything new from those.
195            if obligation.predicate.has_non_region_infer() {
196                match obligation.predicate.kind().skip_binder() {
197                    ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
198                    | ty::PredicateKind::AliasRelate(..) => {
199                        ocx.register_obligation(obligation.clone());
200                    }
201                    _ => {}
202                }
203            }
204
205            let pred = match obligation.predicate.kind().no_bound_vars() {
206                None => continue,
207                Some(pred) => pred,
208            };
209            match pred {
210                // FIXME(const_generics): Make sure that `<'a, 'b, const N: &'a &'b u32>` is sound
211                // if we ever support that
212                ty::PredicateKind::Clause(ty::ClauseKind::Trait(..))
213                | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..))
214                | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..))
215                | ty::PredicateKind::Subtype(..)
216                | ty::PredicateKind::Coerce(..)
217                | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..))
218                | ty::PredicateKind::DynCompatible(..)
219                | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
220                | ty::PredicateKind::ConstEquate(..)
221                | ty::PredicateKind::Ambiguous
222                | ty::PredicateKind::NormalizesTo(..)
223                | ty::PredicateKind::AliasRelate(..) => {}
224
225                // We need to search through *all* WellFormed predicates
226                ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
227                    wf_args.push(arg);
228                }
229
230                // We need to register region relationships
231                ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(
232                    ty::OutlivesPredicate(r_a, r_b),
233                )) => outlives_bounds.push(ty::OutlivesPredicate(r_a.into(), r_b)),
234
235                ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
236                    ty_a,
237                    r_b,
238                ))) => outlives_bounds.push(ty::OutlivesPredicate(ty_a.into(), r_b)),
239            }
240        }
241    }
242
243    // This call to `select_all_or_error` is necessary to constrain inference variables, which we
244    // use further down when computing the implied bounds.
245    match ocx.select_all_or_error().as_slice() {
246        [] => (),
247        _ => return Err(NoSolution),
248    }
249
250    // We lazily compute the outlives components as
251    // `select_all_or_error` constrains inference variables.
252    let mut implied_bounds = Vec::new();
253    for ty::OutlivesPredicate(a, r_b) in outlives_bounds {
254        match a.unpack() {
255            ty::GenericArgKind::Lifetime(r_a) => {
256                implied_bounds.push(OutlivesBound::RegionSubRegion(r_b, r_a))
257            }
258            ty::GenericArgKind::Type(ty_a) => {
259                let mut ty_a = ocx.infcx.resolve_vars_if_possible(ty_a);
260                // Need to manually normalize in the new solver as `wf::obligations` does not.
261                if ocx.infcx.next_trait_solver() {
262                    ty_a = ocx
263                        .deeply_normalize(&ObligationCause::dummy_with_span(span), param_env, ty_a)
264                        .map_err(|_| NoSolution)?;
265                }
266                let mut components = smallvec![];
267                push_outlives_components(tcx, ty_a, &mut components);
268                implied_bounds.extend(implied_bounds_from_components(r_b, components))
269            }
270            ty::GenericArgKind::Const(_) => {
271                unreachable!("consts do not participate in outlives bounds")
272            }
273        }
274    }
275
276    Ok(implied_bounds)
277}
278
279/// When we have an implied bound that `T: 'a`, we can further break
280/// this down to determine what relationships would have to hold for
281/// `T: 'a` to hold. We get to assume that the caller has validated
282/// those relationships.
283fn implied_bounds_from_components<'tcx>(
284    sub_region: ty::Region<'tcx>,
285    sup_components: SmallVec<[Component<TyCtxt<'tcx>>; 4]>,
286) -> Vec<OutlivesBound<'tcx>> {
287    sup_components
288        .into_iter()
289        .filter_map(|component| {
290            match component {
291                Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
292                Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
293                Component::Alias(p) => Some(OutlivesBound::RegionSubAlias(sub_region, p)),
294                Component::Placeholder(_p) => {
295                    // FIXME(non_lifetime_binders): Placeholders don't currently
296                    // imply anything for outlives, though they could easily.
297                    None
298                }
299                Component::EscapingAlias(_) =>
300                // If the projection has escaping regions, don't
301                // try to infer any implied bounds even for its
302                // free components. This is conservative, because
303                // the caller will still have to prove that those
304                // free components outlive `sub_region`. But the
305                // idea is that the WAY that the caller proves
306                // that may change in the future and we want to
307                // give ourselves room to get smarter here.
308                {
309                    None
310                }
311                Component::UnresolvedInferenceVariable(..) => None,
312            }
313        })
314        .collect()
315}