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