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