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