1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::ty::{self, Ty};
12 use rustc::ty::fold::{TypeFoldable, TypeVisitor};
13 use rustc::util::nodemap::FxHashSet;
15 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
16 pub struct Parameter(pub u32);
18 impl From<ty::ParamTy> for Parameter {
19 fn from(param: ty::ParamTy) -> Self { Parameter(param.idx) }
22 impl From<ty::EarlyBoundRegion> for Parameter {
23 fn from(param: ty::EarlyBoundRegion) -> Self { Parameter(param.index) }
26 /// Return the set of parameters constrained by the impl header.
27 pub fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>,
28 impl_trait_ref: Option<ty::TraitRef<'tcx>>)
29 -> FxHashSet<Parameter>
31 let vec = match impl_trait_ref {
32 Some(tr) => parameters_for(&tr, false),
33 None => parameters_for(&impl_self_ty, false),
35 vec.into_iter().collect()
38 /// If `include_projections` is false, returns the list of parameters that are
39 /// constrained by `t` - i.e. the value of each parameter in the list is
40 /// uniquely determined by `t` (see RFC 447). If it is true, return the list
41 /// of parameters whose values are needed in order to constrain `ty` - these
42 /// differ, with the latter being a superset, in the presence of projections.
43 pub fn parameters_for<'tcx, T>(t: &T,
44 include_nonconstraining: bool)
46 where T: TypeFoldable<'tcx>
49 let mut collector = ParameterCollector {
51 include_nonconstraining,
53 t.visit_with(&mut collector);
57 struct ParameterCollector {
58 parameters: Vec<Parameter>,
59 include_nonconstraining: bool
62 impl<'tcx> TypeVisitor<'tcx> for ParameterCollector {
63 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
65 ty::TyProjection(..) | ty::TyAnon(..) if !self.include_nonconstraining => {
66 // projections are not injective
69 ty::TyParam(data) => {
70 self.parameters.push(Parameter::from(data));
75 t.super_visit_with(self)
78 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
80 ty::ReEarlyBound(data) => {
81 self.parameters.push(Parameter::from(data));
89 pub fn identify_constrained_type_params<'tcx>(tcx: ty::TyCtxt,
90 predicates: &[ty::Predicate<'tcx>],
91 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
92 input_parameters: &mut FxHashSet<Parameter>)
94 let mut predicates = predicates.to_owned();
95 setup_constraining_predicates(tcx, &mut predicates, impl_trait_ref, input_parameters);
99 /// Order the predicates in `predicates` such that each parameter is
100 /// constrained before it is used, if that is possible, and add the
101 /// parameters so constrained to `input_parameters`. For example,
102 /// imagine the following impl:
104 /// impl<T: Debug, U: Iterator<Item=T>> Trait for U
106 /// The impl's predicates are collected from left to right. Ignoring
107 /// the implicit `Sized` bounds, these are
110 /// * <U as Iterator>::Item = T -- a desugared ProjectionPredicate
112 /// When we, for example, try to go over the trait-reference
113 /// `IntoIter<u32> as Trait`, we substitute the impl parameters with fresh
114 /// variables and match them with the impl trait-ref, so we know that
115 /// `$U = IntoIter<u32>`.
117 /// However, in order to process the `$T: Debug` predicate, we must first
118 /// know the value of `$T` - which is only given by processing the
119 /// projection. As we occasionally want to process predicates in a single
120 /// pass, we want the projection to come first. In fact, as projections
121 /// can (acyclically) depend on one another - see RFC447 for details - we
122 /// need to topologically sort them.
124 /// We *do* have to be somewhat careful when projection targets contain
125 /// projections themselves, for example in
126 /// impl<S,U,V,W> Trait for U where
127 /// /* 0 */ S: Iterator<Item=U>,
128 /// /* - */ U: Iterator,
129 /// /* 1 */ <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>
130 /// /* 2 */ W: Iterator<Item=V>
132 /// we have to evaluate the projections in the order I wrote them:
133 /// `V: Debug` requires `V` to be evaluated. The only projection that
134 /// *determines* `V` is 2 (1 contains it, but *does not determine it*,
135 /// as it is only contained within a projection), but that requires `W`
136 /// which is determined by 1, which requires `U`, that is determined
137 /// by 0. I should probably pick a less tangled example, but I can't
139 pub fn setup_constraining_predicates<'tcx>(tcx: ty::TyCtxt,
140 predicates: &mut [ty::Predicate<'tcx>],
141 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
142 input_parameters: &mut FxHashSet<Parameter>)
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.
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`.
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
163 debug!("setup_constraining_predicates: predicates={:?} \
164 impl_trait_ref={:?} input_parameters={:?}",
165 predicates, impl_trait_ref, input_parameters);
167 let mut changed = true;
171 for j in i..predicates.len() {
172 if let ty::Predicate::Projection(ref poly_projection) = predicates[j] {
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();
177 // Special case: watch out for some kind of sneaky attempt
178 // to project out an associated type defined by this very
180 let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
181 if Some(unbound_trait_ref.clone()) == impl_trait_ref {
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 {
195 input_parameters.extend(parameters_for(&projection.ty, false));
199 // fancy control flow to bypass borrow checker
200 predicates.swap(i, j);
204 debug!("setup_constraining_predicates: predicates={:?} \
205 i={} impl_trait_ref={:?} input_parameters={:?}",
206 predicates, i, impl_trait_ref, input_parameters);