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