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