]> git.lizzy.rs Git - rust.git/blob - src/librustc_traits/implied_outlives_bounds.rs
Auto merge of #61300 - indygreg:upgrade-cross-make, r=sanxiyn
[rust.git] / src / librustc_traits / implied_outlives_bounds.rs
1 //! Provider for the `implied_outlives_bounds` query.
2 //! Do not call this query directory. See [`rustc::traits::query::implied_outlives_bounds`].
3
4 use rustc::hir;
5 use rustc::infer::InferCtxt;
6 use rustc::infer::canonical::{self, Canonical};
7 use rustc::traits::{TraitEngine, TraitEngineExt};
8 use rustc::traits::query::outlives_bounds::OutlivesBound;
9 use rustc::traits::query::{CanonicalTyGoal, Fallible, NoSolution};
10 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
11 use rustc::ty::outlives::Component;
12 use rustc::ty::query::Providers;
13 use rustc::ty::wf;
14 use smallvec::{SmallVec, smallvec};
15 use syntax::source_map::DUMMY_SP;
16 use rustc::traits::FulfillmentContext;
17
18 crate fn provide(p: &mut Providers<'_>) {
19     *p = Providers {
20         implied_outlives_bounds,
21         ..*p
22     };
23 }
24
25 fn implied_outlives_bounds<'tcx>(
26     tcx: TyCtxt<'_, 'tcx, 'tcx>,
27     goal: CanonicalTyGoal<'tcx>,
28 ) -> Result<
29         &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
30         NoSolution,
31 > {
32     tcx.infer_ctxt()
33        .enter_canonical_trait_query(&goal, |infcx, _fulfill_cx, key| {
34            let (param_env, ty) = key.into_parts();
35            compute_implied_outlives_bounds(&infcx, param_env, ty)
36        })
37 }
38
39 fn compute_implied_outlives_bounds<'tcx>(
40     infcx: &InferCtxt<'_, '_, 'tcx>,
41     param_env: ty::ParamEnv<'tcx>,
42     ty: Ty<'tcx>
43 ) -> Fallible<Vec<OutlivesBound<'tcx>>> {
44     let tcx = infcx.tcx;
45
46     // Sometimes when we ask what it takes for T: WF, we get back that
47     // U: WF is required; in that case, we push U onto this stack and
48     // process it next. Currently (at least) these resulting
49     // predicates are always guaranteed to be a subset of the original
50     // type, so we need not fear non-termination.
51     let mut wf_types = vec![ty];
52
53     let mut implied_bounds = vec![];
54
55     let mut fulfill_cx = FulfillmentContext::new();
56
57     while let Some(ty) = wf_types.pop() {
58         // Compute the obligations for `ty` to be well-formed. If `ty` is
59         // an unresolved inference variable, just substituted an empty set
60         // -- because the return type here is going to be things we *add*
61         // to the environment, it's always ok for this set to be smaller
62         // than the ultimate set. (Note: normally there won't be
63         // unresolved inference variables here anyway, but there might be
64         // during typeck under some circumstances.)
65         let obligations =
66             wf::obligations(infcx, param_env, hir::DUMMY_HIR_ID, ty, DUMMY_SP).unwrap_or(vec![]);
67
68         // N.B., all of these predicates *ought* to be easily proven
69         // true. In fact, their correctness is (mostly) implied by
70         // other parts of the program. However, in #42552, we had
71         // an annoying scenario where:
72         //
73         // - Some `T::Foo` gets normalized, resulting in a
74         //   variable `_1` and a `T: Trait<Foo=_1>` constraint
75         //   (not sure why it couldn't immediately get
76         //   solved). This result of `_1` got cached.
77         // - These obligations were dropped on the floor here,
78         //   rather than being registered.
79         // - Then later we would get a request to normalize
80         //   `T::Foo` which would result in `_1` being used from
81         //   the cache, but hence without the `T: Trait<Foo=_1>`
82         //   constraint. As a result, `_1` never gets resolved,
83         //   and we get an ICE (in dropck).
84         //
85         // Therefore, we register any predicates involving
86         // inference variables. We restrict ourselves to those
87         // involving inference variables both for efficiency and
88         // to avoids duplicate errors that otherwise show up.
89         fulfill_cx.register_predicate_obligations(
90             infcx,
91             obligations
92                 .iter()
93                 .filter(|o| o.predicate.has_infer_types())
94                 .cloned(),
95         );
96
97         // From the full set of obligations, just filter down to the
98         // region relationships.
99         implied_bounds.extend(obligations.into_iter().flat_map(|obligation| {
100             assert!(!obligation.has_escaping_bound_vars());
101             match obligation.predicate {
102                 ty::Predicate::Trait(..) |
103                 ty::Predicate::Subtype(..) |
104                 ty::Predicate::Projection(..) |
105                 ty::Predicate::ClosureKind(..) |
106                 ty::Predicate::ObjectSafe(..) |
107                 ty::Predicate::ConstEvaluatable(..) => vec![],
108
109                 ty::Predicate::WellFormed(subty) => {
110                     wf_types.push(subty);
111                     vec![]
112                 }
113
114                 ty::Predicate::RegionOutlives(ref data) => match data.no_bound_vars() {
115                     None => vec![],
116                     Some(ty::OutlivesPredicate(r_a, r_b)) => {
117                         vec![OutlivesBound::RegionSubRegion(r_b, r_a)]
118                     }
119                 },
120
121                 ty::Predicate::TypeOutlives(ref data) => match data.no_bound_vars() {
122                     None => vec![],
123                     Some(ty::OutlivesPredicate(ty_a, r_b)) => {
124                         let ty_a = infcx.resolve_vars_if_possible(&ty_a);
125                         let mut components = smallvec![];
126                         tcx.push_outlives_components(ty_a, &mut components);
127                         implied_bounds_from_components(r_b, components)
128                     }
129                 },
130             }
131         }));
132     }
133
134     // Ensure that those obligations that we had to solve
135     // get solved *here*.
136     match fulfill_cx.select_all_or_error(infcx) {
137         Ok(()) => Ok(implied_bounds),
138         Err(_) => Err(NoSolution),
139     }
140 }
141
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(
147     sub_region: ty::Region<'tcx>,
148     sup_components: SmallVec<[Component<'tcx>; 4]>,
149 ) -> Vec<OutlivesBound<'tcx>> {
150     sup_components
151         .into_iter()
152         .filter_map(|component| {
153             match component {
154                 Component::Region(r) =>
155                     Some(OutlivesBound::RegionSubRegion(sub_region, r)),
156                 Component::Param(p) =>
157                     Some(OutlivesBound::RegionSubParam(sub_region, p)),
158                 Component::Projection(p) =>
159                     Some(OutlivesBound::RegionSubProjection(sub_region, p)),
160                 Component::EscapingProjection(_) =>
161                 // If the projection has escaping regions, don't
162                 // try to infer any implied bounds even for its
163                 // free components. This is conservative, because
164                 // the caller will still have to prove that those
165                 // free components outlive `sub_region`. But the
166                 // idea is that the WAY that the caller proves
167                 // that may change in the future and we want to
168                 // give ourselves room to get smarter here.
169                     None,
170                 Component::UnresolvedInferenceVariable(..) =>
171                     None,
172             }
173         })
174         .collect()
175 }