rustc_hir_analysis/
constrained_generic_params.rs

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