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