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