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