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