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