]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_traits/src/implied_outlives_bounds.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_traits / src / implied_outlives_bounds.rs
CommitLineData
8faf50e0 1//! Provider for the `implied_outlives_bounds` query.
ba9703b0
XL
2//! Do not call this query directory. See
3//! [`rustc_trait_selection::traits::query::type_op::implied_outlives_bounds`].
8faf50e0 4
dfeec247 5use rustc_hir as hir;
74b04a01
XL
6use rustc_infer::infer::canonical::{self, Canonical};
7use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
ba9703b0
XL
8use rustc_infer::traits::TraitEngineExt as _;
9use rustc_middle::ty::outlives::Component;
10use rustc_middle::ty::query::Providers;
11use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
dfeec247 12use rustc_span::source_map::DUMMY_SP;
ba9703b0
XL
13use rustc_trait_selection::infer::InferCtxtBuilderExt;
14use rustc_trait_selection::traits::query::outlives_bounds::OutlivesBound;
15use rustc_trait_selection::traits::query::{CanonicalTyGoal, Fallible, NoSolution};
16use rustc_trait_selection::traits::wf;
17use rustc_trait_selection::traits::FulfillmentContext;
18use rustc_trait_selection::traits::TraitEngine;
dfeec247 19use smallvec::{smallvec, SmallVec};
8faf50e0 20
f035d41b 21crate fn provide(p: &mut Providers) {
dfeec247 22 *p = Providers { implied_outlives_bounds, ..*p };
8faf50e0
XL
23}
24
25fn implied_outlives_bounds<'tcx>(
dc9dc135 26 tcx: TyCtxt<'tcx>,
8faf50e0
XL
27 goal: CanonicalTyGoal<'tcx>,
28) -> Result<
dc9dc135
XL
29 &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
30 NoSolution,
8faf50e0 31> {
dfeec247
XL
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)
35 })
8faf50e0
XL
36}
37
38fn compute_implied_outlives_bounds<'tcx>(
dc9dc135 39 infcx: &InferCtxt<'_, 'tcx>,
8faf50e0 40 param_env: ty::ParamEnv<'tcx>,
dc9dc135 41 ty: Ty<'tcx>,
8faf50e0
XL
42) -> Fallible<Vec<OutlivesBound<'tcx>>> {
43 let tcx = infcx.tcx;
44
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. Currently (at least) these resulting
48 // predicates are always guaranteed to be a subset of the original
49 // type, so we need not fear non-termination.
f035d41b 50 let mut wf_args = vec![ty.into()];
8faf50e0
XL
51
52 let mut implied_bounds = vec![];
53
54 let mut fulfill_cx = FulfillmentContext::new();
55
f035d41b
XL
56 while let Some(arg) = wf_args.pop() {
57 // Compute the obligations for `arg` to be well-formed. If `arg` is
8faf50e0
XL
58 // an unresolved inference variable, just substituted an empty set
59 // -- because the return type here is going to be things we *add*
60 // to the environment, it's always ok for this set to be smaller
61 // than the ultimate set. (Note: normally there won't be
62 // unresolved inference variables here anyway, but there might be
63 // during typeck under some circumstances.)
29967ef6
XL
64 let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP)
65 .unwrap_or_default();
8faf50e0 66
0731742a 67 // N.B., all of these predicates *ought* to be easily proven
8faf50e0
XL
68 // true. In fact, their correctness is (mostly) implied by
69 // other parts of the program. However, in #42552, we had
70 // an annoying scenario where:
71 //
72 // - Some `T::Foo` gets normalized, resulting in a
73 // variable `_1` and a `T: Trait<Foo=_1>` constraint
74 // (not sure why it couldn't immediately get
75 // solved). This result of `_1` got cached.
76 // - These obligations were dropped on the floor here,
77 // rather than being registered.
78 // - Then later we would get a request to normalize
79 // `T::Foo` which would result in `_1` being used from
80 // the cache, but hence without the `T: Trait<Foo=_1>`
81 // constraint. As a result, `_1` never gets resolved,
82 // and we get an ICE (in dropck).
83 //
84 // Therefore, we register any predicates involving
85 // inference variables. We restrict ourselves to those
86 // involving inference variables both for efficiency and
87 // to avoids duplicate errors that otherwise show up.
88 fulfill_cx.register_predicate_obligations(
89 infcx,
74b04a01 90 obligations.iter().filter(|o| o.predicate.has_infer_types_or_consts()).cloned(),
8faf50e0
XL
91 );
92
93 // From the full set of obligations, just filter down to the
94 // region relationships.
95 implied_bounds.extend(obligations.into_iter().flat_map(|obligation| {
a1dfa0c6 96 assert!(!obligation.has_escaping_bound_vars());
5869c6ff
XL
97 match obligation.predicate.kind().no_bound_vars() {
98 None => vec![],
99 Some(pred) => match pred {
100 ty::PredicateKind::Trait(..)
101 | ty::PredicateKind::Subtype(..)
94222f64 102 | ty::PredicateKind::Coerce(..)
5869c6ff
XL
103 | ty::PredicateKind::Projection(..)
104 | ty::PredicateKind::ClosureKind(..)
105 | ty::PredicateKind::ObjectSafe(..)
106 | ty::PredicateKind::ConstEvaluatable(..)
107 | ty::PredicateKind::ConstEquate(..)
108 | ty::PredicateKind::TypeWellFormedFromEnv(..) => vec![],
109 ty::PredicateKind::WellFormed(arg) => {
3dfed10e
XL
110 wf_args.push(arg);
111 vec![]
112 }
8faf50e0 113
5869c6ff 114 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(r_a, r_b)) => {
8faf50e0
XL
115 vec![OutlivesBound::RegionSubRegion(r_b, r_a)]
116 }
8faf50e0 117
5869c6ff 118 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, r_b)) => {
fc512014 119 let ty_a = infcx.resolve_vars_if_possible(ty_a);
a1dfa0c6
XL
120 let mut components = smallvec![];
121 tcx.push_outlives_components(ty_a, &mut components);
8faf50e0
XL
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.
141fn implied_bounds_from_components(
142 sub_region: ty::Region<'tcx>,
a1dfa0c6 143 sup_components: SmallVec<[Component<'tcx>; 4]>,
8faf50e0
XL
144) -> Vec<OutlivesBound<'tcx>> {
145 sup_components
146 .into_iter()
a1dfa0c6 147 .filter_map(|component| {
8faf50e0 148 match component {
dfeec247
XL
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)),
8faf50e0
XL
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.
dfeec247
XL
161 {
162 None
163 }
164 Component::UnresolvedInferenceVariable(..) => None,
8faf50e0
XL
165 }
166 })
167 .collect()
168}