Skip to main content

rustc_hir_analysis/
constrained_generic_params.rs

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