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