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