Skip to main content

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(#[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::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_receiver_is_total_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::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}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)]
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: ::alloc::vec::Vec::new()vec![], include_nonconstraining };
52    let value = if !include_nonconstraining { tcx.expand_free_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 free alias types should've been expanded beforehand.
72            ty::Alias(ty::Free, _) if !self.include_nonconstraining => {
73                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected free alias type"))bug!("unexpected free 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.kind() {
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    // FIXME(hkBst): the big-O bound above would be accurate for the number
171    // of calls to `parameters_for`, which itself is some O(complexity of type).
172    // That would make this potentially cubic instead of merely quadratic...
173    // ...unless we cache those `parameters_for` calls.
174    //
175    // Basically, I iterate over all projections and swap every
176    // "ready" projection to the start of the list, such that
177    // all of the projections before `i` are topologically sorted
178    // and constrain all the parameters in `input_parameters`.
179    //
180    // In the first example, `input_parameters` starts by containing `U`,
181    // which is constrained by the self type `U`. Then, on the first pass we
182    // observe that `<U as Iterator>::Item = T` is a "ready" projection that
183    // constrains `T` and swap it to the front. As it is the sole projection,
184    // no more swaps can take place afterwards, with the result being
185    //   * <U as Iterator>::Item = T
186    //   * T: Debug
187    //   * U: Iterator
188    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/constrained_generic_params.rs:188",
                        "rustc_hir_analysis::constrained_generic_params",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/constrained_generic_params.rs"),
                        ::tracing_core::__macro_support::Option::Some(188u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("setup_constraining_predicates: predicates={0:?} impl_trait_ref={1:?} input_parameters={2:?}",
                                                    predicates, impl_trait_ref, input_parameters) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
189        "setup_constraining_predicates: predicates={:?} \
190            impl_trait_ref={:?} input_parameters={:?}",
191        predicates, impl_trait_ref, input_parameters
192    );
193    let mut i = 0;
194    let mut changed = true;
195    while changed {
196        changed = false;
197
198        for j in i..predicates.len() {
199            // Note that we don't have to care about binders here,
200            // as the impl trait ref never contains any late-bound regions.
201            if let ty::ClauseKind::Projection(projection) = predicates[j].0.kind().skip_binder() &&
202
203            // Special case: watch out for some kind of sneaky attempt to
204            // project out an associated type defined by this very trait.
205            !impl_trait_ref.is_some_and(|t| t == projection.projection_term.trait_ref(tcx)) &&
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                parameters_for(tcx, projection.projection_term, true).iter().all(|p| input_parameters.contains(p))
213            {
214                input_parameters.extend(parameters_for(tcx, projection.term, false));
215
216                predicates.swap(i, j);
217                i += 1;
218                changed = true;
219            }
220        }
221        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/constrained_generic_params.rs:221",
                        "rustc_hir_analysis::constrained_generic_params",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/constrained_generic_params.rs"),
                        ::tracing_core::__macro_support::Option::Some(221u32),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("setup_constraining_predicates: predicates={0:?} i={1} impl_trait_ref={2:?} input_parameters={3:?}",
                                                    predicates, i, impl_trait_ref, input_parameters) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
222            "setup_constraining_predicates: predicates={:?} \
223                i={} impl_trait_ref={:?} input_parameters={:?}",
224            predicates, i, impl_trait_ref, input_parameters
225        );
226    }
227}