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