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