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