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