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