]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
Fix rustdoc
[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, Lift};
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 lifted = self.lift_to_tcx(cx.tcx).unwrap();
555         let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
556             GenericBound::TraitBound(t, _) => t.trait_,
557             GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
558         };
559         Type::QPath {
560             name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
561             self_type: box self.self_ty().clean(cx),
562             trait_: box trait_
563         }
564     }
565 }
566
567 impl Clean<GenericParamDef> for ty::GenericParamDef {
568     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
569         let (name, kind) = match self.kind {
570             ty::GenericParamDefKind::Lifetime => {
571                 (self.name.to_string(), GenericParamDefKind::Lifetime)
572             }
573             ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
574                 let default = if has_default {
575                     Some(cx.tcx.type_of(self.def_id).clean(cx))
576                 } else {
577                     None
578                 };
579                 (self.name.clean(cx), GenericParamDefKind::Type {
580                     did: self.def_id,
581                     bounds: vec![], // These are filled in from the where-clauses.
582                     default,
583                     synthetic,
584                 })
585             }
586             ty::GenericParamDefKind::Const { .. } => {
587                 (self.name.clean(cx), GenericParamDefKind::Const {
588                     did: self.def_id,
589                     ty: cx.tcx.type_of(self.def_id).clean(cx),
590                 })
591             }
592         };
593
594         GenericParamDef {
595             name,
596             kind,
597         }
598     }
599 }
600
601 impl Clean<GenericParamDef> for hir::GenericParam {
602     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
603         let (name, kind) = match self.kind {
604             hir::GenericParamKind::Lifetime { .. } => {
605                 let name = if self.bounds.len() > 0 {
606                     let mut bounds = self.bounds.iter().map(|bound| match bound {
607                         hir::GenericBound::Outlives(lt) => lt,
608                         _ => panic!(),
609                     });
610                     let name = bounds.next().expect("no more bounds").name.ident();
611                     let mut s = format!("{}: {}", self.name.ident(), name);
612                     for bound in bounds {
613                         s.push_str(&format!(" + {}", bound.name.ident()));
614                     }
615                     s
616                 } else {
617                     self.name.ident().to_string()
618                 };
619                 (name, GenericParamDefKind::Lifetime)
620             }
621             hir::GenericParamKind::Type { ref default, synthetic } => {
622                 (self.name.ident().name.clean(cx), GenericParamDefKind::Type {
623                     did: cx.tcx.hir().local_def_id(self.hir_id),
624                     bounds: self.bounds.clean(cx),
625                     default: default.clean(cx),
626                     synthetic,
627                 })
628             }
629             hir::GenericParamKind::Const { ref ty } => {
630                 (self.name.ident().name.clean(cx), GenericParamDefKind::Const {
631                     did: cx.tcx.hir().local_def_id(self.hir_id),
632                     ty: ty.clean(cx),
633                 })
634             }
635         };
636
637         GenericParamDef {
638             name,
639             kind,
640         }
641     }
642 }
643
644 impl Clean<Generics> for hir::Generics {
645     fn clean(&self, cx: &DocContext<'_>) -> Generics {
646         // Synthetic type-parameters are inserted after normal ones.
647         // In order for normal parameters to be able to refer to synthetic ones,
648         // scans them first.
649         fn is_impl_trait(param: &hir::GenericParam) -> bool {
650             match param.kind {
651                 hir::GenericParamKind::Type { synthetic, .. } => {
652                     synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
653                 }
654                 _ => false,
655             }
656         }
657         let impl_trait_params = self.params
658             .iter()
659             .filter(|param| is_impl_trait(param))
660             .map(|param| {
661                 let param: GenericParamDef = param.clean(cx);
662                 match param.kind {
663                     GenericParamDefKind::Lifetime => unreachable!(),
664                     GenericParamDefKind::Type { did, ref bounds, .. } => {
665                         cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
666                     }
667                     GenericParamDefKind::Const { .. } => unreachable!(),
668                 }
669                 param
670             })
671             .collect::<Vec<_>>();
672
673         let mut params = Vec::with_capacity(self.params.len());
674         for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
675             let p = p.clean(cx);
676             params.push(p);
677         }
678         params.extend(impl_trait_params);
679
680         let mut generics = Generics {
681             params,
682             where_predicates: self.where_clause.predicates.clean(cx),
683         };
684
685         // Some duplicates are generated for ?Sized bounds between type params and where
686         // predicates. The point in here is to move the bounds definitions from type params
687         // to where predicates when such cases occur.
688         for where_pred in &mut generics.where_predicates {
689             match *where_pred {
690                 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
691                     if bounds.is_empty() {
692                         for param in &mut generics.params {
693                             match param.kind {
694                                 GenericParamDefKind::Lifetime => {}
695                                 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
696                                     if &param.name == name {
697                                         mem::swap(bounds, ty_bounds);
698                                         break
699                                     }
700                                 }
701                                 GenericParamDefKind::Const { .. } => {}
702                             }
703                         }
704                     }
705                 }
706                 _ => continue,
707             }
708         }
709         generics
710     }
711 }
712
713 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
714     fn clean(&self, cx: &DocContext<'_>) -> Generics {
715         use self::WherePredicate as WP;
716         use std::collections::BTreeMap;
717
718         let (gens, preds) = *self;
719
720         // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
721         // since `Clean for ty::Predicate` would consume them.
722         let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
723
724         // Bounds in the type_params and lifetimes fields are repeated in the
725         // predicates field (see rustc_typeck::collect::ty_generics), so remove
726         // them.
727         let stripped_typarams = gens.params.iter()
728             .filter_map(|param| match param.kind {
729                 ty::GenericParamDefKind::Lifetime => None,
730                 ty::GenericParamDefKind::Type { synthetic, .. } => {
731                     if param.name == kw::SelfUpper {
732                         assert_eq!(param.index, 0);
733                         return None;
734                     }
735                     if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
736                         impl_trait.insert(param.index.into(), vec![]);
737                         return None;
738                     }
739                     Some(param.clean(cx))
740                 }
741                 ty::GenericParamDefKind::Const { .. } => None,
742             }).collect::<Vec<GenericParamDef>>();
743
744         // param index -> [(DefId of trait, associated type name, type)]
745         let mut impl_trait_proj =
746             FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
747
748         let where_predicates = preds.predicates.iter()
749             .flat_map(|(p, _)| {
750                 let mut projection = None;
751                 let param_idx = (|| {
752                     if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
753                         if let ty::Param(param) = trait_ref.self_ty().kind {
754                             return Some(param.index);
755                         }
756                     } else if let Some(outlives) = p.to_opt_type_outlives() {
757                         if let ty::Param(param) = outlives.skip_binder().0.kind {
758                             return Some(param.index);
759                         }
760                     } else if let ty::Predicate::Projection(p) = p {
761                         if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
762                             projection = Some(p);
763                             return Some(param.index);
764                         }
765                     }
766
767                     None
768                 })();
769
770                 if let Some(param_idx) = param_idx {
771                     if let Some(b) = impl_trait.get_mut(&param_idx.into()) {
772                         let p = p.clean(cx)?;
773
774                         b.extend(
775                             p.get_bounds()
776                                 .into_iter()
777                                 .flatten()
778                                 .cloned()
779                                 .filter(|b| !b.is_sized_bound(cx))
780                         );
781
782                         let proj = projection
783                             .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
784                         if let Some(((_, trait_did, name), rhs)) =
785                             proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
786                         {
787                             impl_trait_proj
788                                 .entry(param_idx)
789                                 .or_default()
790                                 .push((trait_did, name.to_string(), rhs));
791                         }
792
793                         return None;
794                     }
795                 }
796
797                 Some(p)
798             })
799             .collect::<Vec<_>>();
800
801         for (param, mut bounds) in impl_trait {
802             // Move trait bounds to the front.
803             bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b {
804                 false
805             } else {
806                 true
807             });
808
809             if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
810                 if let Some(proj) = impl_trait_proj.remove(&idx) {
811                     for (trait_did, name, rhs) in proj {
812                         simplify::merge_bounds(
813                             cx,
814                             &mut bounds,
815                             trait_did,
816                             &name,
817                             &rhs.clean(cx),
818                         );
819                     }
820                 }
821             } else {
822                 unreachable!();
823             }
824
825             cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
826         }
827
828         // Now that `cx.impl_trait_bounds` is populated, we can process
829         // remaining predicates which could contain `impl Trait`.
830         let mut where_predicates = where_predicates
831             .into_iter()
832             .flat_map(|p| p.clean(cx))
833             .collect::<Vec<_>>();
834
835         // Type parameters and have a Sized bound by default unless removed with
836         // ?Sized. Scan through the predicates and mark any type parameter with
837         // a Sized bound, removing the bounds as we find them.
838         //
839         // Note that associated types also have a sized bound by default, but we
840         // don't actually know the set of associated types right here so that's
841         // handled in cleaning associated types
842         let mut sized_params = FxHashSet::default();
843         where_predicates.retain(|pred| {
844             match *pred {
845                 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
846                     if bounds.iter().any(|b| b.is_sized_bound(cx)) {
847                         sized_params.insert(g.clone());
848                         false
849                     } else {
850                         true
851                     }
852                 }
853                 _ => true,
854             }
855         });
856
857         // Run through the type parameters again and insert a ?Sized
858         // unbound for any we didn't find to be Sized.
859         for tp in &stripped_typarams {
860             if !sized_params.contains(&tp.name) {
861                 where_predicates.push(WP::BoundPredicate {
862                     ty: Type::Generic(tp.name.clone()),
863                     bounds: vec![GenericBound::maybe_sized(cx)],
864                 })
865             }
866         }
867
868         // It would be nice to collect all of the bounds on a type and recombine
869         // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
870         // and instead see `where T: Foo + Bar + Sized + 'a`
871
872         Generics {
873             params: gens.params
874                         .iter()
875                         .flat_map(|param| match param.kind {
876                             ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
877                             ty::GenericParamDefKind::Type { .. } => None,
878                             ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
879                         }).chain(simplify::ty_params(stripped_typarams).into_iter())
880                         .collect(),
881             where_predicates: simplify::where_clauses(cx, where_predicates),
882         }
883     }
884 }
885
886 impl<'a> Clean<Method> for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId,
887                             Option<hir::Defaultness>) {
888     fn clean(&self, cx: &DocContext<'_>) -> Method {
889         let (generics, decl) = enter_impl_trait(cx, || {
890             (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
891         });
892         let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
893         Method {
894             decl,
895             generics,
896             header: self.0.header,
897             defaultness: self.3,
898             all_types,
899             ret_types,
900         }
901     }
902 }
903
904 impl Clean<Item> for doctree::Function<'_> {
905     fn clean(&self, cx: &DocContext<'_>) -> Item {
906         let (generics, decl) = enter_impl_trait(cx, || {
907             (self.generics.clean(cx), (self.decl, self.body).clean(cx))
908         });
909
910         let did = cx.tcx.hir().local_def_id(self.id);
911         let constness = if cx.tcx.is_min_const_fn(did) {
912             hir::Constness::Const
913         } else {
914             hir::Constness::NotConst
915         };
916         let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
917         Item {
918             name: Some(self.name.clean(cx)),
919             attrs: self.attrs.clean(cx),
920             source: self.whence.clean(cx),
921             visibility: self.vis.clean(cx),
922             stability: cx.stability(self.id).clean(cx),
923             deprecation: cx.deprecation(self.id).clean(cx),
924             def_id: did,
925             inner: FunctionItem(Function {
926                 decl,
927                 generics,
928                 header: hir::FnHeader { constness, ..self.header },
929                 all_types,
930                 ret_types,
931             }),
932         }
933     }
934 }
935
936 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
937     fn clean(&self, cx: &DocContext<'_>) -> Arguments {
938         Arguments {
939             values: self.0.iter().enumerate().map(|(i, ty)| {
940                 let mut name = self.1.get(i).map(|ident| ident.to_string())
941                                             .unwrap_or(String::new());
942                 if name.is_empty() {
943                     name = "_".to_string();
944                 }
945                 Argument {
946                     name,
947                     type_: ty.clean(cx),
948                 }
949             }).collect()
950         }
951     }
952 }
953
954 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
955     fn clean(&self, cx: &DocContext<'_>) -> Arguments {
956         let body = cx.tcx.hir().body(self.1);
957
958         Arguments {
959             values: self.0.iter().enumerate().map(|(i, ty)| {
960                 Argument {
961                     name: name_from_pat(&body.params[i].pat),
962                     type_: ty.clean(cx),
963                 }
964             }).collect()
965         }
966     }
967 }
968
969 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
970     where (&'a [hir::Ty], A): Clean<Arguments>
971 {
972     fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
973         FnDecl {
974             inputs: (&self.0.inputs[..], self.1).clean(cx),
975             output: self.0.output.clean(cx),
976             c_variadic: self.0.c_variadic,
977             attrs: Attributes::default(),
978         }
979     }
980 }
981
982 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
983     fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
984         let (did, sig) = *self;
985         let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
986             vec![].into_iter()
987         } else {
988             cx.tcx.fn_arg_names(did).into_iter()
989         };
990
991         FnDecl {
992             output: Return(sig.skip_binder().output().clean(cx)),
993             attrs: Attributes::default(),
994             c_variadic: sig.skip_binder().c_variadic,
995             inputs: Arguments {
996                 values: sig.skip_binder().inputs().iter().map(|t| {
997                     Argument {
998                         type_: t.clean(cx),
999                         name: names.next().map_or(String::new(), |name| name.to_string()),
1000                     }
1001                 }).collect(),
1002             },
1003         }
1004     }
1005 }
1006
1007 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1008     fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1009         match *self {
1010             hir::Return(ref typ) => Return(typ.clean(cx)),
1011             hir::DefaultReturn(..) => DefaultReturn,
1012         }
1013     }
1014 }
1015
1016 impl Clean<Item> for doctree::Trait<'_> {
1017     fn clean(&self, cx: &DocContext<'_>) -> Item {
1018         let attrs = self.attrs.clean(cx);
1019         let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1020         Item {
1021             name: Some(self.name.clean(cx)),
1022             attrs,
1023             source: self.whence.clean(cx),
1024             def_id: cx.tcx.hir().local_def_id(self.id),
1025             visibility: self.vis.clean(cx),
1026             stability: cx.stability(self.id).clean(cx),
1027             deprecation: cx.deprecation(self.id).clean(cx),
1028             inner: TraitItem(Trait {
1029                 auto: self.is_auto.clean(cx),
1030                 unsafety: self.unsafety,
1031                 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1032                 generics: self.generics.clean(cx),
1033                 bounds: self.bounds.clean(cx),
1034                 is_spotlight,
1035                 is_auto: self.is_auto.clean(cx),
1036             }),
1037         }
1038     }
1039 }
1040
1041 impl Clean<Item> for doctree::TraitAlias<'_> {
1042     fn clean(&self, cx: &DocContext<'_>) -> Item {
1043         let attrs = self.attrs.clean(cx);
1044         Item {
1045             name: Some(self.name.clean(cx)),
1046             attrs,
1047             source: self.whence.clean(cx),
1048             def_id: cx.tcx.hir().local_def_id(self.id),
1049             visibility: self.vis.clean(cx),
1050             stability: cx.stability(self.id).clean(cx),
1051             deprecation: cx.deprecation(self.id).clean(cx),
1052             inner: TraitAliasItem(TraitAlias {
1053                 generics: self.generics.clean(cx),
1054                 bounds: self.bounds.clean(cx),
1055             }),
1056         }
1057     }
1058 }
1059
1060 impl Clean<bool> for hir::IsAuto {
1061     fn clean(&self, _: &DocContext<'_>) -> bool {
1062         match *self {
1063             hir::IsAuto::Yes => true,
1064             hir::IsAuto::No => false,
1065         }
1066     }
1067 }
1068
1069 impl Clean<Type> for hir::TraitRef {
1070     fn clean(&self, cx: &DocContext<'_>) -> Type {
1071         resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1072     }
1073 }
1074
1075 impl Clean<PolyTrait> for hir::PolyTraitRef {
1076     fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1077         PolyTrait {
1078             trait_: self.trait_ref.clean(cx),
1079             generic_params: self.bound_generic_params.clean(cx)
1080         }
1081     }
1082 }
1083
1084 impl Clean<Item> for hir::TraitItem {
1085     fn clean(&self, cx: &DocContext<'_>) -> Item {
1086         let inner = match self.kind {
1087             hir::TraitItemKind::Const(ref ty, default) => {
1088                 AssocConstItem(ty.clean(cx),
1089                                     default.map(|e| print_const_expr(cx, e)))
1090             }
1091             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1092                 MethodItem((sig, &self.generics, body, None).clean(cx))
1093             }
1094             hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1095                 let (generics, decl) = enter_impl_trait(cx, || {
1096                     (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1097                 });
1098                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1099                 TyMethodItem(TyMethod {
1100                     header: sig.header,
1101                     decl,
1102                     generics,
1103                     all_types,
1104                     ret_types,
1105                 })
1106             }
1107             hir::TraitItemKind::Type(ref bounds, ref default) => {
1108                 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1109             }
1110         };
1111         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1112         Item {
1113             name: Some(self.ident.name.clean(cx)),
1114             attrs: self.attrs.clean(cx),
1115             source: self.span.clean(cx),
1116             def_id: local_did,
1117             visibility: Visibility::Inherited,
1118             stability: get_stability(cx, local_did),
1119             deprecation: get_deprecation(cx, local_did),
1120             inner,
1121         }
1122     }
1123 }
1124
1125 impl Clean<Item> for hir::ImplItem {
1126     fn clean(&self, cx: &DocContext<'_>) -> Item {
1127         let inner = match self.kind {
1128             hir::ImplItemKind::Const(ref ty, expr) => {
1129                 AssocConstItem(ty.clean(cx),
1130                                     Some(print_const_expr(cx, expr)))
1131             }
1132             hir::ImplItemKind::Method(ref sig, body) => {
1133                 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1134             }
1135             hir::ImplItemKind::TyAlias(ref ty) => TypedefItem(Typedef {
1136                 type_: ty.clean(cx),
1137                 generics: Generics::default(),
1138             }, true),
1139             hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(OpaqueTy {
1140                 bounds: bounds.clean(cx),
1141                 generics: Generics::default(),
1142             }, true),
1143         };
1144         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1145         Item {
1146             name: Some(self.ident.name.clean(cx)),
1147             source: self.span.clean(cx),
1148             attrs: self.attrs.clean(cx),
1149             def_id: local_did,
1150             visibility: self.vis.clean(cx),
1151             stability: get_stability(cx, local_did),
1152             deprecation: get_deprecation(cx, local_did),
1153             inner,
1154         }
1155     }
1156 }
1157
1158 impl Clean<Item> for ty::AssocItem {
1159     fn clean(&self, cx: &DocContext<'_>) -> Item {
1160         let inner = match self.kind {
1161             ty::AssocKind::Const => {
1162                 let ty = cx.tcx.type_of(self.def_id);
1163                 let default = if self.defaultness.has_value() {
1164                     Some(inline::print_inlined_const(cx, self.def_id))
1165                 } else {
1166                     None
1167                 };
1168                 AssocConstItem(ty.clean(cx), default)
1169             }
1170             ty::AssocKind::Method => {
1171                 let generics = (cx.tcx.generics_of(self.def_id),
1172                                 cx.tcx.explicit_predicates_of(self.def_id)).clean(cx);
1173                 let sig = cx.tcx.fn_sig(self.def_id);
1174                 let mut decl = (self.def_id, sig).clean(cx);
1175
1176                 if self.method_has_self_argument {
1177                     let self_ty = match self.container {
1178                         ty::ImplContainer(def_id) => {
1179                             cx.tcx.type_of(def_id)
1180                         }
1181                         ty::TraitContainer(_) => cx.tcx.types.self_param,
1182                     };
1183                     let self_arg_ty = *sig.input(0).skip_binder();
1184                     if self_arg_ty == self_ty {
1185                         decl.inputs.values[0].type_ = Generic(String::from("Self"));
1186                     } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1187                         if ty == self_ty {
1188                             match decl.inputs.values[0].type_ {
1189                                 BorrowedRef{ref mut type_, ..} => {
1190                                     **type_ = Generic(String::from("Self"))
1191                                 }
1192                                 _ => unreachable!(),
1193                             }
1194                         }
1195                     }
1196                 }
1197
1198                 let provided = match self.container {
1199                     ty::ImplContainer(_) => true,
1200                     ty::TraitContainer(_) => self.defaultness.has_value()
1201                 };
1202                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1203                 if provided {
1204                     let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1205                         hir::Constness::Const
1206                     } else {
1207                         hir::Constness::NotConst
1208                     };
1209                     let asyncness = cx.tcx.asyncness(self.def_id);
1210                     let defaultness = match self.container {
1211                         ty::ImplContainer(_) => Some(self.defaultness),
1212                         ty::TraitContainer(_) => None,
1213                     };
1214                     MethodItem(Method {
1215                         generics,
1216                         decl,
1217                         header: hir::FnHeader {
1218                             unsafety: sig.unsafety(),
1219                             abi: sig.abi(),
1220                             constness,
1221                             asyncness,
1222                         },
1223                         defaultness,
1224                         all_types,
1225                         ret_types,
1226                     })
1227                 } else {
1228                     TyMethodItem(TyMethod {
1229                         generics,
1230                         decl,
1231                         header: hir::FnHeader {
1232                             unsafety: sig.unsafety(),
1233                             abi: sig.abi(),
1234                             constness: hir::Constness::NotConst,
1235                             asyncness: hir::IsAsync::NotAsync,
1236                         },
1237                         all_types,
1238                         ret_types,
1239                     })
1240                 }
1241             }
1242             ty::AssocKind::Type => {
1243                 let my_name = self.ident.name.clean(cx);
1244
1245                 if let ty::TraitContainer(did) = self.container {
1246                     // When loading a cross-crate associated type, the bounds for this type
1247                     // are actually located on the trait/impl itself, so we need to load
1248                     // all of the generics from there and then look for bounds that are
1249                     // applied to this associated type in question.
1250                     let predicates = cx.tcx.explicit_predicates_of(did);
1251                     let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1252                     let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
1253                         let (name, self_type, trait_, bounds) = match *pred {
1254                             WherePredicate::BoundPredicate {
1255                                 ty: QPath { ref name, ref self_type, ref trait_ },
1256                                 ref bounds
1257                             } => (name, self_type, trait_, bounds),
1258                             _ => return None,
1259                         };
1260                         if *name != my_name { return None }
1261                         match **trait_ {
1262                             ResolvedPath { did, .. } if did == self.container.id() => {}
1263                             _ => return None,
1264                         }
1265                         match **self_type {
1266                             Generic(ref s) if *s == "Self" => {}
1267                             _ => return None,
1268                         }
1269                         Some(bounds)
1270                     }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
1271                     // Our Sized/?Sized bound didn't get handled when creating the generics
1272                     // because we didn't actually get our whole set of bounds until just now
1273                     // (some of them may have come from the trait). If we do have a sized
1274                     // bound, we remove it, and if we don't then we add the `?Sized` bound
1275                     // at the end.
1276                     match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1277                         Some(i) => { bounds.remove(i); }
1278                         None => bounds.push(GenericBound::maybe_sized(cx)),
1279                     }
1280
1281                     let ty = if self.defaultness.has_value() {
1282                         Some(cx.tcx.type_of(self.def_id))
1283                     } else {
1284                         None
1285                     };
1286
1287                     AssocTypeItem(bounds, ty.clean(cx))
1288                 } else {
1289                     TypedefItem(Typedef {
1290                         type_: cx.tcx.type_of(self.def_id).clean(cx),
1291                         generics: Generics {
1292                             params: Vec::new(),
1293                             where_predicates: Vec::new(),
1294                         },
1295                     }, true)
1296                 }
1297             }
1298             ty::AssocKind::OpaqueTy => unimplemented!(),
1299         };
1300
1301         let visibility = match self.container {
1302             ty::ImplContainer(_) => self.vis.clean(cx),
1303             ty::TraitContainer(_) => Inherited,
1304         };
1305
1306         Item {
1307             name: Some(self.ident.name.clean(cx)),
1308             visibility,
1309             stability: get_stability(cx, self.def_id),
1310             deprecation: get_deprecation(cx, self.def_id),
1311             def_id: self.def_id,
1312             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1313             source: cx.tcx.def_span(self.def_id).clean(cx),
1314             inner,
1315         }
1316     }
1317 }
1318
1319 impl Clean<Type> for hir::Ty {
1320     fn clean(&self, cx: &DocContext<'_>) -> Type {
1321         use rustc::hir::*;
1322
1323         match self.kind {
1324             TyKind::Never => Never,
1325             TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1326             TyKind::Rptr(ref l, ref m) => {
1327                 let lifetime = if l.is_elided() {
1328                     None
1329                 } else {
1330                     Some(l.clean(cx))
1331                 };
1332                 BorrowedRef {lifetime, mutability: m.mutbl.clean(cx),
1333                              type_: box m.ty.clean(cx)}
1334             }
1335             TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1336             TyKind::Array(ref ty, ref length) => {
1337                 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1338                 let param_env = cx.tcx.param_env(def_id);
1339                 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
1340                 let cid = GlobalId {
1341                     instance: ty::Instance::new(def_id, substs),
1342                     promoted: None
1343                 };
1344                 let length = match cx.tcx.const_eval(param_env.and(cid)) {
1345                     Ok(length) => print_const(cx, length),
1346                     Err(_) => cx.sess()
1347                                 .source_map()
1348                                 .span_to_snippet(cx.tcx.def_span(def_id))
1349                                 .unwrap_or_else(|_| "_".to_string()),
1350                 };
1351                 Array(box ty.clean(cx), length)
1352             },
1353             TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1354             TyKind::Def(item_id, _) => {
1355                 let item = cx.tcx.hir().expect_item(item_id.id);
1356                 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1357                     ImplTrait(ty.bounds.clean(cx))
1358                 } else {
1359                     unreachable!()
1360                 }
1361             }
1362             TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1363                 if let Res::Def(DefKind::TyParam, did) = path.res {
1364                     if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1365                         return new_ty;
1366                     }
1367                     if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1368                         return ImplTrait(bounds);
1369                     }
1370                 }
1371
1372                 let mut alias = None;
1373                 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1374                     // Substitute private type aliases
1375                     if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1376                         if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1377                             alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1378                         }
1379                     }
1380                 };
1381
1382                 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1383                     let provided_params = &path.segments.last().expect("segments were empty");
1384                     let mut ty_substs = FxHashMap::default();
1385                     let mut lt_substs = FxHashMap::default();
1386                     let mut ct_substs = FxHashMap::default();
1387                     let generic_args = provided_params.generic_args();
1388                     {
1389                         let mut indices: GenericParamCount = Default::default();
1390                         for param in generics.params.iter() {
1391                             match param.kind {
1392                                 hir::GenericParamKind::Lifetime { .. } => {
1393                                     let mut j = 0;
1394                                     let lifetime = generic_args.args.iter().find_map(|arg| {
1395                                         match arg {
1396                                             hir::GenericArg::Lifetime(lt) => {
1397                                                 if indices.lifetimes == j {
1398                                                     return Some(lt);
1399                                                 }
1400                                                 j += 1;
1401                                                 None
1402                                             }
1403                                             _ => None,
1404                                         }
1405                                     });
1406                                     if let Some(lt) = lifetime.cloned() {
1407                                         if !lt.is_elided() {
1408                                             let lt_def_id =
1409                                                 cx.tcx.hir().local_def_id(param.hir_id);
1410                                             lt_substs.insert(lt_def_id, lt.clean(cx));
1411                                         }
1412                                     }
1413                                     indices.lifetimes += 1;
1414                                 }
1415                                 hir::GenericParamKind::Type { ref default, .. } => {
1416                                     let ty_param_def_id =
1417                                         cx.tcx.hir().local_def_id(param.hir_id);
1418                                     let mut j = 0;
1419                                     let type_ = generic_args.args.iter().find_map(|arg| {
1420                                         match arg {
1421                                             hir::GenericArg::Type(ty) => {
1422                                                 if indices.types == j {
1423                                                     return Some(ty);
1424                                                 }
1425                                                 j += 1;
1426                                                 None
1427                                             }
1428                                             _ => None,
1429                                         }
1430                                     });
1431                                     if let Some(ty) = type_ {
1432                                         ty_substs.insert(ty_param_def_id, ty.clean(cx));
1433                                     } else if let Some(default) = default.clone() {
1434                                         ty_substs.insert(ty_param_def_id,
1435                                                          default.clean(cx));
1436                                     }
1437                                     indices.types += 1;
1438                                 }
1439                                 hir::GenericParamKind::Const { .. } => {
1440                                     let const_param_def_id =
1441                                         cx.tcx.hir().local_def_id(param.hir_id);
1442                                     let mut j = 0;
1443                                     let const_ = generic_args.args.iter().find_map(|arg| {
1444                                         match arg {
1445                                             hir::GenericArg::Const(ct) => {
1446                                                 if indices.consts == j {
1447                                                     return Some(ct);
1448                                                 }
1449                                                 j += 1;
1450                                                 None
1451                                             }
1452                                             _ => None,
1453                                         }
1454                                     });
1455                                     if let Some(ct) = const_ {
1456                                         ct_substs.insert(const_param_def_id, ct.clean(cx));
1457                                     }
1458                                     // FIXME(const_generics:defaults)
1459                                     indices.consts += 1;
1460                                 }
1461                             }
1462                         }
1463                     }
1464                     return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1465                 }
1466                 resolve_type(cx, path.clean(cx), self.hir_id)
1467             }
1468             TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1469                 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1470                 let trait_segments = &segments[..segments.len() - 1];
1471                 let trait_path = self::Path {
1472                     global: p.is_global(),
1473                     res: Res::Def(
1474                         DefKind::Trait,
1475                         cx.tcx.associated_item(p.res.def_id()).container.id(),
1476                     ),
1477                     segments: trait_segments.clean(cx),
1478                 };
1479                 Type::QPath {
1480                     name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1481                     self_type: box qself.clean(cx),
1482                     trait_: box resolve_type(cx, trait_path, self.hir_id)
1483                 }
1484             }
1485             TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1486                 let mut res = Res::Err;
1487                 let ty = hir_ty_to_ty(cx.tcx, self);
1488                 if let ty::Projection(proj) = ty.kind {
1489                     res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1490                 }
1491                 let trait_path = hir::Path {
1492                     span: self.span,
1493                     res,
1494                     segments: vec![].into(),
1495                 };
1496                 Type::QPath {
1497                     name: segment.ident.name.clean(cx),
1498                     self_type: box qself.clean(cx),
1499                     trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id)
1500                 }
1501             }
1502             TyKind::TraitObject(ref bounds, ref lifetime) => {
1503                 match bounds[0].clean(cx).trait_ {
1504                     ResolvedPath { path, param_names: None, did, is_generic } => {
1505                         let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
1506                             self::GenericBound::TraitBound(bound.clean(cx),
1507                                                            hir::TraitBoundModifier::None)
1508                         }).collect();
1509                         if !lifetime.is_elided() {
1510                             bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1511                         }
1512                         ResolvedPath { path, param_names: Some(bounds), did, is_generic, }
1513                     }
1514                     _ => Infer, // shouldn't happen
1515                 }
1516             }
1517             TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1518             TyKind::Infer | TyKind::Err => Infer,
1519             TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1520         }
1521     }
1522 }
1523
1524 impl<'tcx> Clean<Type> for Ty<'tcx> {
1525     fn clean(&self, cx: &DocContext<'_>) -> Type {
1526         debug!("cleaning type: {:?}", self);
1527         match self.kind {
1528             ty::Never => Never,
1529             ty::Bool => Primitive(PrimitiveType::Bool),
1530             ty::Char => Primitive(PrimitiveType::Char),
1531             ty::Int(int_ty) => Primitive(int_ty.into()),
1532             ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1533             ty::Float(float_ty) => Primitive(float_ty.into()),
1534             ty::Str => Primitive(PrimitiveType::Str),
1535             ty::Slice(ty) => Slice(box ty.clean(cx)),
1536             ty::Array(ty, n) => {
1537                 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1538                 if let ty::ConstKind::Unevaluated(def_id, substs) = n.val {
1539                     let param_env = cx.tcx.param_env(def_id);
1540                     let cid = GlobalId {
1541                         instance: ty::Instance::new(def_id, substs),
1542                         promoted: None
1543                     };
1544                     if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) {
1545                         n = new_n;
1546                     }
1547                 };
1548                 let n = print_const(cx, n);
1549                 Array(box ty.clean(cx), n)
1550             }
1551             ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1552             ty::Ref(r, ty, mutbl) => BorrowedRef {
1553                 lifetime: r.clean(cx),
1554                 mutability: mutbl.clean(cx),
1555                 type_: box ty.clean(cx),
1556             },
1557             ty::FnDef(..) |
1558             ty::FnPtr(_) => {
1559                 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1560                 let sig = ty.fn_sig(cx.tcx);
1561                 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1562                 BareFunction(box BareFunctionDecl {
1563                     unsafety: sig.unsafety(),
1564                     generic_params: Vec::new(),
1565                     decl: (local_def_id, sig).clean(cx),
1566                     abi: sig.abi(),
1567                 })
1568             }
1569             ty::Adt(def, substs) => {
1570                 let did = def.did;
1571                 let kind = match def.adt_kind() {
1572                     AdtKind::Struct => TypeKind::Struct,
1573                     AdtKind::Union => TypeKind::Union,
1574                     AdtKind::Enum => TypeKind::Enum,
1575                 };
1576                 inline::record_extern_fqn(cx, did, kind);
1577                 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1578                 ResolvedPath {
1579                     path,
1580                     param_names: None,
1581                     did,
1582                     is_generic: false,
1583                 }
1584             }
1585             ty::Foreign(did) => {
1586                 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1587                 let path = external_path(cx, cx.tcx.item_name(did),
1588                                          None, false, vec![], InternalSubsts::empty());
1589                 ResolvedPath {
1590                     path,
1591                     param_names: None,
1592                     did,
1593                     is_generic: false,
1594                 }
1595             }
1596             ty::Dynamic(ref obj, ref reg) => {
1597                 // HACK: pick the first `did` as the `did` of the trait object. Someone
1598                 // might want to implement "native" support for marker-trait-only
1599                 // trait objects.
1600                 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1601                 let did = dids.next().unwrap_or_else(|| {
1602                     panic!("found trait object `{:?}` with no traits?", self)
1603                 });
1604                 let substs = match obj.principal() {
1605                     Some(principal) => principal.skip_binder().substs,
1606                     // marker traits have no substs.
1607                     _ => cx.tcx.intern_substs(&[])
1608                 };
1609
1610                 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1611
1612                 let mut param_names = vec![];
1613                 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1614                 for did in dids {
1615                     let empty = cx.tcx.intern_substs(&[]);
1616                     let path = external_path(cx, cx.tcx.item_name(did),
1617                         Some(did), false, vec![], empty);
1618                     inline::record_extern_fqn(cx, did, TypeKind::Trait);
1619                     let bound = GenericBound::TraitBound(PolyTrait {
1620                         trait_: ResolvedPath {
1621                             path,
1622                             param_names: None,
1623                             did,
1624                             is_generic: false,
1625                         },
1626                         generic_params: Vec::new(),
1627                     }, hir::TraitBoundModifier::None);
1628                     param_names.push(bound);
1629                 }
1630
1631                 let mut bindings = vec![];
1632                 for pb in obj.projection_bounds() {
1633                     bindings.push(TypeBinding {
1634                         name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1635                         kind: TypeBindingKind::Equality {
1636                             ty: pb.skip_binder().ty.clean(cx)
1637                         },
1638                     });
1639                 }
1640
1641                 let path = external_path(cx, cx.tcx.item_name(did), Some(did),
1642                     false, bindings, substs);
1643                 ResolvedPath {
1644                     path,
1645                     param_names: Some(param_names),
1646                     did,
1647                     is_generic: false,
1648                 }
1649             }
1650             ty::Tuple(ref t) => {
1651                 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1652             }
1653
1654             ty::Projection(ref data) => data.clean(cx),
1655
1656             ty::Param(ref p) => {
1657                 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1658                     ImplTrait(bounds)
1659                 } else {
1660                     Generic(p.name.to_string())
1661                 }
1662             }
1663
1664             ty::Opaque(def_id, substs) => {
1665                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1666                 // by looking up the projections associated with the def_id.
1667                 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1668                 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1669                 let bounds = predicates_of.instantiate(cx.tcx, substs);
1670                 let mut regions = vec![];
1671                 let mut has_sized = false;
1672                 let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
1673                     let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1674                         tr
1675                     } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1676                         // these should turn up at the end
1677                         pred.skip_binder().1.clean(cx).map(|r| {
1678                             regions.push(GenericBound::Outlives(r))
1679                         });
1680                         return None;
1681                     } else {
1682                         return None;
1683                     };
1684
1685                     if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1686                         if trait_ref.def_id() == sized {
1687                             has_sized = true;
1688                             return None;
1689                         }
1690                     }
1691
1692                     let bounds = bounds.predicates.iter().filter_map(|pred|
1693                         if let ty::Predicate::Projection(proj) = *pred {
1694                             let proj = proj.skip_binder();
1695                             if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
1696                                 Some(TypeBinding {
1697                                     name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
1698                                                 .ident.name.clean(cx),
1699                                     kind: TypeBindingKind::Equality {
1700                                         ty: proj.ty.clean(cx),
1701                                     },
1702                                 })
1703                             } else {
1704                                 None
1705                             }
1706                         } else {
1707                             None
1708                         }
1709                     ).collect();
1710
1711                     Some((trait_ref.skip_binder(), bounds).clean(cx))
1712                 }).collect::<Vec<_>>();
1713                 bounds.extend(regions);
1714                 if !has_sized && !bounds.is_empty() {
1715                     bounds.insert(0, GenericBound::maybe_sized(cx));
1716                 }
1717                 ImplTrait(bounds)
1718             }
1719
1720             ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1721
1722             ty::Bound(..) => panic!("Bound"),
1723             ty::Placeholder(..) => panic!("Placeholder"),
1724             ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1725             ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1726             ty::Infer(..) => panic!("Infer"),
1727             ty::Error => panic!("Error"),
1728         }
1729     }
1730 }
1731
1732 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1733     fn clean(&self, cx: &DocContext<'_>) -> Constant {
1734         Constant {
1735             type_: self.ty.clean(cx),
1736             expr: format!("{}", self),
1737         }
1738     }
1739 }
1740
1741 impl Clean<Item> for hir::StructField {
1742     fn clean(&self, cx: &DocContext<'_>) -> Item {
1743         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1744
1745         Item {
1746             name: Some(self.ident.name).clean(cx),
1747             attrs: self.attrs.clean(cx),
1748             source: self.span.clean(cx),
1749             visibility: self.vis.clean(cx),
1750             stability: get_stability(cx, local_did),
1751             deprecation: get_deprecation(cx, local_did),
1752             def_id: local_did,
1753             inner: StructFieldItem(self.ty.clean(cx)),
1754         }
1755     }
1756 }
1757
1758 impl Clean<Item> for ty::FieldDef {
1759     fn clean(&self, cx: &DocContext<'_>) -> Item {
1760         Item {
1761             name: Some(self.ident.name).clean(cx),
1762             attrs: cx.tcx.get_attrs(self.did).clean(cx),
1763             source: cx.tcx.def_span(self.did).clean(cx),
1764             visibility: self.vis.clean(cx),
1765             stability: get_stability(cx, self.did),
1766             deprecation: get_deprecation(cx, self.did),
1767             def_id: self.did,
1768             inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1769         }
1770     }
1771 }
1772
1773 impl Clean<Visibility> for hir::Visibility {
1774     fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1775         match self.node {
1776             hir::VisibilityKind::Public => Visibility::Public,
1777             hir::VisibilityKind::Inherited => Visibility::Inherited,
1778             hir::VisibilityKind::Crate(_) => Visibility::Crate,
1779             hir::VisibilityKind::Restricted { ref path, .. } => {
1780                 let path = path.clean(cx);
1781                 let did = register_res(cx, path.res);
1782                 Visibility::Restricted(did, path)
1783             }
1784         }
1785     }
1786 }
1787
1788 impl Clean<Visibility> for ty::Visibility {
1789     fn clean(&self, _: &DocContext<'_>) -> Visibility {
1790         if *self == ty::Visibility::Public { Public } else { Inherited }
1791     }
1792 }
1793
1794 impl Clean<Item> for doctree::Struct<'_> {
1795     fn clean(&self, cx: &DocContext<'_>) -> Item {
1796         Item {
1797             name: Some(self.name.clean(cx)),
1798             attrs: self.attrs.clean(cx),
1799             source: self.whence.clean(cx),
1800             def_id: cx.tcx.hir().local_def_id(self.id),
1801             visibility: self.vis.clean(cx),
1802             stability: cx.stability(self.id).clean(cx),
1803             deprecation: cx.deprecation(self.id).clean(cx),
1804             inner: StructItem(Struct {
1805                 struct_type: self.struct_type,
1806                 generics: self.generics.clean(cx),
1807                 fields: self.fields.clean(cx),
1808                 fields_stripped: false,
1809             }),
1810         }
1811     }
1812 }
1813
1814 impl Clean<Item> for doctree::Union<'_> {
1815     fn clean(&self, cx: &DocContext<'_>) -> Item {
1816         Item {
1817             name: Some(self.name.clean(cx)),
1818             attrs: self.attrs.clean(cx),
1819             source: self.whence.clean(cx),
1820             def_id: cx.tcx.hir().local_def_id(self.id),
1821             visibility: self.vis.clean(cx),
1822             stability: cx.stability(self.id).clean(cx),
1823             deprecation: cx.deprecation(self.id).clean(cx),
1824             inner: UnionItem(Union {
1825                 struct_type: self.struct_type,
1826                 generics: self.generics.clean(cx),
1827                 fields: self.fields.clean(cx),
1828                 fields_stripped: false,
1829             }),
1830         }
1831     }
1832 }
1833
1834 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1835     fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1836         VariantStruct {
1837             struct_type: doctree::struct_type_from_def(self),
1838             fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1839             fields_stripped: false,
1840         }
1841     }
1842 }
1843
1844 impl Clean<Item> for doctree::Enum<'_> {
1845     fn clean(&self, cx: &DocContext<'_>) -> Item {
1846         Item {
1847             name: Some(self.name.clean(cx)),
1848             attrs: self.attrs.clean(cx),
1849             source: self.whence.clean(cx),
1850             def_id: cx.tcx.hir().local_def_id(self.id),
1851             visibility: self.vis.clean(cx),
1852             stability: cx.stability(self.id).clean(cx),
1853             deprecation: cx.deprecation(self.id).clean(cx),
1854             inner: EnumItem(Enum {
1855                 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1856                 generics: self.generics.clean(cx),
1857                 variants_stripped: false,
1858             }),
1859         }
1860     }
1861 }
1862
1863 impl Clean<Item> for doctree::Variant<'_> {
1864     fn clean(&self, cx: &DocContext<'_>) -> Item {
1865         Item {
1866             name: Some(self.name.clean(cx)),
1867             attrs: self.attrs.clean(cx),
1868             source: self.whence.clean(cx),
1869             visibility: Inherited,
1870             stability: cx.stability(self.id).clean(cx),
1871             deprecation: cx.deprecation(self.id).clean(cx),
1872             def_id: cx.tcx.hir().local_def_id(self.id),
1873             inner: VariantItem(Variant {
1874                 kind: self.def.clean(cx),
1875             }),
1876         }
1877     }
1878 }
1879
1880 impl Clean<Item> for ty::VariantDef {
1881     fn clean(&self, cx: &DocContext<'_>) -> Item {
1882         let kind = match self.ctor_kind {
1883             CtorKind::Const => VariantKind::CLike,
1884             CtorKind::Fn => {
1885                 VariantKind::Tuple(
1886                     self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
1887                 )
1888             }
1889             CtorKind::Fictive => {
1890                 VariantKind::Struct(VariantStruct {
1891                     struct_type: doctree::Plain,
1892                     fields_stripped: false,
1893                     fields: self.fields.iter().map(|field| {
1894                         Item {
1895                             source: cx.tcx.def_span(field.did).clean(cx),
1896                             name: Some(field.ident.name.clean(cx)),
1897                             attrs: cx.tcx.get_attrs(field.did).clean(cx),
1898                             visibility: field.vis.clean(cx),
1899                             def_id: field.did,
1900                             stability: get_stability(cx, field.did),
1901                             deprecation: get_deprecation(cx, field.did),
1902                             inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
1903                         }
1904                     }).collect()
1905                 })
1906             }
1907         };
1908         Item {
1909             name: Some(self.ident.clean(cx)),
1910             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1911             source: cx.tcx.def_span(self.def_id).clean(cx),
1912             visibility: Inherited,
1913             def_id: self.def_id,
1914             inner: VariantItem(Variant { kind }),
1915             stability: get_stability(cx, self.def_id),
1916             deprecation: get_deprecation(cx, self.def_id),
1917         }
1918     }
1919 }
1920
1921 impl Clean<VariantKind> for hir::VariantData {
1922     fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1923         match self {
1924             hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1925             hir::VariantData::Tuple(..) =>
1926                 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()),
1927             hir::VariantData::Unit(..) => VariantKind::CLike,
1928         }
1929     }
1930 }
1931
1932 impl Clean<Span> for syntax_pos::Span {
1933     fn clean(&self, cx: &DocContext<'_>) -> Span {
1934         if self.is_dummy() {
1935             return Span::empty();
1936         }
1937
1938         let cm = cx.sess().source_map();
1939         let filename = cm.span_to_filename(*self);
1940         let lo = cm.lookup_char_pos(self.lo());
1941         let hi = cm.lookup_char_pos(self.hi());
1942         Span {
1943             filename,
1944             loline: lo.line,
1945             locol: lo.col.to_usize(),
1946             hiline: hi.line,
1947             hicol: hi.col.to_usize(),
1948             original: *self,
1949         }
1950     }
1951 }
1952
1953 impl Clean<Path> for hir::Path {
1954     fn clean(&self, cx: &DocContext<'_>) -> Path {
1955         Path {
1956             global: self.is_global(),
1957             res: self.res,
1958             segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1959         }
1960     }
1961 }
1962
1963 impl Clean<GenericArgs> for hir::GenericArgs {
1964     fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1965         if self.parenthesized {
1966             let output = self.bindings[0].ty().clean(cx);
1967             GenericArgs::Parenthesized {
1968                 inputs: self.inputs().clean(cx),
1969                 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
1970             }
1971         } else {
1972             let elide_lifetimes = self.args.iter().all(|arg| match arg {
1973                 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1974                 _ => true,
1975             });
1976             GenericArgs::AngleBracketed {
1977                 args: self.args.iter().filter_map(|arg| match arg {
1978                     hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1979                         Some(GenericArg::Lifetime(lt.clean(cx)))
1980                     }
1981                     hir::GenericArg::Lifetime(_) => None,
1982                     hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1983                     hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1984                 }).collect(),
1985                 bindings: self.bindings.clean(cx),
1986             }
1987         }
1988     }
1989 }
1990
1991 impl Clean<PathSegment> for hir::PathSegment {
1992     fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1993         PathSegment {
1994             name: self.ident.name.clean(cx),
1995             args: self.generic_args().clean(cx),
1996         }
1997     }
1998 }
1999
2000 impl Clean<String> for Ident {
2001     #[inline]
2002     fn clean(&self, cx: &DocContext<'_>) -> String {
2003         self.name.clean(cx)
2004     }
2005 }
2006
2007 impl Clean<String> for ast::Name {
2008     #[inline]
2009     fn clean(&self, _: &DocContext<'_>) -> String {
2010         self.to_string()
2011     }
2012 }
2013
2014 impl Clean<Item> for doctree::Typedef<'_> {
2015     fn clean(&self, cx: &DocContext<'_>) -> Item {
2016         Item {
2017             name: Some(self.name.clean(cx)),
2018             attrs: self.attrs.clean(cx),
2019             source: self.whence.clean(cx),
2020             def_id: cx.tcx.hir().local_def_id(self.id),
2021             visibility: self.vis.clean(cx),
2022             stability: cx.stability(self.id).clean(cx),
2023             deprecation: cx.deprecation(self.id).clean(cx),
2024             inner: TypedefItem(Typedef {
2025                 type_: self.ty.clean(cx),
2026                 generics: self.gen.clean(cx),
2027             }, false),
2028         }
2029     }
2030 }
2031
2032 impl Clean<Item> for doctree::OpaqueTy<'_> {
2033     fn clean(&self, cx: &DocContext<'_>) -> Item {
2034         Item {
2035             name: Some(self.name.clean(cx)),
2036             attrs: self.attrs.clean(cx),
2037             source: self.whence.clean(cx),
2038             def_id: cx.tcx.hir().local_def_id(self.id),
2039             visibility: self.vis.clean(cx),
2040             stability: cx.stability(self.id).clean(cx),
2041             deprecation: cx.deprecation(self.id).clean(cx),
2042             inner: OpaqueTyItem(OpaqueTy {
2043                 bounds: self.opaque_ty.bounds.clean(cx),
2044                 generics: self.opaque_ty.generics.clean(cx),
2045             }, false),
2046         }
2047     }
2048 }
2049
2050 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2051     fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2052         let (generic_params, decl) = enter_impl_trait(cx, || {
2053             (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2054         });
2055         BareFunctionDecl {
2056             unsafety: self.unsafety,
2057             abi: self.abi,
2058             decl,
2059             generic_params,
2060         }
2061     }
2062 }
2063
2064 impl Clean<Item> for doctree::Static<'_> {
2065     fn clean(&self, cx: &DocContext<'_>) -> Item {
2066         debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2067         Item {
2068             name: Some(self.name.clean(cx)),
2069             attrs: self.attrs.clean(cx),
2070             source: self.whence.clean(cx),
2071             def_id: cx.tcx.hir().local_def_id(self.id),
2072             visibility: self.vis.clean(cx),
2073             stability: cx.stability(self.id).clean(cx),
2074             deprecation: cx.deprecation(self.id).clean(cx),
2075             inner: StaticItem(Static {
2076                 type_: self.type_.clean(cx),
2077                 mutability: self.mutability.clean(cx),
2078                 expr: print_const_expr(cx, self.expr),
2079             }),
2080         }
2081     }
2082 }
2083
2084 impl Clean<Item> for doctree::Constant<'_> {
2085     fn clean(&self, cx: &DocContext<'_>) -> Item {
2086         Item {
2087             name: Some(self.name.clean(cx)),
2088             attrs: self.attrs.clean(cx),
2089             source: self.whence.clean(cx),
2090             def_id: cx.tcx.hir().local_def_id(self.id),
2091             visibility: self.vis.clean(cx),
2092             stability: cx.stability(self.id).clean(cx),
2093             deprecation: cx.deprecation(self.id).clean(cx),
2094             inner: ConstantItem(Constant {
2095                 type_: self.type_.clean(cx),
2096                 expr: print_const_expr(cx, self.expr),
2097             }),
2098         }
2099     }
2100 }
2101
2102 impl Clean<Mutability> for hir::Mutability {
2103     fn clean(&self, _: &DocContext<'_>) -> Mutability {
2104         match self {
2105             &hir::Mutability::Mutable => Mutable,
2106             &hir::Mutability::Immutable => Immutable,
2107         }
2108     }
2109 }
2110
2111 impl Clean<ImplPolarity> for ty::ImplPolarity {
2112     fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2113         match self {
2114             &ty::ImplPolarity::Positive |
2115             // FIXME: do we want to do something else here?
2116             &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2117             &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2118         }
2119     }
2120 }
2121
2122 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2123     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2124         let mut ret = Vec::new();
2125         let trait_ = self.trait_.clean(cx);
2126         let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2127         let def_id = cx.tcx.hir().local_def_id(self.id);
2128
2129         // If this impl block is an implementation of the Deref trait, then we
2130         // need to try inlining the target's inherent impl blocks as well.
2131         if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2132             build_deref_target_impls(cx, &items, &mut ret);
2133         }
2134
2135         let provided = trait_.def_id().map(|did| {
2136             cx.tcx.provided_trait_methods(did)
2137                   .into_iter()
2138                   .map(|meth| meth.ident.to_string())
2139                   .collect()
2140         }).unwrap_or_default();
2141
2142         ret.push(Item {
2143             name: None,
2144             attrs: self.attrs.clean(cx),
2145             source: self.whence.clean(cx),
2146             def_id,
2147             visibility: self.vis.clean(cx),
2148             stability: cx.stability(self.id).clean(cx),
2149             deprecation: cx.deprecation(self.id).clean(cx),
2150             inner: ImplItem(Impl {
2151                 unsafety: self.unsafety,
2152                 generics: self.generics.clean(cx),
2153                 provided_trait_methods: provided,
2154                 trait_,
2155                 for_: self.for_.clean(cx),
2156                 items,
2157                 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2158                 synthetic: false,
2159                 blanket_impl: None,
2160             })
2161         });
2162         ret
2163     }
2164 }
2165
2166 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2167     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2168
2169         let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
2170             a.check_name(sym::doc) && match a.meta_item_list() {
2171                 Some(l) => attr::list_contains_name(&l, sym::inline),
2172                 None => false,
2173             }
2174         });
2175
2176         if please_inline {
2177             let mut visited = FxHashSet::default();
2178
2179             let res = Res::Def(
2180                 DefKind::Mod,
2181                 DefId {
2182                     krate: self.cnum,
2183                     index: CRATE_DEF_INDEX,
2184                 },
2185             );
2186
2187             if let Some(items) = inline::try_inline(
2188                 cx, res, self.name,
2189                 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2190                 &mut visited
2191             ) {
2192                 return items;
2193             }
2194         }
2195
2196         vec![Item {
2197             name: None,
2198             attrs: self.attrs.clean(cx),
2199             source: self.whence.clean(cx),
2200             def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2201             visibility: self.vis.clean(cx),
2202             stability: None,
2203             deprecation: None,
2204             inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2205         }]
2206     }
2207 }
2208
2209 impl Clean<Vec<Item>> for doctree::Import<'_> {
2210     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2211         // We consider inlining the documentation of `pub use` statements, but we
2212         // forcefully don't inline if this is not public or if the
2213         // #[doc(no_inline)] attribute is present.
2214         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2215         let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| {
2216             a.check_name(sym::doc) && match a.meta_item_list() {
2217                 Some(l) => attr::list_contains_name(&l, sym::no_inline) ||
2218                            attr::list_contains_name(&l, sym::hidden),
2219                 None => false,
2220             }
2221         });
2222         // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2223         // crate in Rust 2018+
2224         let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2225         let path = self.path.clean(cx);
2226         let inner = if self.glob {
2227             if !denied {
2228                 let mut visited = FxHashSet::default();
2229                 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2230                     return items;
2231                 }
2232             }
2233
2234             Import::Glob(resolve_use_source(cx, path))
2235         } else {
2236             let name = self.name;
2237             if !please_inline {
2238                 match path.res {
2239                     Res::Def(DefKind::Mod, did) => {
2240                         if !did.is_local() && did.index == CRATE_DEF_INDEX {
2241                             // if we're `pub use`ing an extern crate root, don't inline it unless we
2242                             // were specifically asked for it
2243                             denied = true;
2244                         }
2245                     }
2246                     _ => {}
2247                 }
2248             }
2249             if !denied {
2250                 let mut visited = FxHashSet::default();
2251                 if let Some(items) = inline::try_inline(
2252                     cx, path.res, name,
2253                     Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2254                     &mut visited
2255                 ) {
2256                     return items;
2257                 }
2258             }
2259             Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2260         };
2261
2262         vec![Item {
2263             name: None,
2264             attrs: self.attrs.clean(cx),
2265             source: self.whence.clean(cx),
2266             def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2267             visibility: self.vis.clean(cx),
2268             stability: None,
2269             deprecation: None,
2270             inner: ImportItem(inner)
2271         }]
2272     }
2273 }
2274
2275 impl Clean<Item> for doctree::ForeignItem<'_> {
2276     fn clean(&self, cx: &DocContext<'_>) -> Item {
2277         let inner = match self.kind {
2278             hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2279                 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2280                 let (generics, decl) = enter_impl_trait(cx, || {
2281                     (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2282                 });
2283                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2284                 ForeignFunctionItem(Function {
2285                     decl,
2286                     generics,
2287                     header: hir::FnHeader {
2288                         unsafety: hir::Unsafety::Unsafe,
2289                         abi,
2290                         constness: hir::Constness::NotConst,
2291                         asyncness: hir::IsAsync::NotAsync,
2292                     },
2293                     all_types,
2294                     ret_types,
2295                 })
2296             }
2297             hir::ForeignItemKind::Static(ref ty, mutbl) => {
2298                 ForeignStaticItem(Static {
2299                     type_: ty.clean(cx),
2300                     mutability: mutbl.clean(cx),
2301                     expr: String::new(),
2302                 })
2303             }
2304             hir::ForeignItemKind::Type => {
2305                 ForeignTypeItem
2306             }
2307         };
2308
2309         Item {
2310             name: Some(self.name.clean(cx)),
2311             attrs: self.attrs.clean(cx),
2312             source: self.whence.clean(cx),
2313             def_id: cx.tcx.hir().local_def_id(self.id),
2314             visibility: self.vis.clean(cx),
2315             stability: cx.stability(self.id).clean(cx),
2316             deprecation: cx.deprecation(self.id).clean(cx),
2317             inner,
2318         }
2319     }
2320 }
2321
2322 impl Clean<Item> for doctree::Macro<'_> {
2323     fn clean(&self, cx: &DocContext<'_>) -> Item {
2324         let name = self.name.clean(cx);
2325         Item {
2326             name: Some(name.clone()),
2327             attrs: self.attrs.clean(cx),
2328             source: self.whence.clean(cx),
2329             visibility: Public,
2330             stability: cx.stability(self.hid).clean(cx),
2331             deprecation: cx.deprecation(self.hid).clean(cx),
2332             def_id: self.def_id,
2333             inner: MacroItem(Macro {
2334                 source: format!("macro_rules! {} {{\n{}}}",
2335                                 name,
2336                                 self.matchers.iter().map(|span| {
2337                                     format!("    {} => {{ ... }};\n", span.to_src(cx))
2338                                 }).collect::<String>()),
2339                 imported_from: self.imported_from.clean(cx),
2340             }),
2341         }
2342     }
2343 }
2344
2345 impl Clean<Item> for doctree::ProcMacro<'_> {
2346     fn clean(&self, cx: &DocContext<'_>) -> Item {
2347         Item {
2348             name: Some(self.name.clean(cx)),
2349             attrs: self.attrs.clean(cx),
2350             source: self.whence.clean(cx),
2351             visibility: Public,
2352             stability: cx.stability(self.id).clean(cx),
2353             deprecation: cx.deprecation(self.id).clean(cx),
2354             def_id: cx.tcx.hir().local_def_id(self.id),
2355             inner: ProcMacroItem(ProcMacro {
2356                 kind: self.kind,
2357                 helpers: self.helpers.clean(cx),
2358             }),
2359         }
2360     }
2361 }
2362
2363 impl Clean<Stability> for attr::Stability {
2364     fn clean(&self, _: &DocContext<'_>) -> Stability {
2365         Stability {
2366             level: stability::StabilityLevel::from_attr_level(&self.level),
2367             feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2368             since: match self.level {
2369                 attr::Stable {ref since} => since.to_string(),
2370                 _ => String::new(),
2371             },
2372             deprecation: self.rustc_depr.as_ref().map(|d| {
2373                 Deprecation {
2374                     note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2375                     since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2376                 }
2377             }),
2378             unstable_reason: match self.level {
2379                 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2380                 _ => None,
2381             },
2382             issue: match self.level {
2383                 attr::Unstable {issue, ..} => issue,
2384                 _ => None,
2385             }
2386         }
2387     }
2388 }
2389
2390 impl<'a> Clean<Stability> for &'a attr::Stability {
2391     fn clean(&self, dc: &DocContext<'_>) -> Stability {
2392         (**self).clean(dc)
2393     }
2394 }
2395
2396 impl Clean<Deprecation> for attr::Deprecation {
2397     fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2398         Deprecation {
2399             since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2400             note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2401         }
2402     }
2403 }
2404
2405 impl Clean<TypeBinding> for hir::TypeBinding {
2406     fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2407         TypeBinding {
2408             name: self.ident.name.clean(cx),
2409             kind: self.kind.clean(cx),
2410         }
2411     }
2412 }
2413
2414 impl Clean<TypeBindingKind> for hir::TypeBindingKind {
2415     fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2416         match *self {
2417             hir::TypeBindingKind::Equality { ref ty } =>
2418                 TypeBindingKind::Equality {
2419                     ty: ty.clean(cx),
2420                 },
2421             hir::TypeBindingKind::Constraint { ref bounds } =>
2422                 TypeBindingKind::Constraint {
2423                     bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2424                 },
2425         }
2426     }
2427 }
2428
2429 enum SimpleBound {
2430     TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2431     Outlives(Lifetime),
2432 }
2433
2434 impl From<GenericBound> for SimpleBound {
2435     fn from(bound: GenericBound) -> Self {
2436         match bound.clone() {
2437             GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2438             GenericBound::TraitBound(t, mod_) => match t.trait_ {
2439                 Type::ResolvedPath { path, param_names, .. } => {
2440                     SimpleBound::TraitBound(path.segments,
2441                                             param_names
2442                                                 .map_or_else(|| Vec::new(), |v| v.iter()
2443                                                         .map(|p| SimpleBound::from(p.clone()))
2444                                                         .collect()),
2445                                             t.generic_params,
2446                                             mod_)
2447                 }
2448                 _ => panic!("Unexpected bound {:?}", bound),
2449             }
2450         }
2451     }
2452 }