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