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