]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/simplify.rs
Rollup merge of #64851 - Mark-Simulacrum:mailmap-update, r=varkor
[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::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 std::mem;
15 use std::collections::BTreeMap;
16
17 use rustc::hir::def_id::DefId;
18 use rustc::ty;
19
20 use crate::clean::GenericArgs as PP;
21 use crate::clean::WherePredicate as WP;
22 use crate::clean;
23 use crate::core::DocContext;
24
25 pub fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> Vec<WP> {
26     // First, partition the where clause into its separate components
27     let mut params: BTreeMap<_, Vec<_>> = BTreeMap::new();
28     let mut lifetimes = Vec::new();
29     let mut equalities = Vec::new();
30     let mut tybounds = Vec::new();
31
32     for clause in clauses {
33         match clause {
34             WP::BoundPredicate { ty, bounds } => {
35                 match ty {
36                     clean::Generic(s) => params.entry(s).or_default()
37                                                .extend(bounds),
38                     t => tybounds.push((t, bounds)),
39                 }
40             }
41             WP::RegionPredicate { lifetime, bounds } => {
42                 lifetimes.push((lifetime, bounds));
43             }
44             WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)),
45         }
46     }
47
48     // Look for equality predicates on associated types that can be merged into
49     // general bound predicates
50     equalities.retain(|&(ref lhs, ref rhs)| {
51         let (self_, trait_did, name) = if let Some(p) = lhs.projection() {
52             p
53         } else {
54             return true;
55         };
56         let generic = match self_ {
57             clean::Generic(s) => s,
58             _ => return true,
59         };
60         let bounds = match params.get_mut(generic) {
61             Some(bound) => bound,
62             None => return true,
63         };
64
65         merge_bounds(cx, bounds, trait_did, name, rhs)
66     });
67
68     // And finally, let's reassemble everything
69     let mut clauses = Vec::new();
70     clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
71         WP::RegionPredicate { lifetime: lt, bounds }
72     }));
73     clauses.extend(params.into_iter().map(|(k, v)| {
74         WP::BoundPredicate {
75             ty: clean::Generic(k),
76             bounds: v,
77         }
78     }));
79     clauses.extend(tybounds.into_iter().map(|(ty, bounds)| {
80         WP::BoundPredicate { ty, bounds }
81     }));
82     clauses.extend(equalities.into_iter().map(|(lhs, rhs)| {
83         WP::EqPredicate { lhs, rhs }
84     }));
85     clauses
86 }
87
88 pub fn merge_bounds(
89     cx: &clean::DocContext<'_>,
90     bounds: &mut Vec<clean::GenericBound>,
91     trait_did: DefId,
92     name: &str,
93     rhs: &clean::Type,
94 ) -> bool {
95     !bounds.iter_mut().any(|b| {
96         let trait_ref = match *b {
97             clean::GenericBound::TraitBound(ref mut tr, _) => tr,
98             clean::GenericBound::Outlives(..) => return false,
99         };
100         let (did, path) = match trait_ref.trait_ {
101             clean::ResolvedPath { did, ref mut path, ..} => (did, path),
102             _ => return false,
103         };
104         // If this QPath's trait `trait_did` is the same as, or a supertrait
105         // of, the bound's trait `did` then we can keep going, otherwise
106         // this is just a plain old equality bound.
107         if !trait_is_same_or_supertrait(cx, did, trait_did) {
108             return false
109         }
110         let last = path.segments.last_mut().expect("segments were empty");
111         match last.args {
112             PP::AngleBracketed { ref mut bindings, .. } => {
113                 bindings.push(clean::TypeBinding {
114                     name: name.to_string(),
115                     kind: clean::TypeBindingKind::Equality {
116                         ty: rhs.clone(),
117                     },
118                 });
119             }
120             PP::Parenthesized { ref mut output, .. } => match output {
121                 Some(o) => assert_eq!(o, rhs),
122                 None => if *rhs != clean::Type::Tuple(Vec::new()) {
123                     *output = Some(rhs.clone());
124                 }
125             }
126         };
127         true
128     })
129 }
130
131 pub fn ty_params(mut params: Vec<clean::GenericParamDef>) -> Vec<clean::GenericParamDef> {
132     for param in &mut params {
133         match param.kind {
134             clean::GenericParamDefKind::Type { ref mut bounds, .. } => {
135                 *bounds = mem::take(bounds);
136             }
137             _ => panic!("expected only type parameters"),
138         }
139     }
140     params
141 }
142
143 fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId,
144                                trait_: DefId) -> bool {
145     if child == trait_ {
146         return true
147     }
148     let predicates = cx.tcx.super_predicates_of(child);
149     debug_assert!(cx.tcx.generics_of(child).has_self);
150     let self_ty = cx.tcx.types.self_param;
151     predicates.predicates.iter().filter_map(|(pred, _)| {
152         if let ty::Predicate::Trait(ref pred) = *pred {
153             if pred.skip_binder().trait_ref.self_ty() == self_ty {
154                 Some(pred.def_id())
155             } else {
156                 None
157             }
158         } else {
159             None
160         }
161     }).any(|did| trait_is_same_or_supertrait(cx, did, trait_))
162 }