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