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