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