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