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