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