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