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