]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/constrained_generic_params.rs
Auto merge of #106810 - oli-obk:resolver_reverse_plumbing, r=petrochenkov
[rust.git] / compiler / rustc_hir_analysis / src / constrained_generic_params.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
3 use rustc_middle::ty::{self, Ty, TyCtxt};
4 use rustc_span::source_map::Span;
5 use std::ops::ControlFlow;
6
7 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
8 pub struct Parameter(pub u32);
9
10 impl From<ty::ParamTy> for Parameter {
11     fn from(param: ty::ParamTy) -> Self {
12         Parameter(param.index)
13     }
14 }
15
16 impl From<ty::EarlyBoundRegion> for Parameter {
17     fn from(param: ty::EarlyBoundRegion) -> Self {
18         Parameter(param.index)
19     }
20 }
21
22 impl From<ty::ParamConst> for Parameter {
23     fn from(param: ty::ParamConst) -> Self {
24         Parameter(param.index)
25     }
26 }
27
28 /// Returns the set of parameters constrained by the impl header.
29 pub fn parameters_for_impl<'tcx>(
30     impl_self_ty: Ty<'tcx>,
31     impl_trait_ref: Option<ty::TraitRef<'tcx>>,
32 ) -> FxHashSet<Parameter> {
33     let vec = match impl_trait_ref {
34         Some(tr) => parameters_for(&tr, false),
35         None => parameters_for(&impl_self_ty, false),
36     };
37     vec.into_iter().collect()
38 }
39
40 /// If `include_nonconstraining` is false, returns the list of parameters that are
41 /// constrained by `t` - i.e., the value of each parameter in the list is
42 /// uniquely determined by `t` (see RFC 447). If it is true, return the list
43 /// of parameters whose values are needed in order to constrain `ty` - these
44 /// differ, with the latter being a superset, in the presence of projections.
45 pub fn parameters_for<'tcx>(
46     t: &impl TypeVisitable<'tcx>,
47     include_nonconstraining: bool,
48 ) -> Vec<Parameter> {
49     let mut collector = ParameterCollector { parameters: vec![], include_nonconstraining };
50     t.visit_with(&mut collector);
51     collector.parameters
52 }
53
54 struct ParameterCollector {
55     parameters: Vec<Parameter>,
56     include_nonconstraining: bool,
57 }
58
59 impl<'tcx> TypeVisitor<'tcx> for ParameterCollector {
60     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
61         match *t.kind() {
62             ty::Alias(ty::Projection, ..) if !self.include_nonconstraining => {
63                 // projections are not injective
64                 return ControlFlow::Continue(());
65             }
66             ty::Param(data) => {
67                 self.parameters.push(Parameter::from(data));
68             }
69             _ => {}
70         }
71
72         t.super_visit_with(self)
73     }
74
75     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
76         if let ty::ReEarlyBound(data) = *r {
77             self.parameters.push(Parameter::from(data));
78         }
79         ControlFlow::Continue(())
80     }
81
82     fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
83         match c.kind() {
84             ty::ConstKind::Unevaluated(..) if !self.include_nonconstraining => {
85                 // Constant expressions are not injective
86                 return c.ty().visit_with(self);
87             }
88             ty::ConstKind::Param(data) => {
89                 self.parameters.push(Parameter::from(data));
90             }
91             _ => {}
92         }
93
94         c.super_visit_with(self)
95     }
96 }
97
98 pub fn identify_constrained_generic_params<'tcx>(
99     tcx: TyCtxt<'tcx>,
100     predicates: ty::GenericPredicates<'tcx>,
101     impl_trait_ref: Option<ty::TraitRef<'tcx>>,
102     input_parameters: &mut FxHashSet<Parameter>,
103 ) {
104     let mut predicates = predicates.predicates.to_vec();
105     setup_constraining_predicates(tcx, &mut predicates, impl_trait_ref, input_parameters);
106 }
107
108 /// Order the predicates in `predicates` such that each parameter is
109 /// constrained before it is used, if that is possible, and add the
110 /// parameters so constrained to `input_parameters`. For example,
111 /// imagine the following impl:
112 /// ```ignore (illustrative)
113 /// impl<T: Debug, U: Iterator<Item = T>> Trait for U
114 /// ```
115 /// The impl's predicates are collected from left to right. Ignoring
116 /// the implicit `Sized` bounds, these are
117 ///   * `T: Debug`
118 ///   * `U: Iterator`
119 ///   * `<U as Iterator>::Item = T` -- a desugared ProjectionPredicate
120 ///
121 /// When we, for example, try to go over the trait-reference
122 /// `IntoIter<u32> as Trait`, we substitute the impl parameters with fresh
123 /// variables and match them with the impl trait-ref, so we know that
124 /// `$U = IntoIter<u32>`.
125 ///
126 /// However, in order to process the `$T: Debug` predicate, we must first
127 /// know the value of `$T` - which is only given by processing the
128 /// projection. As we occasionally want to process predicates in a single
129 /// pass, we want the projection to come first. In fact, as projections
130 /// can (acyclically) depend on one another - see RFC447 for details - we
131 /// need to topologically sort them.
132 ///
133 /// We *do* have to be somewhat careful when projection targets contain
134 /// projections themselves, for example in
135 ///
136 /// ```ignore (illustrative)
137 ///     impl<S,U,V,W> Trait for U where
138 /// /* 0 */   S: Iterator<Item = U>,
139 /// /* - */   U: Iterator,
140 /// /* 1 */   <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>
141 /// /* 2 */   W: Iterator<Item = V>
142 /// /* 3 */   V: Debug
143 /// ```
144 ///
145 /// we have to evaluate the projections in the order I wrote them:
146 /// `V: Debug` requires `V` to be evaluated. The only projection that
147 /// *determines* `V` is 2 (1 contains it, but *does not determine it*,
148 /// as it is only contained within a projection), but that requires `W`
149 /// which is determined by 1, which requires `U`, that is determined
150 /// by 0. I should probably pick a less tangled example, but I can't
151 /// think of any.
152 pub fn setup_constraining_predicates<'tcx>(
153     tcx: TyCtxt<'tcx>,
154     predicates: &mut [(ty::Predicate<'tcx>, Span)],
155     impl_trait_ref: Option<ty::TraitRef<'tcx>>,
156     input_parameters: &mut FxHashSet<Parameter>,
157 ) {
158     // The canonical way of doing the needed topological sort
159     // would be a DFS, but getting the graph and its ownership
160     // right is annoying, so I am using an in-place fixed-point iteration,
161     // which is `O(nt)` where `t` is the depth of type-parameter constraints,
162     // remembering that `t` should be less than 7 in practice.
163     //
164     // Basically, I iterate over all projections and swap every
165     // "ready" projection to the start of the list, such that
166     // all of the projections before `i` are topologically sorted
167     // and constrain all the parameters in `input_parameters`.
168     //
169     // In the example, `input_parameters` starts by containing `U` - which
170     // is constrained by the trait-ref - and so on the first pass we
171     // observe that `<U as Iterator>::Item = T` is a "ready" projection that
172     // constrains `T` and swap it to front. As it is the sole projection,
173     // no more swaps can take place afterwards, with the result being
174     //   * <U as Iterator>::Item = T
175     //   * T: Debug
176     //   * U: Iterator
177     debug!(
178         "setup_constraining_predicates: predicates={:?} \
179             impl_trait_ref={:?} input_parameters={:?}",
180         predicates, impl_trait_ref, input_parameters
181     );
182     let mut i = 0;
183     let mut changed = true;
184     while changed {
185         changed = false;
186
187         for j in i..predicates.len() {
188             // Note that we don't have to care about binders here,
189             // as the impl trait ref never contains any late-bound regions.
190             if let ty::PredicateKind::Clause(ty::Clause::Projection(projection)) =
191                 predicates[j].0.kind().skip_binder()
192             {
193                 // Special case: watch out for some kind of sneaky attempt
194                 // to project out an associated type defined by this very
195                 // trait.
196                 let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
197                 if Some(unbound_trait_ref) == impl_trait_ref {
198                     continue;
199                 }
200
201                 // A projection depends on its input types and determines its output
202                 // type. For example, if we have
203                 //     `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
204                 // Then the projection only applies if `T` is known, but it still
205                 // does not determine `U`.
206                 let inputs = parameters_for(&projection.projection_ty, true);
207                 let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(p));
208                 if !relies_only_on_inputs {
209                     continue;
210                 }
211                 input_parameters.extend(parameters_for(&projection.term, false));
212             } else {
213                 continue;
214             }
215             // fancy control flow to bypass borrow checker
216             predicates.swap(i, j);
217             i += 1;
218             changed = true;
219         }
220         debug!(
221             "setup_constraining_predicates: predicates={:?} \
222                 i={} impl_trait_ref={:?} input_parameters={:?}",
223             predicates, i, impl_trait_ref, input_parameters
224         );
225     }
226 }