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