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