Skip to main content

rustdoc/clean/
simplify.rs

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!
13
14use rustc_data_structures::fx::FxIndexMap;
15use rustc_data_structures::thin_vec::ThinVec;
16use rustc_data_structures::unord::UnordSet;
17use rustc_hir::def_id::DefId;
18use rustc_middle::ty::TyCtxt;
19
20use crate::clean;
21use crate::clean::{GenericArgs as PP, WherePredicate as WP};
22use crate::core::DocContext;
23
24pub(crate) fn where_clauses(tcx: TyCtxt<'_>, clauses: ThinVec<WP>) -> ThinVec<WP> {
25    // First, partition the where clause into its separate components.
26    //
27    // We use `FxIndexMap` so that the insertion order is preserved to prevent messing up to
28    // the order of the generated bounds.
29    let mut tybounds = FxIndexMap::default();
30    let mut lifetimes = Vec::new();
31    let mut equalities = Vec::new();
32
33    for clause in clauses {
34        match clause {
35            WP::BoundPredicate { ty, bounds, bound_params } => {
36                let (b, p): &mut (Vec<_>, Vec<_>) = tybounds.entry(ty).or_default();
37                b.extend(bounds);
38                p.extend(bound_params);
39            }
40            WP::RegionPredicate { lifetime, bounds } => {
41                lifetimes.push((lifetime, bounds));
42            }
43            WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
44        }
45    }
46
47    // Look for equality predicates on associated types that can be merged into
48    // general bound predicates.
49    equalities.retain(|(lhs, rhs)| {
50        let Some((bounds, _)) = tybounds.get_mut(&lhs.self_type) else { return true };
51        merge_bounds(tcx, bounds, lhs.trait_.as_ref().unwrap().def_id(), lhs.assoc.clone(), rhs)
52    });
53
54    // And finally, let's reassemble everything
55    let mut clauses = ThinVec::with_capacity(lifetimes.len() + tybounds.len() + equalities.len());
56    clauses.extend(
57        lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
58    );
59    clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
60        ty,
61        bounds,
62        bound_params,
63    }));
64    clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
65    clauses
66}
67
68pub(crate) fn merge_bounds(
69    tcx: TyCtxt<'_>,
70    bounds: &mut [clean::GenericBound],
71    trait_did: DefId,
72    assoc: clean::PathSegment,
73    rhs: &clean::Term,
74) -> bool {
75    !bounds.iter_mut().any(|b| {
76        let trait_ref = match *b {
77            clean::GenericBound::TraitBound(ref mut tr, _) => tr,
78            clean::GenericBound::Outlives(..) | clean::GenericBound::Use(_) => return false,
79        };
80        // If this QPath's trait `trait_did` is the same as, or a supertrait
81        // of, the bound's trait `did` then we can keep going, otherwise
82        // this is just a plain old equality bound.
83        if !trait_is_same_or_supertrait(tcx, trait_ref.trait_.def_id(), trait_did) {
84            return false;
85        }
86        let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
87
88        match last.args {
89            PP::AngleBracketed { ref mut constraints, .. } => {
90                constraints.push(clean::AssocItemConstraint {
91                    assoc: assoc.clone(),
92                    kind: clean::AssocItemConstraintKind::Equality { term: rhs.clone() },
93                });
94            }
95            PP::Parenthesized { ref mut output, .. } => match output {
96                Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
97                None => {
98                    if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
99                        *output = Some(Box::new(rhs.ty().unwrap().clone()));
100                    }
101                }
102            },
103            PP::ReturnTypeNotation => {
104                // Cannot merge bounds with RTN.
105                return false;
106            }
107        };
108        true
109    })
110}
111
112fn trait_is_same_or_supertrait(tcx: TyCtxt<'_>, child: DefId, trait_: DefId) -> bool {
113    if child == trait_ {
114        return true;
115    }
116    let predicates = tcx.explicit_super_predicates_of(child);
117    predicates
118        .iter_identity_copied()
119        .filter_map(|(pred, _)| Some(pred.as_trait_clause()?.def_id()))
120        .any(|did| trait_is_same_or_supertrait(tcx, did, trait_))
121}
122
123pub(crate) fn sized_bounds(cx: &mut DocContext<'_>, generics: &mut clean::Generics) {
124    let mut sized_params = UnordSet::new();
125
126    // In the surface language, all type parameters except `Self` have an
127    // implicit `Sized` bound unless removed with `?Sized`.
128    // However, in the list of where-predicates below, `Sized` appears like a
129    // normal bound: It's either present (the type is sized) or
130    // absent (the type might be unsized) but never *maybe* (i.e. `?Sized`).
131    //
132    // This is unsuitable for rendering.
133    // Thus, as a first step remove all `Sized` bounds that should be implicit.
134    //
135    // Note that associated types also have an implicit `Sized` bound but we
136    // don't actually know the set of associated types right here so that
137    // should be handled when cleaning associated types.
138    generics.where_predicates.retain(|pred| {
139        let WP::BoundPredicate { ty: clean::Generic(param), bounds, .. } = pred else {
140            return true;
141        };
142
143        if bounds.iter().any(|b| b.is_sized_bound(cx.tcx)) {
144            sized_params.insert(*param);
145            false
146        } else if bounds.iter().any(|b| b.is_meta_sized_bound(cx.tcx)) {
147            // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
148            // is shown and none of the new sizedness traits leak into documentation.
149            false
150        } else {
151            true
152        }
153    });
154
155    // As a final step, go through the type parameters again and insert a
156    // `?Sized` bound for each one we didn't find to be `Sized`.
157    for param in &generics.params {
158        if let clean::GenericParamDefKind::Type { .. } = param.kind
159            && !sized_params.contains(&param.name)
160        {
161            generics.where_predicates.push(WP::BoundPredicate {
162                ty: clean::Type::Generic(param.name),
163                bounds: vec![clean::GenericBound::maybe_sized(cx)],
164                bound_params: Vec::new(),
165            })
166        }
167    }
168}
169
170/// Move bounds that are (likely) directly attached to generic parameters from the where-clause to
171/// the respective parameter.
172///
173/// There is no guarantee that this is what the user actually wrote but we have no way of knowing.
174// FIXME(fmease): It'd make a lot of sense to just incorporate this logic into `clean_ty_generics`
175// making every of its users benefit from it.
176pub(crate) fn move_bounds_to_generic_parameters(generics: &mut clean::Generics) {
177    use clean::types::*;
178
179    let mut where_predicates = ThinVec::new();
180    for mut pred in generics.where_predicates.drain(..) {
181        if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
182            && let Some(GenericParamDef {
183                kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
184                ..
185            }) = generics.params.iter_mut().find(|param| &param.name == arg)
186        {
187            param_bounds.extend(bounds.drain(..));
188        } else if let WherePredicate::RegionPredicate { lifetime: Lifetime(arg), bounds } =
189            &mut pred
190            && let Some(GenericParamDef {
191                kind: GenericParamDefKind::Lifetime { outlives: param_bounds },
192                ..
193            }) = generics.params.iter_mut().find(|param| &param.name == arg)
194        {
195            param_bounds.extend(bounds.drain(..).map(|bound| match bound {
196                GenericBound::Outlives(lifetime) => lifetime,
197                _ => unreachable!(),
198            }));
199        } else {
200            where_predicates.push(pred);
201        }
202    }
203    generics.where_predicates = where_predicates;
204}