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