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