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