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;
67#[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_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::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);
910impl From<ty::ParamTy> for Parameter {
11fn from(param: ty::ParamTy) -> Self {
12Parameter(param.index)
13 }
14}
1516impl From<ty::EarlyParamRegion> for Parameter {
17fn from(param: ty::EarlyParamRegion) -> Self {
18Parameter(param.index)
19 }
20}
2122impl From<ty::ParamConst> for Parameter {
23fn from(param: ty::ParamConst) -> Self {
24Parameter(param.index)
25 }
26}
2728/// 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> {
34let vec = match impl_trait_ref {
35Some(tr) => parameters_for(tcx, tr, false),
36None => parameters_for(tcx, impl_self_ty, false),
37 };
38vec.into_iter().collect()
39}
4041/// 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> {
51let mut collector = ParameterCollector { parameters: ::alloc::vec::Vec::new()vec![], include_nonconstraining };
52let value = if !include_nonconstraining { tcx.expand_free_alias_tys(value) } else { value };
53value.visit_with(&mut collector);
54collector.parameters
55}
5657struct ParameterCollector {
58 parameters: Vec<Parameter>,
59 include_nonconstraining: bool,
60}
6162impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParameterCollector {
63fn visit_ty(&mut self, t: Ty<'tcx>) {
64match *t.kind() {
65// Projections are not injective in general.
66ty::Alias(ty::AliasTy {
67 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Opaque { .. },
68 ..
69 }) if !self.include_nonconstraining => {
70return;
71 }
72// All free alias types should've been expanded beforehand.
73ty::Alias(ty::AliasTy { kind: ty::Free { .. }, .. })
74if !self.include_nonconstraining =>
75 {
76::rustc_middle::util::bug::bug_fmt(format_args!("unexpected free alias type"))bug!("unexpected free alias type")77 }
78 ty::Param(param) => self.parameters.push(Parameter::from(param)),
79_ => {}
80 }
8182t.super_visit_with(self)
83 }
8485fn visit_region(&mut self, r: ty::Region<'tcx>) {
86if let ty::ReEarlyParam(data) = r.kind() {
87self.parameters.push(Parameter::from(data));
88 }
89 }
9091fn visit_const(&mut self, c: ty::Const<'tcx>) {
92match c.kind() {
93 ty::ConstKind::Unevaluated(..) if !self.include_nonconstraining => {
94// Constant expressions are not injective in general.
95return;
96 }
97 ty::ConstKind::Param(data) => {
98self.parameters.push(Parameter::from(data));
99 }
100_ => {}
101 }
102103c.super_visit_with(self)
104 }
105}
106107pub(crate) fn identify_constrained_generic_params<'tcx>(
108 tcx: TyCtxt<'tcx>,
109 predicates: ty::GenericPredicates<'tcx>,
110 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
111 input_parameters: &mut FxHashSet<Parameter>,
112) {
113let mut predicates = predicates.predicates.to_vec();
114setup_constraining_predicates(tcx, &mut predicates, impl_trait_ref, input_parameters);
115}
116117/// Order the predicates in `predicates` such that each parameter is
118/// constrained before it is used, if that is possible, and add the
119/// parameters so constrained to `input_parameters`. For example,
120/// imagine the following impl:
121/// ```ignore (illustrative)
122/// impl<T: Debug, U: Iterator<Item = T>> Trait for U
123/// ```
124/// The impl's predicates are collected from left to right. Ignoring
125/// the implicit `Sized` bounds, these are
126/// * `T: Debug`
127/// * `U: Iterator`
128/// * `<U as Iterator>::Item = T` -- a desugared ProjectionPredicate
129///
130/// When we, for example, try to go over the trait-reference
131/// `IntoIter<u32> as Trait`, we instantiate the impl parameters with fresh
132/// variables and match them with the impl trait-ref, so we know that
133/// `$U = IntoIter<u32>`.
134///
135/// However, in order to process the `$T: Debug` predicate, we must first
136/// know the value of `$T` - which is only given by processing the
137/// projection. As we occasionally want to process predicates in a single
138/// pass, we want the projection to come first. In fact, as projections
139/// can (acyclically) depend on one another - see RFC447 for details - we
140/// need to topologically sort them.
141///
142/// We *do* have to be somewhat careful when projection targets contain
143/// projections themselves, for example in
144///
145/// ```ignore (illustrative)
146/// impl<S,U,V,W> Trait for U where
147/// /* 0 */ S: Iterator<Item = U>,
148/// /* - */ U: Iterator,
149/// /* 1 */ <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>
150/// /* 2 */ W: Iterator<Item = V>
151/// /* 3 */ V: Debug
152/// ```
153///
154/// we have to evaluate the projections in the order I wrote them:
155/// `V: Debug` requires `V` to be evaluated. The only projection that
156/// *determines* `V` is 2 (1 contains it, but *does not determine it*,
157/// as it is only contained within a projection), but that requires `W`
158/// which is determined by 1, which requires `U`, that is determined
159/// by 0. I should probably pick a less tangled example, but I can't
160/// think of any.
161pub(crate) fn setup_constraining_predicates<'tcx>(
162 tcx: TyCtxt<'tcx>,
163 predicates: &mut [(ty::Clause<'tcx>, Span)],
164 impl_trait_ref: Option<ty::TraitRef<'tcx>>,
165 input_parameters: &mut FxHashSet<Parameter>,
166) {
167// The canonical way of doing the needed topological sort
168 // would be a DFS, but getting the graph and its ownership
169 // right is annoying, so I am using an in-place fixed-point iteration,
170 // which is `O(nt)` where `t` is the depth of type-parameter constraints,
171 // remembering that `t` should be less than 7 in practice.
172 //
173 // FIXME(hkBst): the big-O bound above would be accurate for the number
174 // of calls to `parameters_for`, which itself is some O(complexity of type).
175 // That would make this potentially cubic instead of merely quadratic...
176 // ...unless we cache those `parameters_for` calls.
177 //
178 // Basically, I iterate over all projections and swap every
179 // "ready" projection to the start of the list, such that
180 // all of the projections before `i` are topologically sorted
181 // and constrain all the parameters in `input_parameters`.
182 //
183 // In the first example, `input_parameters` starts by containing `U`,
184 // which is constrained by the self type `U`. Then, on the first pass we
185 // observe that `<U as Iterator>::Item = T` is a "ready" projection that
186 // constrains `T` and swap it to the front. As it is the sole projection,
187 // no more swaps can take place afterwards, with the result being
188 // * <U as Iterator>::Item = T
189 // * T: Debug
190 // * U: Iterator
191{
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:191",
"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(191u32),
::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!(
192"setup_constraining_predicates: predicates={:?} \
193 impl_trait_ref={:?} input_parameters={:?}",
194 predicates, impl_trait_ref, input_parameters
195 );
196let mut i = 0;
197let mut changed = true;
198while changed {
199 changed = false;
200201for j in i..predicates.len() {
202// Note that we don't have to care about binders here,
203 // as the impl trait ref never contains any late-bound regions.
204if let ty::ClauseKind::Projection(projection) = predicates[j].0.kind().skip_binder() &&
205206// Special case: watch out for some kind of sneaky attempt to
207 // project out an associated type defined by this very trait.
208!impl_trait_ref.is_some_and(|t| t == projection.projection_term.trait_ref(tcx)) &&
209210// A projection depends on its input types and determines its output
211 // type. For example, if we have
212 // `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
213 // then the projection only applies if `T` is known, but it still
214 // does not determine `U`.
215parameters_for(tcx, projection.projection_term, true).iter().all(|p| input_parameters.contains(p))
216 {
217 input_parameters.extend(parameters_for(tcx, projection.term, false));
218219 predicates.swap(i, j);
220 i += 1;
221 changed = true;
222 }
223 }
224{
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:224",
"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(224u32),
::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!(
225"setup_constraining_predicates: predicates={:?} \
226 i={} impl_trait_ref={:?} input_parameters={:?}",
227 predicates, i, impl_trait_ref, input_parameters
228 );
229 }
230}