]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/clean/simplify.rs
New upstream version 1.66.0+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;
9346a6ac 17
dfeec247 18use crate::clean;
9fa01778
XL
19use crate::clean::GenericArgs as PP;
20use crate::clean::WherePredicate as WP;
9fa01778 21use crate::core::DocContext;
9346a6ac 22
923072b8 23pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
c295e0f8
XL
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.
2b03887a 28 let mut tybounds = FxIndexMap::default();
9346a6ac
AL
29 let mut lifetimes = Vec::new();
30 let mut equalities = Vec::new();
ff7c6d11 31
9346a6ac
AL
32 for clause in clauses {
33 match clause {
2b03887a
FG
34 WP::BoundPredicate { ty, bounds, bound_params } => {
35 let (b, p): &mut (Vec<_>, Vec<_>) = tybounds.entry(ty).or_default();
36 b.extend(bounds);
37 p.extend(bound_params);
38 }
9346a6ac
AL
39 WP::RegionPredicate { lifetime, bounds } => {
40 lifetimes.push((lifetime, bounds));
41 }
2b03887a 42 WP::EqPredicate { lhs, rhs, bound_params } => equalities.push((lhs, rhs, bound_params)),
9346a6ac
AL
43 }
44 }
45
9346a6ac 46 // Look for equality predicates on associated types that can be merged into
2b03887a
FG
47 // general bound predicates.
48 equalities.retain(|&(ref lhs, ref rhs, ref bound_params)| {
49 let Some((ty, trait_did, name)) = lhs.projection() else { return true; };
50 let Some((bounds, _)) = tybounds.get_mut(ty) else { return true };
51 let bound_params = bound_params
52 .into_iter()
53 .map(|param| clean::GenericParamDef {
54 name: param.0,
55 kind: clean::GenericParamDefKind::Lifetime { outlives: Vec::new() },
56 })
57 .collect();
58 merge_bounds(cx, bounds, bound_params, trait_did, name, rhs)
9346a6ac
AL
59 });
60
61 // And finally, let's reassemble everything
62 let mut clauses = Vec::new();
dfeec247
XL
63 clauses.extend(
64 lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
65 );
136023e0
XL
66 clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
67 ty,
68 bounds,
69 bound_params,
70 }));
2b03887a
FG
71 clauses.extend(equalities.into_iter().map(|(lhs, rhs, bound_params)| WP::EqPredicate {
72 lhs,
73 rhs,
74 bound_params,
75 }));
9346a6ac
AL
76 clauses
77}
78
923072b8 79pub(crate) fn merge_bounds(
e1599b0c
XL
80 cx: &clean::DocContext<'_>,
81 bounds: &mut Vec<clean::GenericBound>,
2b03887a 82 mut bound_params: Vec<clean::GenericParamDef>,
e1599b0c 83 trait_did: DefId,
5e7ed085 84 assoc: clean::PathSegment,
5099ac24 85 rhs: &clean::Term,
e1599b0c
XL
86) -> bool {
87 !bounds.iter_mut().any(|b| {
88 let trait_ref = match *b {
89 clean::GenericBound::TraitBound(ref mut tr, _) => tr,
90 clean::GenericBound::Outlives(..) => return false,
91 };
e1599b0c
XL
92 // If this QPath's trait `trait_did` is the same as, or a supertrait
93 // of, the bound's trait `did` then we can keep going, otherwise
94 // this is just a plain old equality bound.
c295e0f8 95 if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
dfeec247 96 return false;
e1599b0c 97 }
c295e0f8 98 let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
2b03887a
FG
99
100 trait_ref.generic_params.append(&mut bound_params);
101 // Since the parameters (probably) originate from `tcx.collect_*_late_bound_regions` which
102 // returns a hash set, sort them alphabetically to guarantee a stable and deterministic
103 // output (and to fully deduplicate them).
104 trait_ref.generic_params.sort_unstable_by(|p, q| p.name.as_str().cmp(q.name.as_str()));
105 trait_ref.generic_params.dedup_by_key(|p| p.name);
106
e1599b0c
XL
107 match last.args {
108 PP::AngleBracketed { ref mut bindings, .. } => {
109 bindings.push(clean::TypeBinding {
5e7ed085 110 assoc: assoc.clone(),
5099ac24 111 kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
e1599b0c
XL
112 });
113 }
e74abb32 114 PP::Parenthesized { ref mut output, .. } => match output {
5099ac24 115 Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
dfeec247 116 None => {
5099ac24
FG
117 if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
118 *output = Some(Box::new(rhs.ty().unwrap().clone()));
dfeec247 119 }
e1599b0c 120 }
dfeec247 121 },
e1599b0c
XL
122 };
123 true
124 })
125}
126
dfeec247 127fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
9346a6ac 128 if child == trait_ {
dfeec247 129 return true;
9346a6ac 130 }
a1dfa0c6 131 let predicates = cx.tcx.super_predicates_of(child);
e1599b0c
XL
132 debug_assert!(cx.tcx.generics_of(child).has_self);
133 let self_ty = cx.tcx.types.self_param;
dfeec247
XL
134 predicates
135 .predicates
136 .iter()
137 .filter_map(|(pred, _)| {
94222f64 138 if let ty::PredicateKind::Trait(pred) = pred.kind().skip_binder() {
3dfed10e 139 if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
9e0c209e
SL
140 } else {
141 None
9346a6ac 142 }
dfeec247
XL
143 })
144 .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
9346a6ac 145}