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