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