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