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