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