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