]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
More review comments
[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};
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 crate trait Clean<T> {
52     fn clean(&self, cx: &DocContext<'_>) -> T;
53 }
54
55 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
56     fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
57         self.iter().map(|x| x.clean(cx)).collect()
58     }
59 }
60
61 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
62     fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
63         self.iter().map(|x| x.clean(cx)).collect()
64     }
65 }
66
67 impl<T: Clean<U>, U> Clean<U> for &T {
68     fn clean(&self, cx: &DocContext<'_>) -> U {
69         (**self).clean(cx)
70     }
71 }
72
73 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
74     fn clean(&self, cx: &DocContext<'_>) -> U {
75         (**self).clean(cx)
76     }
77 }
78
79 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
80     fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
81         self.as_ref().map(|v| v.clean(cx))
82     }
83 }
84
85 impl Clean<ExternalCrate> for CrateNum {
86     fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
87         let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
88         let krate_span = cx.tcx.def_span(root);
89         let krate_src = cx.sess().source_map().span_to_filename(krate_span);
90
91         // Collect all inner modules which are tagged as implementations of
92         // primitives.
93         //
94         // Note that this loop only searches the top-level items of the crate,
95         // and this is intentional. If we were to search the entire crate for an
96         // item tagged with `#[doc(primitive)]` then we would also have to
97         // search the entirety of external modules for items tagged
98         // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
99         // all that metadata unconditionally).
100         //
101         // In order to keep the metadata load under control, the
102         // `#[doc(primitive)]` feature is explicitly designed to only allow the
103         // primitive tags to show up as the top level items in a crate.
104         //
105         // Also note that this does not attempt to deal with modules tagged
106         // duplicately for the same primitive. This is handled later on when
107         // rendering by delegating everything to a hash map.
108         let as_primitive = |res: Res| {
109             if let Res::Def(DefKind::Mod, def_id) = res {
110                 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
111                 let mut prim = None;
112                 for attr in attrs.lists(sym::doc) {
113                     if let Some(v) = attr.value_str() {
114                         if attr.has_name(sym::primitive) {
115                             prim = PrimitiveType::from_symbol(v);
116                             if prim.is_some() {
117                                 break;
118                             }
119                             // FIXME: should warn on unknown primitives?
120                         }
121                     }
122                 }
123                 return prim.map(|p| (def_id, p));
124             }
125             None
126         };
127         let primitives = if root.is_local() {
128             cx.tcx
129                 .hir()
130                 .krate()
131                 .item
132                 .module
133                 .item_ids
134                 .iter()
135                 .filter_map(|&id| {
136                     let item = cx.tcx.hir().expect_item(id.id);
137                     match item.kind {
138                         hir::ItemKind::Mod(_) => as_primitive(Res::Def(
139                             DefKind::Mod,
140                             cx.tcx.hir().local_def_id(id.id).to_def_id(),
141                         )),
142                         hir::ItemKind::Use(ref path, hir::UseKind::Single)
143                             if item.vis.node.is_pub() =>
144                         {
145                             as_primitive(path.res).map(|(_, prim)| {
146                                 // Pretend the primitive is local.
147                                 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
148                             })
149                         }
150                         _ => None,
151                     }
152                 })
153                 .collect()
154         } else {
155             cx.tcx
156                 .item_children(root)
157                 .iter()
158                 .map(|item| item.res)
159                 .filter_map(as_primitive)
160                 .collect()
161         };
162
163         let as_keyword = |res: Res| {
164             if let Res::Def(DefKind::Mod, def_id) = res {
165                 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
166                 let mut keyword = None;
167                 for attr in attrs.lists(sym::doc) {
168                     if attr.has_name(sym::keyword) {
169                         if let Some(v) = attr.value_str() {
170                             keyword = Some(v);
171                             break;
172                         }
173                     }
174                 }
175                 return keyword.map(|p| (def_id, p));
176             }
177             None
178         };
179         let keywords = if root.is_local() {
180             cx.tcx
181                 .hir()
182                 .krate()
183                 .item
184                 .module
185                 .item_ids
186                 .iter()
187                 .filter_map(|&id| {
188                     let item = cx.tcx.hir().expect_item(id.id);
189                     match item.kind {
190                         hir::ItemKind::Mod(_) => as_keyword(Res::Def(
191                             DefKind::Mod,
192                             cx.tcx.hir().local_def_id(id.id).to_def_id(),
193                         )),
194                         hir::ItemKind::Use(ref path, hir::UseKind::Single)
195                             if item.vis.node.is_pub() =>
196                         {
197                             as_keyword(path.res).map(|(_, prim)| {
198                                 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
199                             })
200                         }
201                         _ => None,
202                     }
203                 })
204                 .collect()
205         } else {
206             cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
207         };
208
209         ExternalCrate {
210             name: cx.tcx.crate_name(*self),
211             src: krate_src,
212             attrs: cx.tcx.get_attrs(root).clean(cx),
213             primitives,
214             keywords,
215         }
216     }
217 }
218
219 impl Clean<Item> for doctree::Module<'_> {
220     fn clean(&self, cx: &DocContext<'_>) -> Item {
221         let mut items: Vec<Item> = vec![];
222         items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
223         items.extend(self.mods.iter().map(|x| x.clean(cx)));
224         items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
225         items.extend(self.macros.iter().map(|x| x.clean(cx)));
226
227         // determine if we should display the inner contents or
228         // the outer `mod` item for the source code.
229         let span = {
230             let sm = cx.sess().source_map();
231             let outer = sm.lookup_char_pos(self.where_outer.lo());
232             let inner = sm.lookup_char_pos(self.where_inner.lo());
233             if outer.file.start_pos == inner.file.start_pos {
234                 // mod foo { ... }
235                 self.where_outer
236             } else {
237                 // mod foo; (and a separate SourceFile for the contents)
238                 self.where_inner
239             }
240         };
241
242         let what_rustc_thinks = Item::from_hir_id_and_parts(
243             self.id,
244             self.name,
245             ModuleItem(Module { is_crate: self.is_crate, items }),
246             cx,
247         );
248         Item { source: span.clean(cx), ..what_rustc_thinks }
249     }
250 }
251
252 impl Clean<Attributes> for [ast::Attribute] {
253     fn clean(&self, cx: &DocContext<'_>) -> Attributes {
254         Attributes::from_ast(cx.sess().diagnostic(), self, None)
255     }
256 }
257
258 impl Clean<GenericBound> for hir::GenericBound<'_> {
259     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
260         match *self {
261             hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
262             hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
263                 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
264
265                 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
266
267                 let generic_args = generic_args.clean(cx);
268                 let bindings = match generic_args {
269                     GenericArgs::AngleBracketed { bindings, .. } => bindings,
270                     _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
271                 };
272
273                 GenericBound::TraitBound(
274                     PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
275                     hir::TraitBoundModifier::None,
276                 )
277             }
278             hir::GenericBound::Trait(ref t, modifier) => {
279                 GenericBound::TraitBound(t.clean(cx), modifier)
280             }
281         }
282     }
283 }
284
285 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
286     fn clean(&self, cx: &DocContext<'_>) -> Type {
287         let (trait_ref, bounds) = *self;
288         inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
289         let path = external_path(
290             cx,
291             cx.tcx.item_name(trait_ref.def_id),
292             Some(trait_ref.def_id),
293             true,
294             bounds.to_vec(),
295             trait_ref.substs,
296         );
297
298         debug!("ty::TraitRef\n  subst: {:?}\n", trait_ref.substs);
299
300         ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
301     }
302 }
303
304 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
305     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
306         GenericBound::TraitBound(
307             PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
308             hir::TraitBoundModifier::None,
309         )
310     }
311 }
312
313 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
314     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
315         let (poly_trait_ref, bounds) = *self;
316         let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
317
318         // collect any late bound regions
319         let late_bound_regions: Vec<_> = cx
320             .tcx
321             .collect_referenced_late_bound_regions(&poly_trait_ref)
322             .into_iter()
323             .filter_map(|br| match br {
324                 ty::BrNamed(_, name) => {
325                     Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
326                 }
327                 _ => None,
328             })
329             .collect();
330
331         GenericBound::TraitBound(
332             PolyTrait {
333                 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
334                 generic_params: late_bound_regions,
335             },
336             hir::TraitBoundModifier::None,
337         )
338     }
339 }
340
341 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
342     fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
343         (*self, &[][..]).clean(cx)
344     }
345 }
346
347 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
348     fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
349         let mut v = Vec::new();
350         v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
351         v.extend(self.types().map(|t| {
352             GenericBound::TraitBound(
353                 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
354                 hir::TraitBoundModifier::None,
355             )
356         }));
357         if !v.is_empty() { Some(v) } else { None }
358     }
359 }
360
361 impl Clean<Lifetime> for hir::Lifetime {
362     fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
363         let def = cx.tcx.named_region(self.hir_id);
364         match def {
365             Some(
366                 rl::Region::EarlyBound(_, node_id, _)
367                 | rl::Region::LateBound(_, node_id, _)
368                 | rl::Region::Free(_, node_id),
369             ) => {
370                 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
371                     return lt;
372                 }
373             }
374             _ => {}
375         }
376         Lifetime(self.name.ident().name)
377     }
378 }
379
380 impl Clean<Lifetime> for hir::GenericParam<'_> {
381     fn clean(&self, _: &DocContext<'_>) -> Lifetime {
382         match self.kind {
383             hir::GenericParamKind::Lifetime { .. } => {
384                 if !self.bounds.is_empty() {
385                     let mut bounds = self.bounds.iter().map(|bound| match bound {
386                         hir::GenericBound::Outlives(lt) => lt,
387                         _ => panic!(),
388                     });
389                     let name = bounds.next().expect("no more bounds").name.ident();
390                     let mut s = format!("{}: {}", self.name.ident(), name);
391                     for bound in bounds {
392                         s.push_str(&format!(" + {}", bound.name.ident()));
393                     }
394                     Lifetime(Symbol::intern(&s))
395                 } else {
396                     Lifetime(self.name.ident().name)
397                 }
398             }
399             _ => panic!(),
400         }
401     }
402 }
403
404 impl Clean<Constant> for hir::ConstArg {
405     fn clean(&self, cx: &DocContext<'_>) -> Constant {
406         Constant {
407             type_: cx
408                 .tcx
409                 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
410                 .clean(cx),
411             expr: print_const_expr(cx, self.value.body),
412             value: None,
413             is_literal: is_literal_expr(cx, self.value.body.hir_id),
414         }
415     }
416 }
417
418 impl Clean<Lifetime> for ty::GenericParamDef {
419     fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
420         Lifetime(self.name)
421     }
422 }
423
424 impl Clean<Option<Lifetime>> for ty::RegionKind {
425     fn clean(&self, _cx: &DocContext<'_>) -> Option<Lifetime> {
426         match *self {
427             ty::ReStatic => Some(Lifetime::statik()),
428             ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) => {
429                 Some(Lifetime(name))
430             }
431             ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
432
433             ty::ReLateBound(..)
434             | ty::ReFree(..)
435             | ty::ReVar(..)
436             | ty::RePlaceholder(..)
437             | ty::ReEmpty(_)
438             | ty::ReErased => {
439                 debug!("cannot clean region {:?}", self);
440                 None
441             }
442         }
443     }
444 }
445
446 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
447     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
448         match *self {
449             hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
450                 ty: wbp.bounded_ty.clean(cx),
451                 bounds: wbp.bounds.clean(cx),
452             },
453
454             hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
455                 lifetime: wrp.lifetime.clean(cx),
456                 bounds: wrp.bounds.clean(cx),
457             },
458
459             hir::WherePredicate::EqPredicate(ref wrp) => {
460                 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
461             }
462         }
463     }
464 }
465
466 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
467     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
468         let bound_predicate = self.kind();
469         match bound_predicate.skip_binder() {
470             ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
471             ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
472             ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
473             ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
474
475             ty::PredicateKind::Subtype(..)
476             | ty::PredicateKind::WellFormed(..)
477             | ty::PredicateKind::ObjectSafe(..)
478             | ty::PredicateKind::ClosureKind(..)
479             | ty::PredicateKind::ConstEvaluatable(..)
480             | ty::PredicateKind::ConstEquate(..)
481             | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
482         }
483     }
484 }
485
486 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
487     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
488         let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
489         WherePredicate::BoundPredicate {
490             ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
491             bounds: vec![poly_trait_ref.clean(cx)],
492         }
493     }
494 }
495
496 impl<'tcx> Clean<Option<WherePredicate>>
497     for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
498 {
499     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
500         let ty::OutlivesPredicate(a, b) = self;
501
502         if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
503             return None;
504         }
505
506         Some(WherePredicate::RegionPredicate {
507             lifetime: a.clean(cx).expect("failed to clean lifetime"),
508             bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
509         })
510     }
511 }
512
513 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
514     fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
515         let ty::OutlivesPredicate(ty, lt) = self;
516
517         if let ty::ReEmpty(_) = lt {
518             return None;
519         }
520
521         Some(WherePredicate::BoundPredicate {
522             ty: ty.clean(cx),
523             bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
524         })
525     }
526 }
527
528 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
529     fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
530         let ty::ProjectionPredicate { projection_ty, ty } = self;
531         WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
532     }
533 }
534
535 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
536     fn clean(&self, cx: &DocContext<'_>) -> Type {
537         let lifted = self.lift_to_tcx(cx.tcx).unwrap();
538         let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
539             GenericBound::TraitBound(t, _) => t.trait_,
540             GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
541         };
542         Type::QPath {
543             name: cx.tcx.associated_item(self.item_def_id).ident.name,
544             self_type: box self.self_ty().clean(cx),
545             trait_: box trait_,
546         }
547     }
548 }
549
550 impl Clean<GenericParamDef> for ty::GenericParamDef {
551     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
552         let (name, kind) = match self.kind {
553             ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
554             ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
555                 let default =
556                     if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
557                 (
558                     self.name,
559                     GenericParamDefKind::Type {
560                         did: self.def_id,
561                         bounds: vec![], // These are filled in from the where-clauses.
562                         default,
563                         synthetic,
564                     },
565                 )
566             }
567             ty::GenericParamDefKind::Const { .. } => (
568                 self.name,
569                 GenericParamDefKind::Const {
570                     did: self.def_id,
571                     ty: cx.tcx.type_of(self.def_id).clean(cx),
572                 },
573             ),
574         };
575
576         GenericParamDef { name, kind }
577     }
578 }
579
580 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
581     fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
582         let (name, kind) = match self.kind {
583             hir::GenericParamKind::Lifetime { .. } => {
584                 let name = if !self.bounds.is_empty() {
585                     let mut bounds = self.bounds.iter().map(|bound| match bound {
586                         hir::GenericBound::Outlives(lt) => lt,
587                         _ => panic!(),
588                     });
589                     let name = bounds.next().expect("no more bounds").name.ident();
590                     let mut s = format!("{}: {}", self.name.ident(), name);
591                     for bound in bounds {
592                         s.push_str(&format!(" + {}", bound.name.ident()));
593                     }
594                     Symbol::intern(&s)
595                 } else {
596                     self.name.ident().name
597                 };
598                 (name, GenericParamDefKind::Lifetime)
599             }
600             hir::GenericParamKind::Type { ref default, synthetic } => (
601                 self.name.ident().name,
602                 GenericParamDefKind::Type {
603                     did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
604                     bounds: self.bounds.clean(cx),
605                     default: default.clean(cx),
606                     synthetic,
607                 },
608             ),
609             hir::GenericParamKind::Const { ref ty, default: _ } => (
610                 self.name.ident().name,
611                 GenericParamDefKind::Const {
612                     did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
613                     ty: ty.clean(cx),
614                     // FIXME(const_generics_defaults): add `default` field here for docs
615                 },
616             ),
617         };
618
619         GenericParamDef { name, kind }
620     }
621 }
622
623 impl Clean<Generics> for hir::Generics<'_> {
624     fn clean(&self, cx: &DocContext<'_>) -> Generics {
625         // Synthetic type-parameters are inserted after normal ones.
626         // In order for normal parameters to be able to refer to synthetic ones,
627         // scans them first.
628         fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
629             match param.kind {
630                 hir::GenericParamKind::Type { synthetic, .. } => {
631                     synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
632                 }
633                 _ => false,
634             }
635         }
636         /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
637         ///
638         /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
639         ///
640         /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
641         fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
642             matches!(
643                 param.kind,
644                 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
645             )
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) && !is_elided_lifetime(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, Symbol, 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                     let bound_p = p.kind();
747                     match bound_p.skip_binder() {
748                         ty::PredicateKind::Trait(pred, _constness) => {
749                             if let ty::Param(param) = pred.self_ty().kind() {
750                                 return Some(param.index);
751                             }
752                         }
753                         ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
754                             if let ty::Param(param) = ty.kind() {
755                                 return Some(param.index);
756                             }
757                         }
758                         ty::PredicateKind::Projection(p) => {
759                             if let ty::Param(param) = p.projection_ty.self_ty().kind() {
760                                 projection = Some(bound_p.rebind(p));
761                                 return Some(param.index);
762                             }
763                         }
764                         _ => (),
765                     }
766
767                     None
768                 })();
769
770                 if let Some(param_idx) = param_idx {
771                     if let Some(b) = impl_trait.get_mut(&param_idx.into()) {
772                         let p = p.clean(cx)?;
773
774                         b.extend(
775                             p.get_bounds()
776                                 .into_iter()
777                                 .flatten()
778                                 .cloned()
779                                 .filter(|b| !b.is_sized_bound(cx)),
780                         );
781
782                         let proj = projection
783                             .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
784                         if let Some(((_, trait_did, name), rhs)) =
785                             proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
786                         {
787                             impl_trait_proj
788                                 .entry(param_idx)
789                                 .or_default()
790                                 .push((trait_did, name, rhs));
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| !matches!(b, GenericBound::TraitBound(..)));
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);
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),
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 })
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_or(kw::Empty, |ident| ident.name);
945                     if name.is_empty() {
946                         name = kw::Underscore;
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: Symbol::intern(&rustc_hir_pretty::param_to_string(&body.params[i])),
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(kw::Empty, |i| i.name),
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), 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 hir_ty) => {
1122                     let type_ = hir_ty.clean(cx);
1123                     let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1124                     TypedefItem(
1125                         Typedef {
1126                             type_,
1127                             generics: Generics::default(),
1128                             item_type: Some(item_type),
1129                         },
1130                         true,
1131                     )
1132                 }
1133             };
1134             Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1135         })
1136     }
1137 }
1138
1139 impl Clean<Item> for ty::AssocItem {
1140     fn clean(&self, cx: &DocContext<'_>) -> Item {
1141         let kind = match self.kind {
1142             ty::AssocKind::Const => {
1143                 let ty = cx.tcx.type_of(self.def_id);
1144                 let default = if self.defaultness.has_value() {
1145                     Some(inline::print_inlined_const(cx, self.def_id))
1146                 } else {
1147                     None
1148                 };
1149                 AssocConstItem(ty.clean(cx), default)
1150             }
1151             ty::AssocKind::Fn => {
1152                 let generics =
1153                     (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1154                         .clean(cx);
1155                 let sig = cx.tcx.fn_sig(self.def_id);
1156                 let mut decl = (self.def_id, sig).clean(cx);
1157
1158                 if self.fn_has_self_parameter {
1159                     let self_ty = match self.container {
1160                         ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1161                         ty::TraitContainer(_) => cx.tcx.types.self_param,
1162                     };
1163                     let self_arg_ty = sig.input(0).skip_binder();
1164                     if self_arg_ty == self_ty {
1165                         decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1166                     } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1167                         if ty == self_ty {
1168                             match decl.inputs.values[0].type_ {
1169                                 BorrowedRef { ref mut type_, .. } => {
1170                                     **type_ = Generic(kw::SelfUpper)
1171                                 }
1172                                 _ => unreachable!(),
1173                             }
1174                         }
1175                     }
1176                 }
1177
1178                 let provided = match self.container {
1179                     ty::ImplContainer(_) => true,
1180                     ty::TraitContainer(_) => self.defaultness.has_value(),
1181                 };
1182                 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1183                 if provided {
1184                     let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1185                         hir::Constness::Const
1186                     } else {
1187                         hir::Constness::NotConst
1188                     };
1189                     let asyncness = cx.tcx.asyncness(self.def_id);
1190                     let defaultness = match self.container {
1191                         ty::ImplContainer(_) => Some(self.defaultness),
1192                         ty::TraitContainer(_) => None,
1193                     };
1194                     MethodItem(
1195                         Function {
1196                             generics,
1197                             decl,
1198                             header: hir::FnHeader {
1199                                 unsafety: sig.unsafety(),
1200                                 abi: sig.abi(),
1201                                 constness,
1202                                 asyncness,
1203                             },
1204                             all_types,
1205                             ret_types,
1206                         },
1207                         defaultness,
1208                     )
1209                 } else {
1210                     TyMethodItem(Function {
1211                         generics,
1212                         decl,
1213                         header: hir::FnHeader {
1214                             unsafety: sig.unsafety(),
1215                             abi: sig.abi(),
1216                             constness: hir::Constness::NotConst,
1217                             asyncness: hir::IsAsync::NotAsync,
1218                         },
1219                         all_types,
1220                         ret_types,
1221                     })
1222                 }
1223             }
1224             ty::AssocKind::Type => {
1225                 let my_name = self.ident.name;
1226
1227                 if let ty::TraitContainer(_) = self.container {
1228                     let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1229                     let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1230                     let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1231                     let mut bounds = generics
1232                         .where_predicates
1233                         .iter()
1234                         .filter_map(|pred| {
1235                             let (name, self_type, trait_, bounds) = match *pred {
1236                                 WherePredicate::BoundPredicate {
1237                                     ty: QPath { ref name, ref self_type, ref trait_ },
1238                                     ref bounds,
1239                                 } => (name, self_type, trait_, bounds),
1240                                 _ => return None,
1241                             };
1242                             if *name != my_name {
1243                                 return None;
1244                             }
1245                             match **trait_ {
1246                                 ResolvedPath { did, .. } if did == self.container.id() => {}
1247                                 _ => return None,
1248                             }
1249                             match **self_type {
1250                                 Generic(ref s) if *s == kw::SelfUpper => {}
1251                                 _ => return None,
1252                             }
1253                             Some(bounds)
1254                         })
1255                         .flat_map(|i| i.iter().cloned())
1256                         .collect::<Vec<_>>();
1257                     // Our Sized/?Sized bound didn't get handled when creating the generics
1258                     // because we didn't actually get our whole set of bounds until just now
1259                     // (some of them may have come from the trait). If we do have a sized
1260                     // bound, we remove it, and if we don't then we add the `?Sized` bound
1261                     // at the end.
1262                     match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1263                         Some(i) => {
1264                             bounds.remove(i);
1265                         }
1266                         None => bounds.push(GenericBound::maybe_sized(cx)),
1267                     }
1268
1269                     let ty = if self.defaultness.has_value() {
1270                         Some(cx.tcx.type_of(self.def_id))
1271                     } else {
1272                         None
1273                     };
1274
1275                     AssocTypeItem(bounds, ty.clean(cx))
1276                 } else {
1277                     // FIXME: when could this happen? ASsociated items in inherent impls?
1278                     let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1279                     TypedefItem(
1280                         Typedef {
1281                             type_,
1282                             generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1283                             item_type: None,
1284                         },
1285                         true,
1286                     )
1287                 }
1288             }
1289         };
1290
1291         Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1292     }
1293 }
1294
1295 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1296     use rustc_hir::GenericParamCount;
1297     let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1298     let qpath = match kind {
1299         hir::TyKind::Path(qpath) => qpath,
1300         _ => unreachable!(),
1301     };
1302
1303     match qpath {
1304         hir::QPath::Resolved(None, ref path) => {
1305             if let Res::Def(DefKind::TyParam, did) = path.res {
1306                 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1307                     return new_ty;
1308                 }
1309                 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1310                     return ImplTrait(bounds);
1311                 }
1312             }
1313
1314             let mut alias = None;
1315             if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1316                 // Substitute private type aliases
1317                 if let Some(def_id) = def_id.as_local() {
1318                     let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1319                     if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1320                         alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1321                     }
1322                 }
1323             };
1324
1325             if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1326                 let provided_params = &path.segments.last().expect("segments were empty");
1327                 let mut ty_substs = FxHashMap::default();
1328                 let mut lt_substs = FxHashMap::default();
1329                 let mut ct_substs = FxHashMap::default();
1330                 let generic_args = provided_params.args();
1331                 {
1332                     let mut indices: GenericParamCount = Default::default();
1333                     for param in generics.params.iter() {
1334                         match param.kind {
1335                             hir::GenericParamKind::Lifetime { .. } => {
1336                                 let mut j = 0;
1337                                 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1338                                     hir::GenericArg::Lifetime(lt) => {
1339                                         if indices.lifetimes == j {
1340                                             return Some(lt);
1341                                         }
1342                                         j += 1;
1343                                         None
1344                                     }
1345                                     _ => None,
1346                                 });
1347                                 if let Some(lt) = lifetime.cloned() {
1348                                     let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1349                                     let cleaned = if !lt.is_elided() {
1350                                         lt.clean(cx)
1351                                     } else {
1352                                         self::types::Lifetime::elided()
1353                                     };
1354                                     lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1355                                 }
1356                                 indices.lifetimes += 1;
1357                             }
1358                             hir::GenericParamKind::Type { ref default, .. } => {
1359                                 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1360                                 let mut j = 0;
1361                                 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1362                                     hir::GenericArg::Type(ty) => {
1363                                         if indices.types == j {
1364                                             return Some(ty);
1365                                         }
1366                                         j += 1;
1367                                         None
1368                                     }
1369                                     _ => None,
1370                                 });
1371                                 if let Some(ty) = type_ {
1372                                     ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1373                                 } else if let Some(default) = *default {
1374                                     ty_substs
1375                                         .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1376                                 }
1377                                 indices.types += 1;
1378                             }
1379                             hir::GenericParamKind::Const { .. } => {
1380                                 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1381                                 let mut j = 0;
1382                                 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1383                                     hir::GenericArg::Const(ct) => {
1384                                         if indices.consts == j {
1385                                             return Some(ct);
1386                                         }
1387                                         j += 1;
1388                                         None
1389                                     }
1390                                     _ => None,
1391                                 });
1392                                 if let Some(ct) = const_ {
1393                                     ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1394                                 }
1395                                 // FIXME(const_generics_defaults)
1396                                 indices.consts += 1;
1397                             }
1398                         }
1399                     }
1400                 }
1401                 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1402             }
1403             resolve_type(cx, path.clean(cx), hir_id)
1404         }
1405         hir::QPath::Resolved(Some(ref qself), ref p) => {
1406             // Try to normalize `<X as Y>::T` to a type
1407             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1408             if let Some(normalized_value) = normalize(cx, ty) {
1409                 return normalized_value.clean(cx);
1410             }
1411
1412             let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1413             let trait_segments = &segments[..segments.len() - 1];
1414             let trait_path = self::Path {
1415                 global: p.is_global(),
1416                 res: Res::Def(
1417                     DefKind::Trait,
1418                     cx.tcx.associated_item(p.res.def_id()).container.id(),
1419                 ),
1420                 segments: trait_segments.clean(cx),
1421             };
1422             Type::QPath {
1423                 name: p.segments.last().expect("segments were empty").ident.name,
1424                 self_type: box qself.clean(cx),
1425                 trait_: box resolve_type(cx, trait_path, hir_id),
1426             }
1427         }
1428         hir::QPath::TypeRelative(ref qself, ref segment) => {
1429             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1430             let res = if let ty::Projection(proj) = ty.kind() {
1431                 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1432             } else {
1433                 Res::Err
1434             };
1435             let trait_path = hir::Path { span, res, segments: &[] };
1436             Type::QPath {
1437                 name: segment.ident.name,
1438                 self_type: box qself.clean(cx),
1439                 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1440             }
1441         }
1442         hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1443     }
1444 }
1445
1446 impl Clean<Type> for hir::Ty<'_> {
1447     fn clean(&self, cx: &DocContext<'_>) -> Type {
1448         use rustc_hir::*;
1449
1450         match self.kind {
1451             TyKind::Never => Never,
1452             TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1453             TyKind::Rptr(ref l, ref m) => {
1454                 // There are two times a `Fresh` lifetime can be created:
1455                 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1456                 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1457                 //    See #59286 for more information.
1458                 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1459                 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1460                 // there's no case where it could cause the function to fail to compile.
1461                 let elided =
1462                     l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1463                 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1464                 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1465             }
1466             TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1467             TyKind::Array(ref ty, ref length) => {
1468                 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1469                 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1470                 // as we currently do not supply the parent generics to anonymous constants
1471                 // but do allow `ConstKind::Param`.
1472                 //
1473                 // `const_eval_poly` tries to to first substitute generic parameters which
1474                 // results in an ICE while manually constructing the constant and using `eval`
1475                 // does nothing for `ConstKind::Param`.
1476                 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1477                 let param_env = cx.tcx.param_env(def_id);
1478                 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1479                 Array(box ty.clean(cx), length)
1480             }
1481             TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1482             TyKind::OpaqueDef(item_id, _) => {
1483                 let item = cx.tcx.hir().expect_item(item_id.id);
1484                 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1485                     ImplTrait(ty.bounds.clean(cx))
1486                 } else {
1487                     unreachable!()
1488                 }
1489             }
1490             TyKind::Path(_) => clean_qpath(&self, cx),
1491             TyKind::TraitObject(ref bounds, ref lifetime) => {
1492                 match bounds[0].clean(cx).trait_ {
1493                     ResolvedPath { path, param_names: None, did, is_generic } => {
1494                         let mut bounds: Vec<self::GenericBound> = bounds[1..]
1495                             .iter()
1496                             .map(|bound| {
1497                                 self::GenericBound::TraitBound(
1498                                     bound.clean(cx),
1499                                     hir::TraitBoundModifier::None,
1500                                 )
1501                             })
1502                             .collect();
1503                         if !lifetime.is_elided() {
1504                             bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1505                         }
1506                         ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1507                     }
1508                     _ => Infer, // shouldn't happen
1509                 }
1510             }
1511             TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1512             TyKind::Infer | TyKind::Err => Infer,
1513             TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1514         }
1515     }
1516 }
1517
1518 /// Returns `None` if the type could not be normalized
1519 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1520     // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1521     if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1522         return None;
1523     }
1524
1525     use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1526     use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1527     use rustc_middle::traits::ObligationCause;
1528
1529     // Try to normalize `<X as Y>::T` to a type
1530     let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1531     let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1532         infcx
1533             .at(&ObligationCause::dummy(), cx.param_env.get())
1534             .normalize(lifted)
1535             .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1536     });
1537     match normalized {
1538         Ok(normalized_value) => {
1539             debug!("normalized {:?} to {:?}", ty, normalized_value);
1540             Some(normalized_value)
1541         }
1542         Err(err) => {
1543             debug!("failed to normalize {:?}: {:?}", ty, err);
1544             None
1545         }
1546     }
1547 }
1548
1549 impl<'tcx> Clean<Type> for Ty<'tcx> {
1550     fn clean(&self, cx: &DocContext<'_>) -> Type {
1551         debug!("cleaning type: {:?}", self);
1552         let ty = normalize(cx, self).unwrap_or(self);
1553         match *ty.kind() {
1554             ty::Never => Never,
1555             ty::Bool => Primitive(PrimitiveType::Bool),
1556             ty::Char => Primitive(PrimitiveType::Char),
1557             ty::Int(int_ty) => Primitive(int_ty.into()),
1558             ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1559             ty::Float(float_ty) => Primitive(float_ty.into()),
1560             ty::Str => Primitive(PrimitiveType::Str),
1561             ty::Slice(ty) => Slice(box ty.clean(cx)),
1562             ty::Array(ty, n) => {
1563                 let mut n = cx.tcx.lift(n).expect("array lift failed");
1564                 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1565                 let n = print_const(cx, n);
1566                 Array(box ty.clean(cx), n)
1567             }
1568             ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1569             ty::Ref(r, ty, mutbl) => {
1570                 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1571             }
1572             ty::FnDef(..) | ty::FnPtr(_) => {
1573                 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1574                 let sig = ty.fn_sig(cx.tcx);
1575                 let def_id = DefId::local(CRATE_DEF_INDEX);
1576                 BareFunction(box BareFunctionDecl {
1577                     unsafety: sig.unsafety(),
1578                     generic_params: Vec::new(),
1579                     decl: (def_id, sig).clean(cx),
1580                     abi: sig.abi(),
1581                 })
1582             }
1583             ty::Adt(def, substs) => {
1584                 let did = def.did;
1585                 let kind = match def.adt_kind() {
1586                     AdtKind::Struct => TypeKind::Struct,
1587                     AdtKind::Union => TypeKind::Union,
1588                     AdtKind::Enum => TypeKind::Enum,
1589                 };
1590                 inline::record_extern_fqn(cx, did, kind);
1591                 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1592                 ResolvedPath { path, param_names: None, did, is_generic: false }
1593             }
1594             ty::Foreign(did) => {
1595                 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1596                 let path = external_path(
1597                     cx,
1598                     cx.tcx.item_name(did),
1599                     None,
1600                     false,
1601                     vec![],
1602                     InternalSubsts::empty(),
1603                 );
1604                 ResolvedPath { path, param_names: None, did, is_generic: false }
1605             }
1606             ty::Dynamic(ref obj, ref reg) => {
1607                 // HACK: pick the first `did` as the `did` of the trait object. Someone
1608                 // might want to implement "native" support for marker-trait-only
1609                 // trait objects.
1610                 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1611                 let did = dids
1612                     .next()
1613                     .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1614                 let substs = match obj.principal() {
1615                     Some(principal) => principal.skip_binder().substs,
1616                     // marker traits have no substs.
1617                     _ => cx.tcx.intern_substs(&[]),
1618                 };
1619
1620                 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1621
1622                 let mut param_names = vec![];
1623                 if let Some(b) = reg.clean(cx) {
1624                     param_names.push(GenericBound::Outlives(b));
1625                 }
1626                 for did in dids {
1627                     let empty = cx.tcx.intern_substs(&[]);
1628                     let path =
1629                         external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1630                     inline::record_extern_fqn(cx, did, TypeKind::Trait);
1631                     let bound = GenericBound::TraitBound(
1632                         PolyTrait {
1633                             trait_: ResolvedPath {
1634                                 path,
1635                                 param_names: None,
1636                                 did,
1637                                 is_generic: false,
1638                             },
1639                             generic_params: Vec::new(),
1640                         },
1641                         hir::TraitBoundModifier::None,
1642                     );
1643                     param_names.push(bound);
1644                 }
1645
1646                 let mut bindings = vec![];
1647                 for pb in obj.projection_bounds() {
1648                     bindings.push(TypeBinding {
1649                         name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1650                         kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1651                     });
1652                 }
1653
1654                 let path =
1655                     external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1656                 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1657             }
1658             ty::Tuple(ref t) => {
1659                 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1660             }
1661
1662             ty::Projection(ref data) => data.clean(cx),
1663
1664             ty::Param(ref p) => {
1665                 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1666                     ImplTrait(bounds)
1667                 } else {
1668                     Generic(p.name)
1669                 }
1670             }
1671
1672             ty::Opaque(def_id, substs) => {
1673                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1674                 // by looking up the bounds associated with the def_id.
1675                 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1676                 let bounds = cx
1677                     .tcx
1678                     .explicit_item_bounds(def_id)
1679                     .iter()
1680                     .map(|(bound, _)| bound.subst(cx.tcx, substs))
1681                     .collect::<Vec<_>>();
1682                 let mut regions = vec![];
1683                 let mut has_sized = false;
1684                 let mut bounds = bounds
1685                     .iter()
1686                     .filter_map(|bound| {
1687                         let bound_predicate = bound.kind();
1688                         let trait_ref = match bound_predicate.skip_binder() {
1689                             ty::PredicateKind::Trait(tr, _constness) => {
1690                                 bound_predicate.rebind(tr.trait_ref)
1691                             }
1692                             ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1693                                 if let Some(r) = reg.clean(cx) {
1694                                     regions.push(GenericBound::Outlives(r));
1695                                 }
1696                                 return None;
1697                             }
1698                             _ => return None,
1699                         };
1700
1701                         if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1702                             if trait_ref.def_id() == sized {
1703                                 has_sized = true;
1704                                 return None;
1705                             }
1706                         }
1707
1708                         let bounds: Vec<_> = bounds
1709                             .iter()
1710                             .filter_map(|bound| {
1711                                 if let ty::PredicateKind::Projection(proj) =
1712                                     bound.kind().skip_binder()
1713                                 {
1714                                     if proj.projection_ty.trait_ref(cx.tcx)
1715                                         == trait_ref.skip_binder()
1716                                     {
1717                                         Some(TypeBinding {
1718                                             name: cx
1719                                                 .tcx
1720                                                 .associated_item(proj.projection_ty.item_def_id)
1721                                                 .ident
1722                                                 .name,
1723                                             kind: TypeBindingKind::Equality {
1724                                                 ty: proj.ty.clean(cx),
1725                                             },
1726                                         })
1727                                     } else {
1728                                         None
1729                                     }
1730                                 } else {
1731                                     None
1732                                 }
1733                             })
1734                             .collect();
1735
1736                         Some((trait_ref, &bounds[..]).clean(cx))
1737                     })
1738                     .collect::<Vec<_>>();
1739                 bounds.extend(regions);
1740                 if !has_sized && !bounds.is_empty() {
1741                     bounds.insert(0, GenericBound::maybe_sized(cx));
1742                 }
1743                 ImplTrait(bounds)
1744             }
1745
1746             ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1747
1748             ty::Bound(..) => panic!("Bound"),
1749             ty::Placeholder(..) => panic!("Placeholder"),
1750             ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1751             ty::Infer(..) => panic!("Infer"),
1752             ty::Error(_) => panic!("Error"),
1753         }
1754     }
1755 }
1756
1757 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1758     fn clean(&self, cx: &DocContext<'_>) -> Constant {
1759         Constant {
1760             type_: self.ty.clean(cx),
1761             expr: format!("{}", self),
1762             value: None,
1763             is_literal: false,
1764         }
1765     }
1766 }
1767
1768 impl Clean<Item> for hir::StructField<'_> {
1769     fn clean(&self, cx: &DocContext<'_>) -> Item {
1770         let what_rustc_thinks = Item::from_hir_id_and_parts(
1771             self.hir_id,
1772             Some(self.ident.name),
1773             StructFieldItem(self.ty.clean(cx)),
1774             cx,
1775         );
1776         // Don't show `pub` for fields on enum variants; they are always public
1777         Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1778     }
1779 }
1780
1781 impl Clean<Item> for ty::FieldDef {
1782     fn clean(&self, cx: &DocContext<'_>) -> Item {
1783         let what_rustc_thinks = Item::from_def_id_and_parts(
1784             self.did,
1785             Some(self.ident.name),
1786             StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1787             cx,
1788         );
1789         // Don't show `pub` for fields on enum variants; they are always public
1790         Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1791     }
1792 }
1793
1794 impl Clean<Visibility> for hir::Visibility<'_> {
1795     fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1796         match self.node {
1797             hir::VisibilityKind::Public => Visibility::Public,
1798             hir::VisibilityKind::Inherited => Visibility::Inherited,
1799             hir::VisibilityKind::Crate(_) => {
1800                 let krate = DefId::local(CRATE_DEF_INDEX);
1801                 Visibility::Restricted(krate)
1802             }
1803             hir::VisibilityKind::Restricted { ref path, .. } => {
1804                 let path = path.clean(cx);
1805                 let did = register_res(cx, path.res);
1806                 Visibility::Restricted(did)
1807             }
1808         }
1809     }
1810 }
1811
1812 impl Clean<Visibility> for ty::Visibility {
1813     fn clean(&self, _cx: &DocContext<'_>) -> Visibility {
1814         match *self {
1815             ty::Visibility::Public => Visibility::Public,
1816             // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1817             // while rustdoc really does mean inherited. That means that for enum variants, such as
1818             // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1819             // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1820             // override `tcx.visibility` explicitly to make sure this distinction is captured.
1821             ty::Visibility::Invisible => Visibility::Inherited,
1822             ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1823         }
1824     }
1825 }
1826
1827 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1828     fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1829         VariantStruct {
1830             struct_type: doctree::struct_type_from_def(self),
1831             fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1832             fields_stripped: false,
1833         }
1834     }
1835 }
1836
1837 impl Clean<Item> for ty::VariantDef {
1838     fn clean(&self, cx: &DocContext<'_>) -> Item {
1839         let kind = match self.ctor_kind {
1840             CtorKind::Const => Variant::CLike,
1841             CtorKind::Fn => Variant::Tuple(
1842                 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1843             ),
1844             CtorKind::Fictive => Variant::Struct(VariantStruct {
1845                 struct_type: doctree::Plain,
1846                 fields_stripped: false,
1847                 fields: self
1848                     .fields
1849                     .iter()
1850                     .map(|field| {
1851                         let name = Some(field.ident.name);
1852                         let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1853                         let what_rustc_thinks =
1854                             Item::from_def_id_and_parts(field.did, name, kind, cx);
1855                         // don't show `pub` for fields, which are always public
1856                         Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1857                     })
1858                     .collect(),
1859             }),
1860         };
1861         let what_rustc_thinks =
1862             Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1863         // don't show `pub` for fields, which are always public
1864         Item { visibility: Inherited, ..what_rustc_thinks }
1865     }
1866 }
1867
1868 impl Clean<Variant> for hir::VariantData<'_> {
1869     fn clean(&self, cx: &DocContext<'_>) -> Variant {
1870         match self {
1871             hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1872             hir::VariantData::Tuple(..) => {
1873                 Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1874             }
1875             hir::VariantData::Unit(..) => Variant::CLike,
1876         }
1877     }
1878 }
1879
1880 impl Clean<Span> for rustc_span::Span {
1881     fn clean(&self, _cx: &DocContext<'_>) -> Span {
1882         Span::from_rustc_span(*self)
1883     }
1884 }
1885
1886 impl Clean<Path> for hir::Path<'_> {
1887     fn clean(&self, cx: &DocContext<'_>) -> Path {
1888         Path {
1889             global: self.is_global(),
1890             res: self.res,
1891             segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1892         }
1893     }
1894 }
1895
1896 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1897     fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1898         if self.parenthesized {
1899             let output = self.bindings[0].ty().clean(cx);
1900             GenericArgs::Parenthesized {
1901                 inputs: self.inputs().clean(cx),
1902                 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1903             }
1904         } else {
1905             GenericArgs::AngleBracketed {
1906                 args: self
1907                     .args
1908                     .iter()
1909                     .map(|arg| match arg {
1910                         hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1911                             GenericArg::Lifetime(lt.clean(cx))
1912                         }
1913                         hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1914                         hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1915                         hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1916                     })
1917                     .collect(),
1918                 bindings: self.bindings.clean(cx),
1919             }
1920         }
1921     }
1922 }
1923
1924 impl Clean<PathSegment> for hir::PathSegment<'_> {
1925     fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1926         PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1927     }
1928 }
1929
1930 impl Clean<String> for Ident {
1931     #[inline]
1932     fn clean(&self, cx: &DocContext<'_>) -> String {
1933         self.name.clean(cx)
1934     }
1935 }
1936
1937 impl Clean<String> for Symbol {
1938     #[inline]
1939     fn clean(&self, _: &DocContext<'_>) -> String {
1940         self.to_string()
1941     }
1942 }
1943
1944 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1945     fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1946         let (generic_params, decl) = enter_impl_trait(cx, || {
1947             (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1948         });
1949         BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1950     }
1951 }
1952
1953 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1954     fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1955         use hir::ItemKind;
1956
1957         let (item, renamed) = self;
1958         let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1959         let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id));
1960         cx.with_param_env(def_id, || {
1961             let kind = match item.kind {
1962                 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
1963                     type_: ty.clean(cx),
1964                     mutability,
1965                     expr: print_const_expr(cx, body_id),
1966                 }),
1967                 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1968                     type_: ty.clean(cx),
1969                     expr: print_const_expr(cx, body_id),
1970                     value: print_evaluated_const(cx, def_id),
1971                     is_literal: is_literal_expr(cx, body_id.hir_id),
1972                 }),
1973                 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1974                     bounds: ty.bounds.clean(cx),
1975                     generics: ty.generics.clean(cx),
1976                 }),
1977                 ItemKind::TyAlias(hir_ty, ref generics) => {
1978                     let rustdoc_ty = hir_ty.clean(cx);
1979                     let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1980                     TypedefItem(
1981                         Typedef {
1982                             type_: rustdoc_ty,
1983                             generics: generics.clean(cx),
1984                             item_type: Some(ty),
1985                         },
1986                         false,
1987                     )
1988                 }
1989                 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1990                     variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1991                     generics: generics.clean(cx),
1992                     variants_stripped: false,
1993                 }),
1994                 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1995                     generics: generics.clean(cx),
1996                     bounds: bounds.clean(cx),
1997                 }),
1998                 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1999                     struct_type: doctree::struct_type_from_def(&variant_data),
2000                     generics: generics.clean(cx),
2001                     fields: variant_data.fields().clean(cx),
2002                     fields_stripped: false,
2003                 }),
2004                 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2005                     struct_type: doctree::struct_type_from_def(&variant_data),
2006                     generics: generics.clean(cx),
2007                     fields: variant_data.fields().clean(cx),
2008                     fields_stripped: false,
2009                 }),
2010                 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id, cx),
2011                 // proc macros can have a name set by attributes
2012                 ItemKind::Fn(ref sig, ref generics, body_id) => {
2013                     clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2014                 }
2015                 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2016                     let items = item_ids
2017                         .iter()
2018                         .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2019                         .collect();
2020                     let attrs = item.attrs.clean(cx);
2021                     let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2022                     TraitItem(Trait {
2023                         unsafety,
2024                         items,
2025                         generics: generics.clean(cx),
2026                         bounds: bounds.clean(cx),
2027                         is_spotlight,
2028                         is_auto: is_auto.clean(cx),
2029                     })
2030                 }
2031                 ItemKind::ExternCrate(orig_name) => {
2032                     return clean_extern_crate(item, name, orig_name, cx);
2033                 }
2034                 ItemKind::Use(path, kind) => {
2035                     return clean_use_statement(item, name, path, kind, cx);
2036                 }
2037                 _ => unreachable!("not yet converted"),
2038             };
2039
2040             vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2041         })
2042     }
2043 }
2044
2045 impl Clean<Item> for hir::Variant<'_> {
2046     fn clean(&self, cx: &DocContext<'_>) -> Item {
2047         let kind = VariantItem(self.data.clean(cx));
2048         let what_rustc_thinks =
2049             Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2050         // don't show `pub` for variants, which are always public
2051         Item { visibility: Inherited, ..what_rustc_thinks }
2052     }
2053 }
2054
2055 impl Clean<bool> for ty::ImplPolarity {
2056     /// Returns whether the impl has negative polarity.
2057     fn clean(&self, _: &DocContext<'_>) -> bool {
2058         match self {
2059             &ty::ImplPolarity::Positive |
2060             // FIXME: do we want to do something else here?
2061             &ty::ImplPolarity::Reservation => false,
2062             &ty::ImplPolarity::Negative => true,
2063         }
2064     }
2065 }
2066
2067 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &DocContext<'_>) -> Vec<Item> {
2068     let mut ret = Vec::new();
2069     let trait_ = impl_.of_trait.clean(cx);
2070     let items =
2071         impl_.items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2072     let def_id = cx.tcx.hir().local_def_id(hir_id);
2073
2074     // If this impl block is an implementation of the Deref trait, then we
2075     // need to try inlining the target's inherent impl blocks as well.
2076     if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2077         build_deref_target_impls(cx, &items, &mut ret);
2078     }
2079
2080     let provided: FxHashSet<Symbol> = trait_
2081         .def_id()
2082         .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2083         .unwrap_or_default();
2084
2085     let for_ = impl_.self_ty.clean(cx);
2086     let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2087         DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2088         _ => None,
2089     });
2090     let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2091         let kind = ImplItem(Impl {
2092             unsafety: impl_.unsafety,
2093             generics: impl_.generics.clean(cx),
2094             provided_trait_methods: provided.clone(),
2095             trait_,
2096             for_,
2097             items,
2098             negative_polarity: cx.tcx.impl_polarity(def_id).clean(cx),
2099             synthetic: false,
2100             blanket_impl: None,
2101         });
2102         Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2103     };
2104     if let Some(type_alias) = type_alias {
2105         ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2106     }
2107     ret.push(make_item(trait_, for_, items));
2108     ret
2109 }
2110
2111 fn clean_extern_crate(
2112     krate: &hir::Item<'_>,
2113     name: Symbol,
2114     orig_name: Option<Symbol>,
2115     cx: &DocContext<'_>,
2116 ) -> Vec<Item> {
2117     // this is the ID of the `extern crate` statement
2118     let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2119     let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2120     // this is the ID of the crate itself
2121     let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2122     let please_inline = krate.vis.node.is_pub()
2123         && krate.attrs.iter().any(|a| {
2124             a.has_name(sym::doc)
2125                 && match a.meta_item_list() {
2126                     Some(l) => attr::list_contains_name(&l, sym::inline),
2127                     None => false,
2128                 }
2129         });
2130
2131     if please_inline {
2132         let mut visited = FxHashSet::default();
2133
2134         let res = Res::Def(DefKind::Mod, crate_def_id);
2135
2136         if let Some(items) = inline::try_inline(
2137             cx,
2138             cx.tcx.parent_module(krate.hir_id).to_def_id(),
2139             res,
2140             name,
2141             Some(krate.attrs),
2142             &mut visited,
2143         ) {
2144             return items;
2145         }
2146     }
2147     // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2148     vec![Item {
2149         name: None,
2150         attrs: box krate.attrs.clean(cx),
2151         source: krate.span.clean(cx),
2152         def_id: crate_def_id,
2153         visibility: krate.vis.clean(cx),
2154         kind: box ExternCrateItem(name, orig_name),
2155     }]
2156 }
2157
2158 fn clean_use_statement(
2159     import: &hir::Item<'_>,
2160     name: Symbol,
2161     path: &hir::Path<'_>,
2162     kind: hir::UseKind,
2163     cx: &DocContext<'_>,
2164 ) -> Vec<Item> {
2165     // We need this comparison because some imports (for std types for example)
2166     // are "inserted" as well but directly by the compiler and they should not be
2167     // taken into account.
2168     if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2169         return Vec::new();
2170     }
2171
2172     let (doc_meta_item, please_inline) = import.attrs.lists(sym::doc).get_word_attr(sym::inline);
2173     let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2174
2175     if pub_underscore && please_inline {
2176         rustc_errors::struct_span_err!(
2177             cx.tcx.sess,
2178             doc_meta_item.unwrap().span(),
2179             E0780,
2180             "anonymous imports cannot be inlined"
2181         )
2182         .span_label(import.span, "anonymous import")
2183         .emit();
2184     }
2185
2186     // We consider inlining the documentation of `pub use` statements, but we
2187     // forcefully don't inline if this is not public or if the
2188     // #[doc(no_inline)] attribute is present.
2189     // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2190     let mut denied = !import.vis.node.is_pub()
2191         || pub_underscore
2192         || import.attrs.iter().any(|a| {
2193             a.has_name(sym::doc)
2194                 && match a.meta_item_list() {
2195                     Some(l) => {
2196                         attr::list_contains_name(&l, sym::no_inline)
2197                             || attr::list_contains_name(&l, sym::hidden)
2198                     }
2199                     None => false,
2200                 }
2201         });
2202
2203     // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2204     // crate in Rust 2018+
2205     let def_id = cx.tcx.hir().local_def_id(import.hir_id).to_def_id();
2206     let path = path.clean(cx);
2207     let inner = if kind == hir::UseKind::Glob {
2208         if !denied {
2209             let mut visited = FxHashSet::default();
2210             if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2211                 return items;
2212             }
2213         }
2214         Import::new_glob(resolve_use_source(cx, path), true)
2215     } else {
2216         if !please_inline {
2217             if let Res::Def(DefKind::Mod, did) = path.res {
2218                 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2219                     // if we're `pub use`ing an extern crate root, don't inline it unless we
2220                     // were specifically asked for it
2221                     denied = true;
2222                 }
2223             }
2224         }
2225         if !denied {
2226             let mut visited = FxHashSet::default();
2227
2228             if let Some(mut items) = inline::try_inline(
2229                 cx,
2230                 cx.tcx.parent_module(import.hir_id).to_def_id(),
2231                 path.res,
2232                 name,
2233                 Some(import.attrs),
2234                 &mut visited,
2235             ) {
2236                 items.push(Item::from_def_id_and_parts(
2237                     def_id,
2238                     None,
2239                     ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2240                     cx,
2241                 ));
2242                 return items;
2243             }
2244         }
2245         Import::new_simple(name, resolve_use_source(cx, path), true)
2246     };
2247
2248     vec![Item::from_def_id_and_parts(def_id, None, ImportItem(inner), cx)]
2249 }
2250
2251 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2252     fn clean(&self, cx: &DocContext<'_>) -> Item {
2253         let (item, renamed) = self;
2254         cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2255             let kind = match item.kind {
2256                 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2257                     let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2258                     let (generics, decl) = enter_impl_trait(cx, || {
2259                         (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2260                     });
2261                     let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2262                     ForeignFunctionItem(Function {
2263                         decl,
2264                         generics,
2265                         header: hir::FnHeader {
2266                             unsafety: hir::Unsafety::Unsafe,
2267                             abi,
2268                             constness: hir::Constness::NotConst,
2269                             asyncness: hir::IsAsync::NotAsync,
2270                         },
2271                         all_types,
2272                         ret_types,
2273                     })
2274                 }
2275                 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2276                     type_: ty.clean(cx),
2277                     mutability,
2278                     expr: String::new(),
2279                 }),
2280                 hir::ForeignItemKind::Type => ForeignTypeItem,
2281             };
2282
2283             Item::from_hir_id_and_parts(
2284                 item.hir_id,
2285                 Some(renamed.unwrap_or(item.ident.name)),
2286                 kind,
2287                 cx,
2288             )
2289         })
2290     }
2291 }
2292
2293 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2294     fn clean(&self, cx: &DocContext<'_>) -> Item {
2295         let (item, renamed) = self;
2296         let name = renamed.unwrap_or(item.ident.name);
2297         let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2298         // Extract the spans of all matchers. They represent the "interface" of the macro.
2299         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2300         let source = if item.ast.macro_rules {
2301             format!(
2302                 "macro_rules! {} {{\n{}}}",
2303                 name,
2304                 matchers
2305                     .iter()
2306                     .map(|span| { format!("    {} => {{ ... }};\n", span.to_src(cx)) })
2307                     .collect::<String>(),
2308             )
2309         } else {
2310             let vis = item.vis.clean(cx);
2311             let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
2312
2313             if matchers.len() <= 1 {
2314                 format!(
2315                     "{}macro {}{} {{\n    ...\n}}",
2316                     vis.print_with_space(cx.tcx, def_id),
2317                     name,
2318                     matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2319                 )
2320             } else {
2321                 format!(
2322                     "{}macro {} {{\n{}}}",
2323                     vis.print_with_space(cx.tcx, def_id),
2324                     name,
2325                     matchers
2326                         .iter()
2327                         .map(|span| { format!("    {} => {{ ... }},\n", span.to_src(cx)) })
2328                         .collect::<String>(),
2329                 )
2330             }
2331         };
2332
2333         Item::from_hir_id_and_parts(
2334             item.hir_id,
2335             Some(name),
2336             MacroItem(Macro { source, imported_from: None }),
2337             cx,
2338         )
2339     }
2340 }
2341
2342 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2343     fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2344         TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2345     }
2346 }
2347
2348 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2349     fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2350         match *self {
2351             hir::TypeBindingKind::Equality { ref ty } => {
2352                 TypeBindingKind::Equality { ty: ty.clean(cx) }
2353             }
2354             hir::TypeBindingKind::Constraint { ref bounds } => {
2355                 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2356             }
2357         }
2358     }
2359 }
2360
2361 enum SimpleBound {
2362     TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2363     Outlives(Lifetime),
2364 }
2365
2366 impl From<GenericBound> for SimpleBound {
2367     fn from(bound: GenericBound) -> Self {
2368         match bound.clone() {
2369             GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2370             GenericBound::TraitBound(t, mod_) => match t.trait_ {
2371                 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2372                     path.segments,
2373                     param_names.map_or_else(Vec::new, |v| {
2374                         v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2375                     }),
2376                     t.generic_params,
2377                     mod_,
2378                 ),
2379                 _ => panic!("Unexpected bound {:?}", bound),
2380             },
2381         }
2382     }
2383 }