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