]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/simplify.rs
2142d6de5da5dce58783e5f54265d23281bb18e6
[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, ty_bounds(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     // Simplify the type parameter bounds on all the generics
49     let mut params = params.into_iter().map(|(k, v)| {
50         (k, ty_bounds(v))
51     }).collect::<BTreeMap<_, _>>();
52
53     // Look for equality predicates on associated types that can be merged into
54     // general bound predicates
55     equalities.retain(|&(ref lhs, ref rhs)| {
56         let (self_, trait_did, name) = if let Some(p) = lhs.projection() {
57             p
58         } else {
59             return true;
60         };
61         let generic = match self_ {
62             clean::Generic(s) => s,
63             _ => return true,
64         };
65         let bounds = match params.get_mut(generic) {
66             Some(bound) => bound,
67             None => return true,
68         };
69
70         merge_bounds(cx, bounds, trait_did, name, rhs)
71     });
72
73     // And finally, let's reassemble everything
74     let mut clauses = Vec::new();
75     clauses.extend(lifetimes.into_iter().map(|(lt, bounds)| {
76         WP::RegionPredicate { lifetime: lt, bounds: bounds }
77     }));
78     clauses.extend(params.into_iter().map(|(k, v)| {
79         WP::BoundPredicate {
80             ty: clean::Generic(k),
81             bounds: v,
82         }
83     }));
84     clauses.extend(tybounds.into_iter().map(|(ty, bounds)| {
85         WP::BoundPredicate { ty: ty, bounds: bounds }
86     }));
87     clauses.extend(equalities.into_iter().map(|(lhs, rhs)| {
88         WP::EqPredicate { lhs: lhs, rhs: rhs }
89     }));
90     clauses
91 }
92
93 pub fn merge_bounds(
94     cx: &clean::DocContext<'_>,
95     bounds: &mut Vec<clean::GenericBound>,
96     trait_did: DefId,
97     name: &str,
98     rhs: &clean::Type,
99 ) -> bool {
100     !bounds.iter_mut().any(|b| {
101         let trait_ref = match *b {
102             clean::GenericBound::TraitBound(ref mut tr, _) => tr,
103             clean::GenericBound::Outlives(..) => return false,
104         };
105         let (did, path) = match trait_ref.trait_ {
106             clean::ResolvedPath { did, ref mut path, ..} => (did, path),
107             _ => return false,
108         };
109         // If this QPath's trait `trait_did` is the same as, or a supertrait
110         // of, the bound's trait `did` then we can keep going, otherwise
111         // this is just a plain old equality bound.
112         if !trait_is_same_or_supertrait(cx, did, trait_did) {
113             return false
114         }
115         let last = path.segments.last_mut().expect("segments were empty");
116         match last.args {
117             PP::AngleBracketed { ref mut bindings, .. } => {
118                 bindings.push(clean::TypeBinding {
119                     name: name.to_string(),
120                     kind: clean::TypeBindingKind::Equality {
121                         ty: rhs.clone(),
122                     },
123                 });
124             }
125             PP::Parenthesized { ref mut output, .. } => match output {
126                 Some(o) => assert!(o == rhs),
127                 None => if *rhs != clean::Type::Tuple(Vec::new()) {
128                     *output = Some(rhs.clone());
129                 }
130             }
131         };
132         true
133     })
134 }
135
136 pub fn ty_params(mut params: Vec<clean::GenericParamDef>) -> Vec<clean::GenericParamDef> {
137     for param in &mut params {
138         match param.kind {
139             clean::GenericParamDefKind::Type { ref mut bounds, .. } => {
140                 *bounds = ty_bounds(mem::take(bounds));
141             }
142             _ => panic!("expected only type parameters"),
143         }
144     }
145     params
146 }
147
148 fn ty_bounds(bounds: Vec<clean::GenericBound>) -> Vec<clean::GenericBound> {
149     bounds
150 }
151
152 fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId,
153                                trait_: DefId) -> bool {
154     if child == trait_ {
155         return true
156     }
157     let predicates = cx.tcx.super_predicates_of(child);
158     debug_assert!(cx.tcx.generics_of(child).has_self);
159     let self_ty = cx.tcx.types.self_param;
160     predicates.predicates.iter().filter_map(|(pred, _)| {
161         if let ty::Predicate::Trait(ref pred) = *pred {
162             if pred.skip_binder().trait_ref.self_ty() == self_ty {
163                 Some(pred.def_id())
164             } else {
165                 None
166             }
167         } else {
168             None
169         }
170     }).any(|did| trait_is_same_or_supertrait(cx, did, trait_))
171 }