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