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