1 //! This module contains the "cleaned" pieces of the AST, and the functions
12 use rustc_index::vec::{IndexVec, Idx};
13 use rustc_typeck::hir_ty_to_ty;
14 use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
15 use rustc::middle::resolve_lifetime as rl;
16 use rustc::middle::lang_items;
17 use rustc::middle::stability;
18 use rustc::mir::interpret::GlobalId;
20 use rustc::hir::def::{CtorKind, DefKind, Res};
21 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
22 use rustc::hir::ptr::P;
23 use rustc::ty::subst::InternalSubsts;
24 use rustc::ty::{self, TyCtxt, Ty, AdtKind, Lift};
25 use rustc::ty::fold::TypeFolder;
26 use rustc::util::nodemap::{FxHashMap, FxHashSet};
27 use syntax::ast::{self, Ident};
29 use syntax_pos::symbol::{kw, sym};
30 use syntax_pos::hygiene::MacroKind;
31 use syntax_pos::{self, Pos};
33 use std::collections::hash_map::Entry;
35 use std::default::Default;
40 use crate::core::{self, DocContext, ImplTraitParam};
45 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47 pub use self::types::*;
48 pub use self::types::Type::*;
49 pub use self::types::Mutability::*;
50 pub use self::types::ItemEnum::*;
51 pub use self::types::SelfTy::*;
52 pub use self::types::FunctionRetTy::*;
53 pub use self::types::Visibility::{Public, Inherited};
55 const FN_OUTPUT_NAME: &'static str = "Output";
58 fn clean(&self, cx: &DocContext<'_>) -> T;
61 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
62 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
63 self.iter().map(|x| x.clean(cx)).collect()
67 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
68 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
69 self.iter().map(|x| x.clean(cx)).collect()
73 impl<T: Clean<U>, U> Clean<U> for P<T> {
74 fn clean(&self, cx: &DocContext<'_>) -> U {
79 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
80 fn clean(&self, cx: &DocContext<'_>) -> U {
85 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
86 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
87 self.as_ref().map(|v| v.clean(cx))
91 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
92 fn clean(&self, cx: &DocContext<'_>) -> U {
93 self.skip_binder().clean(cx)
97 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
98 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
99 self.iter().map(|x| x.clean(cx)).collect()
103 impl Clean<ExternalCrate> for CrateNum {
104 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
105 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
106 let krate_span = cx.tcx.def_span(root);
107 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
109 // Collect all inner modules which are tagged as implementations of
112 // Note that this loop only searches the top-level items of the crate,
113 // and this is intentional. If we were to search the entire crate for an
114 // item tagged with `#[doc(primitive)]` then we would also have to
115 // search the entirety of external modules for items tagged
116 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
117 // all that metadata unconditionally).
119 // In order to keep the metadata load under control, the
120 // `#[doc(primitive)]` feature is explicitly designed to only allow the
121 // primitive tags to show up as the top level items in a crate.
123 // Also note that this does not attempt to deal with modules tagged
124 // duplicately for the same primitive. This is handled later on when
125 // rendering by delegating everything to a hash map.
126 let as_primitive = |res: Res| {
127 if let Res::Def(DefKind::Mod, def_id) = res {
128 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
130 for attr in attrs.lists(sym::doc) {
131 if let Some(v) = attr.value_str() {
132 if attr.check_name(sym::primitive) {
133 prim = PrimitiveType::from_str(&v.as_str());
137 // FIXME: should warn on unknown primitives?
141 return prim.map(|p| (def_id, p, attrs));
145 let primitives = if root.is_local() {
146 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
147 let item = cx.tcx.hir().expect_item(id.id);
149 hir::ItemKind::Mod(_) => {
150 as_primitive(Res::Def(
152 cx.tcx.hir().local_def_id(id.id),
155 hir::ItemKind::Use(ref path, hir::UseKind::Single)
156 if item.vis.node.is_pub() => {
157 as_primitive(path.res).map(|(_, prim, attrs)| {
158 // Pretend the primitive is local.
159 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
166 cx.tcx.item_children(root).iter().map(|item| item.res)
167 .filter_map(as_primitive).collect()
170 let as_keyword = |res: Res| {
171 if let Res::Def(DefKind::Mod, def_id) = res {
172 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
173 let mut keyword = None;
174 for attr in attrs.lists(sym::doc) {
175 if let Some(v) = attr.value_str() {
176 if attr.check_name(sym::keyword) {
177 if v.is_doc_keyword() {
178 keyword = Some(v.to_string());
181 // FIXME: should warn on unknown keywords?
185 return keyword.map(|p| (def_id, p, attrs));
189 let keywords = if root.is_local() {
190 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
191 let item = cx.tcx.hir().expect_item(id.id);
193 hir::ItemKind::Mod(_) => {
196 cx.tcx.hir().local_def_id(id.id),
199 hir::ItemKind::Use(ref path, hir::UseKind::Single)
200 if item.vis.node.is_pub() => {
201 as_keyword(path.res).map(|(_, prim, attrs)| {
202 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
209 cx.tcx.item_children(root).iter().map(|item| item.res)
210 .filter_map(as_keyword).collect()
214 name: cx.tcx.crate_name(*self).to_string(),
216 attrs: cx.tcx.get_attrs(root).clean(cx),
223 impl Clean<Item> for doctree::Module<'_> {
224 fn clean(&self, cx: &DocContext<'_>) -> Item {
225 let name = if self.name.is_some() {
226 self.name.expect("No name provided").clean(cx)
231 // maintain a stack of mod ids, for doc comment path resolution
232 // but we also need to resolve the module's own docs based on whether its docs were written
233 // inside or outside the module, so check for that
234 let attrs = self.attrs.clean(cx);
236 let mut items: Vec<Item> = vec![];
237 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
238 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
239 items.extend(self.structs.iter().map(|x| x.clean(cx)));
240 items.extend(self.unions.iter().map(|x| x.clean(cx)));
241 items.extend(self.enums.iter().map(|x| x.clean(cx)));
242 items.extend(self.fns.iter().map(|x| x.clean(cx)));
243 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
244 items.extend(self.mods.iter().map(|x| x.clean(cx)));
245 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
246 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
247 items.extend(self.statics.iter().map(|x| x.clean(cx)));
248 items.extend(self.constants.iter().map(|x| x.clean(cx)));
249 items.extend(self.traits.iter().map(|x| x.clean(cx)));
250 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
251 items.extend(self.macros.iter().map(|x| x.clean(cx)));
252 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
253 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
255 // determine if we should display the inner contents or
256 // the outer `mod` item for the source code.
258 let cm = cx.sess().source_map();
259 let outer = cm.lookup_char_pos(self.where_outer.lo());
260 let inner = cm.lookup_char_pos(self.where_inner.lo());
261 if outer.file.start_pos == inner.file.start_pos {
265 // mod foo; (and a separate SourceFile for the contents)
273 source: whence.clean(cx),
274 visibility: self.vis.clean(cx),
275 stability: cx.stability(self.id).clean(cx),
276 deprecation: cx.deprecation(self.id).clean(cx),
277 def_id: cx.tcx.hir().local_def_id(self.id),
278 inner: ModuleItem(Module {
279 is_crate: self.is_crate,
286 impl Clean<Attributes> for [ast::Attribute] {
287 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
288 Attributes::from_ast(cx.sess().diagnostic(), self)
292 impl Clean<GenericBound> for hir::GenericBound {
293 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
295 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
296 hir::GenericBound::Trait(ref t, modifier) => {
297 GenericBound::TraitBound(t.clean(cx), modifier)
303 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
304 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
305 let (trait_ref, ref bounds) = *self;
306 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
307 let path = external_path(cx, cx.tcx.item_name(trait_ref.def_id),
308 Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs);
310 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
312 // collect any late bound regions
313 let mut late_bounds = vec![];
314 for ty_s in trait_ref.input_types().skip(1) {
315 if let ty::Tuple(ts) = ty_s.kind {
317 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
318 if let &ty::RegionKind::ReLateBound(..) = *reg {
319 debug!(" hit an ReLateBound {:?}", reg);
320 if let Some(Lifetime(name)) = reg.clean(cx) {
321 late_bounds.push(GenericParamDef {
323 kind: GenericParamDefKind::Lifetime,
332 GenericBound::TraitBound(
334 trait_: ResolvedPath {
337 did: trait_ref.def_id,
340 generic_params: late_bounds,
342 hir::TraitBoundModifier::None
347 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
348 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
349 (self, vec![]).clean(cx)
353 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
354 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
355 let mut v = Vec::new();
356 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
357 v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
359 generic_params: Vec::new(),
360 }, hir::TraitBoundModifier::None)));
361 if !v.is_empty() {Some(v)} else {None}
365 impl Clean<Lifetime> for hir::Lifetime {
366 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
367 if self.hir_id != hir::DUMMY_HIR_ID {
368 let def = cx.tcx.named_region(self.hir_id);
370 Some(rl::Region::EarlyBound(_, node_id, _)) |
371 Some(rl::Region::LateBound(_, node_id, _)) |
372 Some(rl::Region::Free(_, node_id)) => {
373 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
380 Lifetime(self.name.ident().to_string())
384 impl Clean<Lifetime> for hir::GenericParam {
385 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
387 hir::GenericParamKind::Lifetime { .. } => {
388 if self.bounds.len() > 0 {
389 let mut bounds = self.bounds.iter().map(|bound| match bound {
390 hir::GenericBound::Outlives(lt) => lt,
393 let name = bounds.next().expect("no more bounds").name.ident();
394 let mut s = format!("{}: {}", self.name.ident(), name);
395 for bound in bounds {
396 s.push_str(&format!(" + {}", bound.name.ident()));
400 Lifetime(self.name.ident().to_string())
408 impl Clean<Constant> for hir::ConstArg {
409 fn clean(&self, cx: &DocContext<'_>) -> Constant {
411 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
412 expr: print_const_expr(cx, self.value.body),
417 impl Clean<Lifetime> for ty::GenericParamDef {
418 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
419 Lifetime(self.name.to_string())
423 impl Clean<Option<Lifetime>> for ty::RegionKind {
424 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
426 ty::ReStatic => Some(Lifetime::statik()),
427 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
428 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
430 ty::ReLateBound(..) |
434 ty::RePlaceholder(..) |
436 ty::ReClosureBound(_) |
438 debug!("cannot clean region {:?}", self);
445 impl Clean<WherePredicate> for hir::WherePredicate {
446 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
448 hir::WherePredicate::BoundPredicate(ref wbp) => {
449 WherePredicate::BoundPredicate {
450 ty: wbp.bounded_ty.clean(cx),
451 bounds: wbp.bounds.clean(cx)
455 hir::WherePredicate::RegionPredicate(ref wrp) => {
456 WherePredicate::RegionPredicate {
457 lifetime: wrp.lifetime.clean(cx),
458 bounds: wrp.bounds.clean(cx)
462 hir::WherePredicate::EqPredicate(ref wrp) => {
463 WherePredicate::EqPredicate {
464 lhs: wrp.lhs_ty.clean(cx),
465 rhs: wrp.rhs_ty.clean(cx)
472 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
473 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
474 use rustc::ty::Predicate;
477 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
478 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
479 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
480 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
481 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
483 Predicate::WellFormed(..) |
484 Predicate::ObjectSafe(..) |
485 Predicate::ClosureKind(..) |
486 Predicate::ConstEvaluatable(..) => panic!("not user writable"),
491 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
492 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
493 WherePredicate::BoundPredicate {
494 ty: self.trait_ref.self_ty().clean(cx),
495 bounds: vec![self.trait_ref.clean(cx)]
500 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
501 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
502 panic!("subtype predicates are an internal rustc artifact \
503 and should not be seen by rustdoc")
507 impl<'tcx> Clean<Option<WherePredicate>> for
508 ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> {
510 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
511 let ty::OutlivesPredicate(ref a, ref b) = *self;
514 (ty::ReEmpty, ty::ReEmpty) => {
520 Some(WherePredicate::RegionPredicate {
521 lifetime: a.clean(cx).expect("failed to clean lifetime"),
522 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))]
527 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
528 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
529 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
532 ty::ReEmpty => return None,
536 Some(WherePredicate::BoundPredicate {
538 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))]
543 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
544 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
545 WherePredicate::EqPredicate {
546 lhs: self.projection_ty.clean(cx),
547 rhs: self.ty.clean(cx)
552 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
553 fn clean(&self, cx: &DocContext<'_>) -> Type {
554 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
555 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
556 GenericBound::TraitBound(t, _) => t.trait_,
557 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
560 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
561 self_type: box self.self_ty().clean(cx),
567 impl Clean<GenericParamDef> for ty::GenericParamDef {
568 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
569 let (name, kind) = match self.kind {
570 ty::GenericParamDefKind::Lifetime => {
571 (self.name.to_string(), GenericParamDefKind::Lifetime)
573 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
574 let default = if has_default {
575 Some(cx.tcx.type_of(self.def_id).clean(cx))
579 (self.name.clean(cx), GenericParamDefKind::Type {
581 bounds: vec![], // These are filled in from the where-clauses.
586 ty::GenericParamDefKind::Const { .. } => {
587 (self.name.clean(cx), GenericParamDefKind::Const {
589 ty: cx.tcx.type_of(self.def_id).clean(cx),
601 impl Clean<GenericParamDef> for hir::GenericParam {
602 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
603 let (name, kind) = match self.kind {
604 hir::GenericParamKind::Lifetime { .. } => {
605 let name = if self.bounds.len() > 0 {
606 let mut bounds = self.bounds.iter().map(|bound| match bound {
607 hir::GenericBound::Outlives(lt) => lt,
610 let name = bounds.next().expect("no more bounds").name.ident();
611 let mut s = format!("{}: {}", self.name.ident(), name);
612 for bound in bounds {
613 s.push_str(&format!(" + {}", bound.name.ident()));
617 self.name.ident().to_string()
619 (name, GenericParamDefKind::Lifetime)
621 hir::GenericParamKind::Type { ref default, synthetic } => {
622 (self.name.ident().name.clean(cx), GenericParamDefKind::Type {
623 did: cx.tcx.hir().local_def_id(self.hir_id),
624 bounds: self.bounds.clean(cx),
625 default: default.clean(cx),
629 hir::GenericParamKind::Const { ref ty } => {
630 (self.name.ident().name.clean(cx), GenericParamDefKind::Const {
631 did: cx.tcx.hir().local_def_id(self.hir_id),
644 impl Clean<Generics> for hir::Generics {
645 fn clean(&self, cx: &DocContext<'_>) -> Generics {
646 // Synthetic type-parameters are inserted after normal ones.
647 // In order for normal parameters to be able to refer to synthetic ones,
649 fn is_impl_trait(param: &hir::GenericParam) -> bool {
651 hir::GenericParamKind::Type { synthetic, .. } => {
652 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
657 let impl_trait_params = self.params
659 .filter(|param| is_impl_trait(param))
661 let param: GenericParamDef = param.clean(cx);
663 GenericParamDefKind::Lifetime => unreachable!(),
664 GenericParamDefKind::Type { did, ref bounds, .. } => {
665 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
667 GenericParamDefKind::Const { .. } => unreachable!(),
671 .collect::<Vec<_>>();
673 let mut params = Vec::with_capacity(self.params.len());
674 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
678 params.extend(impl_trait_params);
680 let mut generics = Generics {
682 where_predicates: self.where_clause.predicates.clean(cx),
685 // Some duplicates are generated for ?Sized bounds between type params and where
686 // predicates. The point in here is to move the bounds definitions from type params
687 // to where predicates when such cases occur.
688 for where_pred in &mut generics.where_predicates {
690 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
691 if bounds.is_empty() {
692 for param in &mut generics.params {
694 GenericParamDefKind::Lifetime => {}
695 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
696 if ¶m.name == name {
697 mem::swap(bounds, ty_bounds);
701 GenericParamDefKind::Const { .. } => {}
713 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
714 fn clean(&self, cx: &DocContext<'_>) -> Generics {
715 use self::WherePredicate as WP;
716 use std::collections::BTreeMap;
718 let (gens, preds) = *self;
720 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
721 // since `Clean for ty::Predicate` would consume them.
722 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
724 // Bounds in the type_params and lifetimes fields are repeated in the
725 // predicates field (see rustc_typeck::collect::ty_generics), so remove
727 let stripped_typarams = gens.params.iter()
728 .filter_map(|param| match param.kind {
729 ty::GenericParamDefKind::Lifetime => None,
730 ty::GenericParamDefKind::Type { synthetic, .. } => {
731 if param.name == kw::SelfUpper {
732 assert_eq!(param.index, 0);
735 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
736 impl_trait.insert(param.index.into(), vec![]);
739 Some(param.clean(cx))
741 ty::GenericParamDefKind::Const { .. } => None,
742 }).collect::<Vec<GenericParamDef>>();
744 // param index -> [(DefId of trait, associated type name, type)]
745 let mut impl_trait_proj =
746 FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
748 let where_predicates = preds.predicates.iter()
750 let mut projection = None;
751 let param_idx = (|| {
752 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
753 if let ty::Param(param) = trait_ref.self_ty().kind {
754 return Some(param.index);
756 } else if let Some(outlives) = p.to_opt_type_outlives() {
757 if let ty::Param(param) = outlives.skip_binder().0.kind {
758 return Some(param.index);
760 } else if let ty::Predicate::Projection(p) = p {
761 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
762 projection = Some(p);
763 return Some(param.index);
770 if let Some(param_idx) = param_idx {
771 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
772 let p = p.clean(cx)?;
779 .filter(|b| !b.is_sized_bound(cx))
782 let proj = projection
783 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
784 if let Some(((_, trait_did, name), rhs)) =
785 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
790 .push((trait_did, name.to_string(), rhs));
799 .collect::<Vec<_>>();
801 for (param, mut bounds) in impl_trait {
802 // Move trait bounds to the front.
803 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b {
809 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
810 if let Some(proj) = impl_trait_proj.remove(&idx) {
811 for (trait_did, name, rhs) in proj {
812 simplify::merge_bounds(
825 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
828 // Now that `cx.impl_trait_bounds` is populated, we can process
829 // remaining predicates which could contain `impl Trait`.
830 let mut where_predicates = where_predicates
832 .flat_map(|p| p.clean(cx))
833 .collect::<Vec<_>>();
835 // Type parameters and have a Sized bound by default unless removed with
836 // ?Sized. Scan through the predicates and mark any type parameter with
837 // a Sized bound, removing the bounds as we find them.
839 // Note that associated types also have a sized bound by default, but we
840 // don't actually know the set of associated types right here so that's
841 // handled in cleaning associated types
842 let mut sized_params = FxHashSet::default();
843 where_predicates.retain(|pred| {
845 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
846 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
847 sized_params.insert(g.clone());
857 // Run through the type parameters again and insert a ?Sized
858 // unbound for any we didn't find to be Sized.
859 for tp in &stripped_typarams {
860 if !sized_params.contains(&tp.name) {
861 where_predicates.push(WP::BoundPredicate {
862 ty: Type::Generic(tp.name.clone()),
863 bounds: vec![GenericBound::maybe_sized(cx)],
868 // It would be nice to collect all of the bounds on a type and recombine
869 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
870 // and instead see `where T: Foo + Bar + Sized + 'a`
875 .flat_map(|param| match param.kind {
876 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
877 ty::GenericParamDefKind::Type { .. } => None,
878 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
879 }).chain(simplify::ty_params(stripped_typarams).into_iter())
881 where_predicates: simplify::where_clauses(cx, where_predicates),
886 impl<'a> Clean<Method> for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId,
887 Option<hir::Defaultness>) {
888 fn clean(&self, cx: &DocContext<'_>) -> Method {
889 let (generics, decl) = enter_impl_trait(cx, || {
890 (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
892 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
896 header: self.0.header,
904 impl Clean<Item> for doctree::Function<'_> {
905 fn clean(&self, cx: &DocContext<'_>) -> Item {
906 let (generics, decl) = enter_impl_trait(cx, || {
907 (self.generics.clean(cx), (self.decl, self.body).clean(cx))
910 let did = cx.tcx.hir().local_def_id(self.id);
911 let constness = if cx.tcx.is_min_const_fn(did) {
912 hir::Constness::Const
914 hir::Constness::NotConst
916 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
918 name: Some(self.name.clean(cx)),
919 attrs: self.attrs.clean(cx),
920 source: self.whence.clean(cx),
921 visibility: self.vis.clean(cx),
922 stability: cx.stability(self.id).clean(cx),
923 deprecation: cx.deprecation(self.id).clean(cx),
925 inner: FunctionItem(Function {
928 header: hir::FnHeader { constness, ..self.header },
936 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
937 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
939 values: self.0.iter().enumerate().map(|(i, ty)| {
940 let mut name = self.1.get(i).map(|ident| ident.to_string())
941 .unwrap_or(String::new());
943 name = "_".to_string();
954 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
955 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
956 let body = cx.tcx.hir().body(self.1);
959 values: self.0.iter().enumerate().map(|(i, ty)| {
961 name: name_from_pat(&body.params[i].pat),
969 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
970 where (&'a [hir::Ty], A): Clean<Arguments>
972 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
974 inputs: (&self.0.inputs[..], self.1).clean(cx),
975 output: self.0.output.clean(cx),
976 c_variadic: self.0.c_variadic,
977 attrs: Attributes::default(),
982 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
983 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
984 let (did, sig) = *self;
985 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
988 cx.tcx.fn_arg_names(did).into_iter()
992 output: Return(sig.skip_binder().output().clean(cx)),
993 attrs: Attributes::default(),
994 c_variadic: sig.skip_binder().c_variadic,
996 values: sig.skip_binder().inputs().iter().map(|t| {
999 name: names.next().map_or(String::new(), |name| name.to_string()),
1007 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1008 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1010 hir::Return(ref typ) => Return(typ.clean(cx)),
1011 hir::DefaultReturn(..) => DefaultReturn,
1016 impl Clean<Item> for doctree::Trait<'_> {
1017 fn clean(&self, cx: &DocContext<'_>) -> Item {
1018 let attrs = self.attrs.clean(cx);
1019 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1021 name: Some(self.name.clean(cx)),
1023 source: self.whence.clean(cx),
1024 def_id: cx.tcx.hir().local_def_id(self.id),
1025 visibility: self.vis.clean(cx),
1026 stability: cx.stability(self.id).clean(cx),
1027 deprecation: cx.deprecation(self.id).clean(cx),
1028 inner: TraitItem(Trait {
1029 auto: self.is_auto.clean(cx),
1030 unsafety: self.unsafety,
1031 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1032 generics: self.generics.clean(cx),
1033 bounds: self.bounds.clean(cx),
1035 is_auto: self.is_auto.clean(cx),
1041 impl Clean<Item> for doctree::TraitAlias<'_> {
1042 fn clean(&self, cx: &DocContext<'_>) -> Item {
1043 let attrs = self.attrs.clean(cx);
1045 name: Some(self.name.clean(cx)),
1047 source: self.whence.clean(cx),
1048 def_id: cx.tcx.hir().local_def_id(self.id),
1049 visibility: self.vis.clean(cx),
1050 stability: cx.stability(self.id).clean(cx),
1051 deprecation: cx.deprecation(self.id).clean(cx),
1052 inner: TraitAliasItem(TraitAlias {
1053 generics: self.generics.clean(cx),
1054 bounds: self.bounds.clean(cx),
1060 impl Clean<bool> for hir::IsAuto {
1061 fn clean(&self, _: &DocContext<'_>) -> bool {
1063 hir::IsAuto::Yes => true,
1064 hir::IsAuto::No => false,
1069 impl Clean<Type> for hir::TraitRef {
1070 fn clean(&self, cx: &DocContext<'_>) -> Type {
1071 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1075 impl Clean<PolyTrait> for hir::PolyTraitRef {
1076 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1078 trait_: self.trait_ref.clean(cx),
1079 generic_params: self.bound_generic_params.clean(cx)
1084 impl Clean<Item> for hir::TraitItem {
1085 fn clean(&self, cx: &DocContext<'_>) -> Item {
1086 let inner = match self.kind {
1087 hir::TraitItemKind::Const(ref ty, default) => {
1088 AssocConstItem(ty.clean(cx),
1089 default.map(|e| print_const_expr(cx, e)))
1091 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1092 MethodItem((sig, &self.generics, body, None).clean(cx))
1094 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1095 let (generics, decl) = enter_impl_trait(cx, || {
1096 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1098 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1099 TyMethodItem(TyMethod {
1107 hir::TraitItemKind::Type(ref bounds, ref default) => {
1108 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1111 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1113 name: Some(self.ident.name.clean(cx)),
1114 attrs: self.attrs.clean(cx),
1115 source: self.span.clean(cx),
1117 visibility: Visibility::Inherited,
1118 stability: get_stability(cx, local_did),
1119 deprecation: get_deprecation(cx, local_did),
1125 impl Clean<Item> for hir::ImplItem {
1126 fn clean(&self, cx: &DocContext<'_>) -> Item {
1127 let inner = match self.kind {
1128 hir::ImplItemKind::Const(ref ty, expr) => {
1129 AssocConstItem(ty.clean(cx),
1130 Some(print_const_expr(cx, expr)))
1132 hir::ImplItemKind::Method(ref sig, body) => {
1133 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1135 hir::ImplItemKind::TyAlias(ref ty) => TypedefItem(Typedef {
1136 type_: ty.clean(cx),
1137 generics: Generics::default(),
1139 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(OpaqueTy {
1140 bounds: bounds.clean(cx),
1141 generics: Generics::default(),
1144 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1146 name: Some(self.ident.name.clean(cx)),
1147 source: self.span.clean(cx),
1148 attrs: self.attrs.clean(cx),
1150 visibility: self.vis.clean(cx),
1151 stability: get_stability(cx, local_did),
1152 deprecation: get_deprecation(cx, local_did),
1158 impl Clean<Item> for ty::AssocItem {
1159 fn clean(&self, cx: &DocContext<'_>) -> Item {
1160 let inner = match self.kind {
1161 ty::AssocKind::Const => {
1162 let ty = cx.tcx.type_of(self.def_id);
1163 let default = if self.defaultness.has_value() {
1164 Some(inline::print_inlined_const(cx, self.def_id))
1168 AssocConstItem(ty.clean(cx), default)
1170 ty::AssocKind::Method => {
1171 let generics = (cx.tcx.generics_of(self.def_id),
1172 cx.tcx.explicit_predicates_of(self.def_id)).clean(cx);
1173 let sig = cx.tcx.fn_sig(self.def_id);
1174 let mut decl = (self.def_id, sig).clean(cx);
1176 if self.method_has_self_argument {
1177 let self_ty = match self.container {
1178 ty::ImplContainer(def_id) => {
1179 cx.tcx.type_of(def_id)
1181 ty::TraitContainer(_) => cx.tcx.types.self_param,
1183 let self_arg_ty = *sig.input(0).skip_binder();
1184 if self_arg_ty == self_ty {
1185 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1186 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1188 match decl.inputs.values[0].type_ {
1189 BorrowedRef{ref mut type_, ..} => {
1190 **type_ = Generic(String::from("Self"))
1192 _ => unreachable!(),
1198 let provided = match self.container {
1199 ty::ImplContainer(_) => true,
1200 ty::TraitContainer(_) => self.defaultness.has_value()
1202 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1204 let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1205 hir::Constness::Const
1207 hir::Constness::NotConst
1209 let asyncness = cx.tcx.asyncness(self.def_id);
1210 let defaultness = match self.container {
1211 ty::ImplContainer(_) => Some(self.defaultness),
1212 ty::TraitContainer(_) => None,
1217 header: hir::FnHeader {
1218 unsafety: sig.unsafety(),
1228 TyMethodItem(TyMethod {
1231 header: hir::FnHeader {
1232 unsafety: sig.unsafety(),
1234 constness: hir::Constness::NotConst,
1235 asyncness: hir::IsAsync::NotAsync,
1242 ty::AssocKind::Type => {
1243 let my_name = self.ident.name.clean(cx);
1245 if let ty::TraitContainer(did) = self.container {
1246 // When loading a cross-crate associated type, the bounds for this type
1247 // are actually located on the trait/impl itself, so we need to load
1248 // all of the generics from there and then look for bounds that are
1249 // applied to this associated type in question.
1250 let predicates = cx.tcx.explicit_predicates_of(did);
1251 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1252 let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
1253 let (name, self_type, trait_, bounds) = match *pred {
1254 WherePredicate::BoundPredicate {
1255 ty: QPath { ref name, ref self_type, ref trait_ },
1257 } => (name, self_type, trait_, bounds),
1260 if *name != my_name { return None }
1262 ResolvedPath { did, .. } if did == self.container.id() => {}
1266 Generic(ref s) if *s == "Self" => {}
1270 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
1271 // Our Sized/?Sized bound didn't get handled when creating the generics
1272 // because we didn't actually get our whole set of bounds until just now
1273 // (some of them may have come from the trait). If we do have a sized
1274 // bound, we remove it, and if we don't then we add the `?Sized` bound
1276 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1277 Some(i) => { bounds.remove(i); }
1278 None => bounds.push(GenericBound::maybe_sized(cx)),
1281 let ty = if self.defaultness.has_value() {
1282 Some(cx.tcx.type_of(self.def_id))
1287 AssocTypeItem(bounds, ty.clean(cx))
1289 TypedefItem(Typedef {
1290 type_: cx.tcx.type_of(self.def_id).clean(cx),
1291 generics: Generics {
1293 where_predicates: Vec::new(),
1298 ty::AssocKind::OpaqueTy => unimplemented!(),
1301 let visibility = match self.container {
1302 ty::ImplContainer(_) => self.vis.clean(cx),
1303 ty::TraitContainer(_) => Inherited,
1307 name: Some(self.ident.name.clean(cx)),
1309 stability: get_stability(cx, self.def_id),
1310 deprecation: get_deprecation(cx, self.def_id),
1311 def_id: self.def_id,
1312 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1313 source: cx.tcx.def_span(self.def_id).clean(cx),
1319 impl Clean<Type> for hir::Ty {
1320 fn clean(&self, cx: &DocContext<'_>) -> Type {
1324 TyKind::Never => Never,
1325 TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1326 TyKind::Rptr(ref l, ref m) => {
1327 let lifetime = if l.is_elided() {
1332 BorrowedRef {lifetime, mutability: m.mutbl.clean(cx),
1333 type_: box m.ty.clean(cx)}
1335 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1336 TyKind::Array(ref ty, ref length) => {
1337 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1338 let param_env = cx.tcx.param_env(def_id);
1339 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
1340 let cid = GlobalId {
1341 instance: ty::Instance::new(def_id, substs),
1344 let length = match cx.tcx.const_eval(param_env.and(cid)) {
1345 Ok(length) => print_const(cx, length),
1348 .span_to_snippet(cx.tcx.def_span(def_id))
1349 .unwrap_or_else(|_| "_".to_string()),
1351 Array(box ty.clean(cx), length)
1353 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1354 TyKind::Def(item_id, _) => {
1355 let item = cx.tcx.hir().expect_item(item_id.id);
1356 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1357 ImplTrait(ty.bounds.clean(cx))
1362 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1363 if let Res::Def(DefKind::TyParam, did) = path.res {
1364 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1367 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1368 return ImplTrait(bounds);
1372 let mut alias = None;
1373 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1374 // Substitute private type aliases
1375 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1376 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1377 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1382 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1383 let provided_params = &path.segments.last().expect("segments were empty");
1384 let mut ty_substs = FxHashMap::default();
1385 let mut lt_substs = FxHashMap::default();
1386 let mut ct_substs = FxHashMap::default();
1387 let generic_args = provided_params.generic_args();
1389 let mut indices: GenericParamCount = Default::default();
1390 for param in generics.params.iter() {
1392 hir::GenericParamKind::Lifetime { .. } => {
1394 let lifetime = generic_args.args.iter().find_map(|arg| {
1396 hir::GenericArg::Lifetime(lt) => {
1397 if indices.lifetimes == j {
1406 if let Some(lt) = lifetime.cloned() {
1407 if !lt.is_elided() {
1409 cx.tcx.hir().local_def_id(param.hir_id);
1410 lt_substs.insert(lt_def_id, lt.clean(cx));
1413 indices.lifetimes += 1;
1415 hir::GenericParamKind::Type { ref default, .. } => {
1416 let ty_param_def_id =
1417 cx.tcx.hir().local_def_id(param.hir_id);
1419 let type_ = generic_args.args.iter().find_map(|arg| {
1421 hir::GenericArg::Type(ty) => {
1422 if indices.types == j {
1431 if let Some(ty) = type_ {
1432 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1433 } else if let Some(default) = default.clone() {
1434 ty_substs.insert(ty_param_def_id,
1439 hir::GenericParamKind::Const { .. } => {
1440 let const_param_def_id =
1441 cx.tcx.hir().local_def_id(param.hir_id);
1443 let const_ = generic_args.args.iter().find_map(|arg| {
1445 hir::GenericArg::Const(ct) => {
1446 if indices.consts == j {
1455 if let Some(ct) = const_ {
1456 ct_substs.insert(const_param_def_id, ct.clean(cx));
1458 // FIXME(const_generics:defaults)
1459 indices.consts += 1;
1464 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1466 resolve_type(cx, path.clean(cx), self.hir_id)
1468 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1469 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1470 let trait_segments = &segments[..segments.len() - 1];
1471 let trait_path = self::Path {
1472 global: p.is_global(),
1475 cx.tcx.associated_item(p.res.def_id()).container.id(),
1477 segments: trait_segments.clean(cx),
1480 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1481 self_type: box qself.clean(cx),
1482 trait_: box resolve_type(cx, trait_path, self.hir_id)
1485 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1486 let mut res = Res::Err;
1487 let ty = hir_ty_to_ty(cx.tcx, self);
1488 if let ty::Projection(proj) = ty.kind {
1489 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1491 let trait_path = hir::Path {
1494 segments: vec![].into(),
1497 name: segment.ident.name.clean(cx),
1498 self_type: box qself.clean(cx),
1499 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id)
1502 TyKind::TraitObject(ref bounds, ref lifetime) => {
1503 match bounds[0].clean(cx).trait_ {
1504 ResolvedPath { path, param_names: None, did, is_generic } => {
1505 let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
1506 self::GenericBound::TraitBound(bound.clean(cx),
1507 hir::TraitBoundModifier::None)
1509 if !lifetime.is_elided() {
1510 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1512 ResolvedPath { path, param_names: Some(bounds), did, is_generic, }
1514 _ => Infer, // shouldn't happen
1517 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1518 TyKind::Infer | TyKind::Err => Infer,
1519 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1524 impl<'tcx> Clean<Type> for Ty<'tcx> {
1525 fn clean(&self, cx: &DocContext<'_>) -> Type {
1526 debug!("cleaning type: {:?}", self);
1529 ty::Bool => Primitive(PrimitiveType::Bool),
1530 ty::Char => Primitive(PrimitiveType::Char),
1531 ty::Int(int_ty) => Primitive(int_ty.into()),
1532 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1533 ty::Float(float_ty) => Primitive(float_ty.into()),
1534 ty::Str => Primitive(PrimitiveType::Str),
1535 ty::Slice(ty) => Slice(box ty.clean(cx)),
1536 ty::Array(ty, n) => {
1537 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1538 if let ty::ConstKind::Unevaluated(def_id, substs) = n.val {
1539 let param_env = cx.tcx.param_env(def_id);
1540 let cid = GlobalId {
1541 instance: ty::Instance::new(def_id, substs),
1544 if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) {
1548 let n = print_const(cx, n);
1549 Array(box ty.clean(cx), n)
1551 ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1552 ty::Ref(r, ty, mutbl) => BorrowedRef {
1553 lifetime: r.clean(cx),
1554 mutability: mutbl.clean(cx),
1555 type_: box ty.clean(cx),
1559 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1560 let sig = ty.fn_sig(cx.tcx);
1561 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1562 BareFunction(box BareFunctionDecl {
1563 unsafety: sig.unsafety(),
1564 generic_params: Vec::new(),
1565 decl: (local_def_id, sig).clean(cx),
1569 ty::Adt(def, substs) => {
1571 let kind = match def.adt_kind() {
1572 AdtKind::Struct => TypeKind::Struct,
1573 AdtKind::Union => TypeKind::Union,
1574 AdtKind::Enum => TypeKind::Enum,
1576 inline::record_extern_fqn(cx, did, kind);
1577 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1585 ty::Foreign(did) => {
1586 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1587 let path = external_path(cx, cx.tcx.item_name(did),
1588 None, false, vec![], InternalSubsts::empty());
1596 ty::Dynamic(ref obj, ref reg) => {
1597 // HACK: pick the first `did` as the `did` of the trait object. Someone
1598 // might want to implement "native" support for marker-trait-only
1600 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1601 let did = dids.next().unwrap_or_else(|| {
1602 panic!("found trait object `{:?}` with no traits?", self)
1604 let substs = match obj.principal() {
1605 Some(principal) => principal.skip_binder().substs,
1606 // marker traits have no substs.
1607 _ => cx.tcx.intern_substs(&[])
1610 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1612 let mut param_names = vec![];
1613 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1615 let empty = cx.tcx.intern_substs(&[]);
1616 let path = external_path(cx, cx.tcx.item_name(did),
1617 Some(did), false, vec![], empty);
1618 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1619 let bound = GenericBound::TraitBound(PolyTrait {
1620 trait_: ResolvedPath {
1626 generic_params: Vec::new(),
1627 }, hir::TraitBoundModifier::None);
1628 param_names.push(bound);
1631 let mut bindings = vec![];
1632 for pb in obj.projection_bounds() {
1633 bindings.push(TypeBinding {
1634 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1635 kind: TypeBindingKind::Equality {
1636 ty: pb.skip_binder().ty.clean(cx)
1641 let path = external_path(cx, cx.tcx.item_name(did), Some(did),
1642 false, bindings, substs);
1645 param_names: Some(param_names),
1650 ty::Tuple(ref t) => {
1651 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1654 ty::Projection(ref data) => data.clean(cx),
1656 ty::Param(ref p) => {
1657 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1660 Generic(p.name.to_string())
1664 ty::Opaque(def_id, substs) => {
1665 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1666 // by looking up the projections associated with the def_id.
1667 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1668 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1669 let bounds = predicates_of.instantiate(cx.tcx, substs);
1670 let mut regions = vec![];
1671 let mut has_sized = false;
1672 let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
1673 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1675 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1676 // these should turn up at the end
1677 pred.skip_binder().1.clean(cx).map(|r| {
1678 regions.push(GenericBound::Outlives(r))
1685 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1686 if trait_ref.def_id() == sized {
1692 let bounds = bounds.predicates.iter().filter_map(|pred|
1693 if let ty::Predicate::Projection(proj) = *pred {
1694 let proj = proj.skip_binder();
1695 if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
1697 name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
1698 .ident.name.clean(cx),
1699 kind: TypeBindingKind::Equality {
1700 ty: proj.ty.clean(cx),
1711 Some((trait_ref.skip_binder(), bounds).clean(cx))
1712 }).collect::<Vec<_>>();
1713 bounds.extend(regions);
1714 if !has_sized && !bounds.is_empty() {
1715 bounds.insert(0, GenericBound::maybe_sized(cx));
1720 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1722 ty::Bound(..) => panic!("Bound"),
1723 ty::Placeholder(..) => panic!("Placeholder"),
1724 ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1725 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1726 ty::Infer(..) => panic!("Infer"),
1727 ty::Error => panic!("Error"),
1732 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1733 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1735 type_: self.ty.clean(cx),
1736 expr: format!("{}", self),
1741 impl Clean<Item> for hir::StructField {
1742 fn clean(&self, cx: &DocContext<'_>) -> Item {
1743 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1746 name: Some(self.ident.name).clean(cx),
1747 attrs: self.attrs.clean(cx),
1748 source: self.span.clean(cx),
1749 visibility: self.vis.clean(cx),
1750 stability: get_stability(cx, local_did),
1751 deprecation: get_deprecation(cx, local_did),
1753 inner: StructFieldItem(self.ty.clean(cx)),
1758 impl Clean<Item> for ty::FieldDef {
1759 fn clean(&self, cx: &DocContext<'_>) -> Item {
1761 name: Some(self.ident.name).clean(cx),
1762 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1763 source: cx.tcx.def_span(self.did).clean(cx),
1764 visibility: self.vis.clean(cx),
1765 stability: get_stability(cx, self.did),
1766 deprecation: get_deprecation(cx, self.did),
1768 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1773 impl Clean<Visibility> for hir::Visibility {
1774 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1776 hir::VisibilityKind::Public => Visibility::Public,
1777 hir::VisibilityKind::Inherited => Visibility::Inherited,
1778 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1779 hir::VisibilityKind::Restricted { ref path, .. } => {
1780 let path = path.clean(cx);
1781 let did = register_res(cx, path.res);
1782 Visibility::Restricted(did, path)
1788 impl Clean<Visibility> for ty::Visibility {
1789 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1790 if *self == ty::Visibility::Public { Public } else { Inherited }
1794 impl Clean<Item> for doctree::Struct<'_> {
1795 fn clean(&self, cx: &DocContext<'_>) -> Item {
1797 name: Some(self.name.clean(cx)),
1798 attrs: self.attrs.clean(cx),
1799 source: self.whence.clean(cx),
1800 def_id: cx.tcx.hir().local_def_id(self.id),
1801 visibility: self.vis.clean(cx),
1802 stability: cx.stability(self.id).clean(cx),
1803 deprecation: cx.deprecation(self.id).clean(cx),
1804 inner: StructItem(Struct {
1805 struct_type: self.struct_type,
1806 generics: self.generics.clean(cx),
1807 fields: self.fields.clean(cx),
1808 fields_stripped: false,
1814 impl Clean<Item> for doctree::Union<'_> {
1815 fn clean(&self, cx: &DocContext<'_>) -> Item {
1817 name: Some(self.name.clean(cx)),
1818 attrs: self.attrs.clean(cx),
1819 source: self.whence.clean(cx),
1820 def_id: cx.tcx.hir().local_def_id(self.id),
1821 visibility: self.vis.clean(cx),
1822 stability: cx.stability(self.id).clean(cx),
1823 deprecation: cx.deprecation(self.id).clean(cx),
1824 inner: UnionItem(Union {
1825 struct_type: self.struct_type,
1826 generics: self.generics.clean(cx),
1827 fields: self.fields.clean(cx),
1828 fields_stripped: false,
1834 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1835 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1837 struct_type: doctree::struct_type_from_def(self),
1838 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1839 fields_stripped: false,
1844 impl Clean<Item> for doctree::Enum<'_> {
1845 fn clean(&self, cx: &DocContext<'_>) -> Item {
1847 name: Some(self.name.clean(cx)),
1848 attrs: self.attrs.clean(cx),
1849 source: self.whence.clean(cx),
1850 def_id: cx.tcx.hir().local_def_id(self.id),
1851 visibility: self.vis.clean(cx),
1852 stability: cx.stability(self.id).clean(cx),
1853 deprecation: cx.deprecation(self.id).clean(cx),
1854 inner: EnumItem(Enum {
1855 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1856 generics: self.generics.clean(cx),
1857 variants_stripped: false,
1863 impl Clean<Item> for doctree::Variant<'_> {
1864 fn clean(&self, cx: &DocContext<'_>) -> Item {
1866 name: Some(self.name.clean(cx)),
1867 attrs: self.attrs.clean(cx),
1868 source: self.whence.clean(cx),
1869 visibility: Inherited,
1870 stability: cx.stability(self.id).clean(cx),
1871 deprecation: cx.deprecation(self.id).clean(cx),
1872 def_id: cx.tcx.hir().local_def_id(self.id),
1873 inner: VariantItem(Variant {
1874 kind: self.def.clean(cx),
1880 impl Clean<Item> for ty::VariantDef {
1881 fn clean(&self, cx: &DocContext<'_>) -> Item {
1882 let kind = match self.ctor_kind {
1883 CtorKind::Const => VariantKind::CLike,
1886 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
1889 CtorKind::Fictive => {
1890 VariantKind::Struct(VariantStruct {
1891 struct_type: doctree::Plain,
1892 fields_stripped: false,
1893 fields: self.fields.iter().map(|field| {
1895 source: cx.tcx.def_span(field.did).clean(cx),
1896 name: Some(field.ident.name.clean(cx)),
1897 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1898 visibility: field.vis.clean(cx),
1900 stability: get_stability(cx, field.did),
1901 deprecation: get_deprecation(cx, field.did),
1902 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
1909 name: Some(self.ident.clean(cx)),
1910 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1911 source: cx.tcx.def_span(self.def_id).clean(cx),
1912 visibility: Inherited,
1913 def_id: self.def_id,
1914 inner: VariantItem(Variant { kind }),
1915 stability: get_stability(cx, self.def_id),
1916 deprecation: get_deprecation(cx, self.def_id),
1921 impl Clean<VariantKind> for hir::VariantData {
1922 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1924 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1925 hir::VariantData::Tuple(..) =>
1926 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()),
1927 hir::VariantData::Unit(..) => VariantKind::CLike,
1932 impl Clean<Span> for syntax_pos::Span {
1933 fn clean(&self, cx: &DocContext<'_>) -> Span {
1934 if self.is_dummy() {
1935 return Span::empty();
1938 let cm = cx.sess().source_map();
1939 let filename = cm.span_to_filename(*self);
1940 let lo = cm.lookup_char_pos(self.lo());
1941 let hi = cm.lookup_char_pos(self.hi());
1945 locol: lo.col.to_usize(),
1947 hicol: hi.col.to_usize(),
1953 impl Clean<Path> for hir::Path {
1954 fn clean(&self, cx: &DocContext<'_>) -> Path {
1956 global: self.is_global(),
1958 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1963 impl Clean<GenericArgs> for hir::GenericArgs {
1964 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1965 if self.parenthesized {
1966 let output = self.bindings[0].ty().clean(cx);
1967 GenericArgs::Parenthesized {
1968 inputs: self.inputs().clean(cx),
1969 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
1972 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1973 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1976 GenericArgs::AngleBracketed {
1977 args: self.args.iter().filter_map(|arg| match arg {
1978 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1979 Some(GenericArg::Lifetime(lt.clean(cx)))
1981 hir::GenericArg::Lifetime(_) => None,
1982 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1983 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1985 bindings: self.bindings.clean(cx),
1991 impl Clean<PathSegment> for hir::PathSegment {
1992 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1994 name: self.ident.name.clean(cx),
1995 args: self.generic_args().clean(cx),
2000 impl Clean<String> for Ident {
2002 fn clean(&self, cx: &DocContext<'_>) -> String {
2007 impl Clean<String> for ast::Name {
2009 fn clean(&self, _: &DocContext<'_>) -> String {
2014 impl Clean<Item> for doctree::Typedef<'_> {
2015 fn clean(&self, cx: &DocContext<'_>) -> Item {
2017 name: Some(self.name.clean(cx)),
2018 attrs: self.attrs.clean(cx),
2019 source: self.whence.clean(cx),
2020 def_id: cx.tcx.hir().local_def_id(self.id),
2021 visibility: self.vis.clean(cx),
2022 stability: cx.stability(self.id).clean(cx),
2023 deprecation: cx.deprecation(self.id).clean(cx),
2024 inner: TypedefItem(Typedef {
2025 type_: self.ty.clean(cx),
2026 generics: self.gen.clean(cx),
2032 impl Clean<Item> for doctree::OpaqueTy<'_> {
2033 fn clean(&self, cx: &DocContext<'_>) -> Item {
2035 name: Some(self.name.clean(cx)),
2036 attrs: self.attrs.clean(cx),
2037 source: self.whence.clean(cx),
2038 def_id: cx.tcx.hir().local_def_id(self.id),
2039 visibility: self.vis.clean(cx),
2040 stability: cx.stability(self.id).clean(cx),
2041 deprecation: cx.deprecation(self.id).clean(cx),
2042 inner: OpaqueTyItem(OpaqueTy {
2043 bounds: self.opaque_ty.bounds.clean(cx),
2044 generics: self.opaque_ty.generics.clean(cx),
2050 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2051 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2052 let (generic_params, decl) = enter_impl_trait(cx, || {
2053 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2056 unsafety: self.unsafety,
2064 impl Clean<Item> for doctree::Static<'_> {
2065 fn clean(&self, cx: &DocContext<'_>) -> Item {
2066 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2068 name: Some(self.name.clean(cx)),
2069 attrs: self.attrs.clean(cx),
2070 source: self.whence.clean(cx),
2071 def_id: cx.tcx.hir().local_def_id(self.id),
2072 visibility: self.vis.clean(cx),
2073 stability: cx.stability(self.id).clean(cx),
2074 deprecation: cx.deprecation(self.id).clean(cx),
2075 inner: StaticItem(Static {
2076 type_: self.type_.clean(cx),
2077 mutability: self.mutability.clean(cx),
2078 expr: print_const_expr(cx, self.expr),
2084 impl Clean<Item> for doctree::Constant<'_> {
2085 fn clean(&self, cx: &DocContext<'_>) -> Item {
2087 name: Some(self.name.clean(cx)),
2088 attrs: self.attrs.clean(cx),
2089 source: self.whence.clean(cx),
2090 def_id: cx.tcx.hir().local_def_id(self.id),
2091 visibility: self.vis.clean(cx),
2092 stability: cx.stability(self.id).clean(cx),
2093 deprecation: cx.deprecation(self.id).clean(cx),
2094 inner: ConstantItem(Constant {
2095 type_: self.type_.clean(cx),
2096 expr: print_const_expr(cx, self.expr),
2102 impl Clean<Mutability> for hir::Mutability {
2103 fn clean(&self, _: &DocContext<'_>) -> Mutability {
2105 &hir::Mutability::Mutable => Mutable,
2106 &hir::Mutability::Immutable => Immutable,
2111 impl Clean<ImplPolarity> for ty::ImplPolarity {
2112 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2114 &ty::ImplPolarity::Positive |
2115 // FIXME: do we want to do something else here?
2116 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2117 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2122 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2123 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2124 let mut ret = Vec::new();
2125 let trait_ = self.trait_.clean(cx);
2126 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2127 let def_id = cx.tcx.hir().local_def_id(self.id);
2129 // If this impl block is an implementation of the Deref trait, then we
2130 // need to try inlining the target's inherent impl blocks as well.
2131 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2132 build_deref_target_impls(cx, &items, &mut ret);
2135 let provided = trait_.def_id().map(|did| {
2136 cx.tcx.provided_trait_methods(did)
2138 .map(|meth| meth.ident.to_string())
2140 }).unwrap_or_default();
2144 attrs: self.attrs.clean(cx),
2145 source: self.whence.clean(cx),
2147 visibility: self.vis.clean(cx),
2148 stability: cx.stability(self.id).clean(cx),
2149 deprecation: cx.deprecation(self.id).clean(cx),
2150 inner: ImplItem(Impl {
2151 unsafety: self.unsafety,
2152 generics: self.generics.clean(cx),
2153 provided_trait_methods: provided,
2155 for_: self.for_.clean(cx),
2157 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2166 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2167 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2169 let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
2170 a.check_name(sym::doc) && match a.meta_item_list() {
2171 Some(l) => attr::list_contains_name(&l, sym::inline),
2177 let mut visited = FxHashSet::default();
2183 index: CRATE_DEF_INDEX,
2187 if let Some(items) = inline::try_inline(
2189 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
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),
2204 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
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() || self.attrs.iter().any(|a| {
2216 a.check_name(sym::doc) && match a.meta_item_list() {
2217 Some(l) => attr::list_contains_name(&l, sym::no_inline) ||
2218 attr::list_contains_name(&l, sym::hidden),
2222 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2223 // crate in Rust 2018+
2224 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2225 let path = self.path.clean(cx);
2226 let inner = if self.glob {
2228 let mut visited = FxHashSet::default();
2229 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2234 Import::Glob(resolve_use_source(cx, path))
2236 let name = self.name;
2239 Res::Def(DefKind::Mod, did) => {
2240 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2241 // if we're `pub use`ing an extern crate root, don't inline it unless we
2242 // were specifically asked for it
2250 let mut visited = FxHashSet::default();
2251 if let Some(items) = inline::try_inline(
2253 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2259 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2264 attrs: self.attrs.clean(cx),
2265 source: self.whence.clean(cx),
2266 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2267 visibility: self.vis.clean(cx),
2270 inner: ImportItem(inner)
2275 impl Clean<Item> for doctree::ForeignItem<'_> {
2276 fn clean(&self, cx: &DocContext<'_>) -> Item {
2277 let inner = match self.kind {
2278 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2279 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2280 let (generics, decl) = enter_impl_trait(cx, || {
2281 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2283 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2284 ForeignFunctionItem(Function {
2287 header: hir::FnHeader {
2288 unsafety: hir::Unsafety::Unsafe,
2290 constness: hir::Constness::NotConst,
2291 asyncness: hir::IsAsync::NotAsync,
2297 hir::ForeignItemKind::Static(ref ty, mutbl) => {
2298 ForeignStaticItem(Static {
2299 type_: ty.clean(cx),
2300 mutability: mutbl.clean(cx),
2301 expr: String::new(),
2304 hir::ForeignItemKind::Type => {
2310 name: Some(self.name.clean(cx)),
2311 attrs: self.attrs.clean(cx),
2312 source: self.whence.clean(cx),
2313 def_id: cx.tcx.hir().local_def_id(self.id),
2314 visibility: self.vis.clean(cx),
2315 stability: cx.stability(self.id).clean(cx),
2316 deprecation: cx.deprecation(self.id).clean(cx),
2322 impl Clean<Item> for doctree::Macro<'_> {
2323 fn clean(&self, cx: &DocContext<'_>) -> Item {
2324 let name = self.name.clean(cx);
2326 name: Some(name.clone()),
2327 attrs: self.attrs.clean(cx),
2328 source: self.whence.clean(cx),
2330 stability: cx.stability(self.hid).clean(cx),
2331 deprecation: cx.deprecation(self.hid).clean(cx),
2332 def_id: self.def_id,
2333 inner: MacroItem(Macro {
2334 source: format!("macro_rules! {} {{\n{}}}",
2336 self.matchers.iter().map(|span| {
2337 format!(" {} => {{ ... }};\n", span.to_src(cx))
2338 }).collect::<String>()),
2339 imported_from: self.imported_from.clean(cx),
2345 impl Clean<Item> for doctree::ProcMacro<'_> {
2346 fn clean(&self, cx: &DocContext<'_>) -> Item {
2348 name: Some(self.name.clean(cx)),
2349 attrs: self.attrs.clean(cx),
2350 source: self.whence.clean(cx),
2352 stability: cx.stability(self.id).clean(cx),
2353 deprecation: cx.deprecation(self.id).clean(cx),
2354 def_id: cx.tcx.hir().local_def_id(self.id),
2355 inner: ProcMacroItem(ProcMacro {
2357 helpers: self.helpers.clean(cx),
2363 impl Clean<Stability> for attr::Stability {
2364 fn clean(&self, _: &DocContext<'_>) -> Stability {
2366 level: stability::StabilityLevel::from_attr_level(&self.level),
2367 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2368 since: match self.level {
2369 attr::Stable {ref since} => since.to_string(),
2372 deprecation: self.rustc_depr.as_ref().map(|d| {
2374 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2375 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2378 unstable_reason: match self.level {
2379 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2382 issue: match self.level {
2383 attr::Unstable {issue, ..} => issue,
2390 impl<'a> Clean<Stability> for &'a attr::Stability {
2391 fn clean(&self, dc: &DocContext<'_>) -> Stability {
2396 impl Clean<Deprecation> for attr::Deprecation {
2397 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2399 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2400 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2405 impl Clean<TypeBinding> for hir::TypeBinding {
2406 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2408 name: self.ident.name.clean(cx),
2409 kind: self.kind.clean(cx),
2414 impl Clean<TypeBindingKind> for hir::TypeBindingKind {
2415 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2417 hir::TypeBindingKind::Equality { ref ty } =>
2418 TypeBindingKind::Equality {
2421 hir::TypeBindingKind::Constraint { ref bounds } =>
2422 TypeBindingKind::Constraint {
2423 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2430 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2434 impl From<GenericBound> for SimpleBound {
2435 fn from(bound: GenericBound) -> Self {
2436 match bound.clone() {
2437 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2438 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2439 Type::ResolvedPath { path, param_names, .. } => {
2440 SimpleBound::TraitBound(path.segments,
2442 .map_or_else(|| Vec::new(), |v| v.iter()
2443 .map(|p| SimpleBound::from(p.clone()))
2448 _ => panic!("Unexpected bound {:?}", bound),