]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/constrained_generic_params.rs
fix most compiler/ doctests
[rust.git] / compiler / rustc_typeck / src / constrained_generic_params.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_middle::ty::fold::{TypeFoldable, 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 TypeFoldable<'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::Projection(..) | ty::Opaque(..) 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.val() {
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 ///     impl<S,U,V,W> Trait for U where
136 /// /* 0 */   S: Iterator<Item = U>,
137 /// /* - */   U: Iterator,
138 /// /* 1 */   <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>
139 /// /* 2 */   W: Iterator<Item = V>
140 /// /* 3 */   V: Debug
141 /// we have to evaluate the projections in the order I wrote them:
142 /// `V: Debug` requires `V` to be evaluated. The only projection that
143 /// *determines* `V` is 2 (1 contains it, but *does not determine it*,
144 /// as it is only contained within a projection), but that requires `W`
145 /// which is determined by 1, which requires `U`, that is determined
146 /// by 0. I should probably pick a less tangled example, but I can't
147 /// think of any.
148 pub fn setup_constraining_predicates<'tcx>(
149     tcx: TyCtxt<'tcx>,
150     predicates: &mut [(ty::Predicate<'tcx>, Span)],
151     impl_trait_ref: Option<ty::TraitRef<'tcx>>,
152     input_parameters: &mut FxHashSet<Parameter>,
153 ) {
154     // The canonical way of doing the needed topological sort
155     // would be a DFS, but getting the graph and its ownership
156     // right is annoying, so I am using an in-place fixed-point iteration,
157     // which is `O(nt)` where `t` is the depth of type-parameter constraints,
158     // remembering that `t` should be less than 7 in practice.
159     //
160     // Basically, I iterate over all projections and swap every
161     // "ready" projection to the start of the list, such that
162     // all of the projections before `i` are topologically sorted
163     // and constrain all the parameters in `input_parameters`.
164     //
165     // In the example, `input_parameters` starts by containing `U` - which
166     // is constrained by the trait-ref - and so on the first pass we
167     // observe that `<U as Iterator>::Item = T` is a "ready" projection that
168     // constrains `T` and swap it to front. As it is the sole projection,
169     // no more swaps can take place afterwards, with the result being
170     //   * <U as Iterator>::Item = T
171     //   * T: Debug
172     //   * U: Iterator
173     debug!(
174         "setup_constraining_predicates: predicates={:?} \
175             impl_trait_ref={:?} input_parameters={:?}",
176         predicates, impl_trait_ref, input_parameters
177     );
178     let mut i = 0;
179     let mut changed = true;
180     while changed {
181         changed = false;
182
183         for j in i..predicates.len() {
184             // Note that we don't have to care about binders here,
185             // as the impl trait ref never contains any late-bound regions.
186             if let ty::PredicateKind::Projection(projection) = predicates[j].0.kind().skip_binder()
187             {
188                 // Special case: watch out for some kind of sneaky attempt
189                 // to project out an associated type defined by this very
190                 // trait.
191                 let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
192                 if Some(unbound_trait_ref) == impl_trait_ref {
193                     continue;
194                 }
195
196                 // A projection depends on its input types and determines its output
197                 // type. For example, if we have
198                 //     `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
199                 // Then the projection only applies if `T` is known, but it still
200                 // does not determine `U`.
201                 let inputs = parameters_for(&projection.projection_ty, true);
202                 let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(p));
203                 if !relies_only_on_inputs {
204                     continue;
205                 }
206                 input_parameters.extend(parameters_for(&projection.term, false));
207             } else {
208                 continue;
209             }
210             // fancy control flow to bypass borrow checker
211             predicates.swap(i, j);
212             i += 1;
213             changed = true;
214         }
215         debug!(
216             "setup_constraining_predicates: predicates={:?} \
217                 i={} impl_trait_ref={:?} input_parameters={:?}",
218             predicates, i, impl_trait_ref, input_parameters
219         );
220     }
221 }