]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/simplify.rs
Rollup merge of #92134 - nico-abram:patch-1, r=michaelwoerister
[rust.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 rustc_span::Symbol;
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 crate fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<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 params: FxIndexMap<Symbol, (Vec<_>, Vec<_>)> = FxIndexMap::default();
30     let mut lifetimes = Vec::new();
31     let mut equalities = Vec::new();
32     let mut tybounds = Vec::new();
33
34     for clause in clauses {
35         match clause {
36             WP::BoundPredicate { ty, bounds, bound_params } => match ty {
37                 clean::Generic(s) => {
38                     let (b, p) = params.entry(s).or_default();
39                     b.extend(bounds);
40                     p.extend(bound_params);
41                 }
42                 t => tybounds.push((t, (bounds, bound_params))),
43             },
44             WP::RegionPredicate { lifetime, bounds } => {
45                 lifetimes.push((lifetime, bounds));
46             }
47             WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
48         }
49     }
50
51     // Look for equality predicates on associated types that can be merged into
52     // general bound predicates
53     equalities.retain(|&(ref lhs, ref rhs)| {
54         let (self_, trait_did, name) = if let Some(p) = lhs.projection() {
55             p
56         } else {
57             return true;
58         };
59         let generic = match self_ {
60             clean::Generic(s) => s,
61             _ => return true,
62         };
63         let (bounds, _) = match params.get_mut(generic) {
64             Some(bound) => bound,
65             None => return true,
66         };
67
68         merge_bounds(cx, bounds, trait_did, name, rhs)
69     });
70
71     // And finally, let's reassemble everything
72     let mut clauses = Vec::new();
73     clauses.extend(
74         lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }),
75     );
76     clauses.extend(params.into_iter().map(|(k, (bounds, params))| WP::BoundPredicate {
77         ty: clean::Generic(k),
78         bounds,
79         bound_params: params,
80     }));
81     clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate {
82         ty,
83         bounds,
84         bound_params,
85     }));
86     clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs }));
87     clauses
88 }
89
90 crate fn merge_bounds(
91     cx: &clean::DocContext<'_>,
92     bounds: &mut Vec<clean::GenericBound>,
93     trait_did: DefId,
94     name: Symbol,
95     rhs: &clean::Term,
96 ) -> bool {
97     !bounds.iter_mut().any(|b| {
98         let trait_ref = match *b {
99             clean::GenericBound::TraitBound(ref mut tr, _) => tr,
100             clean::GenericBound::Outlives(..) => return false,
101         };
102         // If this QPath's trait `trait_did` is the same as, or a supertrait
103         // of, the bound's trait `did` then we can keep going, otherwise
104         // this is just a plain old equality bound.
105         if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) {
106             return false;
107         }
108         let last = trait_ref.trait_.segments.last_mut().expect("segments were empty");
109         match last.args {
110             PP::AngleBracketed { ref mut bindings, .. } => {
111                 bindings.push(clean::TypeBinding {
112                     name,
113                     kind: clean::TypeBindingKind::Equality { term: rhs.clone() },
114                 });
115             }
116             PP::Parenthesized { ref mut output, .. } => match output {
117                 Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs),
118                 None => {
119                     if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) {
120                         *output = Some(Box::new(rhs.ty().unwrap().clone()));
121                     }
122                 }
123             },
124         };
125         true
126     })
127 }
128
129 fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool {
130     if child == trait_ {
131         return true;
132     }
133     let predicates = cx.tcx.super_predicates_of(child);
134     debug_assert!(cx.tcx.generics_of(child).has_self);
135     let self_ty = cx.tcx.types.self_param;
136     predicates
137         .predicates
138         .iter()
139         .filter_map(|(pred, _)| {
140             if let ty::PredicateKind::Trait(pred) = pred.kind().skip_binder() {
141                 if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None }
142             } else {
143                 None
144             }
145         })
146         .any(|did| trait_is_same_or_supertrait(cx, did, trait_))
147 }