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