]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/clean/simplify.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / src / librustdoc / clean / simplify.rs
CommitLineData
9fa01778 1//! Simplification of where-clauses and parameter bounds into a prettier and
9346a6ac
AL
2//! more canonical form.
3//!
ba9703b0 4//! Currently all cross-crate-inlined function use `rustc_middle::ty` to reconstruct
0731742a 5//! the AST (e.g., see all of `clean::inline`), but this is not always a
9fa01778 6//! non-lossy transformation. The current format of storage for where-clauses
9346a6ac 7//! for functions and such is simply a list of predicates. One example of this
9fa01778 8//! is that the AST predicate of: `where T: Trait<Foo = Bar>` is encoded as:
ea8adc8c 9//! `where T: Trait, <T as Trait>::Foo = Bar`.
9346a6ac
AL
10//!
11//! This module attempts to reconstruct the original where and/or parameter
12//! bounds by special casing scenarios such as these. Fun!
13
c295e0f8 14use rustc_data_structures::fx::FxIndexMap;
dfeec247 15use rustc_hir::def_id::DefId;
ba9703b0 16use rustc_middle::ty;
487cf647 17use thin_vec::ThinVec;
9346a6ac 18
dfeec247 19use crate::clean;
9fa01778
XL
20use crate::clean::GenericArgs as PP;
21use crate::clean::WherePredicate as WP;
9fa01778 22use crate::core::DocContext;
9346a6ac 23
487cf647 24pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> ThinVec<WP> {
c295e0f8
XL
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.
2b03887a 29 let mut tybounds = FxIndexMap::default();
9346a6ac
AL
30 let mut lifetimes = Vec::new();
31 let mut equalities = Vec::new();
ff7c6d11 32
9346a6ac
AL
33 for clause in clauses {
34 match clause {
2b03887a
FG
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 }
9346a6ac
AL
40 WP::RegionPredicate { lifetime, bounds } => {
41 lifetimes.push((lifetime, bounds));
42 }
2b03887a 43 WP::EqPredicate { lhs, rhs, bound_params } => equalities.push((lhs, rhs, bound_params)),
9346a6ac
AL
44 }
45 }
46
9346a6ac 47 // Look for equality predicates on associated types that can be merged into
2b03887a
FG
48 // general bound predicates.
49 equalities.retain(|&(ref lhs, ref rhs, ref bound_params)| {
50 let Some((ty, trait_did, name)) = lhs.projection() else { return true; };
51 let Some((bounds, _)) = tybounds.get_mut(ty) else { return true };
52 let bound_params = bound_params
53 .into_iter()
487cf647 54 .map(|param| clean::GenericParamDef::lifetime(param.0))
2b03887a
FG
55 .collect();
56 merge_bounds(cx, bounds, bound_params, trait_did, name, rhs)
9346a6ac
AL
57 });
58
59 // And finally, let's reassemble everything
487cf647 60 let mut clauses = ThinVec::with_capacity(lifetimes.len() + tybounds.len() + equalities.len());
dfeec247
XL
61 clauses.extend(
62 lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
63 );
136023e0
XL
64 clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
65 ty,
66 bounds,
67 bound_params,
68 }));
2b03887a
FG
69 clauses.extend(equalities.into_iter().map(|(lhs, rhs, bound_params)| WP::EqPredicate {
70 lhs,
71 rhs,
72 bound_params,
73 }));
9346a6ac
AL
74 clauses
75}
76
923072b8 77pub(crate) fn merge_bounds(
e1599b0c
XL
78 cx: &clean::DocContext<'_>,
79 bounds: &mut Vec<clean::GenericBound>,
2b03887a 80 mut bound_params: Vec<clean::GenericParamDef>,
e1599b0c 81 trait_did: DefId,
5e7ed085 82 assoc: clean::PathSegment,
5099ac24 83 rhs: &clean::Term,
e1599b0c
XL
84) -> bool {
85 !bounds.iter_mut().any(|b| {
86 let trait_ref = match *b {
87 clean::GenericBound::TraitBound(ref mut tr, _) => tr,
88 clean::GenericBound::Outlives(..) => return false,
89 };
e1599b0c
XL
90 // If this QPath's trait `trait_did` is the same as, or a supertrait
91 // of, the bound's trait `did` then we can keep going, otherwise
92 // this is just a plain old equality bound.
c295e0f8 93 if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
dfeec247 94 return false;
e1599b0c 95 }
c295e0f8 96 let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
2b03887a
FG
97
98 trait_ref.generic_params.append(&mut bound_params);
487cf647
FG
99 // Sort parameters (likely) originating from a hashset alphabetically to
100 // produce predictable output (and to allow for full deduplication).
2b03887a
FG
101 trait_ref.generic_params.sort_unstable_by(|p, q| p.name.as_str().cmp(q.name.as_str()));
102 trait_ref.generic_params.dedup_by_key(|p| p.name);
103
e1599b0c
XL
104 match last.args {
105 PP::AngleBracketed { ref mut bindings, .. } => {
106 bindings.push(clean::TypeBinding {
5e7ed085 107 assoc: assoc.clone(),
5099ac24 108 kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
e1599b0c
XL
109 });
110 }
e74abb32 111 PP::Parenthesized { ref mut output, .. } => match output {
5099ac24 112 Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
dfeec247 113 None => {
5099ac24
FG
114 if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
115 *output = Some(Box::new(rhs.ty().unwrap().clone()));
dfeec247 116 }
e1599b0c 117 }
dfeec247 118 },
e1599b0c
XL
119 };
120 true
121 })
122}
123
dfeec247 124fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
9346a6ac 125 if child == trait_ {
dfeec247 126 return true;
9346a6ac 127 }
a1dfa0c6 128 let predicates = cx.tcx.super_predicates_of(child);
e1599b0c
XL
129 debug_assert!(cx.tcx.generics_of(child).has_self);
130 let self_ty = cx.tcx.types.self_param;
dfeec247
XL
131 predicates
132 .predicates
133 .iter()
134 .filter_map(|(pred, _)| {
487cf647 135 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) = pred.kind().skip_binder() {
3dfed10e 136 if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
9e0c209e
SL
137 } else {
138 None
9346a6ac 139 }
dfeec247
XL
140 })
141 .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
9346a6ac 142}