1//! Simplification of where-clauses and parameter bounds into a prettier and
2//! more canonical form.
3//!
4//! Currently all cross-crate-inlined function use `rustc_middle::ty` to reconstruct
5//! the AST (e.g., see all of `clean::inline`), but this is not always a
6//! non-lossy transformation. The current format of storage for where-clauses
7//! for functions and such is simply a list of predicates. One example of this
8//! is that the AST predicate of: `where T: Trait<Foo = Bar>` is encoded as:
9//! `where T: Trait, <T as Trait>::Foo = Bar`.
10//!
11//! This module attempts to reconstruct the original where and/or parameter
12//! bounds by special casing scenarios such as these. Fun!
1314use rustc_data_structures::fx::FxIndexMap;
15use rustc_data_structures::unord::UnordSet;
16use rustc_hir::def_id::DefId;
17use thin_vec::ThinVec;
1819use crate::clean;
20use crate::clean::{GenericArgsas PP, WherePredicateas WP};
21use crate::core::DocContext;
2223pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: ThinVec<WP>) -> ThinVec<WP> {
24// First, partition the where clause into its separate components.
25 //
26 // We use `FxIndexMap` so that the insertion order is preserved to prevent messing up to
27 // the order of the generated bounds.
28let mut tybounds = FxIndexMap::default();
29let mut lifetimes = Vec::new();
30let mut equalities = Vec::new();
3132for clause in clauses {
33match clause {
34 WP::BoundPredicate { ty, bounds, bound_params } => {
35let (b, p): &mut (Vec<_>, Vec<_>) = tybounds.entry(ty).or_default();
36 b.extend(bounds);
37 p.extend(bound_params);
38 }
39 WP::RegionPredicate { lifetime, bounds } => {
40 lifetimes.push((lifetime, bounds));
41 }
42 WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
43 }
44 }
4546// Look for equality predicates on associated types that can be merged into
47 // general bound predicates.
48equalities.retain(|(lhs, rhs)| {
49let Some((ty, trait_did, name)) = lhs.projection() else {
50return true;
51 };
52let Some((bounds, _)) = tybounds.get_mut(ty) else { return true };
53merge_bounds(cx, bounds, trait_did, name, rhs)
54 });
5556// And finally, let's reassemble everything
57let mut clauses = ThinVec::with_capacity(lifetimes.len() + tybounds.len() + equalities.len());
58clauses.extend(
59lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
60 );
61clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
62ty,
63bounds,
64bound_params,
65 }));
66clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
67clauses68}
6970pub(crate) fn merge_bounds(
71 cx: &clean::DocContext<'_>,
72 bounds: &mut [clean::GenericBound],
73 trait_did: DefId,
74 assoc: clean::PathSegment,
75 rhs: &clean::Term,
76) -> bool {
77 !bounds.iter_mut().any(|b| {
78let trait_ref = match *b {
79clean::GenericBound::TraitBound(ref mut tr, _) => tr,
80clean::GenericBound::Outlives(..) | clean::GenericBound::Use(_) => return false,
81 };
82// If this QPath's trait `trait_did` is the same as, or a supertrait
83 // of, the bound's trait `did` then we can keep going, otherwise
84 // this is just a plain old equality bound.
85if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
86return false;
87 }
88let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
8990match last.args {
91PP::AngleBracketed { ref mut constraints, .. } => {
92constraints.push(clean::AssocItemConstraint {
93 assoc: assoc.clone(),
94 kind: clean::AssocItemConstraintKind::Equality { term: rhs.clone() },
95 });
96 }
97PP::Parenthesized { ref mut output, .. } => match output {
98Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
99None => {
100if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
101*output = Some(Box::new(rhs.ty().unwrap().clone()));
102 }
103 }
104 },
105PP::ReturnTypeNotation => {
106// Cannot merge bounds with RTN.
107return false;
108 }
109 };
110true
111})
112}
113114fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
115if child == trait_ {
116return true;
117 }
118let predicates = cx.tcx.explicit_super_predicates_of(child);
119predicates120 .iter_identity_copied()
121 .filter_map(|(pred, _)| Some(pred.as_trait_clause()?.def_id()))
122 .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
123}
124125pub(crate) fn sized_bounds(cx: &mut DocContext<'_>, generics: &mut clean::Generics) {
126let mut sized_params = UnordSet::new();
127128// In the surface language, all type parameters except `Self` have an
129 // implicit `Sized` bound unless removed with `?Sized`.
130 // However, in the list of where-predicates below, `Sized` appears like a
131 // normal bound: It's either present (the type is sized) or
132 // absent (the type might be unsized) but never *maybe* (i.e. `?Sized`).
133 //
134 // This is unsuitable for rendering.
135 // Thus, as a first step remove all `Sized` bounds that should be implicit.
136 //
137 // Note that associated types also have an implicit `Sized` bound but we
138 // don't actually know the set of associated types right here so that
139 // should be handled when cleaning associated types.
140generics.where_predicates.retain(|pred| {
141if let WP::BoundPredicate { ty: clean::Generic(param), bounds, .. } = pred142 && bounds.iter().any(|b| b.is_sized_bound(cx))
143 {
144sized_params.insert(*param);
145false
146} else {
147true
148}
149 });
150151// As a final step, go through the type parameters again and insert a
152 // `?Sized` bound for each one we didn't find to be `Sized`.
153for param in &generics.params {
154if let clean::GenericParamDefKind::Type { .. } = param.kind
155 && !sized_params.contains(¶m.name)
156 {
157 generics.where_predicates.push(WP::BoundPredicate {
158 ty: clean::Type::Generic(param.name),
159 bounds: vec![clean::GenericBound::maybe_sized(cx)],
160 bound_params: Vec::new(),
161 })
162 }
163 }
164}
165166/// Move bounds that are (likely) directly attached to generic parameters from the where-clause to
167/// the respective parameter.
168///
169/// There is no guarantee that this is what the user actually wrote but we have no way of knowing.
170// FIXME(fmease): It'd make a lot of sense to just incorporate this logic into `clean_ty_generics`
171// making every of its users benefit from it.
172pub(crate) fn move_bounds_to_generic_parameters(generics: &mut clean::Generics) {
173use clean::types::*;
174175let mut where_predicates = ThinVec::new();
176for mut pred in generics.where_predicates.drain(..) {
177if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
178 && let Some(GenericParamDef {
179 kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
180 ..
181 }) = generics.params.iter_mut().find(|param| ¶m.name == arg)
182 {
183 param_bounds.extend(bounds.drain(..));
184 } else if let WherePredicate::RegionPredicate { lifetime: Lifetime(arg), bounds } =
185&mut pred
186 && let Some(GenericParamDef {
187 kind: GenericParamDefKind::Lifetime { outlives: param_bounds },
188 ..
189 }) = generics.params.iter_mut().find(|param| ¶m.name == arg)
190 {
191 param_bounds.extend(bounds.drain(..).map(|bound| match bound {
192 GenericBound::Outlives(lifetime) => lifetime,
193_ => unreachable!(),
194 }));
195 } else {
196 where_predicates.push(pred);
197 }
198 }
199generics.where_predicates = where_predicates;
200}