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;
7 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
8 pub struct Parameter(pub u32);
10 impl From<ty::ParamTy> for Parameter {
11 fn from(param: ty::ParamTy) -> Self {
12 Parameter(param.index)
16 impl From<ty::EarlyBoundRegion> for Parameter {
17 fn from(param: ty::EarlyBoundRegion) -> Self {
18 Parameter(param.index)
22 impl From<ty::ParamConst> for Parameter {
23 fn from(param: ty::ParamConst) -> Self {
24 Parameter(param.index)
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),
37 vec.into_iter().collect()
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,
49 let mut collector = ParameterCollector { parameters: vec![], include_nonconstraining };
50 t.visit_with(&mut collector);
54 struct ParameterCollector {
55 parameters: Vec<Parameter>,
56 include_nonconstraining: bool,
59 impl<'tcx> TypeVisitor<'tcx> for ParameterCollector {
60 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
62 ty::Projection(..) | ty::Opaque(..) if !self.include_nonconstraining => {
63 // projections are not injective
64 return ControlFlow::CONTINUE;
67 self.parameters.push(Parameter::from(data));
72 t.super_visit_with(self)
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));
82 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
84 ty::ConstKind::Unevaluated(..) if !self.include_nonconstraining => {
85 // Constant expressions are not injective
86 return c.ty().visit_with(self);
88 ty::ConstKind::Param(data) => {
89 self.parameters.push(Parameter::from(data));
94 c.super_visit_with(self)
98 pub fn identify_constrained_generic_params<'tcx>(
100 predicates: ty::GenericPredicates<'tcx>,
101 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
102 input_parameters: &mut FxHashSet<Parameter>,
104 let mut predicates = predicates.predicates.to_vec();
105 setup_constraining_predicates(tcx, &mut predicates, impl_trait_ref, input_parameters);
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:
113 /// impl<T: Debug, U: Iterator<Item = T>> Trait for U
115 /// The impl's predicates are collected from left to right. Ignoring
116 /// the implicit `Sized` bounds, these are
119 /// * <U as Iterator>::Item = T -- a desugared ProjectionPredicate
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>`.
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.
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>
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
148 pub fn setup_constraining_predicates<'tcx>(
150 predicates: &mut [(ty::Predicate<'tcx>, Span)],
151 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
152 input_parameters: &mut FxHashSet<Parameter>,
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.
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`.
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
174 "setup_constraining_predicates: predicates={:?} \
175 impl_trait_ref={:?} input_parameters={:?}",
176 predicates, impl_trait_ref, input_parameters
179 let mut changed = true;
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()
188 // Special case: watch out for some kind of sneaky attempt
189 // to project out an associated type defined by this very
191 let unbound_trait_ref = projection.projection_ty.trait_ref(tcx);
192 if Some(unbound_trait_ref) == impl_trait_ref {
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 {
206 input_parameters.extend(parameters_for(&projection.term, false));
210 // fancy control flow to bypass borrow checker
211 predicates.swap(i, j);
216 "setup_constraining_predicates: predicates={:?} \
217 i={} impl_trait_ref={:?} input_parameters={:?}",
218 predicates, i, impl_trait_ref, input_parameters