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