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