]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
55c3e9e4a244aaa1817089d34753b66b0fd41455
[rust.git] / src / librustdoc / clean / mod.rs
1 //! This module contains the "cleaned" pieces of the AST, and the functions
2 //! that clean them.
3
4 pub mod inline;
5 pub mod cfg;
6 pub mod utils;
7 mod auto_trait;
8 mod blanket_impl;
9 mod simplify;
10 pub mod types;
11
12 use rustc_index::vec::{IndexVec, Idx};
13 use rustc_typeck::hir_ty_to_ty;
14 use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
15 use rustc::middle::resolve_lifetime as rl;
16 use rustc::middle::lang_items;
17 use rustc::middle::stability;
18 use rustc::mir::interpret::GlobalId;
19 use rustc::hir;
20 use rustc::hir::def::{CtorKind, DefKind, Res};
21 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
22 use rustc::hir::ptr::P;
23 use rustc::ty::subst::InternalSubsts;
24 use rustc::ty::{self, TyCtxt, Ty, AdtKind};
25 use rustc::ty::fold::TypeFolder;
26 use rustc::util::nodemap::{FxHashMap, FxHashSet};
27 use syntax::ast::{self, Ident};
28 use syntax::attr;
29 use syntax_pos::symbol::{kw, sym};
30 use syntax_pos::hygiene::MacroKind;
31 use syntax_pos::{self, Pos};
32
33 use std::collections::hash_map::Entry;
34 use std::hash::Hash;
35 use std::default::Default;
36 use std::{mem, vec};
37 use std::rc::Rc;
38 use std::u32;
39
40 use crate::core::{self, DocContext, ImplTraitParam};
41 use crate::doctree;
42
43 use utils::*;
44
45 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
46
47 pub use self::types::*;
48 pub use self::types::Type::*;
49 pub use self::types::Mutability::*;
50 pub use self::types::ItemEnum::*;
51 pub use self::types::SelfTy::*;
52 pub use self::types::FunctionRetTy::*;
53 pub use self::types::Visibility::{Public, Inherited};
54
55 const FN_OUTPUT_NAME: &'static str = "Output";
56
57 pub trait Clean<T> {
58     fn clean(&self, cx: &DocContext<'_>) -> T;
59 }
60
61 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
62     fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
63         self.iter().map(|x| x.clean(cx)).collect()
64     }
65 }
66
67 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
68     fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
69         self.iter().map(|x| x.clean(cx)).collect()
70     }
71 }
72
73 impl<T: Clean<U>, U> Clean<U> for &T {
74     fn clean(&self, cx: &DocContext<'_>) -> U {
75         (**self).clean(cx)
76     }
77 }
78
79 impl<T: Clean<U>, U> Clean<U> for P<T> {
80     fn clean(&self, cx: &DocContext<'_>) -> U {
81         (**self).clean(cx)
82     }
83 }
84
85 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
86     fn clean(&self, cx: &DocContext<'_>) -> U {
87         (**self).clean(cx)
88     }
89 }
90
91 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
92     fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
93         self.as_ref().map(|v| v.clean(cx))
94     }
95 }
96
97 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
98     fn clean(&self, cx: &DocContext<'_>) -> U {
99         self.skip_binder().clean(cx)
100     }
101 }
102
103 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
104     fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
105         self.iter().map(|x| x.clean(cx)).collect()
106     }
107 }
108
109 impl Clean<ExternalCrate> for CrateNum {
110     fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
111         let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
112         let krate_span = cx.tcx.def_span(root);
113         let krate_src = cx.sess().source_map().span_to_filename(krate_span);
114
115         // Collect all inner modules which are tagged as implementations of
116         // primitives.
117         //
118         // Note that this loop only searches the top-level items of the crate,
119         // and this is intentional. If we were to search the entire crate for an
120         // item tagged with `#[doc(primitive)]` then we would also have to
121         // search the entirety of external modules for items tagged
122         // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
123         // all that metadata unconditionally).
124         //
125         // In order to keep the metadata load under control, the
126         // `#[doc(primitive)]` feature is explicitly designed to only allow the
127         // primitive tags to show up as the top level items in a crate.
128         //
129         // Also note that this does not attempt to deal with modules tagged
130         // duplicately for the same primitive. This is handled later on when
131         // rendering by delegating everything to a hash map.
132         let as_primitive = |res: Res| {
133             if let Res::Def(DefKind::Mod, def_id) = res {
134                 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
135                 let mut prim = None;
136                 for attr in attrs.lists(sym::doc) {
137                     if let Some(v) = attr.value_str() {
138                         if attr.check_name(sym::primitive) {
139                             prim = PrimitiveType::from_str(&v.as_str());
140                             if prim.is_some() {
141                                 break;
142                             }
143                             // FIXME: should warn on unknown primitives?
144                         }
145                     }
146                 }
147                 return prim.map(|p| (def_id, p, attrs));
148             }
149             None
150         };
151         let primitives = if root.is_local() {
152             cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
153                 let item = cx.tcx.hir().expect_item(id.id);
154                 match item.kind {
155                     hir::ItemKind::Mod(_) => {
156                         as_primitive(Res::Def(
157                             DefKind::Mod,
158                             cx.tcx.hir().local_def_id(id.id),
159                         ))
160                     }
161                     hir::ItemKind::Use(ref path, hir::UseKind::Single)
162                     if item.vis.node.is_pub() => {
163                         as_primitive(path.res).map(|(_, prim, attrs)| {
164                             // Pretend the primitive is local.
165                             (cx.tcx.hir().local_def_id(id.id), prim, attrs)
166                         })
167                     }
168                     _ => None
169                 }
170             }).collect()
171         } else {
172             cx.tcx.item_children(root).iter().map(|item| item.res)
173               .filter_map(as_primitive).collect()
174         };
175
176         let as_keyword = |res: Res| {
177             if let Res::Def(DefKind::Mod, def_id) = res {
178                 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
179                 let mut keyword = None;
180                 for attr in attrs.lists(sym::doc) {
181                     if let Some(v) = attr.value_str() {
182                         if attr.check_name(sym::keyword) {
183                             if v.is_doc_keyword() {
184                                 keyword = Some(v.to_string());
185                                 break;
186                             }
187                             // FIXME: should warn on unknown keywords?
188                         }
189                     }
190                 }
191                 return keyword.map(|p| (def_id, p, attrs));
192             }
193             None
194         };
195         let keywords = if root.is_local() {
196             cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
197                 let item = cx.tcx.hir().expect_item(id.id);
198                 match item.kind {
199                     hir::ItemKind::Mod(_) => {
200                         as_keyword(Res::Def(
201                             DefKind::Mod,
202                             cx.tcx.hir().local_def_id(id.id),
203                         ))
204                     }
205                     hir::ItemKind::Use(ref path, hir::UseKind::Single)
206                     if item.vis.node.is_pub() => {
207                         as_keyword(path.res).map(|(_, prim, attrs)| {
208                             (cx.tcx.hir().local_def_id(id.id), prim, attrs)
209                         })
210                     }
211                     _ => None
212                 }
213             }).collect()
214         } else {
215             cx.tcx.item_children(root).iter().map(|item| item.res)
216               .filter_map(as_keyword).collect()
217         };
218
219         ExternalCrate {
220             name: cx.tcx.crate_name(*self).to_string(),
221             src: krate_src,
222             attrs: cx.tcx.get_attrs(root).clean(cx),
223             primitives,
224             keywords,
225         }
226     }
227 }
228
229 impl Clean<Item> for doctree::Module<'_> {
230     fn clean(&self, cx: &DocContext<'_>) -> Item {
231         let name = if self.name.is_some() {
232             self.name.expect("No name provided").clean(cx)
233         } else {
234             String::new()
235         };
236
237         // maintain a stack of mod ids, for doc comment path resolution
238         // but we also need to resolve the module's own docs based on whether its docs were written
239         // inside or outside the module, so check for that
240         let attrs = self.attrs.clean(cx);
241
242         let mut items: Vec<Item> = vec![];
243         items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
244         items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
245         items.extend(self.structs.iter().map(|x| x.clean(cx)));
246         items.extend(self.unions.iter().map(|x| x.clean(cx)));
247         items.extend(self.enums.iter().map(|x| x.clean(cx)));
248         items.extend(self.fns.iter().map(|x| x.clean(cx)));
249         items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
250         items.extend(self.mods.iter().map(|x| x.clean(cx)));
251         items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
252         items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
253         items.extend(self.statics.iter().map(|x| x.clean(cx)));
254         items.extend(self.constants.iter().map(|x| x.clean(cx)));
255         items.extend(self.traits.iter().map(|x| x.clean(cx)));
256         items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
257         items.extend(self.macros.iter().map(|x| x.clean(cx)));
258         items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
259         items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
260
261         // determine if we should display the inner contents or
262         // the outer `mod` item for the source code.
263         let whence = {
264             let cm = cx.sess().source_map();
265             let outer = cm.lookup_char_pos(self.where_outer.lo());
266             let inner = cm.lookup_char_pos(self.where_inner.lo());
267             if outer.file.start_pos == inner.file.start_pos {
268                 // mod foo { ... }
269                 self.where_outer
270             } else {
271                 // mod foo; (and a separate SourceFile for the contents)
272                 self.where_inner
273             }
274         };
275
276         Item {
277             name: Some(name),
278             attrs,
279             source: whence.clean(cx),
280             visibility: self.vis.clean(cx),
281             stability: cx.stability(self.id).clean(cx),
282             deprecation: cx.deprecation(self.id).clean(cx),
283             def_id: cx.tcx.hir().local_def_id(self.id),
284             inner: ModuleItem(Module {
285                is_crate: self.is_crate,
286                items,
287             })
288         }
289     }
290 }
291
292 impl Clean<Attributes> for [ast::Attribute] {
293     fn clean(&self, cx: &DocContext<'_>) -> Attributes {
294         Attributes::from_ast(cx.sess().diagnostic(), self)
295     }
296 }
297
298 impl Clean<GenericBound> for hir::GenericBound {
299     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
300         match *self {
301             hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
302             hir::GenericBound::Trait(ref t, modifier) => {
303                 GenericBound::TraitBound(t.clean(cx), modifier)
304             }
305         }
306     }
307 }
308
309 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
310     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
311         let (trait_ref, ref bounds) = *self;
312         inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
313         let path = external_path(cx, cx.tcx.item_name(trait_ref.def_id),
314                                  Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs);
315
316         debug!("ty::TraitRef\n  subst: {:?}\n", trait_ref.substs);
317
318         // collect any late bound regions
319         let mut late_bounds = vec![];
320         for ty_s in trait_ref.input_types().skip(1) {
321             if let ty::Tuple(ts) = ty_s.kind {
322                 for &ty_s in ts {
323                     if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
324                         if let &ty::RegionKind::ReLateBound(..) = *reg {
325                             debug!("  hit an ReLateBound {:?}", reg);
326                             if let Some(Lifetime(name)) = reg.clean(cx) {
327                                 late_bounds.push(GenericParamDef {
328                                     name,
329                                     kind: GenericParamDefKind::Lifetime,
330                                 });
331                             }
332                         }
333                     }
334                 }
335             }
336         }
337
338         GenericBound::TraitBound(
339             PolyTrait {
340                 trait_: ResolvedPath {
341                     path,
342                     param_names: None,
343                     did: trait_ref.def_id,
344                     is_generic: false,
345                 },
346                 generic_params: late_bounds,
347             },
348             hir::TraitBoundModifier::None
349         )
350     }
351 }
352
353 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
354     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
355         (self, vec![]).clean(cx)
356     }
357 }
358
359 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
360     fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
361         let mut v = Vec::new();
362         v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
363         v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
364             trait_: t.clean(cx),
365             generic_params: Vec::new(),
366         }, hir::TraitBoundModifier::None)));
367         if !v.is_empty() {Some(v)} else {None}
368     }
369 }
370
371 impl Clean<Lifetime> for hir::Lifetime {
372     fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
373         if self.hir_id != hir::DUMMY_HIR_ID {
374             let def = cx.tcx.named_region(self.hir_id);
375             match def {
376                 Some(rl::Region::EarlyBound(_, node_id, _)) |
377                 Some(rl::Region::LateBound(_, node_id, _)) |
378                 Some(rl::Region::Free(_, node_id)) => {
379                     if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
380                         return lt;
381                     }
382                 }
383                 _ => {}
384             }
385         }
386         Lifetime(self.name.ident().to_string())
387     }
388 }
389
390 impl Clean<Lifetime> for hir::GenericParam {
391     fn clean(&self, _: &DocContext<'_>) -> Lifetime {
392         match self.kind {
393             hir::GenericParamKind::Lifetime { .. } => {
394                 if self.bounds.len() > 0 {
395                     let mut bounds = self.bounds.iter().map(|bound| match bound {
396                         hir::GenericBound::Outlives(lt) => lt,
397                         _ => panic!(),
398                     });
399                     let name = bounds.next().expect("no more bounds").name.ident();
400                     let mut s = format!("{}: {}", self.name.ident(), name);
401                     for bound in bounds {
402                         s.push_str(&format!(" + {}", bound.name.ident()));
403                     }
404                     Lifetime(s)
405                 } else {
406                     Lifetime(self.name.ident().to_string())
407                 }
408             }
409             _ => panic!(),
410         }
411     }
412 }
413
414 impl Clean<Constant> for hir::ConstArg {
415     fn clean(&self, cx: &DocContext<'_>) -> Constant {
416         Constant {
417             type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
418             expr: print_const_expr(cx, self.value.body),
419         }
420     }
421 }
422
423 impl Clean<Lifetime> for ty::GenericParamDef {
424     fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
425         Lifetime(self.name.to_string())
426     }
427 }
428
429 impl Clean<Option<Lifetime>> for ty::RegionKind {
430     fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
431         match *self {
432             ty::ReStatic => Some(Lifetime::statik()),
433             ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
434             ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
435
436             ty::ReLateBound(..) |
437             ty::ReFree(..) |
438             ty::ReScope(..) |
439             ty::ReVar(..) |
440             ty::RePlaceholder(..) |
441             ty::ReEmpty |
442             ty::ReClosureBound(_) |
443             ty::ReErased => {
444                 debug!("cannot clean region {:?}", self);
445                 None
446             }
447         }
448     }
449 }
450
451 impl Clean<WherePredicate> for hir::WherePredicate {
452     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
453         match *self {
454             hir::WherePredicate::BoundPredicate(ref wbp) => {
455                 WherePredicate::BoundPredicate {
456                     ty: wbp.bounded_ty.clean(cx),
457                     bounds: wbp.bounds.clean(cx)
458                 }
459             }
460
461             hir::WherePredicate::RegionPredicate(ref wrp) => {
462                 WherePredicate::RegionPredicate {
463                     lifetime: wrp.lifetime.clean(cx),
464                     bounds: wrp.bounds.clean(cx)
465                 }
466             }
467
468             hir::WherePredicate::EqPredicate(ref wrp) => {
469                 WherePredicate::EqPredicate {
470                     lhs: wrp.lhs_ty.clean(cx),
471                     rhs: wrp.rhs_ty.clean(cx)
472                 }
473             }
474         }
475     }
476 }
477
478 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
479     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
480         use rustc::ty::Predicate;
481
482         match *self {
483             Predicate::Trait(ref pred) => Some(pred.clean(cx)),
484             Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
485             Predicate::RegionOutlives(ref pred) => pred.clean(cx),
486             Predicate::TypeOutlives(ref pred) => pred.clean(cx),
487             Predicate::Projection(ref pred) => Some(pred.clean(cx)),
488
489             Predicate::WellFormed(..) |
490             Predicate::ObjectSafe(..) |
491             Predicate::ClosureKind(..) |
492             Predicate::ConstEvaluatable(..) => panic!("not user writable"),
493         }
494     }
495 }
496
497 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
498     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
499         WherePredicate::BoundPredicate {
500             ty: self.trait_ref.self_ty().clean(cx),
501             bounds: vec![self.trait_ref.clean(cx)]
502         }
503     }
504 }
505
506 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
507     fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
508         panic!("subtype predicates are an internal rustc artifact \
509                 and should not be seen by rustdoc")
510     }
511 }
512
513 impl<'tcx> Clean<Option<WherePredicate>> for
514     ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> {
515
516     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
517         let ty::OutlivesPredicate(ref a, ref b) = *self;
518
519         match (a, b) {
520             (ty::ReEmpty, ty::ReEmpty) => {
521                 return None;
522             },
523             _ => {}
524         }
525
526         Some(WherePredicate::RegionPredicate {
527             lifetime: a.clean(cx).expect("failed to clean lifetime"),
528             bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))]
529         })
530     }
531 }
532
533 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
534     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
535         let ty::OutlivesPredicate(ref ty, ref lt) = *self;
536
537         match lt {
538             ty::ReEmpty => return None,
539             _ => {}
540         }
541
542         Some(WherePredicate::BoundPredicate {
543             ty: ty.clean(cx),
544             bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))]
545         })
546     }
547 }
548
549 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
550     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
551         WherePredicate::EqPredicate {
552             lhs: self.projection_ty.clean(cx),
553             rhs: self.ty.clean(cx)
554         }
555     }
556 }
557
558 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
559     fn clean(&self, cx: &DocContext<'_>) -> Type {
560         let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
561             GenericBound::TraitBound(t, _) => t.trait_,
562             GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
563         };
564         Type::QPath {
565             name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
566             self_type: box self.self_ty().clean(cx),
567             trait_: box trait_
568         }
569     }
570 }
571
572 impl Clean<GenericParamDef> for ty::GenericParamDef {
573     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
574         let (name, kind) = match self.kind {
575             ty::GenericParamDefKind::Lifetime => {
576                 (self.name.to_string(), GenericParamDefKind::Lifetime)
577             }
578             ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
579                 let default = if has_default {
580                     Some(cx.tcx.type_of(self.def_id).clean(cx))
581                 } else {
582                     None
583                 };
584                 (self.name.clean(cx), GenericParamDefKind::Type {
585                     did: self.def_id,
586                     bounds: vec![], // These are filled in from the where-clauses.
587                     default,
588                     synthetic,
589                 })
590             }
591             ty::GenericParamDefKind::Const { .. } => {
592                 (self.name.clean(cx), GenericParamDefKind::Const {
593                     did: self.def_id,
594                     ty: cx.tcx.type_of(self.def_id).clean(cx),
595                 })
596             }
597         };
598
599         GenericParamDef {
600             name,
601             kind,
602         }
603     }
604 }
605
606 impl Clean<GenericParamDef> for hir::GenericParam {
607     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
608         let (name, kind) = match self.kind {
609             hir::GenericParamKind::Lifetime { .. } => {
610                 let name = if self.bounds.len() > 0 {
611                     let mut bounds = self.bounds.iter().map(|bound| match bound {
612                         hir::GenericBound::Outlives(lt) => lt,
613                         _ => panic!(),
614                     });
615                     let name = bounds.next().expect("no more bounds").name.ident();
616                     let mut s = format!("{}: {}", self.name.ident(), name);
617                     for bound in bounds {
618                         s.push_str(&format!(" + {}", bound.name.ident()));
619                     }
620                     s
621                 } else {
622                     self.name.ident().to_string()
623                 };
624                 (name, GenericParamDefKind::Lifetime)
625             }
626             hir::GenericParamKind::Type { ref default, synthetic } => {
627                 (self.name.ident().name.clean(cx), GenericParamDefKind::Type {
628                     did: cx.tcx.hir().local_def_id(self.hir_id),
629                     bounds: self.bounds.clean(cx),
630                     default: default.clean(cx),
631                     synthetic,
632                 })
633             }
634             hir::GenericParamKind::Const { ref ty } => {
635                 (self.name.ident().name.clean(cx), GenericParamDefKind::Const {
636                     did: cx.tcx.hir().local_def_id(self.hir_id),
637                     ty: ty.clean(cx),
638                 })
639             }
640         };
641
642         GenericParamDef {
643             name,
644             kind,
645         }
646     }
647 }
648
649 impl Clean<Generics> for hir::Generics {
650     fn clean(&self, cx: &DocContext<'_>) -> Generics {
651         // Synthetic type-parameters are inserted after normal ones.
652         // In order for normal parameters to be able to refer to synthetic ones,
653         // scans them first.
654         fn is_impl_trait(param: &hir::GenericParam) -> bool {
655             match param.kind {
656                 hir::GenericParamKind::Type { synthetic, .. } => {
657                     synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
658                 }
659                 _ => false,
660             }
661         }
662         let impl_trait_params = self.params
663             .iter()
664             .filter(|param| is_impl_trait(param))
665             .map(|param| {
666                 let param: GenericParamDef = param.clean(cx);
667                 match param.kind {
668                     GenericParamDefKind::Lifetime => unreachable!(),
669                     GenericParamDefKind::Type { did, ref bounds, .. } => {
670                         cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
671                     }
672                     GenericParamDefKind::Const { .. } => unreachable!(),
673                 }
674                 param
675             })
676             .collect::<Vec<_>>();
677
678         let mut params = Vec::with_capacity(self.params.len());
679         for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
680             let p = p.clean(cx);
681             params.push(p);
682         }
683         params.extend(impl_trait_params);
684
685         let mut generics = Generics {
686             params,
687             where_predicates: self.where_clause.predicates.clean(cx),
688         };
689
690         // Some duplicates are generated for ?Sized bounds between type params and where
691         // predicates. The point in here is to move the bounds definitions from type params
692         // to where predicates when such cases occur.
693         for where_pred in &mut generics.where_predicates {
694             match *where_pred {
695                 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
696                     if bounds.is_empty() {
697                         for param in &mut generics.params {
698                             match param.kind {
699                                 GenericParamDefKind::Lifetime => {}
700                                 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
701                                     if &param.name == name {
702                                         mem::swap(bounds, ty_bounds);
703                                         break
704                                     }
705                                 }
706                                 GenericParamDefKind::Const { .. } => {}
707                             }
708                         }
709                     }
710                 }
711                 _ => continue,
712             }
713         }
714         generics
715     }
716 }
717
718 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
719     fn clean(&self, cx: &DocContext<'_>) -> Generics {
720         use self::WherePredicate as WP;
721         use std::collections::BTreeMap;
722
723         let (gens, preds) = *self;
724
725         // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
726         // since `Clean for ty::Predicate` would consume them.
727         let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
728
729         // Bounds in the type_params and lifetimes fields are repeated in the
730         // predicates field (see rustc_typeck::collect::ty_generics), so remove
731         // them.
732         let stripped_typarams = gens.params.iter()
733             .filter_map(|param| match param.kind {
734                 ty::GenericParamDefKind::Lifetime => None,
735                 ty::GenericParamDefKind::Type { synthetic, .. } => {
736                     if param.name == kw::SelfUpper {
737                         assert_eq!(param.index, 0);
738                         return None;
739                     }
740                     if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
741                         impl_trait.insert(param.index.into(), vec![]);
742                         return None;
743                     }
744                     Some(param.clean(cx))
745                 }
746                 ty::GenericParamDefKind::Const { .. } => None,
747             }).collect::<Vec<GenericParamDef>>();
748
749         // param index -> [(DefId of trait, associated type name, type)]
750         let mut impl_trait_proj =
751             FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
752
753         let where_predicates = preds.predicates.iter()
754             .flat_map(|(p, _)| {
755                 let mut projection = None;
756                 let param_idx = (|| {
757                     if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
758                         if let ty::Param(param) = trait_ref.self_ty().kind {
759                             return Some(param.index);
760                         }
761                     } else if let Some(outlives) = p.to_opt_type_outlives() {
762                         if let ty::Param(param) = outlives.skip_binder().0.kind {
763                             return Some(param.index);
764                         }
765                     } else if let ty::Predicate::Projection(p) = p {
766                         if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
767                             projection = Some(p);
768                             return Some(param.index);
769                         }
770                     }
771
772                     None
773                 })();
774
775                 if let Some(param_idx) = param_idx {
776                     if let Some(b) = impl_trait.get_mut(&param_idx.into()) {
777                         let p = p.clean(cx)?;
778
779                         b.extend(
780                             p.get_bounds()
781                                 .into_iter()
782                                 .flatten()
783                                 .cloned()
784                                 .filter(|b| !b.is_sized_bound(cx))
785                         );
786
787                         let proj = projection
788                             .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
789                         if let Some(((_, trait_did, name), rhs)) =
790                             proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
791                         {
792                             impl_trait_proj
793                                 .entry(param_idx)
794                                 .or_default()
795                                 .push((trait_did, name.to_string(), rhs));
796                         }
797
798                         return None;
799                     }
800                 }
801
802                 Some(p)
803             })
804             .collect::<Vec<_>>();
805
806         for (param, mut bounds) in impl_trait {
807             // Move trait bounds to the front.
808             bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b {
809                 false
810             } else {
811                 true
812             });
813
814             if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
815                 if let Some(proj) = impl_trait_proj.remove(&idx) {
816                     for (trait_did, name, rhs) in proj {
817                         simplify::merge_bounds(
818                             cx,
819                             &mut bounds,
820                             trait_did,
821                             &name,
822                             &rhs.clean(cx),
823                         );
824                     }
825                 }
826             } else {
827                 unreachable!();
828             }
829
830             cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
831         }
832
833         // Now that `cx.impl_trait_bounds` is populated, we can process
834         // remaining predicates which could contain `impl Trait`.
835         let mut where_predicates = where_predicates
836             .into_iter()
837             .flat_map(|p| p.clean(cx))
838             .collect::<Vec<_>>();
839
840         // Type parameters and have a Sized bound by default unless removed with
841         // ?Sized. Scan through the predicates and mark any type parameter with
842         // a Sized bound, removing the bounds as we find them.
843         //
844         // Note that associated types also have a sized bound by default, but we
845         // don't actually know the set of associated types right here so that's
846         // handled in cleaning associated types
847         let mut sized_params = FxHashSet::default();
848         where_predicates.retain(|pred| {
849             match *pred {
850                 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
851                     if bounds.iter().any(|b| b.is_sized_bound(cx)) {
852                         sized_params.insert(g.clone());
853                         false
854                     } else {
855                         true
856                     }
857                 }
858                 _ => true,
859             }
860         });
861
862         // Run through the type parameters again and insert a ?Sized
863         // unbound for any we didn't find to be Sized.
864         for tp in &stripped_typarams {
865             if !sized_params.contains(&tp.name) {
866                 where_predicates.push(WP::BoundPredicate {
867                     ty: Type::Generic(tp.name.clone()),
868                     bounds: vec![GenericBound::maybe_sized(cx)],
869                 })
870             }
871         }
872
873         // It would be nice to collect all of the bounds on a type and recombine
874         // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
875         // and instead see `where T: Foo + Bar + Sized + 'a`
876
877         Generics {
878             params: gens.params
879                         .iter()
880                         .flat_map(|param| match param.kind {
881                             ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
882                             ty::GenericParamDefKind::Type { .. } => None,
883                             ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
884                         }).chain(simplify::ty_params(stripped_typarams).into_iter())
885                         .collect(),
886             where_predicates: simplify::where_clauses(cx, where_predicates),
887         }
888     }
889 }
890
891 impl<'a> Clean<Method> for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId,
892                             Option<hir::Defaultness>) {
893     fn clean(&self, cx: &DocContext<'_>) -> Method {
894         let (generics, decl) = enter_impl_trait(cx, || {
895             (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
896         });
897         let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
898         Method {
899             decl,
900             generics,
901             header: self.0.header,
902             defaultness: self.3,
903             all_types,
904             ret_types,
905         }
906     }
907 }
908
909 impl Clean<Item> for doctree::Function<'_> {
910     fn clean(&self, cx: &DocContext<'_>) -> Item {
911         let (generics, decl) = enter_impl_trait(cx, || {
912             (self.generics.clean(cx), (self.decl, self.body).clean(cx))
913         });
914
915         let did = cx.tcx.hir().local_def_id(self.id);
916         let constness = if cx.tcx.is_min_const_fn(did) {
917             hir::Constness::Const
918         } else {
919             hir::Constness::NotConst
920         };
921         let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
922         Item {
923             name: Some(self.name.clean(cx)),
924             attrs: self.attrs.clean(cx),
925             source: self.whence.clean(cx),
926             visibility: self.vis.clean(cx),
927             stability: cx.stability(self.id).clean(cx),
928             deprecation: cx.deprecation(self.id).clean(cx),
929             def_id: did,
930             inner: FunctionItem(Function {
931                 decl,
932                 generics,
933                 header: hir::FnHeader { constness, ..self.header },
934                 all_types,
935                 ret_types,
936             }),
937         }
938     }
939 }
940
941 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
942     fn clean(&self, cx: &DocContext<'_>) -> Arguments {
943         Arguments {
944             values: self.0.iter().enumerate().map(|(i, ty)| {
945                 let mut name = self.1.get(i).map(|ident| ident.to_string())
946                                             .unwrap_or(String::new());
947                 if name.is_empty() {
948                     name = "_".to_string();
949                 }
950                 Argument {
951                     name,
952                     type_: ty.clean(cx),
953                 }
954             }).collect()
955         }
956     }
957 }
958
959 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
960     fn clean(&self, cx: &DocContext<'_>) -> Arguments {
961         let body = cx.tcx.hir().body(self.1);
962
963         Arguments {
964             values: self.0.iter().enumerate().map(|(i, ty)| {
965                 Argument {
966                     name: name_from_pat(&body.params[i].pat),
967                     type_: ty.clean(cx),
968                 }
969             }).collect()
970         }
971     }
972 }
973
974 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
975     where (&'a [hir::Ty], A): Clean<Arguments>
976 {
977     fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
978         FnDecl {
979             inputs: (&self.0.inputs[..], self.1).clean(cx),
980             output: self.0.output.clean(cx),
981             c_variadic: self.0.c_variadic,
982             attrs: Attributes::default(),
983         }
984     }
985 }
986
987 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
988     fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
989         let (did, sig) = *self;
990         let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
991             vec![].into_iter()
992         } else {
993             cx.tcx.fn_arg_names(did).into_iter()
994         };
995
996         FnDecl {
997             output: Return(sig.skip_binder().output().clean(cx)),
998             attrs: Attributes::default(),
999             c_variadic: sig.skip_binder().c_variadic,
1000             inputs: Arguments {
1001                 values: sig.skip_binder().inputs().iter().map(|t| {
1002                     Argument {
1003                         type_: t.clean(cx),
1004                         name: names.next().map_or(String::new(), |name| name.to_string()),
1005                     }
1006                 }).collect(),
1007             },
1008         }
1009     }
1010 }
1011
1012 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1013     fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1014         match *self {
1015             hir::Return(ref typ) => Return(typ.clean(cx)),
1016             hir::DefaultReturn(..) => DefaultReturn,
1017         }
1018     }
1019 }
1020
1021 impl Clean<Item> for doctree::Trait<'_> {
1022     fn clean(&self, cx: &DocContext<'_>) -> Item {
1023         let attrs = self.attrs.clean(cx);
1024         let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1025         Item {
1026             name: Some(self.name.clean(cx)),
1027             attrs,
1028             source: self.whence.clean(cx),
1029             def_id: cx.tcx.hir().local_def_id(self.id),
1030             visibility: self.vis.clean(cx),
1031             stability: cx.stability(self.id).clean(cx),
1032             deprecation: cx.deprecation(self.id).clean(cx),
1033             inner: TraitItem(Trait {
1034                 auto: self.is_auto.clean(cx),
1035                 unsafety: self.unsafety,
1036                 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1037                 generics: self.generics.clean(cx),
1038                 bounds: self.bounds.clean(cx),
1039                 is_spotlight,
1040                 is_auto: self.is_auto.clean(cx),
1041             }),
1042         }
1043     }
1044 }
1045
1046 impl Clean<Item> for doctree::TraitAlias<'_> {
1047     fn clean(&self, cx: &DocContext<'_>) -> Item {
1048         let attrs = self.attrs.clean(cx);
1049         Item {
1050             name: Some(self.name.clean(cx)),
1051             attrs,
1052             source: self.whence.clean(cx),
1053             def_id: cx.tcx.hir().local_def_id(self.id),
1054             visibility: self.vis.clean(cx),
1055             stability: cx.stability(self.id).clean(cx),
1056             deprecation: cx.deprecation(self.id).clean(cx),
1057             inner: TraitAliasItem(TraitAlias {
1058                 generics: self.generics.clean(cx),
1059                 bounds: self.bounds.clean(cx),
1060             }),
1061         }
1062     }
1063 }
1064
1065 impl Clean<bool> for hir::IsAuto {
1066     fn clean(&self, _: &DocContext<'_>) -> bool {
1067         match *self {
1068             hir::IsAuto::Yes => true,
1069             hir::IsAuto::No => false,
1070         }
1071     }
1072 }
1073
1074 impl Clean<Type> for hir::TraitRef {
1075     fn clean(&self, cx: &DocContext<'_>) -> Type {
1076         resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1077     }
1078 }
1079
1080 impl Clean<PolyTrait> for hir::PolyTraitRef {
1081     fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1082         PolyTrait {
1083             trait_: self.trait_ref.clean(cx),
1084             generic_params: self.bound_generic_params.clean(cx)
1085         }
1086     }
1087 }
1088
1089 impl Clean<Item> for hir::TraitItem<'_> {
1090     fn clean(&self, cx: &DocContext<'_>) -> Item {
1091         let inner = match self.kind {
1092             hir::TraitItemKind::Const(ref ty, default) => {
1093                 AssocConstItem(ty.clean(cx),
1094                                     default.map(|e| print_const_expr(cx, e)))
1095             }
1096             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1097                 MethodItem((sig, &self.generics, body, None).clean(cx))
1098             }
1099             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1100                 let (generics, decl) = enter_impl_trait(cx, || {
1101                     (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1102                 });
1103                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1104                 TyMethodItem(TyMethod {
1105                     header: sig.header,
1106                     decl,
1107                     generics,
1108                     all_types,
1109                     ret_types,
1110                 })
1111             }
1112             hir::TraitItemKind::Type(ref bounds, ref default) => {
1113                 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1114             }
1115         };
1116         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1117         Item {
1118             name: Some(self.ident.name.clean(cx)),
1119             attrs: self.attrs.clean(cx),
1120             source: self.span.clean(cx),
1121             def_id: local_did,
1122             visibility: Visibility::Inherited,
1123             stability: get_stability(cx, local_did),
1124             deprecation: get_deprecation(cx, local_did),
1125             inner,
1126         }
1127     }
1128 }
1129
1130 impl Clean<Item> for hir::ImplItem<'_> {
1131     fn clean(&self, cx: &DocContext<'_>) -> Item {
1132         let inner = match self.kind {
1133             hir::ImplItemKind::Const(ref ty, expr) => {
1134                 AssocConstItem(ty.clean(cx),
1135                                     Some(print_const_expr(cx, expr)))
1136             }
1137             hir::ImplItemKind::Method(ref sig, body) => {
1138                 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1139             }
1140             hir::ImplItemKind::TyAlias(ref ty) => TypedefItem(Typedef {
1141                 type_: ty.clean(cx),
1142                 generics: Generics::default(),
1143             }, true),
1144             hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(OpaqueTy {
1145                 bounds: bounds.clean(cx),
1146                 generics: Generics::default(),
1147             }, true),
1148         };
1149         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1150         Item {
1151             name: Some(self.ident.name.clean(cx)),
1152             source: self.span.clean(cx),
1153             attrs: self.attrs.clean(cx),
1154             def_id: local_did,
1155             visibility: self.vis.clean(cx),
1156             stability: get_stability(cx, local_did),
1157             deprecation: get_deprecation(cx, local_did),
1158             inner,
1159         }
1160     }
1161 }
1162
1163 impl Clean<Item> for ty::AssocItem {
1164     fn clean(&self, cx: &DocContext<'_>) -> Item {
1165         let inner = match self.kind {
1166             ty::AssocKind::Const => {
1167                 let ty = cx.tcx.type_of(self.def_id);
1168                 let default = if self.defaultness.has_value() {
1169                     Some(inline::print_inlined_const(cx, self.def_id))
1170                 } else {
1171                     None
1172                 };
1173                 AssocConstItem(ty.clean(cx), default)
1174             }
1175             ty::AssocKind::Method => {
1176                 let generics = (cx.tcx.generics_of(self.def_id),
1177                                 cx.tcx.explicit_predicates_of(self.def_id)).clean(cx);
1178                 let sig = cx.tcx.fn_sig(self.def_id);
1179                 let mut decl = (self.def_id, sig).clean(cx);
1180
1181                 if self.method_has_self_argument {
1182                     let self_ty = match self.container {
1183                         ty::ImplContainer(def_id) => {
1184                             cx.tcx.type_of(def_id)
1185                         }
1186                         ty::TraitContainer(_) => cx.tcx.types.self_param,
1187                     };
1188                     let self_arg_ty = *sig.input(0).skip_binder();
1189                     if self_arg_ty == self_ty {
1190                         decl.inputs.values[0].type_ = Generic(String::from("Self"));
1191                     } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1192                         if ty == self_ty {
1193                             match decl.inputs.values[0].type_ {
1194                                 BorrowedRef{ref mut type_, ..} => {
1195                                     **type_ = Generic(String::from("Self"))
1196                                 }
1197                                 _ => unreachable!(),
1198                             }
1199                         }
1200                     }
1201                 }
1202
1203                 let provided = match self.container {
1204                     ty::ImplContainer(_) => true,
1205                     ty::TraitContainer(_) => self.defaultness.has_value()
1206                 };
1207                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1208                 if provided {
1209                     let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1210                         hir::Constness::Const
1211                     } else {
1212                         hir::Constness::NotConst
1213                     };
1214                     let asyncness = cx.tcx.asyncness(self.def_id);
1215                     let defaultness = match self.container {
1216                         ty::ImplContainer(_) => Some(self.defaultness),
1217                         ty::TraitContainer(_) => None,
1218                     };
1219                     MethodItem(Method {
1220                         generics,
1221                         decl,
1222                         header: hir::FnHeader {
1223                             unsafety: sig.unsafety(),
1224                             abi: sig.abi(),
1225                             constness,
1226                             asyncness,
1227                         },
1228                         defaultness,
1229                         all_types,
1230                         ret_types,
1231                     })
1232                 } else {
1233                     TyMethodItem(TyMethod {
1234                         generics,
1235                         decl,
1236                         header: hir::FnHeader {
1237                             unsafety: sig.unsafety(),
1238                             abi: sig.abi(),
1239                             constness: hir::Constness::NotConst,
1240                             asyncness: hir::IsAsync::NotAsync,
1241                         },
1242                         all_types,
1243                         ret_types,
1244                     })
1245                 }
1246             }
1247             ty::AssocKind::Type => {
1248                 let my_name = self.ident.name.clean(cx);
1249
1250                 if let ty::TraitContainer(did) = self.container {
1251                     // When loading a cross-crate associated type, the bounds for this type
1252                     // are actually located on the trait/impl itself, so we need to load
1253                     // all of the generics from there and then look for bounds that are
1254                     // applied to this associated type in question.
1255                     let predicates = cx.tcx.explicit_predicates_of(did);
1256                     let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1257                     let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
1258                         let (name, self_type, trait_, bounds) = match *pred {
1259                             WherePredicate::BoundPredicate {
1260                                 ty: QPath { ref name, ref self_type, ref trait_ },
1261                                 ref bounds
1262                             } => (name, self_type, trait_, bounds),
1263                             _ => return None,
1264                         };
1265                         if *name != my_name { return None }
1266                         match **trait_ {
1267                             ResolvedPath { did, .. } if did == self.container.id() => {}
1268                             _ => return None,
1269                         }
1270                         match **self_type {
1271                             Generic(ref s) if *s == "Self" => {}
1272                             _ => return None,
1273                         }
1274                         Some(bounds)
1275                     }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
1276                     // Our Sized/?Sized bound didn't get handled when creating the generics
1277                     // because we didn't actually get our whole set of bounds until just now
1278                     // (some of them may have come from the trait). If we do have a sized
1279                     // bound, we remove it, and if we don't then we add the `?Sized` bound
1280                     // at the end.
1281                     match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1282                         Some(i) => { bounds.remove(i); }
1283                         None => bounds.push(GenericBound::maybe_sized(cx)),
1284                     }
1285
1286                     let ty = if self.defaultness.has_value() {
1287                         Some(cx.tcx.type_of(self.def_id))
1288                     } else {
1289                         None
1290                     };
1291
1292                     AssocTypeItem(bounds, ty.clean(cx))
1293                 } else {
1294                     TypedefItem(Typedef {
1295                         type_: cx.tcx.type_of(self.def_id).clean(cx),
1296                         generics: Generics {
1297                             params: Vec::new(),
1298                             where_predicates: Vec::new(),
1299                         },
1300                     }, true)
1301                 }
1302             }
1303             ty::AssocKind::OpaqueTy => unimplemented!(),
1304         };
1305
1306         let visibility = match self.container {
1307             ty::ImplContainer(_) => self.vis.clean(cx),
1308             ty::TraitContainer(_) => Inherited,
1309         };
1310
1311         Item {
1312             name: Some(self.ident.name.clean(cx)),
1313             visibility,
1314             stability: get_stability(cx, self.def_id),
1315             deprecation: get_deprecation(cx, self.def_id),
1316             def_id: self.def_id,
1317             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1318             source: cx.tcx.def_span(self.def_id).clean(cx),
1319             inner,
1320         }
1321     }
1322 }
1323
1324 impl Clean<Type> for hir::Ty {
1325     fn clean(&self, cx: &DocContext<'_>) -> Type {
1326         use rustc::hir::*;
1327
1328         match self.kind {
1329             TyKind::Never => Never,
1330             TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1331             TyKind::Rptr(ref l, ref m) => {
1332                 let lifetime = if l.is_elided() {
1333                     None
1334                 } else {
1335                     Some(l.clean(cx))
1336                 };
1337                 BorrowedRef {lifetime, mutability: m.mutbl.clean(cx),
1338                              type_: box m.ty.clean(cx)}
1339             }
1340             TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1341             TyKind::Array(ref ty, ref length) => {
1342                 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1343                 let param_env = cx.tcx.param_env(def_id);
1344                 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
1345                 let cid = GlobalId {
1346                     instance: ty::Instance::new(def_id, substs),
1347                     promoted: None
1348                 };
1349                 let length = match cx.tcx.const_eval(param_env.and(cid)) {
1350                     Ok(length) => print_const(cx, length),
1351                     Err(_) => cx.sess()
1352                                 .source_map()
1353                                 .span_to_snippet(cx.tcx.def_span(def_id))
1354                                 .unwrap_or_else(|_| "_".to_string()),
1355                 };
1356                 Array(box ty.clean(cx), length)
1357             },
1358             TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1359             TyKind::Def(item_id, _) => {
1360                 let item = cx.tcx.hir().expect_item(item_id.id);
1361                 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1362                     ImplTrait(ty.bounds.clean(cx))
1363                 } else {
1364                     unreachable!()
1365                 }
1366             }
1367             TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1368                 if let Res::Def(DefKind::TyParam, did) = path.res {
1369                     if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1370                         return new_ty;
1371                     }
1372                     if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1373                         return ImplTrait(bounds);
1374                     }
1375                 }
1376
1377                 let mut alias = None;
1378                 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1379                     // Substitute private type aliases
1380                     if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1381                         if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1382                             alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1383                         }
1384                     }
1385                 };
1386
1387                 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1388                     let provided_params = &path.segments.last().expect("segments were empty");
1389                     let mut ty_substs = FxHashMap::default();
1390                     let mut lt_substs = FxHashMap::default();
1391                     let mut ct_substs = FxHashMap::default();
1392                     let generic_args = provided_params.generic_args();
1393                     {
1394                         let mut indices: GenericParamCount = Default::default();
1395                         for param in generics.params.iter() {
1396                             match param.kind {
1397                                 hir::GenericParamKind::Lifetime { .. } => {
1398                                     let mut j = 0;
1399                                     let lifetime = generic_args.args.iter().find_map(|arg| {
1400                                         match arg {
1401                                             hir::GenericArg::Lifetime(lt) => {
1402                                                 if indices.lifetimes == j {
1403                                                     return Some(lt);
1404                                                 }
1405                                                 j += 1;
1406                                                 None
1407                                             }
1408                                             _ => None,
1409                                         }
1410                                     });
1411                                     if let Some(lt) = lifetime.cloned() {
1412                                         if !lt.is_elided() {
1413                                             let lt_def_id =
1414                                                 cx.tcx.hir().local_def_id(param.hir_id);
1415                                             lt_substs.insert(lt_def_id, lt.clean(cx));
1416                                         }
1417                                     }
1418                                     indices.lifetimes += 1;
1419                                 }
1420                                 hir::GenericParamKind::Type { ref default, .. } => {
1421                                     let ty_param_def_id =
1422                                         cx.tcx.hir().local_def_id(param.hir_id);
1423                                     let mut j = 0;
1424                                     let type_ = generic_args.args.iter().find_map(|arg| {
1425                                         match arg {
1426                                             hir::GenericArg::Type(ty) => {
1427                                                 if indices.types == j {
1428                                                     return Some(ty);
1429                                                 }
1430                                                 j += 1;
1431                                                 None
1432                                             }
1433                                             _ => None,
1434                                         }
1435                                     });
1436                                     if let Some(ty) = type_ {
1437                                         ty_substs.insert(ty_param_def_id, ty.clean(cx));
1438                                     } else if let Some(default) = default.clone() {
1439                                         ty_substs.insert(ty_param_def_id,
1440                                                          default.clean(cx));
1441                                     }
1442                                     indices.types += 1;
1443                                 }
1444                                 hir::GenericParamKind::Const { .. } => {
1445                                     let const_param_def_id =
1446                                         cx.tcx.hir().local_def_id(param.hir_id);
1447                                     let mut j = 0;
1448                                     let const_ = generic_args.args.iter().find_map(|arg| {
1449                                         match arg {
1450                                             hir::GenericArg::Const(ct) => {
1451                                                 if indices.consts == j {
1452                                                     return Some(ct);
1453                                                 }
1454                                                 j += 1;
1455                                                 None
1456                                             }
1457                                             _ => None,
1458                                         }
1459                                     });
1460                                     if let Some(ct) = const_ {
1461                                         ct_substs.insert(const_param_def_id, ct.clean(cx));
1462                                     }
1463                                     // FIXME(const_generics:defaults)
1464                                     indices.consts += 1;
1465                                 }
1466                             }
1467                         }
1468                     }
1469                     return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1470                 }
1471                 resolve_type(cx, path.clean(cx), self.hir_id)
1472             }
1473             TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1474                 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1475                 let trait_segments = &segments[..segments.len() - 1];
1476                 let trait_path = self::Path {
1477                     global: p.is_global(),
1478                     res: Res::Def(
1479                         DefKind::Trait,
1480                         cx.tcx.associated_item(p.res.def_id()).container.id(),
1481                     ),
1482                     segments: trait_segments.clean(cx),
1483                 };
1484                 Type::QPath {
1485                     name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1486                     self_type: box qself.clean(cx),
1487                     trait_: box resolve_type(cx, trait_path, self.hir_id)
1488                 }
1489             }
1490             TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1491                 let mut res = Res::Err;
1492                 let ty = hir_ty_to_ty(cx.tcx, self);
1493                 if let ty::Projection(proj) = ty.kind {
1494                     res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1495                 }
1496                 let trait_path = hir::Path {
1497                     span: self.span,
1498                     res,
1499                     segments: vec![].into(),
1500                 };
1501                 Type::QPath {
1502                     name: segment.ident.name.clean(cx),
1503                     self_type: box qself.clean(cx),
1504                     trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id)
1505                 }
1506             }
1507             TyKind::TraitObject(ref bounds, ref lifetime) => {
1508                 match bounds[0].clean(cx).trait_ {
1509                     ResolvedPath { path, param_names: None, did, is_generic } => {
1510                         let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
1511                             self::GenericBound::TraitBound(bound.clean(cx),
1512                                                            hir::TraitBoundModifier::None)
1513                         }).collect();
1514                         if !lifetime.is_elided() {
1515                             bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1516                         }
1517                         ResolvedPath { path, param_names: Some(bounds), did, is_generic, }
1518                     }
1519                     _ => Infer, // shouldn't happen
1520                 }
1521             }
1522             TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1523             TyKind::Infer | TyKind::Err => Infer,
1524             TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1525         }
1526     }
1527 }
1528
1529 impl<'tcx> Clean<Type> for Ty<'tcx> {
1530     fn clean(&self, cx: &DocContext<'_>) -> Type {
1531         debug!("cleaning type: {:?}", self);
1532         match self.kind {
1533             ty::Never => Never,
1534             ty::Bool => Primitive(PrimitiveType::Bool),
1535             ty::Char => Primitive(PrimitiveType::Char),
1536             ty::Int(int_ty) => Primitive(int_ty.into()),
1537             ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1538             ty::Float(float_ty) => Primitive(float_ty.into()),
1539             ty::Str => Primitive(PrimitiveType::Str),
1540             ty::Slice(ty) => Slice(box ty.clean(cx)),
1541             ty::Array(ty, n) => {
1542                 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1543                 if let ty::ConstKind::Unevaluated(def_id, substs) = n.val {
1544                     let param_env = cx.tcx.param_env(def_id);
1545                     let cid = GlobalId {
1546                         instance: ty::Instance::new(def_id, substs),
1547                         promoted: None
1548                     };
1549                     if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) {
1550                         n = new_n;
1551                     }
1552                 };
1553                 let n = print_const(cx, n);
1554                 Array(box ty.clean(cx), n)
1555             }
1556             ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1557             ty::Ref(r, ty, mutbl) => BorrowedRef {
1558                 lifetime: r.clean(cx),
1559                 mutability: mutbl.clean(cx),
1560                 type_: box ty.clean(cx),
1561             },
1562             ty::FnDef(..) |
1563             ty::FnPtr(_) => {
1564                 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1565                 let sig = ty.fn_sig(cx.tcx);
1566                 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1567                 BareFunction(box BareFunctionDecl {
1568                     unsafety: sig.unsafety(),
1569                     generic_params: Vec::new(),
1570                     decl: (local_def_id, sig).clean(cx),
1571                     abi: sig.abi(),
1572                 })
1573             }
1574             ty::Adt(def, substs) => {
1575                 let did = def.did;
1576                 let kind = match def.adt_kind() {
1577                     AdtKind::Struct => TypeKind::Struct,
1578                     AdtKind::Union => TypeKind::Union,
1579                     AdtKind::Enum => TypeKind::Enum,
1580                 };
1581                 inline::record_extern_fqn(cx, did, kind);
1582                 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1583                 ResolvedPath {
1584                     path,
1585                     param_names: None,
1586                     did,
1587                     is_generic: false,
1588                 }
1589             }
1590             ty::Foreign(did) => {
1591                 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1592                 let path = external_path(cx, cx.tcx.item_name(did),
1593                                          None, false, vec![], InternalSubsts::empty());
1594                 ResolvedPath {
1595                     path,
1596                     param_names: None,
1597                     did,
1598                     is_generic: false,
1599                 }
1600             }
1601             ty::Dynamic(ref obj, ref reg) => {
1602                 // HACK: pick the first `did` as the `did` of the trait object. Someone
1603                 // might want to implement "native" support for marker-trait-only
1604                 // trait objects.
1605                 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1606                 let did = dids.next().unwrap_or_else(|| {
1607                     panic!("found trait object `{:?}` with no traits?", self)
1608                 });
1609                 let substs = match obj.principal() {
1610                     Some(principal) => principal.skip_binder().substs,
1611                     // marker traits have no substs.
1612                     _ => cx.tcx.intern_substs(&[])
1613                 };
1614
1615                 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1616
1617                 let mut param_names = vec![];
1618                 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1619                 for did in dids {
1620                     let empty = cx.tcx.intern_substs(&[]);
1621                     let path = external_path(cx, cx.tcx.item_name(did),
1622                         Some(did), false, vec![], empty);
1623                     inline::record_extern_fqn(cx, did, TypeKind::Trait);
1624                     let bound = GenericBound::TraitBound(PolyTrait {
1625                         trait_: ResolvedPath {
1626                             path,
1627                             param_names: None,
1628                             did,
1629                             is_generic: false,
1630                         },
1631                         generic_params: Vec::new(),
1632                     }, hir::TraitBoundModifier::None);
1633                     param_names.push(bound);
1634                 }
1635
1636                 let mut bindings = vec![];
1637                 for pb in obj.projection_bounds() {
1638                     bindings.push(TypeBinding {
1639                         name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1640                         kind: TypeBindingKind::Equality {
1641                             ty: pb.skip_binder().ty.clean(cx)
1642                         },
1643                     });
1644                 }
1645
1646                 let path = external_path(cx, cx.tcx.item_name(did), Some(did),
1647                     false, bindings, substs);
1648                 ResolvedPath {
1649                     path,
1650                     param_names: Some(param_names),
1651                     did,
1652                     is_generic: false,
1653                 }
1654             }
1655             ty::Tuple(ref t) => {
1656                 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1657             }
1658
1659             ty::Projection(ref data) => data.clean(cx),
1660
1661             ty::Param(ref p) => {
1662                 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1663                     ImplTrait(bounds)
1664                 } else {
1665                     Generic(p.name.to_string())
1666                 }
1667             }
1668
1669             ty::Opaque(def_id, substs) => {
1670                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1671                 // by looking up the projections associated with the def_id.
1672                 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1673                 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1674                 let bounds = predicates_of.instantiate(cx.tcx, substs);
1675                 let mut regions = vec![];
1676                 let mut has_sized = false;
1677                 let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
1678                     let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1679                         tr
1680                     } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1681                         // these should turn up at the end
1682                         pred.skip_binder().1.clean(cx).map(|r| {
1683                             regions.push(GenericBound::Outlives(r))
1684                         });
1685                         return None;
1686                     } else {
1687                         return None;
1688                     };
1689
1690                     if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1691                         if trait_ref.def_id() == sized {
1692                             has_sized = true;
1693                             return None;
1694                         }
1695                     }
1696
1697                     let bounds = bounds.predicates.iter().filter_map(|pred|
1698                         if let ty::Predicate::Projection(proj) = *pred {
1699                             let proj = proj.skip_binder();
1700                             if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
1701                                 Some(TypeBinding {
1702                                     name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
1703                                                 .ident.name.clean(cx),
1704                                     kind: TypeBindingKind::Equality {
1705                                         ty: proj.ty.clean(cx),
1706                                     },
1707                                 })
1708                             } else {
1709                                 None
1710                             }
1711                         } else {
1712                             None
1713                         }
1714                     ).collect();
1715
1716                     Some((trait_ref.skip_binder(), bounds).clean(cx))
1717                 }).collect::<Vec<_>>();
1718                 bounds.extend(regions);
1719                 if !has_sized && !bounds.is_empty() {
1720                     bounds.insert(0, GenericBound::maybe_sized(cx));
1721                 }
1722                 ImplTrait(bounds)
1723             }
1724
1725             ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1726
1727             ty::Bound(..) => panic!("Bound"),
1728             ty::Placeholder(..) => panic!("Placeholder"),
1729             ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1730             ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1731             ty::Infer(..) => panic!("Infer"),
1732             ty::Error => panic!("Error"),
1733         }
1734     }
1735 }
1736
1737 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1738     fn clean(&self, cx: &DocContext<'_>) -> Constant {
1739         Constant {
1740             type_: self.ty.clean(cx),
1741             expr: format!("{}", self),
1742         }
1743     }
1744 }
1745
1746 impl Clean<Item> for hir::StructField {
1747     fn clean(&self, cx: &DocContext<'_>) -> Item {
1748         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1749
1750         Item {
1751             name: Some(self.ident.name).clean(cx),
1752             attrs: self.attrs.clean(cx),
1753             source: self.span.clean(cx),
1754             visibility: self.vis.clean(cx),
1755             stability: get_stability(cx, local_did),
1756             deprecation: get_deprecation(cx, local_did),
1757             def_id: local_did,
1758             inner: StructFieldItem(self.ty.clean(cx)),
1759         }
1760     }
1761 }
1762
1763 impl Clean<Item> for ty::FieldDef {
1764     fn clean(&self, cx: &DocContext<'_>) -> Item {
1765         Item {
1766             name: Some(self.ident.name).clean(cx),
1767             attrs: cx.tcx.get_attrs(self.did).clean(cx),
1768             source: cx.tcx.def_span(self.did).clean(cx),
1769             visibility: self.vis.clean(cx),
1770             stability: get_stability(cx, self.did),
1771             deprecation: get_deprecation(cx, self.did),
1772             def_id: self.did,
1773             inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1774         }
1775     }
1776 }
1777
1778 impl Clean<Visibility> for hir::Visibility {
1779     fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1780         match self.node {
1781             hir::VisibilityKind::Public => Visibility::Public,
1782             hir::VisibilityKind::Inherited => Visibility::Inherited,
1783             hir::VisibilityKind::Crate(_) => Visibility::Crate,
1784             hir::VisibilityKind::Restricted { ref path, .. } => {
1785                 let path = path.clean(cx);
1786                 let did = register_res(cx, path.res);
1787                 Visibility::Restricted(did, path)
1788             }
1789         }
1790     }
1791 }
1792
1793 impl Clean<Visibility> for ty::Visibility {
1794     fn clean(&self, _: &DocContext<'_>) -> Visibility {
1795         if *self == ty::Visibility::Public { Public } else { Inherited }
1796     }
1797 }
1798
1799 impl Clean<Item> for doctree::Struct<'_> {
1800     fn clean(&self, cx: &DocContext<'_>) -> Item {
1801         Item {
1802             name: Some(self.name.clean(cx)),
1803             attrs: self.attrs.clean(cx),
1804             source: self.whence.clean(cx),
1805             def_id: cx.tcx.hir().local_def_id(self.id),
1806             visibility: self.vis.clean(cx),
1807             stability: cx.stability(self.id).clean(cx),
1808             deprecation: cx.deprecation(self.id).clean(cx),
1809             inner: StructItem(Struct {
1810                 struct_type: self.struct_type,
1811                 generics: self.generics.clean(cx),
1812                 fields: self.fields.clean(cx),
1813                 fields_stripped: false,
1814             }),
1815         }
1816     }
1817 }
1818
1819 impl Clean<Item> for doctree::Union<'_> {
1820     fn clean(&self, cx: &DocContext<'_>) -> Item {
1821         Item {
1822             name: Some(self.name.clean(cx)),
1823             attrs: self.attrs.clean(cx),
1824             source: self.whence.clean(cx),
1825             def_id: cx.tcx.hir().local_def_id(self.id),
1826             visibility: self.vis.clean(cx),
1827             stability: cx.stability(self.id).clean(cx),
1828             deprecation: cx.deprecation(self.id).clean(cx),
1829             inner: UnionItem(Union {
1830                 struct_type: self.struct_type,
1831                 generics: self.generics.clean(cx),
1832                 fields: self.fields.clean(cx),
1833                 fields_stripped: false,
1834             }),
1835         }
1836     }
1837 }
1838
1839 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1840     fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1841         VariantStruct {
1842             struct_type: doctree::struct_type_from_def(self),
1843             fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1844             fields_stripped: false,
1845         }
1846     }
1847 }
1848
1849 impl Clean<Item> for doctree::Enum<'_> {
1850     fn clean(&self, cx: &DocContext<'_>) -> Item {
1851         Item {
1852             name: Some(self.name.clean(cx)),
1853             attrs: self.attrs.clean(cx),
1854             source: self.whence.clean(cx),
1855             def_id: cx.tcx.hir().local_def_id(self.id),
1856             visibility: self.vis.clean(cx),
1857             stability: cx.stability(self.id).clean(cx),
1858             deprecation: cx.deprecation(self.id).clean(cx),
1859             inner: EnumItem(Enum {
1860                 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1861                 generics: self.generics.clean(cx),
1862                 variants_stripped: false,
1863             }),
1864         }
1865     }
1866 }
1867
1868 impl Clean<Item> for doctree::Variant<'_> {
1869     fn clean(&self, cx: &DocContext<'_>) -> Item {
1870         Item {
1871             name: Some(self.name.clean(cx)),
1872             attrs: self.attrs.clean(cx),
1873             source: self.whence.clean(cx),
1874             visibility: Inherited,
1875             stability: cx.stability(self.id).clean(cx),
1876             deprecation: cx.deprecation(self.id).clean(cx),
1877             def_id: cx.tcx.hir().local_def_id(self.id),
1878             inner: VariantItem(Variant {
1879                 kind: self.def.clean(cx),
1880             }),
1881         }
1882     }
1883 }
1884
1885 impl Clean<Item> for ty::VariantDef {
1886     fn clean(&self, cx: &DocContext<'_>) -> Item {
1887         let kind = match self.ctor_kind {
1888             CtorKind::Const => VariantKind::CLike,
1889             CtorKind::Fn => {
1890                 VariantKind::Tuple(
1891                     self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
1892                 )
1893             }
1894             CtorKind::Fictive => {
1895                 VariantKind::Struct(VariantStruct {
1896                     struct_type: doctree::Plain,
1897                     fields_stripped: false,
1898                     fields: self.fields.iter().map(|field| {
1899                         Item {
1900                             source: cx.tcx.def_span(field.did).clean(cx),
1901                             name: Some(field.ident.name.clean(cx)),
1902                             attrs: cx.tcx.get_attrs(field.did).clean(cx),
1903                             visibility: field.vis.clean(cx),
1904                             def_id: field.did,
1905                             stability: get_stability(cx, field.did),
1906                             deprecation: get_deprecation(cx, field.did),
1907                             inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
1908                         }
1909                     }).collect()
1910                 })
1911             }
1912         };
1913         Item {
1914             name: Some(self.ident.clean(cx)),
1915             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1916             source: cx.tcx.def_span(self.def_id).clean(cx),
1917             visibility: Inherited,
1918             def_id: self.def_id,
1919             inner: VariantItem(Variant { kind }),
1920             stability: get_stability(cx, self.def_id),
1921             deprecation: get_deprecation(cx, self.def_id),
1922         }
1923     }
1924 }
1925
1926 impl Clean<VariantKind> for hir::VariantData {
1927     fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1928         match self {
1929             hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1930             hir::VariantData::Tuple(..) =>
1931                 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()),
1932             hir::VariantData::Unit(..) => VariantKind::CLike,
1933         }
1934     }
1935 }
1936
1937 impl Clean<Span> for syntax_pos::Span {
1938     fn clean(&self, cx: &DocContext<'_>) -> Span {
1939         if self.is_dummy() {
1940             return Span::empty();
1941         }
1942
1943         let cm = cx.sess().source_map();
1944         let filename = cm.span_to_filename(*self);
1945         let lo = cm.lookup_char_pos(self.lo());
1946         let hi = cm.lookup_char_pos(self.hi());
1947         Span {
1948             filename,
1949             loline: lo.line,
1950             locol: lo.col.to_usize(),
1951             hiline: hi.line,
1952             hicol: hi.col.to_usize(),
1953             original: *self,
1954         }
1955     }
1956 }
1957
1958 impl Clean<Path> for hir::Path {
1959     fn clean(&self, cx: &DocContext<'_>) -> Path {
1960         Path {
1961             global: self.is_global(),
1962             res: self.res,
1963             segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1964         }
1965     }
1966 }
1967
1968 impl Clean<GenericArgs> for hir::GenericArgs {
1969     fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1970         if self.parenthesized {
1971             let output = self.bindings[0].ty().clean(cx);
1972             GenericArgs::Parenthesized {
1973                 inputs: self.inputs().clean(cx),
1974                 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
1975             }
1976         } else {
1977             let elide_lifetimes = self.args.iter().all(|arg| match arg {
1978                 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1979                 _ => true,
1980             });
1981             GenericArgs::AngleBracketed {
1982                 args: self.args.iter().filter_map(|arg| match arg {
1983                     hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1984                         Some(GenericArg::Lifetime(lt.clean(cx)))
1985                     }
1986                     hir::GenericArg::Lifetime(_) => None,
1987                     hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1988                     hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1989                 }).collect(),
1990                 bindings: self.bindings.clean(cx),
1991             }
1992         }
1993     }
1994 }
1995
1996 impl Clean<PathSegment> for hir::PathSegment {
1997     fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1998         PathSegment {
1999             name: self.ident.name.clean(cx),
2000             args: self.generic_args().clean(cx),
2001         }
2002     }
2003 }
2004
2005 impl Clean<String> for Ident {
2006     #[inline]
2007     fn clean(&self, cx: &DocContext<'_>) -> String {
2008         self.name.clean(cx)
2009     }
2010 }
2011
2012 impl Clean<String> for ast::Name {
2013     #[inline]
2014     fn clean(&self, _: &DocContext<'_>) -> String {
2015         self.to_string()
2016     }
2017 }
2018
2019 impl Clean<Item> for doctree::Typedef<'_> {
2020     fn clean(&self, cx: &DocContext<'_>) -> Item {
2021         Item {
2022             name: Some(self.name.clean(cx)),
2023             attrs: self.attrs.clean(cx),
2024             source: self.whence.clean(cx),
2025             def_id: cx.tcx.hir().local_def_id(self.id),
2026             visibility: self.vis.clean(cx),
2027             stability: cx.stability(self.id).clean(cx),
2028             deprecation: cx.deprecation(self.id).clean(cx),
2029             inner: TypedefItem(Typedef {
2030                 type_: self.ty.clean(cx),
2031                 generics: self.gen.clean(cx),
2032             }, false),
2033         }
2034     }
2035 }
2036
2037 impl Clean<Item> for doctree::OpaqueTy<'_> {
2038     fn clean(&self, cx: &DocContext<'_>) -> Item {
2039         Item {
2040             name: Some(self.name.clean(cx)),
2041             attrs: self.attrs.clean(cx),
2042             source: self.whence.clean(cx),
2043             def_id: cx.tcx.hir().local_def_id(self.id),
2044             visibility: self.vis.clean(cx),
2045             stability: cx.stability(self.id).clean(cx),
2046             deprecation: cx.deprecation(self.id).clean(cx),
2047             inner: OpaqueTyItem(OpaqueTy {
2048                 bounds: self.opaque_ty.bounds.clean(cx),
2049                 generics: self.opaque_ty.generics.clean(cx),
2050             }, false),
2051         }
2052     }
2053 }
2054
2055 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2056     fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2057         let (generic_params, decl) = enter_impl_trait(cx, || {
2058             (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2059         });
2060         BareFunctionDecl {
2061             unsafety: self.unsafety,
2062             abi: self.abi,
2063             decl,
2064             generic_params,
2065         }
2066     }
2067 }
2068
2069 impl Clean<Item> for doctree::Static<'_> {
2070     fn clean(&self, cx: &DocContext<'_>) -> Item {
2071         debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2072         Item {
2073             name: Some(self.name.clean(cx)),
2074             attrs: self.attrs.clean(cx),
2075             source: self.whence.clean(cx),
2076             def_id: cx.tcx.hir().local_def_id(self.id),
2077             visibility: self.vis.clean(cx),
2078             stability: cx.stability(self.id).clean(cx),
2079             deprecation: cx.deprecation(self.id).clean(cx),
2080             inner: StaticItem(Static {
2081                 type_: self.type_.clean(cx),
2082                 mutability: self.mutability.clean(cx),
2083                 expr: print_const_expr(cx, self.expr),
2084             }),
2085         }
2086     }
2087 }
2088
2089 impl Clean<Item> for doctree::Constant<'_> {
2090     fn clean(&self, cx: &DocContext<'_>) -> Item {
2091         Item {
2092             name: Some(self.name.clean(cx)),
2093             attrs: self.attrs.clean(cx),
2094             source: self.whence.clean(cx),
2095             def_id: cx.tcx.hir().local_def_id(self.id),
2096             visibility: self.vis.clean(cx),
2097             stability: cx.stability(self.id).clean(cx),
2098             deprecation: cx.deprecation(self.id).clean(cx),
2099             inner: ConstantItem(Constant {
2100                 type_: self.type_.clean(cx),
2101                 expr: print_const_expr(cx, self.expr),
2102             }),
2103         }
2104     }
2105 }
2106
2107 impl Clean<Mutability> for hir::Mutability {
2108     fn clean(&self, _: &DocContext<'_>) -> Mutability {
2109         match self {
2110             &hir::Mutability::Mut => Mutable,
2111             &hir::Mutability::Not => Immutable,
2112         }
2113     }
2114 }
2115
2116 impl Clean<ImplPolarity> for ty::ImplPolarity {
2117     fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2118         match self {
2119             &ty::ImplPolarity::Positive |
2120             // FIXME: do we want to do something else here?
2121             &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2122             &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2123         }
2124     }
2125 }
2126
2127 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2128     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2129         let mut ret = Vec::new();
2130         let trait_ = self.trait_.clean(cx);
2131         let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2132         let def_id = cx.tcx.hir().local_def_id(self.id);
2133
2134         // If this impl block is an implementation of the Deref trait, then we
2135         // need to try inlining the target's inherent impl blocks as well.
2136         if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2137             build_deref_target_impls(cx, &items, &mut ret);
2138         }
2139
2140         let provided = trait_.def_id().map(|did| {
2141             cx.tcx.provided_trait_methods(did)
2142                   .into_iter()
2143                   .map(|meth| meth.ident.to_string())
2144                   .collect()
2145         }).unwrap_or_default();
2146
2147         ret.push(Item {
2148             name: None,
2149             attrs: self.attrs.clean(cx),
2150             source: self.whence.clean(cx),
2151             def_id,
2152             visibility: self.vis.clean(cx),
2153             stability: cx.stability(self.id).clean(cx),
2154             deprecation: cx.deprecation(self.id).clean(cx),
2155             inner: ImplItem(Impl {
2156                 unsafety: self.unsafety,
2157                 generics: self.generics.clean(cx),
2158                 provided_trait_methods: provided,
2159                 trait_,
2160                 for_: self.for_.clean(cx),
2161                 items,
2162                 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2163                 synthetic: false,
2164                 blanket_impl: None,
2165             })
2166         });
2167         ret
2168     }
2169 }
2170
2171 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2172     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2173
2174         let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
2175             a.check_name(sym::doc) && match a.meta_item_list() {
2176                 Some(l) => attr::list_contains_name(&l, sym::inline),
2177                 None => false,
2178             }
2179         });
2180
2181         if please_inline {
2182             let mut visited = FxHashSet::default();
2183
2184             let res = Res::Def(
2185                 DefKind::Mod,
2186                 DefId {
2187                     krate: self.cnum,
2188                     index: CRATE_DEF_INDEX,
2189                 },
2190             );
2191
2192             if let Some(items) = inline::try_inline(
2193                 cx, res, self.name,
2194                 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2195                 &mut visited
2196             ) {
2197                 return items;
2198             }
2199         }
2200
2201         vec![Item {
2202             name: None,
2203             attrs: self.attrs.clean(cx),
2204             source: self.whence.clean(cx),
2205             def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2206             visibility: self.vis.clean(cx),
2207             stability: None,
2208             deprecation: None,
2209             inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2210         }]
2211     }
2212 }
2213
2214 impl Clean<Vec<Item>> for doctree::Import<'_> {
2215     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2216         // We consider inlining the documentation of `pub use` statements, but we
2217         // forcefully don't inline if this is not public or if the
2218         // #[doc(no_inline)] attribute is present.
2219         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2220         let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| {
2221             a.check_name(sym::doc) && match a.meta_item_list() {
2222                 Some(l) => attr::list_contains_name(&l, sym::no_inline) ||
2223                            attr::list_contains_name(&l, sym::hidden),
2224                 None => false,
2225             }
2226         });
2227         // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2228         // crate in Rust 2018+
2229         let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2230         let path = self.path.clean(cx);
2231         let inner = if self.glob {
2232             if !denied {
2233                 let mut visited = FxHashSet::default();
2234                 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2235                     return items;
2236                 }
2237             }
2238
2239             Import::Glob(resolve_use_source(cx, path))
2240         } else {
2241             let name = self.name;
2242             if !please_inline {
2243                 match path.res {
2244                     Res::Def(DefKind::Mod, did) => {
2245                         if !did.is_local() && did.index == CRATE_DEF_INDEX {
2246                             // if we're `pub use`ing an extern crate root, don't inline it unless we
2247                             // were specifically asked for it
2248                             denied = true;
2249                         }
2250                     }
2251                     _ => {}
2252                 }
2253             }
2254             if !denied {
2255                 let mut visited = FxHashSet::default();
2256                 if let Some(items) = inline::try_inline(
2257                     cx, path.res, name,
2258                     Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2259                     &mut visited
2260                 ) {
2261                     return items;
2262                 }
2263             }
2264             Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2265         };
2266
2267         vec![Item {
2268             name: None,
2269             attrs: self.attrs.clean(cx),
2270             source: self.whence.clean(cx),
2271             def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2272             visibility: self.vis.clean(cx),
2273             stability: None,
2274             deprecation: None,
2275             inner: ImportItem(inner)
2276         }]
2277     }
2278 }
2279
2280 impl Clean<Item> for doctree::ForeignItem<'_> {
2281     fn clean(&self, cx: &DocContext<'_>) -> Item {
2282         let inner = match self.kind {
2283             hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2284                 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2285                 let (generics, decl) = enter_impl_trait(cx, || {
2286                     (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2287                 });
2288                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2289                 ForeignFunctionItem(Function {
2290                     decl,
2291                     generics,
2292                     header: hir::FnHeader {
2293                         unsafety: hir::Unsafety::Unsafe,
2294                         abi,
2295                         constness: hir::Constness::NotConst,
2296                         asyncness: hir::IsAsync::NotAsync,
2297                     },
2298                     all_types,
2299                     ret_types,
2300                 })
2301             }
2302             hir::ForeignItemKind::Static(ref ty, mutbl) => {
2303                 ForeignStaticItem(Static {
2304                     type_: ty.clean(cx),
2305                     mutability: mutbl.clean(cx),
2306                     expr: String::new(),
2307                 })
2308             }
2309             hir::ForeignItemKind::Type => {
2310                 ForeignTypeItem
2311             }
2312         };
2313
2314         Item {
2315             name: Some(self.name.clean(cx)),
2316             attrs: self.attrs.clean(cx),
2317             source: self.whence.clean(cx),
2318             def_id: cx.tcx.hir().local_def_id(self.id),
2319             visibility: self.vis.clean(cx),
2320             stability: cx.stability(self.id).clean(cx),
2321             deprecation: cx.deprecation(self.id).clean(cx),
2322             inner,
2323         }
2324     }
2325 }
2326
2327 impl Clean<Item> for doctree::Macro<'_> {
2328     fn clean(&self, cx: &DocContext<'_>) -> Item {
2329         let name = self.name.clean(cx);
2330         Item {
2331             name: Some(name.clone()),
2332             attrs: self.attrs.clean(cx),
2333             source: self.whence.clean(cx),
2334             visibility: Public,
2335             stability: cx.stability(self.hid).clean(cx),
2336             deprecation: cx.deprecation(self.hid).clean(cx),
2337             def_id: self.def_id,
2338             inner: MacroItem(Macro {
2339                 source: format!("macro_rules! {} {{\n{}}}",
2340                                 name,
2341                                 self.matchers.iter().map(|span| {
2342                                     format!("    {} => {{ ... }};\n", span.to_src(cx))
2343                                 }).collect::<String>()),
2344                 imported_from: self.imported_from.clean(cx),
2345             }),
2346         }
2347     }
2348 }
2349
2350 impl Clean<Item> for doctree::ProcMacro<'_> {
2351     fn clean(&self, cx: &DocContext<'_>) -> Item {
2352         Item {
2353             name: Some(self.name.clean(cx)),
2354             attrs: self.attrs.clean(cx),
2355             source: self.whence.clean(cx),
2356             visibility: Public,
2357             stability: cx.stability(self.id).clean(cx),
2358             deprecation: cx.deprecation(self.id).clean(cx),
2359             def_id: cx.tcx.hir().local_def_id(self.id),
2360             inner: ProcMacroItem(ProcMacro {
2361                 kind: self.kind,
2362                 helpers: self.helpers.clean(cx),
2363             }),
2364         }
2365     }
2366 }
2367
2368 impl Clean<Stability> for attr::Stability {
2369     fn clean(&self, _: &DocContext<'_>) -> Stability {
2370         Stability {
2371             level: stability::StabilityLevel::from_attr_level(&self.level),
2372             feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2373             since: match self.level {
2374                 attr::Stable {ref since} => since.to_string(),
2375                 _ => String::new(),
2376             },
2377             deprecation: self.rustc_depr.as_ref().map(|d| {
2378                 Deprecation {
2379                     note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2380                     since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2381                 }
2382             }),
2383             unstable_reason: match self.level {
2384                 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2385                 _ => None,
2386             },
2387             issue: match self.level {
2388                 attr::Unstable {issue, ..} => issue,
2389                 _ => None,
2390             }
2391         }
2392     }
2393 }
2394
2395 impl Clean<Deprecation> for attr::Deprecation {
2396     fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2397         Deprecation {
2398             since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2399             note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2400         }
2401     }
2402 }
2403
2404 impl Clean<TypeBinding> for hir::TypeBinding {
2405     fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2406         TypeBinding {
2407             name: self.ident.name.clean(cx),
2408             kind: self.kind.clean(cx),
2409         }
2410     }
2411 }
2412
2413 impl Clean<TypeBindingKind> for hir::TypeBindingKind {
2414     fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2415         match *self {
2416             hir::TypeBindingKind::Equality { ref ty } =>
2417                 TypeBindingKind::Equality {
2418                     ty: ty.clean(cx),
2419                 },
2420             hir::TypeBindingKind::Constraint { ref bounds } =>
2421                 TypeBindingKind::Constraint {
2422                     bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2423                 },
2424         }
2425     }
2426 }
2427
2428 enum SimpleBound {
2429     TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2430     Outlives(Lifetime),
2431 }
2432
2433 impl From<GenericBound> for SimpleBound {
2434     fn from(bound: GenericBound) -> Self {
2435         match bound.clone() {
2436             GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2437             GenericBound::TraitBound(t, mod_) => match t.trait_ {
2438                 Type::ResolvedPath { path, param_names, .. } => {
2439                     SimpleBound::TraitBound(path.segments,
2440                                             param_names
2441                                                 .map_or_else(|| Vec::new(), |v| v.iter()
2442                                                         .map(|p| SimpleBound::from(p.clone()))
2443                                                         .collect()),
2444                                             t.generic_params,
2445                                             mod_)
2446                 }
2447                 _ => panic!("Unexpected bound {:?}", bound),
2448             }
2449         }
2450     }
2451 }