]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/clean/simplify.rs
New upstream version 1.73.0+dfsg1
[rustc.git] / src / librustdoc / 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
14 use rustc_data_structures::fx::FxIndexMap;
15 use rustc_hir::def_id::DefId;
16 use rustc_middle::ty;
17 use thin_vec::ThinVec;
18
19 use crate::clean;
20 use crate::clean::GenericArgs as PP;
21 use crate::clean::WherePredicate as WP;
22 use crate::core::DocContext;
23
24 pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec<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, bound_params } => equalities.push((lhs, rhs, bound_params)),
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, bound_params)| {
50 let Some((ty, trait_did, name)) = lhs.projection() else {
51 return true;
52 };
53 let Some((bounds, _)) = tybounds.get_mut(ty) else { return true };
54 merge_bounds(cx, bounds, bound_params.clone(), trait_did, name, rhs)
55 });
56
57 // And finally, let's reassemble everything
58 let mut clauses = ThinVec::with_capacity(lifetimes.len() + tybounds.len() + equalities.len());
59 clauses.extend(
60 lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
61 );
62 clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
63 ty,
64 bounds,
65 bound_params,
66 }));
67 clauses.extend(equalities.into_iter().map(|(lhs, rhs, bound_params)| WP::EqPredicate {
68 lhs,
69 rhs,
70 bound_params,
71 }));
72 clauses
73 }
74
75 pub(crate) fn merge_bounds(
76 cx: &clean::DocContext<'_>,
77 bounds: &mut Vec<clean::GenericBound>,
78 mut bound_params: Vec<clean::GenericParamDef>,
79 trait_did: DefId,
80 assoc: clean::PathSegment,
81 rhs: &clean::Term,
82 ) -> bool {
83 !bounds.iter_mut().any(|b| {
84 let trait_ref = match *b {
85 clean::GenericBound::TraitBound(ref mut tr, _) => tr,
86 clean::GenericBound::Outlives(..) => return false,
87 };
88 // If this QPath's trait `trait_did` is the same as, or a supertrait
89 // of, the bound's trait `did` then we can keep going, otherwise
90 // this is just a plain old equality bound.
91 if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
92 return false;
93 }
94 let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
95
96 trait_ref.generic_params.append(&mut bound_params);
97 // Sort parameters (likely) originating from a hashset alphabetically to
98 // produce predictable output (and to allow for full deduplication).
99 trait_ref.generic_params.sort_unstable_by(|p, q| p.name.as_str().cmp(q.name.as_str()));
100 trait_ref.generic_params.dedup_by_key(|p| p.name);
101
102 match last.args {
103 PP::AngleBracketed { ref mut bindings, .. } => {
104 bindings.push(clean::TypeBinding {
105 assoc: assoc.clone(),
106 kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
107 });
108 }
109 PP::Parenthesized { ref mut output, .. } => match output {
110 Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
111 None => {
112 if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
113 *output = Some(Box::new(rhs.ty().unwrap().clone()));
114 }
115 }
116 },
117 };
118 true
119 })
120 }
121
122 fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
123 if child == trait_ {
124 return true;
125 }
126 let predicates = cx.tcx.super_predicates_of(child);
127 debug_assert!(cx.tcx.generics_of(child).has_self);
128 let self_ty = cx.tcx.types.self_param;
129 predicates
130 .predicates
131 .iter()
132 .filter_map(|(pred, _)| {
133 if let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder() {
134 if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
135 } else {
136 None
137 }
138 })
139 .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
140 }
141
142 /// Move bounds that are (likely) directly attached to generic parameters from the where-clause to
143 /// the respective parameter.
144 ///
145 /// There is no guarantee that this is what the user actually wrote but we have no way of knowing.
146 // FIXME(fmease): It'd make a lot of sense to just incorporate this logic into `clean_ty_generics`
147 // making every of its users benefit from it.
148 pub(crate) fn move_bounds_to_generic_parameters(generics: &mut clean::Generics) {
149 use clean::types::*;
150
151 let mut where_predicates = ThinVec::new();
152 for mut pred in generics.where_predicates.drain(..) {
153 if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
154 && let Some(GenericParamDef {
155 kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
156 ..
157 }) = generics.params.iter_mut().find(|param| &param.name == arg)
158 {
159 param_bounds.append(bounds);
160 } else if let WherePredicate::RegionPredicate { lifetime: Lifetime(arg), bounds } = &mut pred
161 && let Some(GenericParamDef {
162 kind: GenericParamDefKind::Lifetime { outlives: param_bounds },
163 ..
164 }) = generics.params.iter_mut().find(|param| &param.name == arg)
165 {
166 param_bounds.extend(bounds.drain(..).map(|bound| match bound {
167 GenericBound::Outlives(lifetime) => lifetime,
168 _ => unreachable!(),
169 }));
170 } else {
171 where_predicates.push(pred);
172 }
173 }
174 generics.where_predicates = where_predicates;
175 }