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