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