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