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};
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 &T {
74 fn clean(&self, cx: &DocContext<'_>) -> U {
79 impl<T: Clean<U>, U> Clean<U> for P<T> {
80 fn clean(&self, cx: &DocContext<'_>) -> U {
85 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
86 fn clean(&self, cx: &DocContext<'_>) -> U {
91 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
92 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
93 self.as_ref().map(|v| v.clean(cx))
97 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
98 fn clean(&self, cx: &DocContext<'_>) -> U {
99 self.skip_binder().clean(cx)
103 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
104 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
105 self.iter().map(|x| x.clean(cx)).collect()
109 impl Clean<ExternalCrate> for CrateNum {
110 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
111 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
112 let krate_span = cx.tcx.def_span(root);
113 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
115 // Collect all inner modules which are tagged as implementations of
118 // Note that this loop only searches the top-level items of the crate,
119 // and this is intentional. If we were to search the entire crate for an
120 // item tagged with `#[doc(primitive)]` then we would also have to
121 // search the entirety of external modules for items tagged
122 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
123 // all that metadata unconditionally).
125 // In order to keep the metadata load under control, the
126 // `#[doc(primitive)]` feature is explicitly designed to only allow the
127 // primitive tags to show up as the top level items in a crate.
129 // Also note that this does not attempt to deal with modules tagged
130 // duplicately for the same primitive. This is handled later on when
131 // rendering by delegating everything to a hash map.
132 let as_primitive = |res: Res| {
133 if let Res::Def(DefKind::Mod, def_id) = res {
134 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
136 for attr in attrs.lists(sym::doc) {
137 if let Some(v) = attr.value_str() {
138 if attr.check_name(sym::primitive) {
139 prim = PrimitiveType::from_str(&v.as_str());
143 // FIXME: should warn on unknown primitives?
147 return prim.map(|p| (def_id, p, attrs));
151 let primitives = if root.is_local() {
152 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
153 let item = cx.tcx.hir().expect_item(id.id);
155 hir::ItemKind::Mod(_) => {
156 as_primitive(Res::Def(
158 cx.tcx.hir().local_def_id(id.id),
161 hir::ItemKind::Use(ref path, hir::UseKind::Single)
162 if item.vis.node.is_pub() => {
163 as_primitive(path.res).map(|(_, prim, attrs)| {
164 // Pretend the primitive is local.
165 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
172 cx.tcx.item_children(root).iter().map(|item| item.res)
173 .filter_map(as_primitive).collect()
176 let as_keyword = |res: Res| {
177 if let Res::Def(DefKind::Mod, def_id) = res {
178 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
179 let mut keyword = None;
180 for attr in attrs.lists(sym::doc) {
181 if let Some(v) = attr.value_str() {
182 if attr.check_name(sym::keyword) {
183 if v.is_doc_keyword() {
184 keyword = Some(v.to_string());
187 // FIXME: should warn on unknown keywords?
191 return keyword.map(|p| (def_id, p, attrs));
195 let keywords = if root.is_local() {
196 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
197 let item = cx.tcx.hir().expect_item(id.id);
199 hir::ItemKind::Mod(_) => {
202 cx.tcx.hir().local_def_id(id.id),
205 hir::ItemKind::Use(ref path, hir::UseKind::Single)
206 if item.vis.node.is_pub() => {
207 as_keyword(path.res).map(|(_, prim, attrs)| {
208 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
215 cx.tcx.item_children(root).iter().map(|item| item.res)
216 .filter_map(as_keyword).collect()
220 name: cx.tcx.crate_name(*self).to_string(),
222 attrs: cx.tcx.get_attrs(root).clean(cx),
229 impl Clean<Item> for doctree::Module<'_> {
230 fn clean(&self, cx: &DocContext<'_>) -> Item {
231 let name = if self.name.is_some() {
232 self.name.expect("No name provided").clean(cx)
237 // maintain a stack of mod ids, for doc comment path resolution
238 // but we also need to resolve the module's own docs based on whether its docs were written
239 // inside or outside the module, so check for that
240 let attrs = self.attrs.clean(cx);
242 let mut items: Vec<Item> = vec![];
243 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
244 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
245 items.extend(self.structs.iter().map(|x| x.clean(cx)));
246 items.extend(self.unions.iter().map(|x| x.clean(cx)));
247 items.extend(self.enums.iter().map(|x| x.clean(cx)));
248 items.extend(self.fns.iter().map(|x| x.clean(cx)));
249 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
250 items.extend(self.mods.iter().map(|x| x.clean(cx)));
251 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
252 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
253 items.extend(self.statics.iter().map(|x| x.clean(cx)));
254 items.extend(self.constants.iter().map(|x| x.clean(cx)));
255 items.extend(self.traits.iter().map(|x| x.clean(cx)));
256 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
257 items.extend(self.macros.iter().map(|x| x.clean(cx)));
258 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
259 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
261 // determine if we should display the inner contents or
262 // the outer `mod` item for the source code.
264 let cm = cx.sess().source_map();
265 let outer = cm.lookup_char_pos(self.where_outer.lo());
266 let inner = cm.lookup_char_pos(self.where_inner.lo());
267 if outer.file.start_pos == inner.file.start_pos {
271 // mod foo; (and a separate SourceFile for the contents)
279 source: whence.clean(cx),
280 visibility: self.vis.clean(cx),
281 stability: cx.stability(self.id).clean(cx),
282 deprecation: cx.deprecation(self.id).clean(cx),
283 def_id: cx.tcx.hir().local_def_id(self.id),
284 inner: ModuleItem(Module {
285 is_crate: self.is_crate,
292 impl Clean<Attributes> for [ast::Attribute] {
293 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
294 Attributes::from_ast(cx.sess().diagnostic(), self)
298 impl Clean<GenericBound> for hir::GenericBound {
299 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
301 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
302 hir::GenericBound::Trait(ref t, modifier) => {
303 GenericBound::TraitBound(t.clean(cx), modifier)
309 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
310 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
311 let (trait_ref, ref bounds) = *self;
312 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
313 let path = external_path(cx, cx.tcx.item_name(trait_ref.def_id),
314 Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs);
316 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
318 // collect any late bound regions
319 let mut late_bounds = vec![];
320 for ty_s in trait_ref.input_types().skip(1) {
321 if let ty::Tuple(ts) = ty_s.kind {
323 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
324 if let &ty::RegionKind::ReLateBound(..) = *reg {
325 debug!(" hit an ReLateBound {:?}", reg);
326 if let Some(Lifetime(name)) = reg.clean(cx) {
327 late_bounds.push(GenericParamDef {
329 kind: GenericParamDefKind::Lifetime,
338 GenericBound::TraitBound(
340 trait_: ResolvedPath {
343 did: trait_ref.def_id,
346 generic_params: late_bounds,
348 hir::TraitBoundModifier::None
353 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
354 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
355 (self, vec![]).clean(cx)
359 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
360 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
361 let mut v = Vec::new();
362 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
363 v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
365 generic_params: Vec::new(),
366 }, hir::TraitBoundModifier::None)));
367 if !v.is_empty() {Some(v)} else {None}
371 impl Clean<Lifetime> for hir::Lifetime {
372 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
373 if self.hir_id != hir::DUMMY_HIR_ID {
374 let def = cx.tcx.named_region(self.hir_id);
376 Some(rl::Region::EarlyBound(_, node_id, _)) |
377 Some(rl::Region::LateBound(_, node_id, _)) |
378 Some(rl::Region::Free(_, node_id)) => {
379 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
386 Lifetime(self.name.ident().to_string())
390 impl Clean<Lifetime> for hir::GenericParam {
391 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
393 hir::GenericParamKind::Lifetime { .. } => {
394 if self.bounds.len() > 0 {
395 let mut bounds = self.bounds.iter().map(|bound| match bound {
396 hir::GenericBound::Outlives(lt) => lt,
399 let name = bounds.next().expect("no more bounds").name.ident();
400 let mut s = format!("{}: {}", self.name.ident(), name);
401 for bound in bounds {
402 s.push_str(&format!(" + {}", bound.name.ident()));
406 Lifetime(self.name.ident().to_string())
414 impl Clean<Constant> for hir::ConstArg {
415 fn clean(&self, cx: &DocContext<'_>) -> Constant {
417 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
418 expr: print_const_expr(cx, self.value.body),
423 impl Clean<Lifetime> for ty::GenericParamDef {
424 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
425 Lifetime(self.name.to_string())
429 impl Clean<Option<Lifetime>> for ty::RegionKind {
430 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
432 ty::ReStatic => Some(Lifetime::statik()),
433 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
434 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
436 ty::ReLateBound(..) |
440 ty::RePlaceholder(..) |
442 ty::ReClosureBound(_) |
444 debug!("cannot clean region {:?}", self);
451 impl Clean<WherePredicate> for hir::WherePredicate {
452 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
454 hir::WherePredicate::BoundPredicate(ref wbp) => {
455 WherePredicate::BoundPredicate {
456 ty: wbp.bounded_ty.clean(cx),
457 bounds: wbp.bounds.clean(cx)
461 hir::WherePredicate::RegionPredicate(ref wrp) => {
462 WherePredicate::RegionPredicate {
463 lifetime: wrp.lifetime.clean(cx),
464 bounds: wrp.bounds.clean(cx)
468 hir::WherePredicate::EqPredicate(ref wrp) => {
469 WherePredicate::EqPredicate {
470 lhs: wrp.lhs_ty.clean(cx),
471 rhs: wrp.rhs_ty.clean(cx)
478 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
479 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
480 use rustc::ty::Predicate;
483 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
484 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
485 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
486 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
487 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
489 Predicate::WellFormed(..) |
490 Predicate::ObjectSafe(..) |
491 Predicate::ClosureKind(..) |
492 Predicate::ConstEvaluatable(..) => panic!("not user writable"),
497 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
498 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
499 WherePredicate::BoundPredicate {
500 ty: self.trait_ref.self_ty().clean(cx),
501 bounds: vec![self.trait_ref.clean(cx)]
506 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
507 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
508 panic!("subtype predicates are an internal rustc artifact \
509 and should not be seen by rustdoc")
513 impl<'tcx> Clean<Option<WherePredicate>> for
514 ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> {
516 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
517 let ty::OutlivesPredicate(ref a, ref b) = *self;
520 (ty::ReEmpty, ty::ReEmpty) => {
526 Some(WherePredicate::RegionPredicate {
527 lifetime: a.clean(cx).expect("failed to clean lifetime"),
528 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))]
533 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
534 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
535 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
538 ty::ReEmpty => return None,
542 Some(WherePredicate::BoundPredicate {
544 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))]
549 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
550 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
551 WherePredicate::EqPredicate {
552 lhs: self.projection_ty.clean(cx),
553 rhs: self.ty.clean(cx)
558 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
559 fn clean(&self, cx: &DocContext<'_>) -> Type {
560 let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
561 GenericBound::TraitBound(t, _) => t.trait_,
562 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
565 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
566 self_type: box self.self_ty().clean(cx),
572 impl Clean<GenericParamDef> for ty::GenericParamDef {
573 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
574 let (name, kind) = match self.kind {
575 ty::GenericParamDefKind::Lifetime => {
576 (self.name.to_string(), GenericParamDefKind::Lifetime)
578 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
579 let default = if has_default {
580 Some(cx.tcx.type_of(self.def_id).clean(cx))
584 (self.name.clean(cx), GenericParamDefKind::Type {
586 bounds: vec![], // These are filled in from the where-clauses.
591 ty::GenericParamDefKind::Const { .. } => {
592 (self.name.clean(cx), GenericParamDefKind::Const {
594 ty: cx.tcx.type_of(self.def_id).clean(cx),
606 impl Clean<GenericParamDef> for hir::GenericParam {
607 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
608 let (name, kind) = match self.kind {
609 hir::GenericParamKind::Lifetime { .. } => {
610 let name = if self.bounds.len() > 0 {
611 let mut bounds = self.bounds.iter().map(|bound| match bound {
612 hir::GenericBound::Outlives(lt) => lt,
615 let name = bounds.next().expect("no more bounds").name.ident();
616 let mut s = format!("{}: {}", self.name.ident(), name);
617 for bound in bounds {
618 s.push_str(&format!(" + {}", bound.name.ident()));
622 self.name.ident().to_string()
624 (name, GenericParamDefKind::Lifetime)
626 hir::GenericParamKind::Type { ref default, synthetic } => {
627 (self.name.ident().name.clean(cx), GenericParamDefKind::Type {
628 did: cx.tcx.hir().local_def_id(self.hir_id),
629 bounds: self.bounds.clean(cx),
630 default: default.clean(cx),
634 hir::GenericParamKind::Const { ref ty } => {
635 (self.name.ident().name.clean(cx), GenericParamDefKind::Const {
636 did: cx.tcx.hir().local_def_id(self.hir_id),
649 impl Clean<Generics> for hir::Generics {
650 fn clean(&self, cx: &DocContext<'_>) -> Generics {
651 // Synthetic type-parameters are inserted after normal ones.
652 // In order for normal parameters to be able to refer to synthetic ones,
654 fn is_impl_trait(param: &hir::GenericParam) -> bool {
656 hir::GenericParamKind::Type { synthetic, .. } => {
657 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
662 let impl_trait_params = self.params
664 .filter(|param| is_impl_trait(param))
666 let param: GenericParamDef = param.clean(cx);
668 GenericParamDefKind::Lifetime => unreachable!(),
669 GenericParamDefKind::Type { did, ref bounds, .. } => {
670 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
672 GenericParamDefKind::Const { .. } => unreachable!(),
676 .collect::<Vec<_>>();
678 let mut params = Vec::with_capacity(self.params.len());
679 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
683 params.extend(impl_trait_params);
685 let mut generics = Generics {
687 where_predicates: self.where_clause.predicates.clean(cx),
690 // Some duplicates are generated for ?Sized bounds between type params and where
691 // predicates. The point in here is to move the bounds definitions from type params
692 // to where predicates when such cases occur.
693 for where_pred in &mut generics.where_predicates {
695 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
696 if bounds.is_empty() {
697 for param in &mut generics.params {
699 GenericParamDefKind::Lifetime => {}
700 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
701 if ¶m.name == name {
702 mem::swap(bounds, ty_bounds);
706 GenericParamDefKind::Const { .. } => {}
718 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
719 fn clean(&self, cx: &DocContext<'_>) -> Generics {
720 use self::WherePredicate as WP;
721 use std::collections::BTreeMap;
723 let (gens, preds) = *self;
725 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
726 // since `Clean for ty::Predicate` would consume them.
727 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
729 // Bounds in the type_params and lifetimes fields are repeated in the
730 // predicates field (see rustc_typeck::collect::ty_generics), so remove
732 let stripped_typarams = gens.params.iter()
733 .filter_map(|param| match param.kind {
734 ty::GenericParamDefKind::Lifetime => None,
735 ty::GenericParamDefKind::Type { synthetic, .. } => {
736 if param.name == kw::SelfUpper {
737 assert_eq!(param.index, 0);
740 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
741 impl_trait.insert(param.index.into(), vec![]);
744 Some(param.clean(cx))
746 ty::GenericParamDefKind::Const { .. } => None,
747 }).collect::<Vec<GenericParamDef>>();
749 // param index -> [(DefId of trait, associated type name, type)]
750 let mut impl_trait_proj =
751 FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
753 let where_predicates = preds.predicates.iter()
755 let mut projection = None;
756 let param_idx = (|| {
757 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
758 if let ty::Param(param) = trait_ref.self_ty().kind {
759 return Some(param.index);
761 } else if let Some(outlives) = p.to_opt_type_outlives() {
762 if let ty::Param(param) = outlives.skip_binder().0.kind {
763 return Some(param.index);
765 } else if let ty::Predicate::Projection(p) = p {
766 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
767 projection = Some(p);
768 return Some(param.index);
775 if let Some(param_idx) = param_idx {
776 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
777 let p = p.clean(cx)?;
784 .filter(|b| !b.is_sized_bound(cx))
787 let proj = projection
788 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
789 if let Some(((_, trait_did, name), rhs)) =
790 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
795 .push((trait_did, name.to_string(), rhs));
804 .collect::<Vec<_>>();
806 for (param, mut bounds) in impl_trait {
807 // Move trait bounds to the front.
808 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b {
814 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
815 if let Some(proj) = impl_trait_proj.remove(&idx) {
816 for (trait_did, name, rhs) in proj {
817 simplify::merge_bounds(
830 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
833 // Now that `cx.impl_trait_bounds` is populated, we can process
834 // remaining predicates which could contain `impl Trait`.
835 let mut where_predicates = where_predicates
837 .flat_map(|p| p.clean(cx))
838 .collect::<Vec<_>>();
840 // Type parameters and have a Sized bound by default unless removed with
841 // ?Sized. Scan through the predicates and mark any type parameter with
842 // a Sized bound, removing the bounds as we find them.
844 // Note that associated types also have a sized bound by default, but we
845 // don't actually know the set of associated types right here so that's
846 // handled in cleaning associated types
847 let mut sized_params = FxHashSet::default();
848 where_predicates.retain(|pred| {
850 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
851 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
852 sized_params.insert(g.clone());
862 // Run through the type parameters again and insert a ?Sized
863 // unbound for any we didn't find to be Sized.
864 for tp in &stripped_typarams {
865 if !sized_params.contains(&tp.name) {
866 where_predicates.push(WP::BoundPredicate {
867 ty: Type::Generic(tp.name.clone()),
868 bounds: vec![GenericBound::maybe_sized(cx)],
873 // It would be nice to collect all of the bounds on a type and recombine
874 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
875 // and instead see `where T: Foo + Bar + Sized + 'a`
880 .flat_map(|param| match param.kind {
881 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
882 ty::GenericParamDefKind::Type { .. } => None,
883 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
884 }).chain(simplify::ty_params(stripped_typarams).into_iter())
886 where_predicates: simplify::where_clauses(cx, where_predicates),
891 impl<'a> Clean<Method> for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId,
892 Option<hir::Defaultness>) {
893 fn clean(&self, cx: &DocContext<'_>) -> Method {
894 let (generics, decl) = enter_impl_trait(cx, || {
895 (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
897 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
901 header: self.0.header,
909 impl Clean<Item> for doctree::Function<'_> {
910 fn clean(&self, cx: &DocContext<'_>) -> Item {
911 let (generics, decl) = enter_impl_trait(cx, || {
912 (self.generics.clean(cx), (self.decl, self.body).clean(cx))
915 let did = cx.tcx.hir().local_def_id(self.id);
916 let constness = if cx.tcx.is_min_const_fn(did) {
917 hir::Constness::Const
919 hir::Constness::NotConst
921 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
923 name: Some(self.name.clean(cx)),
924 attrs: self.attrs.clean(cx),
925 source: self.whence.clean(cx),
926 visibility: self.vis.clean(cx),
927 stability: cx.stability(self.id).clean(cx),
928 deprecation: cx.deprecation(self.id).clean(cx),
930 inner: FunctionItem(Function {
933 header: hir::FnHeader { constness, ..self.header },
941 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
942 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
944 values: self.0.iter().enumerate().map(|(i, ty)| {
945 let mut name = self.1.get(i).map(|ident| ident.to_string())
946 .unwrap_or(String::new());
948 name = "_".to_string();
959 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
960 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
961 let body = cx.tcx.hir().body(self.1);
964 values: self.0.iter().enumerate().map(|(i, ty)| {
966 name: name_from_pat(&body.params[i].pat),
974 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
975 where (&'a [hir::Ty], A): Clean<Arguments>
977 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
979 inputs: (&self.0.inputs[..], self.1).clean(cx),
980 output: self.0.output.clean(cx),
981 c_variadic: self.0.c_variadic,
982 attrs: Attributes::default(),
987 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
988 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
989 let (did, sig) = *self;
990 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
993 cx.tcx.fn_arg_names(did).into_iter()
997 output: Return(sig.skip_binder().output().clean(cx)),
998 attrs: Attributes::default(),
999 c_variadic: sig.skip_binder().c_variadic,
1001 values: sig.skip_binder().inputs().iter().map(|t| {
1004 name: names.next().map_or(String::new(), |name| name.to_string()),
1012 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1013 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1015 hir::Return(ref typ) => Return(typ.clean(cx)),
1016 hir::DefaultReturn(..) => DefaultReturn,
1021 impl Clean<Item> for doctree::Trait<'_> {
1022 fn clean(&self, cx: &DocContext<'_>) -> Item {
1023 let attrs = self.attrs.clean(cx);
1024 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1026 name: Some(self.name.clean(cx)),
1028 source: self.whence.clean(cx),
1029 def_id: cx.tcx.hir().local_def_id(self.id),
1030 visibility: self.vis.clean(cx),
1031 stability: cx.stability(self.id).clean(cx),
1032 deprecation: cx.deprecation(self.id).clean(cx),
1033 inner: TraitItem(Trait {
1034 auto: self.is_auto.clean(cx),
1035 unsafety: self.unsafety,
1036 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1037 generics: self.generics.clean(cx),
1038 bounds: self.bounds.clean(cx),
1040 is_auto: self.is_auto.clean(cx),
1046 impl Clean<Item> for doctree::TraitAlias<'_> {
1047 fn clean(&self, cx: &DocContext<'_>) -> Item {
1048 let attrs = self.attrs.clean(cx);
1050 name: Some(self.name.clean(cx)),
1052 source: self.whence.clean(cx),
1053 def_id: cx.tcx.hir().local_def_id(self.id),
1054 visibility: self.vis.clean(cx),
1055 stability: cx.stability(self.id).clean(cx),
1056 deprecation: cx.deprecation(self.id).clean(cx),
1057 inner: TraitAliasItem(TraitAlias {
1058 generics: self.generics.clean(cx),
1059 bounds: self.bounds.clean(cx),
1065 impl Clean<bool> for hir::IsAuto {
1066 fn clean(&self, _: &DocContext<'_>) -> bool {
1068 hir::IsAuto::Yes => true,
1069 hir::IsAuto::No => false,
1074 impl Clean<Type> for hir::TraitRef {
1075 fn clean(&self, cx: &DocContext<'_>) -> Type {
1076 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1080 impl Clean<PolyTrait> for hir::PolyTraitRef {
1081 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1083 trait_: self.trait_ref.clean(cx),
1084 generic_params: self.bound_generic_params.clean(cx)
1089 impl Clean<Item> for hir::TraitItem<'_> {
1090 fn clean(&self, cx: &DocContext<'_>) -> Item {
1091 let inner = match self.kind {
1092 hir::TraitItemKind::Const(ref ty, default) => {
1093 AssocConstItem(ty.clean(cx),
1094 default.map(|e| print_const_expr(cx, e)))
1096 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1097 MethodItem((sig, &self.generics, body, None).clean(cx))
1099 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1100 let (generics, decl) = enter_impl_trait(cx, || {
1101 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1103 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1104 TyMethodItem(TyMethod {
1112 hir::TraitItemKind::Type(ref bounds, ref default) => {
1113 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1116 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1118 name: Some(self.ident.name.clean(cx)),
1119 attrs: self.attrs.clean(cx),
1120 source: self.span.clean(cx),
1122 visibility: Visibility::Inherited,
1123 stability: get_stability(cx, local_did),
1124 deprecation: get_deprecation(cx, local_did),
1130 impl Clean<Item> for hir::ImplItem<'_> {
1131 fn clean(&self, cx: &DocContext<'_>) -> Item {
1132 let inner = match self.kind {
1133 hir::ImplItemKind::Const(ref ty, expr) => {
1134 AssocConstItem(ty.clean(cx),
1135 Some(print_const_expr(cx, expr)))
1137 hir::ImplItemKind::Method(ref sig, body) => {
1138 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1140 hir::ImplItemKind::TyAlias(ref ty) => TypedefItem(Typedef {
1141 type_: ty.clean(cx),
1142 generics: Generics::default(),
1144 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(OpaqueTy {
1145 bounds: bounds.clean(cx),
1146 generics: Generics::default(),
1149 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1151 name: Some(self.ident.name.clean(cx)),
1152 source: self.span.clean(cx),
1153 attrs: self.attrs.clean(cx),
1155 visibility: self.vis.clean(cx),
1156 stability: get_stability(cx, local_did),
1157 deprecation: get_deprecation(cx, local_did),
1163 impl Clean<Item> for ty::AssocItem {
1164 fn clean(&self, cx: &DocContext<'_>) -> Item {
1165 let inner = match self.kind {
1166 ty::AssocKind::Const => {
1167 let ty = cx.tcx.type_of(self.def_id);
1168 let default = if self.defaultness.has_value() {
1169 Some(inline::print_inlined_const(cx, self.def_id))
1173 AssocConstItem(ty.clean(cx), default)
1175 ty::AssocKind::Method => {
1176 let generics = (cx.tcx.generics_of(self.def_id),
1177 cx.tcx.explicit_predicates_of(self.def_id)).clean(cx);
1178 let sig = cx.tcx.fn_sig(self.def_id);
1179 let mut decl = (self.def_id, sig).clean(cx);
1181 if self.method_has_self_argument {
1182 let self_ty = match self.container {
1183 ty::ImplContainer(def_id) => {
1184 cx.tcx.type_of(def_id)
1186 ty::TraitContainer(_) => cx.tcx.types.self_param,
1188 let self_arg_ty = *sig.input(0).skip_binder();
1189 if self_arg_ty == self_ty {
1190 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1191 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1193 match decl.inputs.values[0].type_ {
1194 BorrowedRef{ref mut type_, ..} => {
1195 **type_ = Generic(String::from("Self"))
1197 _ => unreachable!(),
1203 let provided = match self.container {
1204 ty::ImplContainer(_) => true,
1205 ty::TraitContainer(_) => self.defaultness.has_value()
1207 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1209 let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1210 hir::Constness::Const
1212 hir::Constness::NotConst
1214 let asyncness = cx.tcx.asyncness(self.def_id);
1215 let defaultness = match self.container {
1216 ty::ImplContainer(_) => Some(self.defaultness),
1217 ty::TraitContainer(_) => None,
1222 header: hir::FnHeader {
1223 unsafety: sig.unsafety(),
1233 TyMethodItem(TyMethod {
1236 header: hir::FnHeader {
1237 unsafety: sig.unsafety(),
1239 constness: hir::Constness::NotConst,
1240 asyncness: hir::IsAsync::NotAsync,
1247 ty::AssocKind::Type => {
1248 let my_name = self.ident.name.clean(cx);
1250 if let ty::TraitContainer(did) = self.container {
1251 // When loading a cross-crate associated type, the bounds for this type
1252 // are actually located on the trait/impl itself, so we need to load
1253 // all of the generics from there and then look for bounds that are
1254 // applied to this associated type in question.
1255 let predicates = cx.tcx.explicit_predicates_of(did);
1256 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1257 let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
1258 let (name, self_type, trait_, bounds) = match *pred {
1259 WherePredicate::BoundPredicate {
1260 ty: QPath { ref name, ref self_type, ref trait_ },
1262 } => (name, self_type, trait_, bounds),
1265 if *name != my_name { return None }
1267 ResolvedPath { did, .. } if did == self.container.id() => {}
1271 Generic(ref s) if *s == "Self" => {}
1275 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
1276 // Our Sized/?Sized bound didn't get handled when creating the generics
1277 // because we didn't actually get our whole set of bounds until just now
1278 // (some of them may have come from the trait). If we do have a sized
1279 // bound, we remove it, and if we don't then we add the `?Sized` bound
1281 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1282 Some(i) => { bounds.remove(i); }
1283 None => bounds.push(GenericBound::maybe_sized(cx)),
1286 let ty = if self.defaultness.has_value() {
1287 Some(cx.tcx.type_of(self.def_id))
1292 AssocTypeItem(bounds, ty.clean(cx))
1294 TypedefItem(Typedef {
1295 type_: cx.tcx.type_of(self.def_id).clean(cx),
1296 generics: Generics {
1298 where_predicates: Vec::new(),
1303 ty::AssocKind::OpaqueTy => unimplemented!(),
1306 let visibility = match self.container {
1307 ty::ImplContainer(_) => self.vis.clean(cx),
1308 ty::TraitContainer(_) => Inherited,
1312 name: Some(self.ident.name.clean(cx)),
1314 stability: get_stability(cx, self.def_id),
1315 deprecation: get_deprecation(cx, self.def_id),
1316 def_id: self.def_id,
1317 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1318 source: cx.tcx.def_span(self.def_id).clean(cx),
1324 impl Clean<Type> for hir::Ty {
1325 fn clean(&self, cx: &DocContext<'_>) -> Type {
1329 TyKind::Never => Never,
1330 TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1331 TyKind::Rptr(ref l, ref m) => {
1332 let lifetime = if l.is_elided() {
1337 BorrowedRef {lifetime, mutability: m.mutbl.clean(cx),
1338 type_: box m.ty.clean(cx)}
1340 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1341 TyKind::Array(ref ty, ref length) => {
1342 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1343 let param_env = cx.tcx.param_env(def_id);
1344 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
1345 let cid = GlobalId {
1346 instance: ty::Instance::new(def_id, substs),
1349 let length = match cx.tcx.const_eval(param_env.and(cid)) {
1350 Ok(length) => print_const(cx, length),
1353 .span_to_snippet(cx.tcx.def_span(def_id))
1354 .unwrap_or_else(|_| "_".to_string()),
1356 Array(box ty.clean(cx), length)
1358 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1359 TyKind::Def(item_id, _) => {
1360 let item = cx.tcx.hir().expect_item(item_id.id);
1361 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1362 ImplTrait(ty.bounds.clean(cx))
1367 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1368 if let Res::Def(DefKind::TyParam, did) = path.res {
1369 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1372 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1373 return ImplTrait(bounds);
1377 let mut alias = None;
1378 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1379 // Substitute private type aliases
1380 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1381 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1382 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1387 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1388 let provided_params = &path.segments.last().expect("segments were empty");
1389 let mut ty_substs = FxHashMap::default();
1390 let mut lt_substs = FxHashMap::default();
1391 let mut ct_substs = FxHashMap::default();
1392 let generic_args = provided_params.generic_args();
1394 let mut indices: GenericParamCount = Default::default();
1395 for param in generics.params.iter() {
1397 hir::GenericParamKind::Lifetime { .. } => {
1399 let lifetime = generic_args.args.iter().find_map(|arg| {
1401 hir::GenericArg::Lifetime(lt) => {
1402 if indices.lifetimes == j {
1411 if let Some(lt) = lifetime.cloned() {
1412 if !lt.is_elided() {
1414 cx.tcx.hir().local_def_id(param.hir_id);
1415 lt_substs.insert(lt_def_id, lt.clean(cx));
1418 indices.lifetimes += 1;
1420 hir::GenericParamKind::Type { ref default, .. } => {
1421 let ty_param_def_id =
1422 cx.tcx.hir().local_def_id(param.hir_id);
1424 let type_ = generic_args.args.iter().find_map(|arg| {
1426 hir::GenericArg::Type(ty) => {
1427 if indices.types == j {
1436 if let Some(ty) = type_ {
1437 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1438 } else if let Some(default) = default.clone() {
1439 ty_substs.insert(ty_param_def_id,
1444 hir::GenericParamKind::Const { .. } => {
1445 let const_param_def_id =
1446 cx.tcx.hir().local_def_id(param.hir_id);
1448 let const_ = generic_args.args.iter().find_map(|arg| {
1450 hir::GenericArg::Const(ct) => {
1451 if indices.consts == j {
1460 if let Some(ct) = const_ {
1461 ct_substs.insert(const_param_def_id, ct.clean(cx));
1463 // FIXME(const_generics:defaults)
1464 indices.consts += 1;
1469 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1471 resolve_type(cx, path.clean(cx), self.hir_id)
1473 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1474 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1475 let trait_segments = &segments[..segments.len() - 1];
1476 let trait_path = self::Path {
1477 global: p.is_global(),
1480 cx.tcx.associated_item(p.res.def_id()).container.id(),
1482 segments: trait_segments.clean(cx),
1485 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1486 self_type: box qself.clean(cx),
1487 trait_: box resolve_type(cx, trait_path, self.hir_id)
1490 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1491 let mut res = Res::Err;
1492 let ty = hir_ty_to_ty(cx.tcx, self);
1493 if let ty::Projection(proj) = ty.kind {
1494 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1496 let trait_path = hir::Path {
1499 segments: vec![].into(),
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)
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..].iter().map(|bound| {
1511 self::GenericBound::TraitBound(bound.clean(cx),
1512 hir::TraitBoundModifier::None)
1514 if !lifetime.is_elided() {
1515 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1517 ResolvedPath { path, param_names: Some(bounds), did, is_generic, }
1519 _ => Infer, // shouldn't happen
1522 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1523 TyKind::Infer | TyKind::Err => Infer,
1524 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1529 impl<'tcx> Clean<Type> for Ty<'tcx> {
1530 fn clean(&self, cx: &DocContext<'_>) -> Type {
1531 debug!("cleaning type: {:?}", self);
1534 ty::Bool => Primitive(PrimitiveType::Bool),
1535 ty::Char => Primitive(PrimitiveType::Char),
1536 ty::Int(int_ty) => Primitive(int_ty.into()),
1537 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1538 ty::Float(float_ty) => Primitive(float_ty.into()),
1539 ty::Str => Primitive(PrimitiveType::Str),
1540 ty::Slice(ty) => Slice(box ty.clean(cx)),
1541 ty::Array(ty, n) => {
1542 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1543 if let ty::ConstKind::Unevaluated(def_id, substs) = n.val {
1544 let param_env = cx.tcx.param_env(def_id);
1545 let cid = GlobalId {
1546 instance: ty::Instance::new(def_id, substs),
1549 if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) {
1553 let n = print_const(cx, n);
1554 Array(box ty.clean(cx), n)
1556 ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1557 ty::Ref(r, ty, mutbl) => BorrowedRef {
1558 lifetime: r.clean(cx),
1559 mutability: mutbl.clean(cx),
1560 type_: box ty.clean(cx),
1564 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1565 let sig = ty.fn_sig(cx.tcx);
1566 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1567 BareFunction(box BareFunctionDecl {
1568 unsafety: sig.unsafety(),
1569 generic_params: Vec::new(),
1570 decl: (local_def_id, sig).clean(cx),
1574 ty::Adt(def, substs) => {
1576 let kind = match def.adt_kind() {
1577 AdtKind::Struct => TypeKind::Struct,
1578 AdtKind::Union => TypeKind::Union,
1579 AdtKind::Enum => TypeKind::Enum,
1581 inline::record_extern_fqn(cx, did, kind);
1582 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1590 ty::Foreign(did) => {
1591 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1592 let path = external_path(cx, cx.tcx.item_name(did),
1593 None, false, vec![], InternalSubsts::empty());
1601 ty::Dynamic(ref obj, ref reg) => {
1602 // HACK: pick the first `did` as the `did` of the trait object. Someone
1603 // might want to implement "native" support for marker-trait-only
1605 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1606 let did = dids.next().unwrap_or_else(|| {
1607 panic!("found trait object `{:?}` with no traits?", self)
1609 let substs = match obj.principal() {
1610 Some(principal) => principal.skip_binder().substs,
1611 // marker traits have no substs.
1612 _ => cx.tcx.intern_substs(&[])
1615 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1617 let mut param_names = vec![];
1618 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1620 let empty = cx.tcx.intern_substs(&[]);
1621 let path = external_path(cx, cx.tcx.item_name(did),
1622 Some(did), false, vec![], empty);
1623 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1624 let bound = GenericBound::TraitBound(PolyTrait {
1625 trait_: ResolvedPath {
1631 generic_params: Vec::new(),
1632 }, hir::TraitBoundModifier::None);
1633 param_names.push(bound);
1636 let mut bindings = vec![];
1637 for pb in obj.projection_bounds() {
1638 bindings.push(TypeBinding {
1639 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1640 kind: TypeBindingKind::Equality {
1641 ty: pb.skip_binder().ty.clean(cx)
1646 let path = external_path(cx, cx.tcx.item_name(did), Some(did),
1647 false, bindings, substs);
1650 param_names: Some(param_names),
1655 ty::Tuple(ref t) => {
1656 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1659 ty::Projection(ref data) => data.clean(cx),
1661 ty::Param(ref p) => {
1662 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1665 Generic(p.name.to_string())
1669 ty::Opaque(def_id, substs) => {
1670 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1671 // by looking up the projections associated with the def_id.
1672 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1673 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1674 let bounds = predicates_of.instantiate(cx.tcx, substs);
1675 let mut regions = vec![];
1676 let mut has_sized = false;
1677 let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
1678 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1680 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1681 // these should turn up at the end
1682 pred.skip_binder().1.clean(cx).map(|r| {
1683 regions.push(GenericBound::Outlives(r))
1690 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1691 if trait_ref.def_id() == sized {
1697 let bounds = bounds.predicates.iter().filter_map(|pred|
1698 if let ty::Predicate::Projection(proj) = *pred {
1699 let proj = proj.skip_binder();
1700 if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
1702 name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
1703 .ident.name.clean(cx),
1704 kind: TypeBindingKind::Equality {
1705 ty: proj.ty.clean(cx),
1716 Some((trait_ref.skip_binder(), bounds).clean(cx))
1717 }).collect::<Vec<_>>();
1718 bounds.extend(regions);
1719 if !has_sized && !bounds.is_empty() {
1720 bounds.insert(0, GenericBound::maybe_sized(cx));
1725 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1727 ty::Bound(..) => panic!("Bound"),
1728 ty::Placeholder(..) => panic!("Placeholder"),
1729 ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1730 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1731 ty::Infer(..) => panic!("Infer"),
1732 ty::Error => panic!("Error"),
1737 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1738 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1740 type_: self.ty.clean(cx),
1741 expr: format!("{}", self),
1746 impl Clean<Item> for hir::StructField {
1747 fn clean(&self, cx: &DocContext<'_>) -> Item {
1748 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1751 name: Some(self.ident.name).clean(cx),
1752 attrs: self.attrs.clean(cx),
1753 source: self.span.clean(cx),
1754 visibility: self.vis.clean(cx),
1755 stability: get_stability(cx, local_did),
1756 deprecation: get_deprecation(cx, local_did),
1758 inner: StructFieldItem(self.ty.clean(cx)),
1763 impl Clean<Item> for ty::FieldDef {
1764 fn clean(&self, cx: &DocContext<'_>) -> Item {
1766 name: Some(self.ident.name).clean(cx),
1767 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1768 source: cx.tcx.def_span(self.did).clean(cx),
1769 visibility: self.vis.clean(cx),
1770 stability: get_stability(cx, self.did),
1771 deprecation: get_deprecation(cx, self.did),
1773 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1778 impl Clean<Visibility> for hir::Visibility {
1779 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1781 hir::VisibilityKind::Public => Visibility::Public,
1782 hir::VisibilityKind::Inherited => Visibility::Inherited,
1783 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1784 hir::VisibilityKind::Restricted { ref path, .. } => {
1785 let path = path.clean(cx);
1786 let did = register_res(cx, path.res);
1787 Visibility::Restricted(did, path)
1793 impl Clean<Visibility> for ty::Visibility {
1794 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1795 if *self == ty::Visibility::Public { Public } else { Inherited }
1799 impl Clean<Item> for doctree::Struct<'_> {
1800 fn clean(&self, cx: &DocContext<'_>) -> Item {
1802 name: Some(self.name.clean(cx)),
1803 attrs: self.attrs.clean(cx),
1804 source: self.whence.clean(cx),
1805 def_id: cx.tcx.hir().local_def_id(self.id),
1806 visibility: self.vis.clean(cx),
1807 stability: cx.stability(self.id).clean(cx),
1808 deprecation: cx.deprecation(self.id).clean(cx),
1809 inner: StructItem(Struct {
1810 struct_type: self.struct_type,
1811 generics: self.generics.clean(cx),
1812 fields: self.fields.clean(cx),
1813 fields_stripped: false,
1819 impl Clean<Item> for doctree::Union<'_> {
1820 fn clean(&self, cx: &DocContext<'_>) -> Item {
1822 name: Some(self.name.clean(cx)),
1823 attrs: self.attrs.clean(cx),
1824 source: self.whence.clean(cx),
1825 def_id: cx.tcx.hir().local_def_id(self.id),
1826 visibility: self.vis.clean(cx),
1827 stability: cx.stability(self.id).clean(cx),
1828 deprecation: cx.deprecation(self.id).clean(cx),
1829 inner: UnionItem(Union {
1830 struct_type: self.struct_type,
1831 generics: self.generics.clean(cx),
1832 fields: self.fields.clean(cx),
1833 fields_stripped: false,
1839 impl Clean<VariantStruct> for ::rustc::hir::VariantData<'_> {
1840 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1842 struct_type: doctree::struct_type_from_def(self),
1843 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1844 fields_stripped: false,
1849 impl Clean<Item> for doctree::Enum<'_> {
1850 fn clean(&self, cx: &DocContext<'_>) -> Item {
1852 name: Some(self.name.clean(cx)),
1853 attrs: self.attrs.clean(cx),
1854 source: self.whence.clean(cx),
1855 def_id: cx.tcx.hir().local_def_id(self.id),
1856 visibility: self.vis.clean(cx),
1857 stability: cx.stability(self.id).clean(cx),
1858 deprecation: cx.deprecation(self.id).clean(cx),
1859 inner: EnumItem(Enum {
1860 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1861 generics: self.generics.clean(cx),
1862 variants_stripped: false,
1868 impl Clean<Item> for doctree::Variant<'_> {
1869 fn clean(&self, cx: &DocContext<'_>) -> Item {
1871 name: Some(self.name.clean(cx)),
1872 attrs: self.attrs.clean(cx),
1873 source: self.whence.clean(cx),
1874 visibility: Inherited,
1875 stability: cx.stability(self.id).clean(cx),
1876 deprecation: cx.deprecation(self.id).clean(cx),
1877 def_id: cx.tcx.hir().local_def_id(self.id),
1878 inner: VariantItem(Variant {
1879 kind: self.def.clean(cx),
1885 impl Clean<Item> for ty::VariantDef {
1886 fn clean(&self, cx: &DocContext<'_>) -> Item {
1887 let kind = match self.ctor_kind {
1888 CtorKind::Const => VariantKind::CLike,
1891 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
1894 CtorKind::Fictive => {
1895 VariantKind::Struct(VariantStruct {
1896 struct_type: doctree::Plain,
1897 fields_stripped: false,
1898 fields: self.fields.iter().map(|field| {
1900 source: cx.tcx.def_span(field.did).clean(cx),
1901 name: Some(field.ident.name.clean(cx)),
1902 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1903 visibility: field.vis.clean(cx),
1905 stability: get_stability(cx, field.did),
1906 deprecation: get_deprecation(cx, field.did),
1907 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
1914 name: Some(self.ident.clean(cx)),
1915 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1916 source: cx.tcx.def_span(self.def_id).clean(cx),
1917 visibility: Inherited,
1918 def_id: self.def_id,
1919 inner: VariantItem(Variant { kind }),
1920 stability: get_stability(cx, self.def_id),
1921 deprecation: get_deprecation(cx, self.def_id),
1926 impl Clean<VariantKind> for hir::VariantData<'_> {
1927 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1929 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1930 hir::VariantData::Tuple(..) =>
1931 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()),
1932 hir::VariantData::Unit(..) => VariantKind::CLike,
1937 impl Clean<Span> for syntax_pos::Span {
1938 fn clean(&self, cx: &DocContext<'_>) -> Span {
1939 if self.is_dummy() {
1940 return Span::empty();
1943 let cm = cx.sess().source_map();
1944 let filename = cm.span_to_filename(*self);
1945 let lo = cm.lookup_char_pos(self.lo());
1946 let hi = cm.lookup_char_pos(self.hi());
1950 locol: lo.col.to_usize(),
1952 hicol: hi.col.to_usize(),
1958 impl Clean<Path> for hir::Path {
1959 fn clean(&self, cx: &DocContext<'_>) -> Path {
1961 global: self.is_global(),
1963 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1968 impl Clean<GenericArgs> for hir::GenericArgs {
1969 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1970 if self.parenthesized {
1971 let output = self.bindings[0].ty().clean(cx);
1972 GenericArgs::Parenthesized {
1973 inputs: self.inputs().clean(cx),
1974 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
1977 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1978 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1981 GenericArgs::AngleBracketed {
1982 args: self.args.iter().filter_map(|arg| match arg {
1983 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1984 Some(GenericArg::Lifetime(lt.clean(cx)))
1986 hir::GenericArg::Lifetime(_) => None,
1987 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1988 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1990 bindings: self.bindings.clean(cx),
1996 impl Clean<PathSegment> for hir::PathSegment {
1997 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1999 name: self.ident.name.clean(cx),
2000 args: self.generic_args().clean(cx),
2005 impl Clean<String> for Ident {
2007 fn clean(&self, cx: &DocContext<'_>) -> String {
2012 impl Clean<String> for ast::Name {
2014 fn clean(&self, _: &DocContext<'_>) -> String {
2019 impl Clean<Item> for doctree::Typedef<'_> {
2020 fn clean(&self, cx: &DocContext<'_>) -> Item {
2022 name: Some(self.name.clean(cx)),
2023 attrs: self.attrs.clean(cx),
2024 source: self.whence.clean(cx),
2025 def_id: cx.tcx.hir().local_def_id(self.id),
2026 visibility: self.vis.clean(cx),
2027 stability: cx.stability(self.id).clean(cx),
2028 deprecation: cx.deprecation(self.id).clean(cx),
2029 inner: TypedefItem(Typedef {
2030 type_: self.ty.clean(cx),
2031 generics: self.gen.clean(cx),
2037 impl Clean<Item> for doctree::OpaqueTy<'_> {
2038 fn clean(&self, cx: &DocContext<'_>) -> 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),
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(OpaqueTy {
2048 bounds: self.opaque_ty.bounds.clean(cx),
2049 generics: self.opaque_ty.generics.clean(cx),
2055 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2056 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2057 let (generic_params, decl) = enter_impl_trait(cx, || {
2058 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2061 unsafety: self.unsafety,
2069 impl Clean<Item> for doctree::Static<'_> {
2070 fn clean(&self, cx: &DocContext<'_>) -> Item {
2071 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2073 name: Some(self.name.clean(cx)),
2074 attrs: self.attrs.clean(cx),
2075 source: self.whence.clean(cx),
2076 def_id: cx.tcx.hir().local_def_id(self.id),
2077 visibility: self.vis.clean(cx),
2078 stability: cx.stability(self.id).clean(cx),
2079 deprecation: cx.deprecation(self.id).clean(cx),
2080 inner: StaticItem(Static {
2081 type_: self.type_.clean(cx),
2082 mutability: self.mutability.clean(cx),
2083 expr: print_const_expr(cx, self.expr),
2089 impl Clean<Item> for doctree::Constant<'_> {
2090 fn clean(&self, cx: &DocContext<'_>) -> Item {
2092 name: Some(self.name.clean(cx)),
2093 attrs: self.attrs.clean(cx),
2094 source: self.whence.clean(cx),
2095 def_id: cx.tcx.hir().local_def_id(self.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),
2107 impl Clean<Mutability> for hir::Mutability {
2108 fn clean(&self, _: &DocContext<'_>) -> Mutability {
2110 &hir::Mutability::Mut => Mutable,
2111 &hir::Mutability::Not => Immutable,
2116 impl Clean<ImplPolarity> for ty::ImplPolarity {
2117 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2119 &ty::ImplPolarity::Positive |
2120 // FIXME: do we want to do something else here?
2121 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2122 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2127 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2128 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2129 let mut ret = Vec::new();
2130 let trait_ = self.trait_.clean(cx);
2131 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2132 let def_id = cx.tcx.hir().local_def_id(self.id);
2134 // If this impl block is an implementation of the Deref trait, then we
2135 // need to try inlining the target's inherent impl blocks as well.
2136 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2137 build_deref_target_impls(cx, &items, &mut ret);
2140 let provided = trait_.def_id().map(|did| {
2141 cx.tcx.provided_trait_methods(did)
2143 .map(|meth| meth.ident.to_string())
2145 }).unwrap_or_default();
2149 attrs: self.attrs.clean(cx),
2150 source: self.whence.clean(cx),
2152 visibility: self.vis.clean(cx),
2153 stability: cx.stability(self.id).clean(cx),
2154 deprecation: cx.deprecation(self.id).clean(cx),
2155 inner: ImplItem(Impl {
2156 unsafety: self.unsafety,
2157 generics: self.generics.clean(cx),
2158 provided_trait_methods: provided,
2160 for_: self.for_.clean(cx),
2162 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2171 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2172 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2174 let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
2175 a.check_name(sym::doc) && match a.meta_item_list() {
2176 Some(l) => attr::list_contains_name(&l, sym::inline),
2182 let mut visited = FxHashSet::default();
2188 index: CRATE_DEF_INDEX,
2192 if let Some(items) = inline::try_inline(
2194 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2203 attrs: self.attrs.clean(cx),
2204 source: self.whence.clean(cx),
2205 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2206 visibility: self.vis.clean(cx),
2209 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2214 impl Clean<Vec<Item>> for doctree::Import<'_> {
2215 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2216 // We consider inlining the documentation of `pub use` statements, but we
2217 // forcefully don't inline if this is not public or if the
2218 // #[doc(no_inline)] attribute is present.
2219 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2220 let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| {
2221 a.check_name(sym::doc) && match a.meta_item_list() {
2222 Some(l) => attr::list_contains_name(&l, sym::no_inline) ||
2223 attr::list_contains_name(&l, sym::hidden),
2227 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2228 // crate in Rust 2018+
2229 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2230 let path = self.path.clean(cx);
2231 let inner = if self.glob {
2233 let mut visited = FxHashSet::default();
2234 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2239 Import::Glob(resolve_use_source(cx, path))
2241 let name = self.name;
2244 Res::Def(DefKind::Mod, did) => {
2245 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2246 // if we're `pub use`ing an extern crate root, don't inline it unless we
2247 // were specifically asked for it
2255 let mut visited = FxHashSet::default();
2256 if let Some(items) = inline::try_inline(
2258 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2264 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2269 attrs: self.attrs.clean(cx),
2270 source: self.whence.clean(cx),
2271 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2272 visibility: self.vis.clean(cx),
2275 inner: ImportItem(inner)
2280 impl Clean<Item> for doctree::ForeignItem<'_> {
2281 fn clean(&self, cx: &DocContext<'_>) -> Item {
2282 let inner = match self.kind {
2283 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2284 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2285 let (generics, decl) = enter_impl_trait(cx, || {
2286 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2288 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2289 ForeignFunctionItem(Function {
2292 header: hir::FnHeader {
2293 unsafety: hir::Unsafety::Unsafe,
2295 constness: hir::Constness::NotConst,
2296 asyncness: hir::IsAsync::NotAsync,
2302 hir::ForeignItemKind::Static(ref ty, mutbl) => {
2303 ForeignStaticItem(Static {
2304 type_: ty.clean(cx),
2305 mutability: mutbl.clean(cx),
2306 expr: String::new(),
2309 hir::ForeignItemKind::Type => {
2315 name: Some(self.name.clean(cx)),
2316 attrs: self.attrs.clean(cx),
2317 source: self.whence.clean(cx),
2318 def_id: cx.tcx.hir().local_def_id(self.id),
2319 visibility: self.vis.clean(cx),
2320 stability: cx.stability(self.id).clean(cx),
2321 deprecation: cx.deprecation(self.id).clean(cx),
2327 impl Clean<Item> for doctree::Macro<'_> {
2328 fn clean(&self, cx: &DocContext<'_>) -> Item {
2329 let name = self.name.clean(cx);
2331 name: Some(name.clone()),
2332 attrs: self.attrs.clean(cx),
2333 source: self.whence.clean(cx),
2335 stability: cx.stability(self.hid).clean(cx),
2336 deprecation: cx.deprecation(self.hid).clean(cx),
2337 def_id: self.def_id,
2338 inner: MacroItem(Macro {
2339 source: format!("macro_rules! {} {{\n{}}}",
2341 self.matchers.iter().map(|span| {
2342 format!(" {} => {{ ... }};\n", span.to_src(cx))
2343 }).collect::<String>()),
2344 imported_from: self.imported_from.clean(cx),
2350 impl Clean<Item> for doctree::ProcMacro<'_> {
2351 fn clean(&self, cx: &DocContext<'_>) -> Item {
2353 name: Some(self.name.clean(cx)),
2354 attrs: self.attrs.clean(cx),
2355 source: self.whence.clean(cx),
2357 stability: cx.stability(self.id).clean(cx),
2358 deprecation: cx.deprecation(self.id).clean(cx),
2359 def_id: cx.tcx.hir().local_def_id(self.id),
2360 inner: ProcMacroItem(ProcMacro {
2362 helpers: self.helpers.clean(cx),
2368 impl Clean<Stability> for attr::Stability {
2369 fn clean(&self, _: &DocContext<'_>) -> Stability {
2371 level: stability::StabilityLevel::from_attr_level(&self.level),
2372 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2373 since: match self.level {
2374 attr::Stable {ref since} => since.to_string(),
2377 deprecation: self.rustc_depr.as_ref().map(|d| {
2379 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2380 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2383 unstable_reason: match self.level {
2384 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2387 issue: match self.level {
2388 attr::Unstable {issue, ..} => issue,
2395 impl Clean<Deprecation> for attr::Deprecation {
2396 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2398 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2399 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2404 impl Clean<TypeBinding> for hir::TypeBinding {
2405 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2407 name: self.ident.name.clean(cx),
2408 kind: self.kind.clean(cx),
2413 impl Clean<TypeBindingKind> for hir::TypeBindingKind {
2414 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2416 hir::TypeBindingKind::Equality { ref ty } =>
2417 TypeBindingKind::Equality {
2420 hir::TypeBindingKind::Constraint { ref bounds } =>
2421 TypeBindingKind::Constraint {
2422 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2429 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2433 impl From<GenericBound> for SimpleBound {
2434 fn from(bound: GenericBound) -> Self {
2435 match bound.clone() {
2436 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2437 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2438 Type::ResolvedPath { path, param_names, .. } => {
2439 SimpleBound::TraitBound(path.segments,
2441 .map_or_else(|| Vec::new(), |v| v.iter()
2442 .map(|p| SimpleBound::from(p.clone()))
2447 _ => panic!("Unexpected bound {:?}", bound),