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