1 use rustc::ty::fold::{TypeFoldable, TypeVisitor};
2 use rustc::ty::{self, Ty, TyCtxt};
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_span::source_map::Span;
6 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
7 pub struct Parameter(pub u32);
9 impl From<ty::ParamTy> for Parameter {
10 fn from(param: ty::ParamTy) -> Self {
11 Parameter(param.index)
15 impl From<ty::EarlyBoundRegion> for Parameter {
16 fn from(param: ty::EarlyBoundRegion) -> Self {
17 Parameter(param.index)
21 impl From<ty::ParamConst> for Parameter {
22 fn from(param: ty::ParamConst) -> Self {
23 Parameter(param.index)
27 /// Returns the set of parameters constrained by the impl header.
28 pub fn parameters_for_impl<'tcx>(
29 impl_self_ty: Ty<'tcx>,
30 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
31 ) -> FxHashSet<Parameter> {
32 let vec = match impl_trait_ref {
33 Some(tr) => parameters_for(&tr, false),
34 None => parameters_for(&impl_self_ty, false),
36 vec.into_iter().collect()
39 /// If `include_projections` is false, returns the list of parameters that are
40 /// constrained by `t` - i.e., the value of each parameter in the list is
41 /// uniquely determined by `t` (see RFC 447). If it is true, return the list
42 /// of parameters whose values are needed in order to constrain `ty` - these
43 /// differ, with the latter being a superset, in the presence of projections.
44 pub fn parameters_for<'tcx>(
45 t: &impl TypeFoldable<'tcx>,
46 include_nonconstraining: bool,
48 let mut collector = ParameterCollector { parameters: vec![], include_nonconstraining };
49 t.visit_with(&mut collector);
53 struct ParameterCollector {
54 parameters: Vec<Parameter>,
55 include_nonconstraining: bool,
58 impl<'tcx> TypeVisitor<'tcx> for ParameterCollector {
59 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
61 ty::Projection(..) | ty::Opaque(..) if !self.include_nonconstraining => {
62 // projections are not injective
66 self.parameters.push(Parameter::from(data));
71 t.super_visit_with(self)
74 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
75 if let ty::ReEarlyBound(data) = *r {
76 self.parameters.push(Parameter::from(data));
81 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
82 if let ty::ConstKind::Param(data) = c.val {
83 self.parameters.push(Parameter::from(data));
89 pub fn identify_constrained_generic_params<'tcx>(
91 predicates: ty::GenericPredicates<'tcx>,
92 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
93 input_parameters: &mut FxHashSet<Parameter>,
95 let mut predicates = predicates.predicates.to_vec();
96 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>(
141 predicates: &mut [(ty::Predicate<'tcx>, Span)],
142 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
143 input_parameters: &mut FxHashSet<Parameter>,
145 // The canonical way of doing the needed topological sort
146 // would be a DFS, but getting the graph and its ownership
147 // right is annoying, so I am using an in-place fixed-point iteration,
148 // which is `O(nt)` where `t` is the depth of type-parameter constraints,
149 // remembering that `t` should be less than 7 in practice.
151 // Basically, I iterate over all projections and swap every
152 // "ready" projection to the start of the list, such that
153 // all of the projections before `i` are topologically sorted
154 // and constrain all the parameters in `input_parameters`.
156 // In the example, `input_parameters` starts by containing `U` - which
157 // is constrained by the trait-ref - and so on the first pass we
158 // observe that `<U as Iterator>::Item = T` is a "ready" projection that
159 // constrains `T` and swap it to front. As it is the sole projection,
160 // no more swaps can take place afterwards, with the result being
161 // * <U as Iterator>::Item = T
165 "setup_constraining_predicates: predicates={:?} \
166 impl_trait_ref={:?} input_parameters={:?}",
167 predicates, impl_trait_ref, input_parameters
170 let mut changed = true;
174 for j in i..predicates.len() {
175 if let ty::Predicate::Projection(ref poly_projection) = predicates[j].0 {
176 // Note that we can skip binder here because the impl
177 // trait ref never contains any late-bound regions.
178 let projection = poly_projection.skip_binder();
180 // Special case: watch out for some kind of sneaky attempt
181 // to project out an associated type defined by this very
183 let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
184 if Some(unbound_trait_ref) == impl_trait_ref {
188 // A projection depends on its input types and determines its output
189 // type. For example, if we have
190 // `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
191 // Then the projection only applies if `T` is known, but it still
192 // does not determine `U`.
193 let inputs = parameters_for(&projection.projection_ty.trait_ref(tcx), true);
194 let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(&p));
195 if !relies_only_on_inputs {
198 input_parameters.extend(parameters_for(&projection.ty, false));
202 // fancy control flow to bypass borrow checker
203 predicates.swap(i, j);
208 "setup_constraining_predicates: predicates={:?} \
209 i={} impl_trait_ref={:?} input_parameters={:?}",
210 predicates, i, impl_trait_ref, input_parameters