1 //! Provider for the `implied_outlives_bounds` query.
2 //! Do not call this query directory. See
3 //! [`rustc_trait_selection::traits::query::type_op::implied_outlives_bounds`].
6 use rustc_infer::infer::canonical::{self, Canonical};
7 use rustc_infer::infer::outlives::components::{push_outlives_components, Component};
8 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
9 use rustc_infer::traits::query::OutlivesBound;
10 use rustc_infer::traits::TraitEngineExt as _;
11 use rustc_middle::ty::query::Providers;
12 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable};
13 use rustc_span::source_map::DUMMY_SP;
14 use rustc_trait_selection::infer::InferCtxtBuilderExt;
15 use rustc_trait_selection::traits::query::{CanonicalTyGoal, Fallible, NoSolution};
16 use rustc_trait_selection::traits::wf;
17 use rustc_trait_selection::traits::FulfillmentContext;
18 use rustc_trait_selection::traits::TraitEngine;
19 use smallvec::{smallvec, SmallVec};
21 pub(crate) fn provide(p: &mut Providers) {
22 *p = Providers { implied_outlives_bounds, ..*p };
25 fn implied_outlives_bounds<'tcx>(
27 goal: CanonicalTyGoal<'tcx>,
29 &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
32 tcx.infer_ctxt().enter_canonical_trait_query(&goal, |infcx, _fulfill_cx, key| {
33 let (param_env, ty) = key.into_parts();
34 compute_implied_outlives_bounds(&infcx, param_env, ty)
38 fn compute_implied_outlives_bounds<'tcx>(
39 infcx: &InferCtxt<'_, 'tcx>,
40 param_env: ty::ParamEnv<'tcx>,
42 ) -> Fallible<Vec<OutlivesBound<'tcx>>> {
45 // Sometimes when we ask what it takes for T: WF, we get back that
46 // U: WF is required; in that case, we push U onto this stack and
47 // process it next. Because the resulting predicates aren't always
48 // guaranteed to be a subset of the original type, so we need to store the
49 // WF args we've computed in a set.
50 let mut checked_wf_args = rustc_data_structures::stable_set::FxHashSet::default();
51 let mut wf_args = vec![ty.into()];
53 let mut implied_bounds = vec![];
55 let mut fulfill_cx = FulfillmentContext::new();
57 while let Some(arg) = wf_args.pop() {
58 if !checked_wf_args.insert(arg) {
62 // Compute the obligations for `arg` to be well-formed. If `arg` is
63 // an unresolved inference variable, just substituted an empty set
64 // -- because the return type here is going to be things we *add*
65 // to the environment, it's always ok for this set to be smaller
66 // than the ultimate set. (Note: normally there won't be
67 // unresolved inference variables here anyway, but there might be
68 // during typeck under some circumstances.)
69 let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP)
72 // N.B., all of these predicates *ought* to be easily proven
73 // true. In fact, their correctness is (mostly) implied by
74 // other parts of the program. However, in #42552, we had
75 // an annoying scenario where:
77 // - Some `T::Foo` gets normalized, resulting in a
78 // variable `_1` and a `T: Trait<Foo=_1>` constraint
79 // (not sure why it couldn't immediately get
80 // solved). This result of `_1` got cached.
81 // - These obligations were dropped on the floor here,
82 // rather than being registered.
83 // - Then later we would get a request to normalize
84 // `T::Foo` which would result in `_1` being used from
85 // the cache, but hence without the `T: Trait<Foo=_1>`
86 // constraint. As a result, `_1` never gets resolved,
87 // and we get an ICE (in dropck).
89 // Therefore, we register any predicates involving
90 // inference variables. We restrict ourselves to those
91 // involving inference variables both for efficiency and
92 // to avoids duplicate errors that otherwise show up.
93 fulfill_cx.register_predicate_obligations(
95 obligations.iter().filter(|o| o.predicate.has_infer_types_or_consts()).cloned(),
98 // From the full set of obligations, just filter down to the
99 // region relationships.
100 implied_bounds.extend(obligations.into_iter().flat_map(|obligation| {
101 assert!(!obligation.has_escaping_bound_vars());
102 match obligation.predicate.kind().no_bound_vars() {
104 Some(pred) => match pred {
105 ty::PredicateKind::Trait(..)
106 | ty::PredicateKind::Subtype(..)
107 | ty::PredicateKind::Coerce(..)
108 | ty::PredicateKind::Projection(..)
109 | ty::PredicateKind::ClosureKind(..)
110 | ty::PredicateKind::ObjectSafe(..)
111 | ty::PredicateKind::ConstEvaluatable(..)
112 | ty::PredicateKind::ConstEquate(..)
113 | ty::PredicateKind::TypeWellFormedFromEnv(..) => vec![],
114 ty::PredicateKind::WellFormed(arg) => {
119 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => {
120 vec![OutlivesBound::RegionSubRegion(r_b, r_a)]
123 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => {
124 let ty_a = infcx.resolve_vars_if_possible(ty_a);
125 let mut components = smallvec![];
126 push_outlives_components(tcx, ty_a, &mut components);
127 implied_bounds_from_components(r_b, components)
134 // Ensure that those obligations that we had to solve
135 // get solved *here*.
136 match fulfill_cx.select_all_or_error(infcx).as_slice() {
137 [] => Ok(implied_bounds),
138 _ => Err(NoSolution),
142 /// When we have an implied bound that `T: 'a`, we can further break
143 /// this down to determine what relationships would have to hold for
144 /// `T: 'a` to hold. We get to assume that the caller has validated
145 /// those relationships.
146 fn implied_bounds_from_components<'tcx>(
147 sub_region: ty::Region<'tcx>,
148 sup_components: SmallVec<[Component<'tcx>; 4]>,
149 ) -> Vec<OutlivesBound<'tcx>> {
152 .filter_map(|component| {
154 Component::Region(r) => Some(OutlivesBound::RegionSubRegion(sub_region, r)),
155 Component::Param(p) => Some(OutlivesBound::RegionSubParam(sub_region, p)),
156 Component::Projection(p) => Some(OutlivesBound::RegionSubProjection(sub_region, p)),
157 Component::EscapingProjection(_) =>
158 // If the projection has escaping regions, don't
159 // try to infer any implied bounds even for its
160 // free components. This is conservative, because
161 // the caller will still have to prove that those
162 // free components outlive `sub_region`. But the
163 // idea is that the WAY that the caller proves
164 // that may change in the future and we want to
165 // give ourselves room to get smarter here.
169 Component::UnresolvedInferenceVariable(..) => None,