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