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