]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
formatting
[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                 let type_ = ty.clean(cx);
1126                 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1127                 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1128             }
1129             hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(
1130                 OpaqueTy { bounds: bounds.clean(cx), generics: Generics::default() },
1131                 true,
1132             ),
1133         };
1134         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1135         Item {
1136             name: Some(self.ident.name.clean(cx)),
1137             source: self.span.clean(cx),
1138             attrs: self.attrs.clean(cx),
1139             def_id: local_did,
1140             visibility: self.vis.clean(cx),
1141             stability: get_stability(cx, local_did),
1142             deprecation: get_deprecation(cx, local_did),
1143             inner,
1144         }
1145     }
1146 }
1147
1148 impl Clean<Item> for ty::AssocItem {
1149     fn clean(&self, cx: &DocContext<'_>) -> Item {
1150         let inner = match self.kind {
1151             ty::AssocKind::Const => {
1152                 let ty = cx.tcx.type_of(self.def_id);
1153                 let default = if self.defaultness.has_value() {
1154                     Some(inline::print_inlined_const(cx, self.def_id))
1155                 } else {
1156                     None
1157                 };
1158                 AssocConstItem(ty.clean(cx), default)
1159             }
1160             ty::AssocKind::Method => {
1161                 let generics =
1162                     (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1163                         .clean(cx);
1164                 let sig = cx.tcx.fn_sig(self.def_id);
1165                 let mut decl = (self.def_id, sig).clean(cx);
1166
1167                 if self.method_has_self_argument {
1168                     let self_ty = match self.container {
1169                         ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1170                         ty::TraitContainer(_) => cx.tcx.types.self_param,
1171                     };
1172                     let self_arg_ty = *sig.input(0).skip_binder();
1173                     if self_arg_ty == self_ty {
1174                         decl.inputs.values[0].type_ = Generic(String::from("Self"));
1175                     } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1176                         if ty == self_ty {
1177                             match decl.inputs.values[0].type_ {
1178                                 BorrowedRef { ref mut type_, .. } => {
1179                                     **type_ = Generic(String::from("Self"))
1180                                 }
1181                                 _ => unreachable!(),
1182                             }
1183                         }
1184                     }
1185                 }
1186
1187                 let provided = match self.container {
1188                     ty::ImplContainer(_) => true,
1189                     ty::TraitContainer(_) => self.defaultness.has_value(),
1190                 };
1191                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1192                 if provided {
1193                     let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1194                         hir::Constness::Const
1195                     } else {
1196                         hir::Constness::NotConst
1197                     };
1198                     let asyncness = cx.tcx.asyncness(self.def_id);
1199                     let defaultness = match self.container {
1200                         ty::ImplContainer(_) => Some(self.defaultness),
1201                         ty::TraitContainer(_) => None,
1202                     };
1203                     MethodItem(Method {
1204                         generics,
1205                         decl,
1206                         header: hir::FnHeader {
1207                             unsafety: sig.unsafety(),
1208                             abi: sig.abi(),
1209                             constness,
1210                             asyncness,
1211                         },
1212                         defaultness,
1213                         all_types,
1214                         ret_types,
1215                     })
1216                 } else {
1217                     TyMethodItem(TyMethod {
1218                         generics,
1219                         decl,
1220                         header: hir::FnHeader {
1221                             unsafety: sig.unsafety(),
1222                             abi: sig.abi(),
1223                             constness: hir::Constness::NotConst,
1224                             asyncness: hir::IsAsync::NotAsync,
1225                         },
1226                         all_types,
1227                         ret_types,
1228                     })
1229                 }
1230             }
1231             ty::AssocKind::Type => {
1232                 let my_name = self.ident.name.clean(cx);
1233
1234                 if let ty::TraitContainer(did) = self.container {
1235                     // When loading a cross-crate associated type, the bounds for this type
1236                     // are actually located on the trait/impl itself, so we need to load
1237                     // all of the generics from there and then look for bounds that are
1238                     // applied to this associated type in question.
1239                     let predicates = cx.tcx.explicit_predicates_of(did);
1240                     let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1241                     let mut bounds = generics
1242                         .where_predicates
1243                         .iter()
1244                         .filter_map(|pred| {
1245                             let (name, self_type, trait_, bounds) = match *pred {
1246                                 WherePredicate::BoundPredicate {
1247                                     ty: QPath { ref name, ref self_type, ref trait_ },
1248                                     ref bounds,
1249                                 } => (name, self_type, trait_, bounds),
1250                                 _ => return None,
1251                             };
1252                             if *name != my_name {
1253                                 return None;
1254                             }
1255                             match **trait_ {
1256                                 ResolvedPath { did, .. } if did == self.container.id() => {}
1257                                 _ => return None,
1258                             }
1259                             match **self_type {
1260                                 Generic(ref s) if *s == "Self" => {}
1261                                 _ => return None,
1262                             }
1263                             Some(bounds)
1264                         })
1265                         .flat_map(|i| i.iter().cloned())
1266                         .collect::<Vec<_>>();
1267                     // Our Sized/?Sized bound didn't get handled when creating the generics
1268                     // because we didn't actually get our whole set of bounds until just now
1269                     // (some of them may have come from the trait). If we do have a sized
1270                     // bound, we remove it, and if we don't then we add the `?Sized` bound
1271                     // at the end.
1272                     match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1273                         Some(i) => {
1274                             bounds.remove(i);
1275                         }
1276                         None => bounds.push(GenericBound::maybe_sized(cx)),
1277                     }
1278
1279                     let ty = if self.defaultness.has_value() {
1280                         Some(cx.tcx.type_of(self.def_id))
1281                     } else {
1282                         None
1283                     };
1284
1285                     AssocTypeItem(bounds, ty.clean(cx))
1286                 } else {
1287                     let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1288                     let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1289                     TypedefItem(
1290                         Typedef {
1291                             type_,
1292                             generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1293                             item_type,
1294                         },
1295                         true,
1296                     )
1297                 }
1298             }
1299             ty::AssocKind::OpaqueTy => unimplemented!(),
1300         };
1301
1302         let visibility = match self.container {
1303             ty::ImplContainer(_) => self.vis.clean(cx),
1304             ty::TraitContainer(_) => Inherited,
1305         };
1306
1307         Item {
1308             name: Some(self.ident.name.clean(cx)),
1309             visibility,
1310             stability: get_stability(cx, self.def_id),
1311             deprecation: get_deprecation(cx, self.def_id),
1312             def_id: self.def_id,
1313             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1314             source: cx.tcx.def_span(self.def_id).clean(cx),
1315             inner,
1316         }
1317     }
1318 }
1319
1320 impl Clean<Type> for hir::Ty<'_> {
1321     fn clean(&self, cx: &DocContext<'_>) -> Type {
1322         use rustc_hir::*;
1323
1324         match self.kind {
1325             TyKind::Never => Never,
1326             TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1327             TyKind::Rptr(ref l, ref m) => {
1328                 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1329                 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1330             }
1331             TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1332             TyKind::Array(ref ty, ref length) => {
1333                 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1334                 let length = match cx.tcx.const_eval_poly(def_id) {
1335                     Ok(length) => print_const(cx, length),
1336                     Err(_) => cx
1337                         .sess()
1338                         .source_map()
1339                         .span_to_snippet(cx.tcx.def_span(def_id))
1340                         .unwrap_or_else(|_| "_".to_string()),
1341                 };
1342                 Array(box ty.clean(cx), length)
1343             }
1344             TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1345             TyKind::Def(item_id, _) => {
1346                 let item = cx.tcx.hir().expect_item(item_id.id);
1347                 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1348                     ImplTrait(ty.bounds.clean(cx))
1349                 } else {
1350                     unreachable!()
1351                 }
1352             }
1353             TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1354                 if let Res::Def(DefKind::TyParam, did) = path.res {
1355                     if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1356                         return new_ty;
1357                     }
1358                     if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1359                         return ImplTrait(bounds);
1360                     }
1361                 }
1362
1363                 let mut alias = None;
1364                 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1365                     // Substitute private type aliases
1366                     if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1367                         if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1368                             alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1369                         }
1370                     }
1371                 };
1372
1373                 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1374                     let provided_params = &path.segments.last().expect("segments were empty");
1375                     let mut ty_substs = FxHashMap::default();
1376                     let mut lt_substs = FxHashMap::default();
1377                     let mut ct_substs = FxHashMap::default();
1378                     let generic_args = provided_params.generic_args();
1379                     {
1380                         let mut indices: GenericParamCount = Default::default();
1381                         for param in generics.params.iter() {
1382                             match param.kind {
1383                                 hir::GenericParamKind::Lifetime { .. } => {
1384                                     let mut j = 0;
1385                                     let lifetime =
1386                                         generic_args.args.iter().find_map(|arg| match arg {
1387                                             hir::GenericArg::Lifetime(lt) => {
1388                                                 if indices.lifetimes == j {
1389                                                     return Some(lt);
1390                                                 }
1391                                                 j += 1;
1392                                                 None
1393                                             }
1394                                             _ => None,
1395                                         });
1396                                     if let Some(lt) = lifetime.cloned() {
1397                                         if !lt.is_elided() {
1398                                             let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1399                                             lt_substs.insert(lt_def_id, lt.clean(cx));
1400                                         }
1401                                     }
1402                                     indices.lifetimes += 1;
1403                                 }
1404                                 hir::GenericParamKind::Type { ref default, .. } => {
1405                                     let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1406                                     let mut j = 0;
1407                                     let type_ =
1408                                         generic_args.args.iter().find_map(|arg| match arg {
1409                                             hir::GenericArg::Type(ty) => {
1410                                                 if indices.types == j {
1411                                                     return Some(ty);
1412                                                 }
1413                                                 j += 1;
1414                                                 None
1415                                             }
1416                                             _ => None,
1417                                         });
1418                                     if let Some(ty) = type_ {
1419                                         ty_substs.insert(ty_param_def_id, ty.clean(cx));
1420                                     } else if let Some(default) = default.clone() {
1421                                         ty_substs.insert(ty_param_def_id, default.clean(cx));
1422                                     }
1423                                     indices.types += 1;
1424                                 }
1425                                 hir::GenericParamKind::Const { .. } => {
1426                                     let const_param_def_id =
1427                                         cx.tcx.hir().local_def_id(param.hir_id);
1428                                     let mut j = 0;
1429                                     let const_ =
1430                                         generic_args.args.iter().find_map(|arg| match arg {
1431                                             hir::GenericArg::Const(ct) => {
1432                                                 if indices.consts == j {
1433                                                     return Some(ct);
1434                                                 }
1435                                                 j += 1;
1436                                                 None
1437                                             }
1438                                             _ => None,
1439                                         });
1440                                     if let Some(ct) = const_ {
1441                                         ct_substs.insert(const_param_def_id, ct.clean(cx));
1442                                     }
1443                                     // FIXME(const_generics:defaults)
1444                                     indices.consts += 1;
1445                                 }
1446                             }
1447                         }
1448                     }
1449                     return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1450                 }
1451                 resolve_type(cx, path.clean(cx), self.hir_id)
1452             }
1453             TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1454                 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1455                 let trait_segments = &segments[..segments.len() - 1];
1456                 let trait_path = self::Path {
1457                     global: p.is_global(),
1458                     res: Res::Def(
1459                         DefKind::Trait,
1460                         cx.tcx.associated_item(p.res.def_id()).container.id(),
1461                     ),
1462                     segments: trait_segments.clean(cx),
1463                 };
1464                 Type::QPath {
1465                     name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1466                     self_type: box qself.clean(cx),
1467                     trait_: box resolve_type(cx, trait_path, self.hir_id),
1468                 }
1469             }
1470             TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1471                 let mut res = Res::Err;
1472                 let ty = hir_ty_to_ty(cx.tcx, self);
1473                 if let ty::Projection(proj) = ty.kind {
1474                     res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1475                 }
1476                 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1477                 Type::QPath {
1478                     name: segment.ident.name.clean(cx),
1479                     self_type: box qself.clean(cx),
1480                     trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1481                 }
1482             }
1483             TyKind::TraitObject(ref bounds, ref lifetime) => {
1484                 match bounds[0].clean(cx).trait_ {
1485                     ResolvedPath { path, param_names: None, did, is_generic } => {
1486                         let mut bounds: Vec<self::GenericBound> = bounds[1..]
1487                             .iter()
1488                             .map(|bound| {
1489                                 self::GenericBound::TraitBound(
1490                                     bound.clean(cx),
1491                                     hir::TraitBoundModifier::None,
1492                                 )
1493                             })
1494                             .collect();
1495                         if !lifetime.is_elided() {
1496                             bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1497                         }
1498                         ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1499                     }
1500                     _ => Infer, // shouldn't happen
1501                 }
1502             }
1503             TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1504             TyKind::Infer | TyKind::Err => Infer,
1505             TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1506         }
1507     }
1508 }
1509
1510 impl<'tcx> Clean<Type> for Ty<'tcx> {
1511     fn clean(&self, cx: &DocContext<'_>) -> Type {
1512         debug!("cleaning type: {:?}", self);
1513         match self.kind {
1514             ty::Never => Never,
1515             ty::Bool => Primitive(PrimitiveType::Bool),
1516             ty::Char => Primitive(PrimitiveType::Char),
1517             ty::Int(int_ty) => Primitive(int_ty.into()),
1518             ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1519             ty::Float(float_ty) => Primitive(float_ty.into()),
1520             ty::Str => Primitive(PrimitiveType::Str),
1521             ty::Slice(ty) => Slice(box ty.clean(cx)),
1522             ty::Array(ty, n) => {
1523                 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1524                 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1525                 let n = print_const(cx, n);
1526                 Array(box ty.clean(cx), n)
1527             }
1528             ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1529             ty::Ref(r, ty, mutbl) => {
1530                 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1531             }
1532             ty::FnDef(..) | ty::FnPtr(_) => {
1533                 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1534                 let sig = ty.fn_sig(cx.tcx);
1535                 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1536                 BareFunction(box BareFunctionDecl {
1537                     unsafety: sig.unsafety(),
1538                     generic_params: Vec::new(),
1539                     decl: (local_def_id, sig).clean(cx),
1540                     abi: sig.abi(),
1541                 })
1542             }
1543             ty::Adt(def, substs) => {
1544                 let did = def.did;
1545                 let kind = match def.adt_kind() {
1546                     AdtKind::Struct => TypeKind::Struct,
1547                     AdtKind::Union => TypeKind::Union,
1548                     AdtKind::Enum => TypeKind::Enum,
1549                 };
1550                 inline::record_extern_fqn(cx, did, kind);
1551                 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1552                 ResolvedPath { path, param_names: None, did, is_generic: false }
1553             }
1554             ty::Foreign(did) => {
1555                 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1556                 let path = external_path(
1557                     cx,
1558                     cx.tcx.item_name(did),
1559                     None,
1560                     false,
1561                     vec![],
1562                     InternalSubsts::empty(),
1563                 );
1564                 ResolvedPath { path, param_names: None, did, is_generic: false }
1565             }
1566             ty::Dynamic(ref obj, ref reg) => {
1567                 // HACK: pick the first `did` as the `did` of the trait object. Someone
1568                 // might want to implement "native" support for marker-trait-only
1569                 // trait objects.
1570                 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1571                 let did = dids
1572                     .next()
1573                     .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1574                 let substs = match obj.principal() {
1575                     Some(principal) => principal.skip_binder().substs,
1576                     // marker traits have no substs.
1577                     _ => cx.tcx.intern_substs(&[]),
1578                 };
1579
1580                 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1581
1582                 let mut param_names = vec![];
1583                 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1584                 for did in dids {
1585                     let empty = cx.tcx.intern_substs(&[]);
1586                     let path =
1587                         external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1588                     inline::record_extern_fqn(cx, did, TypeKind::Trait);
1589                     let bound = GenericBound::TraitBound(
1590                         PolyTrait {
1591                             trait_: ResolvedPath {
1592                                 path,
1593                                 param_names: None,
1594                                 did,
1595                                 is_generic: false,
1596                             },
1597                             generic_params: Vec::new(),
1598                         },
1599                         hir::TraitBoundModifier::None,
1600                     );
1601                     param_names.push(bound);
1602                 }
1603
1604                 let mut bindings = vec![];
1605                 for pb in obj.projection_bounds() {
1606                     bindings.push(TypeBinding {
1607                         name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1608                         kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1609                     });
1610                 }
1611
1612                 let path =
1613                     external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1614                 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1615             }
1616             ty::Tuple(ref t) => {
1617                 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1618             }
1619
1620             ty::Projection(ref data) => data.clean(cx),
1621
1622             ty::Param(ref p) => {
1623                 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1624                     ImplTrait(bounds)
1625                 } else {
1626                     Generic(p.name.to_string())
1627                 }
1628             }
1629
1630             ty::Opaque(def_id, substs) => {
1631                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1632                 // by looking up the projections associated with the def_id.
1633                 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1634                 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1635                 let bounds = predicates_of.instantiate(cx.tcx, substs);
1636                 let mut regions = vec![];
1637                 let mut has_sized = false;
1638                 let mut bounds = bounds
1639                     .predicates
1640                     .iter()
1641                     .filter_map(|predicate| {
1642                         let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1643                             tr
1644                         } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1645                             // these should turn up at the end
1646                             pred.skip_binder()
1647                                 .1
1648                                 .clean(cx)
1649                                 .map(|r| regions.push(GenericBound::Outlives(r)));
1650                             return None;
1651                         } else {
1652                             return None;
1653                         };
1654
1655                         if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1656                             if trait_ref.def_id() == sized {
1657                                 has_sized = true;
1658                                 return None;
1659                             }
1660                         }
1661
1662                         let bounds = bounds
1663                             .predicates
1664                             .iter()
1665                             .filter_map(|pred| {
1666                                 if let ty::Predicate::Projection(proj) = *pred {
1667                                     let proj = proj.skip_binder();
1668                                     if proj.projection_ty.trait_ref(cx.tcx)
1669                                         == *trait_ref.skip_binder()
1670                                     {
1671                                         Some(TypeBinding {
1672                                             name: cx
1673                                                 .tcx
1674                                                 .associated_item(proj.projection_ty.item_def_id)
1675                                                 .ident
1676                                                 .name
1677                                                 .clean(cx),
1678                                             kind: TypeBindingKind::Equality {
1679                                                 ty: proj.ty.clean(cx),
1680                                             },
1681                                         })
1682                                     } else {
1683                                         None
1684                                     }
1685                                 } else {
1686                                     None
1687                                 }
1688                             })
1689                             .collect();
1690
1691                         Some((trait_ref.skip_binder(), bounds).clean(cx))
1692                     })
1693                     .collect::<Vec<_>>();
1694                 bounds.extend(regions);
1695                 if !has_sized && !bounds.is_empty() {
1696                     bounds.insert(0, GenericBound::maybe_sized(cx));
1697                 }
1698                 ImplTrait(bounds)
1699             }
1700
1701             ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1702
1703             ty::Bound(..) => panic!("Bound"),
1704             ty::Placeholder(..) => panic!("Placeholder"),
1705             ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1706             ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1707             ty::Infer(..) => panic!("Infer"),
1708             ty::Error => panic!("Error"),
1709         }
1710     }
1711 }
1712
1713 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1714     fn clean(&self, cx: &DocContext<'_>) -> Constant {
1715         Constant {
1716             type_: self.ty.clean(cx),
1717             expr: format!("{}", self),
1718             value: None,
1719             is_literal: false,
1720         }
1721     }
1722 }
1723
1724 impl Clean<Item> for hir::StructField<'_> {
1725     fn clean(&self, cx: &DocContext<'_>) -> Item {
1726         let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1727
1728         Item {
1729             name: Some(self.ident.name).clean(cx),
1730             attrs: self.attrs.clean(cx),
1731             source: self.span.clean(cx),
1732             visibility: self.vis.clean(cx),
1733             stability: get_stability(cx, local_did),
1734             deprecation: get_deprecation(cx, local_did),
1735             def_id: local_did,
1736             inner: StructFieldItem(self.ty.clean(cx)),
1737         }
1738     }
1739 }
1740
1741 impl Clean<Item> for ty::FieldDef {
1742     fn clean(&self, cx: &DocContext<'_>) -> Item {
1743         Item {
1744             name: Some(self.ident.name).clean(cx),
1745             attrs: cx.tcx.get_attrs(self.did).clean(cx),
1746             source: cx.tcx.def_span(self.did).clean(cx),
1747             visibility: self.vis.clean(cx),
1748             stability: get_stability(cx, self.did),
1749             deprecation: get_deprecation(cx, self.did),
1750             def_id: self.did,
1751             inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1752         }
1753     }
1754 }
1755
1756 impl Clean<Visibility> for hir::Visibility<'_> {
1757     fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1758         match self.node {
1759             hir::VisibilityKind::Public => Visibility::Public,
1760             hir::VisibilityKind::Inherited => Visibility::Inherited,
1761             hir::VisibilityKind::Crate(_) => Visibility::Crate,
1762             hir::VisibilityKind::Restricted { ref path, .. } => {
1763                 let path = path.clean(cx);
1764                 let did = register_res(cx, path.res);
1765                 Visibility::Restricted(did, path)
1766             }
1767         }
1768     }
1769 }
1770
1771 impl Clean<Visibility> for ty::Visibility {
1772     fn clean(&self, _: &DocContext<'_>) -> Visibility {
1773         if *self == ty::Visibility::Public { Public } else { Inherited }
1774     }
1775 }
1776
1777 impl Clean<Item> for doctree::Struct<'_> {
1778     fn clean(&self, cx: &DocContext<'_>) -> Item {
1779         Item {
1780             name: Some(self.name.clean(cx)),
1781             attrs: self.attrs.clean(cx),
1782             source: self.whence.clean(cx),
1783             def_id: cx.tcx.hir().local_def_id(self.id),
1784             visibility: self.vis.clean(cx),
1785             stability: cx.stability(self.id).clean(cx),
1786             deprecation: cx.deprecation(self.id).clean(cx),
1787             inner: StructItem(Struct {
1788                 struct_type: self.struct_type,
1789                 generics: self.generics.clean(cx),
1790                 fields: self.fields.clean(cx),
1791                 fields_stripped: false,
1792             }),
1793         }
1794     }
1795 }
1796
1797 impl Clean<Item> for doctree::Union<'_> {
1798     fn clean(&self, cx: &DocContext<'_>) -> Item {
1799         Item {
1800             name: Some(self.name.clean(cx)),
1801             attrs: self.attrs.clean(cx),
1802             source: self.whence.clean(cx),
1803             def_id: cx.tcx.hir().local_def_id(self.id),
1804             visibility: self.vis.clean(cx),
1805             stability: cx.stability(self.id).clean(cx),
1806             deprecation: cx.deprecation(self.id).clean(cx),
1807             inner: UnionItem(Union {
1808                 struct_type: self.struct_type,
1809                 generics: self.generics.clean(cx),
1810                 fields: self.fields.clean(cx),
1811                 fields_stripped: false,
1812             }),
1813         }
1814     }
1815 }
1816
1817 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1818     fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1819         VariantStruct {
1820             struct_type: doctree::struct_type_from_def(self),
1821             fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1822             fields_stripped: false,
1823         }
1824     }
1825 }
1826
1827 impl Clean<Item> for doctree::Enum<'_> {
1828     fn clean(&self, cx: &DocContext<'_>) -> Item {
1829         Item {
1830             name: Some(self.name.clean(cx)),
1831             attrs: self.attrs.clean(cx),
1832             source: self.whence.clean(cx),
1833             def_id: cx.tcx.hir().local_def_id(self.id),
1834             visibility: self.vis.clean(cx),
1835             stability: cx.stability(self.id).clean(cx),
1836             deprecation: cx.deprecation(self.id).clean(cx),
1837             inner: EnumItem(Enum {
1838                 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1839                 generics: self.generics.clean(cx),
1840                 variants_stripped: false,
1841             }),
1842         }
1843     }
1844 }
1845
1846 impl Clean<Item> for doctree::Variant<'_> {
1847     fn clean(&self, cx: &DocContext<'_>) -> Item {
1848         Item {
1849             name: Some(self.name.clean(cx)),
1850             attrs: self.attrs.clean(cx),
1851             source: self.whence.clean(cx),
1852             visibility: Inherited,
1853             stability: cx.stability(self.id).clean(cx),
1854             deprecation: cx.deprecation(self.id).clean(cx),
1855             def_id: cx.tcx.hir().local_def_id(self.id),
1856             inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1857         }
1858     }
1859 }
1860
1861 impl Clean<Item> for ty::VariantDef {
1862     fn clean(&self, cx: &DocContext<'_>) -> Item {
1863         let kind = match self.ctor_kind {
1864             CtorKind::Const => VariantKind::CLike,
1865             CtorKind::Fn => VariantKind::Tuple(
1866                 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1867             ),
1868             CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1869                 struct_type: doctree::Plain,
1870                 fields_stripped: false,
1871                 fields: self
1872                     .fields
1873                     .iter()
1874                     .map(|field| Item {
1875                         source: cx.tcx.def_span(field.did).clean(cx),
1876                         name: Some(field.ident.name.clean(cx)),
1877                         attrs: cx.tcx.get_attrs(field.did).clean(cx),
1878                         visibility: field.vis.clean(cx),
1879                         def_id: field.did,
1880                         stability: get_stability(cx, field.did),
1881                         deprecation: get_deprecation(cx, field.did),
1882                         inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1883                     })
1884                     .collect(),
1885             }),
1886         };
1887         Item {
1888             name: Some(self.ident.clean(cx)),
1889             attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1890             source: cx.tcx.def_span(self.def_id).clean(cx),
1891             visibility: Inherited,
1892             def_id: self.def_id,
1893             inner: VariantItem(Variant { kind }),
1894             stability: get_stability(cx, self.def_id),
1895             deprecation: get_deprecation(cx, self.def_id),
1896         }
1897     }
1898 }
1899
1900 impl Clean<VariantKind> for hir::VariantData<'_> {
1901     fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1902         match self {
1903             hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1904             hir::VariantData::Tuple(..) => {
1905                 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1906             }
1907             hir::VariantData::Unit(..) => VariantKind::CLike,
1908         }
1909     }
1910 }
1911
1912 impl Clean<Span> for rustc_span::Span {
1913     fn clean(&self, cx: &DocContext<'_>) -> Span {
1914         if self.is_dummy() {
1915             return Span::empty();
1916         }
1917
1918         let cm = cx.sess().source_map();
1919         let filename = cm.span_to_filename(*self);
1920         let lo = cm.lookup_char_pos(self.lo());
1921         let hi = cm.lookup_char_pos(self.hi());
1922         Span {
1923             filename,
1924             loline: lo.line,
1925             locol: lo.col.to_usize(),
1926             hiline: hi.line,
1927             hicol: hi.col.to_usize(),
1928             original: *self,
1929         }
1930     }
1931 }
1932
1933 impl Clean<Path> for hir::Path<'_> {
1934     fn clean(&self, cx: &DocContext<'_>) -> Path {
1935         Path {
1936             global: self.is_global(),
1937             res: self.res,
1938             segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1939         }
1940     }
1941 }
1942
1943 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1944     fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1945         if self.parenthesized {
1946             let output = self.bindings[0].ty().clean(cx);
1947             GenericArgs::Parenthesized {
1948                 inputs: self.inputs().clean(cx),
1949                 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1950             }
1951         } else {
1952             let elide_lifetimes = self.args.iter().all(|arg| match arg {
1953                 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1954                 _ => true,
1955             });
1956             GenericArgs::AngleBracketed {
1957                 args: self
1958                     .args
1959                     .iter()
1960                     .filter_map(|arg| match arg {
1961                         hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1962                             Some(GenericArg::Lifetime(lt.clean(cx)))
1963                         }
1964                         hir::GenericArg::Lifetime(_) => None,
1965                         hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1966                         hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1967                     })
1968                     .collect(),
1969                 bindings: self.bindings.clean(cx),
1970             }
1971         }
1972     }
1973 }
1974
1975 impl Clean<PathSegment> for hir::PathSegment<'_> {
1976     fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1977         PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1978     }
1979 }
1980
1981 impl Clean<String> for Ident {
1982     #[inline]
1983     fn clean(&self, cx: &DocContext<'_>) -> String {
1984         self.name.clean(cx)
1985     }
1986 }
1987
1988 impl Clean<String> for ast::Name {
1989     #[inline]
1990     fn clean(&self, _: &DocContext<'_>) -> String {
1991         self.to_string()
1992     }
1993 }
1994
1995 impl Clean<Item> for doctree::Typedef<'_> {
1996     fn clean(&self, cx: &DocContext<'_>) -> Item {
1997         let type_ = self.ty.clean(cx);
1998         let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1999         Item {
2000             name: Some(self.name.clean(cx)),
2001             attrs: self.attrs.clean(cx),
2002             source: self.whence.clean(cx),
2003             def_id: cx.tcx.hir().local_def_id(self.id),
2004             visibility: self.vis.clean(cx),
2005             stability: cx.stability(self.id).clean(cx),
2006             deprecation: cx.deprecation(self.id).clean(cx),
2007             inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2008         }
2009     }
2010 }
2011
2012 impl Clean<Item> for doctree::OpaqueTy<'_> {
2013     fn clean(&self, cx: &DocContext<'_>) -> Item {
2014         Item {
2015             name: Some(self.name.clean(cx)),
2016             attrs: self.attrs.clean(cx),
2017             source: self.whence.clean(cx),
2018             def_id: cx.tcx.hir().local_def_id(self.id),
2019             visibility: self.vis.clean(cx),
2020             stability: cx.stability(self.id).clean(cx),
2021             deprecation: cx.deprecation(self.id).clean(cx),
2022             inner: OpaqueTyItem(
2023                 OpaqueTy {
2024                     bounds: self.opaque_ty.bounds.clean(cx),
2025                     generics: self.opaque_ty.generics.clean(cx),
2026                 },
2027                 false,
2028             ),
2029         }
2030     }
2031 }
2032
2033 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2034     fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2035         let (generic_params, decl) = enter_impl_trait(cx, || {
2036             (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2037         });
2038         BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2039     }
2040 }
2041
2042 impl Clean<Item> for doctree::Static<'_> {
2043     fn clean(&self, cx: &DocContext<'_>) -> Item {
2044         debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2045         Item {
2046             name: Some(self.name.clean(cx)),
2047             attrs: self.attrs.clean(cx),
2048             source: self.whence.clean(cx),
2049             def_id: cx.tcx.hir().local_def_id(self.id),
2050             visibility: self.vis.clean(cx),
2051             stability: cx.stability(self.id).clean(cx),
2052             deprecation: cx.deprecation(self.id).clean(cx),
2053             inner: StaticItem(Static {
2054                 type_: self.type_.clean(cx),
2055                 mutability: self.mutability,
2056                 expr: print_const_expr(cx, self.expr),
2057             }),
2058         }
2059     }
2060 }
2061
2062 impl Clean<Item> for doctree::Constant<'_> {
2063     fn clean(&self, cx: &DocContext<'_>) -> Item {
2064         let def_id = cx.tcx.hir().local_def_id(self.id);
2065
2066         Item {
2067             name: Some(self.name.clean(cx)),
2068             attrs: self.attrs.clean(cx),
2069             source: self.whence.clean(cx),
2070             def_id,
2071             visibility: self.vis.clean(cx),
2072             stability: cx.stability(self.id).clean(cx),
2073             deprecation: cx.deprecation(self.id).clean(cx),
2074             inner: ConstantItem(Constant {
2075                 type_: self.type_.clean(cx),
2076                 expr: print_const_expr(cx, self.expr),
2077                 value: print_evaluated_const(cx, def_id),
2078                 is_literal: is_literal_expr(cx, self.expr.hir_id),
2079             }),
2080         }
2081     }
2082 }
2083
2084 impl Clean<ImplPolarity> for ty::ImplPolarity {
2085     fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2086         match self {
2087             &ty::ImplPolarity::Positive |
2088             // FIXME: do we want to do something else here?
2089             &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2090             &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2091         }
2092     }
2093 }
2094
2095 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2096     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2097         let mut ret = Vec::new();
2098         let trait_ = self.trait_.clean(cx);
2099         let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2100         let def_id = cx.tcx.hir().local_def_id(self.id);
2101
2102         // If this impl block is an implementation of the Deref trait, then we
2103         // need to try inlining the target's inherent impl blocks as well.
2104         if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2105             build_deref_target_impls(cx, &items, &mut ret);
2106         }
2107
2108         let provided: FxHashSet<String> = trait_
2109             .def_id()
2110             .map(|did| {
2111                 cx.tcx
2112                     .provided_trait_methods(did)
2113                     .into_iter()
2114                     .map(|meth| meth.ident.to_string())
2115                     .collect()
2116             })
2117             .unwrap_or_default();
2118
2119         let for_ = self.for_.clean(cx);
2120         let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2121             Some(DefKind::TyAlias) => Some(cx.tcx.type_of(did).clean(cx)),
2122             _ => None,
2123         });
2124         let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2125             name: None,
2126             attrs: self.attrs.clean(cx),
2127             source: self.whence.clean(cx),
2128             def_id,
2129             visibility: self.vis.clean(cx),
2130             stability: cx.stability(self.id).clean(cx),
2131             deprecation: cx.deprecation(self.id).clean(cx),
2132             inner: ImplItem(Impl {
2133                 unsafety: self.unsafety,
2134                 generics: self.generics.clean(cx),
2135                 provided_trait_methods: provided.clone(),
2136                 trait_,
2137                 for_,
2138                 items,
2139                 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2140                 synthetic: false,
2141                 blanket_impl: None,
2142             }),
2143         };
2144         if let Some(type_alias) = type_alias {
2145             ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2146         }
2147         ret.push(make_item(trait_, for_, items));
2148         ret
2149     }
2150 }
2151
2152 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2153     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2154         let please_inline = self.vis.node.is_pub()
2155             && self.attrs.iter().any(|a| {
2156                 a.check_name(sym::doc)
2157                     && match a.meta_item_list() {
2158                         Some(l) => attr::list_contains_name(&l, sym::inline),
2159                         None => false,
2160                     }
2161             });
2162
2163         if please_inline {
2164             let mut visited = FxHashSet::default();
2165
2166             let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2167
2168             if let Some(items) = inline::try_inline(
2169                 cx,
2170                 res,
2171                 self.name,
2172                 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2173                 &mut visited,
2174             ) {
2175                 return items;
2176             }
2177         }
2178
2179         vec![Item {
2180             name: None,
2181             attrs: self.attrs.clean(cx),
2182             source: self.whence.clean(cx),
2183             def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2184             visibility: self.vis.clean(cx),
2185             stability: None,
2186             deprecation: None,
2187             inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2188         }]
2189     }
2190 }
2191
2192 impl Clean<Vec<Item>> for doctree::Import<'_> {
2193     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2194         // We consider inlining the documentation of `pub use` statements, but we
2195         // forcefully don't inline if this is not public or if the
2196         // #[doc(no_inline)] attribute is present.
2197         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2198         let mut denied = !self.vis.node.is_pub()
2199             || self.attrs.iter().any(|a| {
2200                 a.check_name(sym::doc)
2201                     && match a.meta_item_list() {
2202                         Some(l) => {
2203                             attr::list_contains_name(&l, sym::no_inline)
2204                                 || attr::list_contains_name(&l, sym::hidden)
2205                         }
2206                         None => false,
2207                     }
2208             });
2209         // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2210         // crate in Rust 2018+
2211         let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2212         let path = self.path.clean(cx);
2213         let inner = if self.glob {
2214             if !denied {
2215                 let mut visited = FxHashSet::default();
2216                 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2217                     return items;
2218                 }
2219             }
2220
2221             Import::Glob(resolve_use_source(cx, path))
2222         } else {
2223             let name = self.name;
2224             if !please_inline {
2225                 match path.res {
2226                     Res::Def(DefKind::Mod, did) => {
2227                         if !did.is_local() && did.index == CRATE_DEF_INDEX {
2228                             // if we're `pub use`ing an extern crate root, don't inline it unless we
2229                             // were specifically asked for it
2230                             denied = true;
2231                         }
2232                     }
2233                     _ => {}
2234                 }
2235             }
2236             if !denied {
2237                 let mut visited = FxHashSet::default();
2238                 if let Some(items) = inline::try_inline(
2239                     cx,
2240                     path.res,
2241                     name,
2242                     Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2243                     &mut visited,
2244                 ) {
2245                     return items;
2246                 }
2247             }
2248             Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2249         };
2250
2251         vec![Item {
2252             name: None,
2253             attrs: self.attrs.clean(cx),
2254             source: self.whence.clean(cx),
2255             def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2256             visibility: self.vis.clean(cx),
2257             stability: None,
2258             deprecation: None,
2259             inner: ImportItem(inner),
2260         }]
2261     }
2262 }
2263
2264 impl Clean<Item> for doctree::ForeignItem<'_> {
2265     fn clean(&self, cx: &DocContext<'_>) -> Item {
2266         let inner = match self.kind {
2267             hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2268                 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2269                 let (generics, decl) =
2270                     enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2271                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2272                 ForeignFunctionItem(Function {
2273                     decl,
2274                     generics,
2275                     header: hir::FnHeader {
2276                         unsafety: hir::Unsafety::Unsafe,
2277                         abi,
2278                         constness: hir::Constness::NotConst,
2279                         asyncness: hir::IsAsync::NotAsync,
2280                     },
2281                     all_types,
2282                     ret_types,
2283                 })
2284             }
2285             hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2286                 type_: ty.clean(cx),
2287                 mutability: *mutbl,
2288                 expr: String::new(),
2289             }),
2290             hir::ForeignItemKind::Type => ForeignTypeItem,
2291         };
2292
2293         Item {
2294             name: Some(self.name.clean(cx)),
2295             attrs: self.attrs.clean(cx),
2296             source: self.whence.clean(cx),
2297             def_id: cx.tcx.hir().local_def_id(self.id),
2298             visibility: self.vis.clean(cx),
2299             stability: cx.stability(self.id).clean(cx),
2300             deprecation: cx.deprecation(self.id).clean(cx),
2301             inner,
2302         }
2303     }
2304 }
2305
2306 impl Clean<Item> for doctree::Macro<'_> {
2307     fn clean(&self, cx: &DocContext<'_>) -> Item {
2308         let name = self.name.clean(cx);
2309         Item {
2310             name: Some(name.clone()),
2311             attrs: self.attrs.clean(cx),
2312             source: self.whence.clean(cx),
2313             visibility: Public,
2314             stability: cx.stability(self.hid).clean(cx),
2315             deprecation: cx.deprecation(self.hid).clean(cx),
2316             def_id: self.def_id,
2317             inner: MacroItem(Macro {
2318                 source: format!(
2319                     "macro_rules! {} {{\n{}}}",
2320                     name,
2321                     self.matchers
2322                         .iter()
2323                         .map(|span| { format!("    {} => {{ ... }};\n", span.to_src(cx)) })
2324                         .collect::<String>()
2325                 ),
2326                 imported_from: self.imported_from.clean(cx),
2327             }),
2328         }
2329     }
2330 }
2331
2332 impl Clean<Item> for doctree::ProcMacro<'_> {
2333     fn clean(&self, cx: &DocContext<'_>) -> Item {
2334         Item {
2335             name: Some(self.name.clean(cx)),
2336             attrs: self.attrs.clean(cx),
2337             source: self.whence.clean(cx),
2338             visibility: Public,
2339             stability: cx.stability(self.id).clean(cx),
2340             deprecation: cx.deprecation(self.id).clean(cx),
2341             def_id: cx.tcx.hir().local_def_id(self.id),
2342             inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2343         }
2344     }
2345 }
2346
2347 impl Clean<Stability> for attr::Stability {
2348     fn clean(&self, _: &DocContext<'_>) -> Stability {
2349         Stability {
2350             level: stability::StabilityLevel::from_attr_level(&self.level),
2351             feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2352             since: match self.level {
2353                 attr::Stable { ref since } => since.to_string(),
2354                 _ => String::new(),
2355             },
2356             deprecation: self.rustc_depr.as_ref().map(|d| Deprecation {
2357                 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2358                 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2359             }),
2360             unstable_reason: match self.level {
2361                 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2362                 _ => None,
2363             },
2364             issue: match self.level {
2365                 attr::Unstable { issue, .. } => issue,
2366                 _ => None,
2367             },
2368         }
2369     }
2370 }
2371
2372 impl Clean<Deprecation> for attr::Deprecation {
2373     fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2374         Deprecation {
2375             since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2376             note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2377         }
2378     }
2379 }
2380
2381 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2382     fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2383         TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2384     }
2385 }
2386
2387 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2388     fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2389         match *self {
2390             hir::TypeBindingKind::Equality { ref ty } => {
2391                 TypeBindingKind::Equality { ty: ty.clean(cx) }
2392             }
2393             hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2394                 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2395             },
2396         }
2397     }
2398 }
2399
2400 enum SimpleBound {
2401     TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2402     Outlives(Lifetime),
2403 }
2404
2405 impl From<GenericBound> for SimpleBound {
2406     fn from(bound: GenericBound) -> Self {
2407         match bound.clone() {
2408             GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2409             GenericBound::TraitBound(t, mod_) => match t.trait_ {
2410                 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2411                     path.segments,
2412                     param_names.map_or_else(
2413                         || Vec::new(),
2414                         |v| v.iter().map(|p| SimpleBound::from(p.clone())).collect(),
2415                     ),
2416                     t.generic_params,
2417                     mod_,
2418                 ),
2419                 _ => panic!("Unexpected bound {:?}", bound),
2420             },
2421         }
2422     }
2423 }