1 //! This module contains the "cleaned" pieces of the AST, and the functions
12 use rustc::infer::region_constraints::{Constraint, RegionConstraintData};
13 use rustc::middle::lang_items;
14 use rustc::middle::resolve_lifetime as rl;
15 use rustc::middle::stability;
16 use rustc::ty::fold::TypeFolder;
17 use rustc::ty::subst::InternalSubsts;
18 use rustc::ty::{self, AdtKind, Lift, Ty, TyCtxt};
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_hir::def::{CtorKind, DefKind, Res};
22 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
23 use rustc_index::vec::{Idx, IndexVec};
24 use rustc_mir::const_eval::is_min_const_fn;
25 use rustc_span::hygiene::MacroKind;
26 use rustc_span::symbol::{kw, sym};
27 use rustc_span::{self, Pos};
28 use rustc_typeck::hir_ty_to_ty;
29 use syntax::ast::{self, Ident};
32 use std::collections::hash_map::Entry;
33 use std::default::Default;
39 use crate::core::{self, DocContext, ImplTraitParam};
44 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
46 pub use self::types::FunctionRetTy::*;
47 pub use self::types::ItemEnum::*;
48 pub use self::types::SelfTy::*;
49 pub use self::types::Type::*;
50 pub use self::types::Visibility::{Inherited, Public};
51 pub use self::types::*;
53 const FN_OUTPUT_NAME: &'static str = "Output";
56 fn clean(&self, cx: &DocContext<'_>) -> T;
59 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
60 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
61 self.iter().map(|x| x.clean(cx)).collect()
65 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
66 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
67 self.iter().map(|x| x.clean(cx)).collect()
71 impl<T: Clean<U>, U> Clean<U> for &T {
72 fn clean(&self, cx: &DocContext<'_>) -> U {
77 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
78 fn clean(&self, cx: &DocContext<'_>) -> U {
83 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
84 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
85 self.as_ref().map(|v| v.clean(cx))
89 impl<T, U> Clean<U> for ty::Binder<T>
93 fn clean(&self, cx: &DocContext<'_>) -> U {
94 self.skip_binder().clean(cx)
98 impl Clean<ExternalCrate> for CrateNum {
99 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
100 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
101 let krate_span = cx.tcx.def_span(root);
102 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
104 // Collect all inner modules which are tagged as implementations of
107 // Note that this loop only searches the top-level items of the crate,
108 // and this is intentional. If we were to search the entire crate for an
109 // item tagged with `#[doc(primitive)]` then we would also have to
110 // search the entirety of external modules for items tagged
111 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
112 // all that metadata unconditionally).
114 // In order to keep the metadata load under control, the
115 // `#[doc(primitive)]` feature is explicitly designed to only allow the
116 // primitive tags to show up as the top level items in a crate.
118 // Also note that this does not attempt to deal with modules tagged
119 // duplicately for the same primitive. This is handled later on when
120 // rendering by delegating everything to a hash map.
121 let as_primitive = |res: Res| {
122 if let Res::Def(DefKind::Mod, def_id) = res {
123 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
125 for attr in attrs.lists(sym::doc) {
126 if let Some(v) = attr.value_str() {
127 if attr.check_name(sym::primitive) {
128 prim = PrimitiveType::from_str(&v.as_str());
132 // FIXME: should warn on unknown primitives?
136 return prim.map(|p| (def_id, p, attrs));
140 let primitives = if root.is_local() {
148 let item = cx.tcx.hir().expect_item(id.id);
150 hir::ItemKind::Mod(_) => {
151 as_primitive(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
153 hir::ItemKind::Use(ref path, hir::UseKind::Single)
154 if item.vis.node.is_pub() =>
156 as_primitive(path.res).map(|(_, prim, attrs)| {
157 // Pretend the primitive is local.
158 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
169 .map(|item| item.res)
170 .filter_map(as_primitive)
174 let as_keyword = |res: Res| {
175 if let Res::Def(DefKind::Mod, def_id) = res {
176 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
177 let mut keyword = None;
178 for attr in attrs.lists(sym::doc) {
179 if let Some(v) = attr.value_str() {
180 if attr.check_name(sym::keyword) {
181 if v.is_doc_keyword() {
182 keyword = Some(v.to_string());
185 // FIXME: should warn on unknown keywords?
189 return keyword.map(|p| (def_id, p, attrs));
193 let keywords = if root.is_local() {
201 let item = cx.tcx.hir().expect_item(id.id);
203 hir::ItemKind::Mod(_) => {
204 as_keyword(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
206 hir::ItemKind::Use(ref path, hir::UseKind::Single)
207 if item.vis.node.is_pub() =>
209 as_keyword(path.res).map(|(_, prim, attrs)| {
210 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
218 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
222 name: cx.tcx.crate_name(*self).to_string(),
224 attrs: cx.tcx.get_attrs(root).clean(cx),
231 impl Clean<Item> for doctree::Module<'_> {
232 fn clean(&self, cx: &DocContext<'_>) -> Item {
233 let name = if self.name.is_some() {
234 self.name.expect("No name provided").clean(cx)
239 // maintain a stack of mod ids, for doc comment path resolution
240 // but we also need to resolve the module's own docs based on whether its docs were written
241 // inside or outside the module, so check for that
242 let attrs = self.attrs.clean(cx);
244 let mut items: Vec<Item> = vec![];
245 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
246 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
247 items.extend(self.structs.iter().map(|x| x.clean(cx)));
248 items.extend(self.unions.iter().map(|x| x.clean(cx)));
249 items.extend(self.enums.iter().map(|x| x.clean(cx)));
250 items.extend(self.fns.iter().map(|x| x.clean(cx)));
251 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
252 items.extend(self.mods.iter().map(|x| x.clean(cx)));
253 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
254 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
255 items.extend(self.statics.iter().map(|x| x.clean(cx)));
256 items.extend(self.constants.iter().map(|x| x.clean(cx)));
257 items.extend(self.traits.iter().map(|x| x.clean(cx)));
258 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
259 items.extend(self.macros.iter().map(|x| x.clean(cx)));
260 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
261 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
263 // determine if we should display the inner contents or
264 // the outer `mod` item for the source code.
266 let cm = cx.sess().source_map();
267 let outer = cm.lookup_char_pos(self.where_outer.lo());
268 let inner = cm.lookup_char_pos(self.where_inner.lo());
269 if outer.file.start_pos == inner.file.start_pos {
273 // mod foo; (and a separate SourceFile for the contents)
281 source: whence.clean(cx),
282 visibility: self.vis.clean(cx),
283 stability: cx.stability(self.id).clean(cx),
284 deprecation: cx.deprecation(self.id).clean(cx),
285 def_id: cx.tcx.hir().local_def_id(self.id),
286 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
291 impl Clean<Attributes> for [ast::Attribute] {
292 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
293 Attributes::from_ast(cx.sess().diagnostic(), self)
297 impl Clean<GenericBound> for hir::GenericBound<'_> {
298 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
300 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
301 hir::GenericBound::Trait(ref t, modifier) => {
302 GenericBound::TraitBound(t.clean(cx), modifier)
308 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
309 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
310 let (trait_ref, ref bounds) = *self;
311 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
312 let path = external_path(
314 cx.tcx.item_name(trait_ref.def_id),
315 Some(trait_ref.def_id),
321 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
323 // collect any late bound regions
324 let mut late_bounds = vec![];
325 for ty_s in trait_ref.input_types().skip(1) {
326 if let ty::Tuple(ts) = ty_s.kind {
328 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
329 if let &ty::RegionKind::ReLateBound(..) = *reg {
330 debug!(" hit an ReLateBound {:?}", reg);
331 if let Some(Lifetime(name)) = reg.clean(cx) {
332 late_bounds.push(GenericParamDef {
334 kind: GenericParamDefKind::Lifetime,
343 GenericBound::TraitBound(
345 trait_: ResolvedPath {
348 did: trait_ref.def_id,
351 generic_params: late_bounds,
353 hir::TraitBoundModifier::None,
358 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
359 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
360 (self, vec![]).clean(cx)
364 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
365 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
366 let mut v = Vec::new();
367 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
368 v.extend(self.types().map(|t| {
369 GenericBound::TraitBound(
370 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
371 hir::TraitBoundModifier::None,
374 if !v.is_empty() { Some(v) } else { None }
378 impl Clean<Lifetime> for hir::Lifetime {
379 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
380 if self.hir_id != hir::DUMMY_HIR_ID {
381 let def = cx.tcx.named_region(self.hir_id);
383 Some(rl::Region::EarlyBound(_, node_id, _))
384 | Some(rl::Region::LateBound(_, node_id, _))
385 | Some(rl::Region::Free(_, node_id)) => {
386 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
393 Lifetime(self.name.ident().to_string())
397 impl Clean<Lifetime> for hir::GenericParam<'_> {
398 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
400 hir::GenericParamKind::Lifetime { .. } => {
401 if self.bounds.len() > 0 {
402 let mut bounds = self.bounds.iter().map(|bound| match bound {
403 hir::GenericBound::Outlives(lt) => lt,
406 let name = bounds.next().expect("no more bounds").name.ident();
407 let mut s = format!("{}: {}", self.name.ident(), name);
408 for bound in bounds {
409 s.push_str(&format!(" + {}", bound.name.ident()));
413 Lifetime(self.name.ident().to_string())
421 impl Clean<Constant> for hir::ConstArg {
422 fn clean(&self, cx: &DocContext<'_>) -> Constant {
424 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
425 expr: print_const_expr(cx, self.value.body),
427 is_literal: is_literal_expr(cx, self.value.body.hir_id),
432 impl Clean<Lifetime> for ty::GenericParamDef {
433 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
434 Lifetime(self.name.to_string())
438 impl Clean<Option<Lifetime>> for ty::RegionKind {
439 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
441 ty::ReStatic => Some(Lifetime::statik()),
442 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
443 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
449 | ty::RePlaceholder(..)
451 | ty::ReClosureBound(_)
453 debug!("cannot clean region {:?}", self);
460 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
461 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
463 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
464 ty: wbp.bounded_ty.clean(cx),
465 bounds: wbp.bounds.clean(cx),
468 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
469 lifetime: wrp.lifetime.clean(cx),
470 bounds: wrp.bounds.clean(cx),
473 hir::WherePredicate::EqPredicate(ref wrp) => {
474 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
480 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
481 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
482 use rustc::ty::Predicate;
485 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
486 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
487 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
488 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
489 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
491 Predicate::WellFormed(..)
492 | Predicate::ObjectSafe(..)
493 | Predicate::ClosureKind(..)
494 | Predicate::ConstEvaluatable(..) => panic!("not user writable"),
499 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
500 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
501 WherePredicate::BoundPredicate {
502 ty: self.trait_ref.self_ty().clean(cx),
503 bounds: vec![self.trait_ref.clean(cx)],
508 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
509 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
511 "subtype predicates are an internal rustc artifact \
512 and should not be seen by rustdoc"
517 impl<'tcx> Clean<Option<WherePredicate>>
518 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
520 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
521 let ty::OutlivesPredicate(ref a, ref b) = *self;
524 (ty::ReEmpty, ty::ReEmpty) => {
530 Some(WherePredicate::RegionPredicate {
531 lifetime: a.clean(cx).expect("failed to clean lifetime"),
532 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
537 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
538 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
539 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
542 ty::ReEmpty => return None,
546 Some(WherePredicate::BoundPredicate {
548 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
553 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
554 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
555 WherePredicate::EqPredicate { lhs: self.projection_ty.clean(cx), rhs: self.ty.clean(cx) }
559 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
560 fn clean(&self, cx: &DocContext<'_>) -> Type {
561 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
562 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
563 GenericBound::TraitBound(t, _) => t.trait_,
564 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
567 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
568 self_type: box self.self_ty().clean(cx),
574 impl Clean<GenericParamDef> for ty::GenericParamDef {
575 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
576 let (name, kind) = match self.kind {
577 ty::GenericParamDefKind::Lifetime => {
578 (self.name.to_string(), GenericParamDefKind::Lifetime)
580 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
582 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
585 GenericParamDefKind::Type {
587 bounds: vec![], // These are filled in from the where-clauses.
593 ty::GenericParamDefKind::Const { .. } => (
595 GenericParamDefKind::Const {
597 ty: cx.tcx.type_of(self.def_id).clean(cx),
602 GenericParamDef { name, kind }
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),
628 GenericParamDefKind::Type {
629 did: cx.tcx.hir().local_def_id(self.hir_id),
630 bounds: self.bounds.clean(cx),
631 default: default.clean(cx),
635 hir::GenericParamKind::Const { ref ty } => (
636 self.name.ident().name.clean(cx),
637 GenericParamDefKind::Const {
638 did: cx.tcx.hir().local_def_id(self.hir_id),
644 GenericParamDef { name, kind }
648 impl Clean<Generics> for hir::Generics<'_> {
649 fn clean(&self, cx: &DocContext<'_>) -> Generics {
650 // Synthetic type-parameters are inserted after normal ones.
651 // In order for normal parameters to be able to refer to synthetic ones,
653 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
655 hir::GenericParamKind::Type { synthetic, .. } => {
656 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
661 let impl_trait_params = self
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);
686 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
688 // Some duplicates are generated for ?Sized bounds between type params and where
689 // predicates. The point in here is to move the bounds definitions from type params
690 // to where predicates when such cases occur.
691 for where_pred in &mut generics.where_predicates {
693 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
694 if bounds.is_empty() {
695 for param in &mut generics.params {
697 GenericParamDefKind::Lifetime => {}
698 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
699 if ¶m.name == name {
700 mem::swap(bounds, ty_bounds);
704 GenericParamDefKind::Const { .. } => {}
716 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
717 fn clean(&self, cx: &DocContext<'_>) -> Generics {
718 use self::WherePredicate as WP;
719 use std::collections::BTreeMap;
721 let (gens, preds) = *self;
723 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
724 // since `Clean for ty::Predicate` would consume them.
725 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
727 // Bounds in the type_params and lifetimes fields are repeated in the
728 // predicates field (see rustc_typeck::collect::ty_generics), so remove
730 let stripped_typarams = gens
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,
748 .collect::<Vec<GenericParamDef>>();
750 // param index -> [(DefId of trait, associated type name, type)]
751 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
753 let where_predicates = preds
757 let mut projection = None;
758 let param_idx = (|| {
759 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
760 if let ty::Param(param) = trait_ref.self_ty().kind {
761 return Some(param.index);
763 } else if let Some(outlives) = p.to_opt_type_outlives() {
764 if let ty::Param(param) = outlives.skip_binder().0.kind {
765 return Some(param.index);
767 } else if let ty::Predicate::Projection(p) = p {
768 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
769 projection = Some(p);
770 return Some(param.index);
777 if let Some(param_idx) = param_idx {
778 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
779 let p = p.clean(cx)?;
786 .filter(|b| !b.is_sized_bound(cx)),
789 let proj = projection
790 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
791 if let Some(((_, trait_did, name), rhs)) =
792 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
794 impl_trait_proj.entry(param_idx).or_default().push((
807 .collect::<Vec<_>>();
809 for (param, mut bounds) in impl_trait {
810 // Move trait bounds to the front.
811 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
813 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
814 if let Some(proj) = impl_trait_proj.remove(&idx) {
815 for (trait_did, name, rhs) in proj {
816 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
823 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
826 // Now that `cx.impl_trait_bounds` is populated, we can process
827 // remaining predicates which could contain `impl Trait`.
828 let mut where_predicates =
829 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
831 // Type parameters and have a Sized bound by default unless removed with
832 // ?Sized. Scan through the predicates and mark any type parameter with
833 // a Sized bound, removing the bounds as we find them.
835 // Note that associated types also have a sized bound by default, but we
836 // don't actually know the set of associated types right here so that's
837 // handled in cleaning associated types
838 let mut sized_params = FxHashSet::default();
839 where_predicates.retain(|pred| match *pred {
840 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
841 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
842 sized_params.insert(g.clone());
851 // Run through the type parameters again and insert a ?Sized
852 // unbound for any we didn't find to be Sized.
853 for tp in &stripped_typarams {
854 if !sized_params.contains(&tp.name) {
855 where_predicates.push(WP::BoundPredicate {
856 ty: Type::Generic(tp.name.clone()),
857 bounds: vec![GenericBound::maybe_sized(cx)],
862 // It would be nice to collect all of the bounds on a type and recombine
863 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
864 // and instead see `where T: Foo + Bar + Sized + 'a`
870 .flat_map(|param| match param.kind {
871 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
872 ty::GenericParamDefKind::Type { .. } => None,
873 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
875 .chain(simplify::ty_params(stripped_typarams).into_iter())
877 where_predicates: simplify::where_clauses(cx, where_predicates),
882 impl<'a> Clean<Method>
883 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
885 fn clean(&self, cx: &DocContext<'_>) -> Method {
886 let (generics, decl) =
887 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
888 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
889 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
893 impl Clean<Item> for doctree::Function<'_> {
894 fn clean(&self, cx: &DocContext<'_>) -> Item {
895 let (generics, decl) =
896 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
898 let did = cx.tcx.hir().local_def_id(self.id);
899 let constness = if is_min_const_fn(cx.tcx, did) {
900 hir::Constness::Const
902 hir::Constness::NotConst
904 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
906 name: Some(self.name.clean(cx)),
907 attrs: self.attrs.clean(cx),
908 source: self.whence.clean(cx),
909 visibility: self.vis.clean(cx),
910 stability: cx.stability(self.id).clean(cx),
911 deprecation: cx.deprecation(self.id).clean(cx),
913 inner: FunctionItem(Function {
916 header: hir::FnHeader { constness, ..self.header },
924 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [ast::Ident]) {
925 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
933 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
935 name = "_".to_string();
937 Argument { name, type_: ty.clean(cx) }
944 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
945 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
946 let body = cx.tcx.hir().body(self.1);
953 .map(|(i, ty)| Argument {
954 name: name_from_pat(&body.params[i].pat),
962 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
964 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
966 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
968 inputs: (&self.0.inputs[..], self.1).clean(cx),
969 output: self.0.output.clean(cx),
970 c_variadic: self.0.c_variadic,
971 attrs: Attributes::default(),
976 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
977 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
978 let (did, sig) = *self;
979 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
982 cx.tcx.fn_arg_names(did).into_iter()
986 output: Return(sig.skip_binder().output().clean(cx)),
987 attrs: Attributes::default(),
988 c_variadic: sig.skip_binder().c_variadic,
996 name: names.next().map_or(String::new(), |name| name.to_string()),
1004 impl Clean<FunctionRetTy> for hir::FunctionRetTy<'_> {
1005 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1007 Self::Return(ref typ) => Return(typ.clean(cx)),
1008 Self::DefaultReturn(..) => DefaultReturn,
1013 impl Clean<Item> for doctree::Trait<'_> {
1014 fn clean(&self, cx: &DocContext<'_>) -> Item {
1015 let attrs = self.attrs.clean(cx);
1016 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1018 name: Some(self.name.clean(cx)),
1020 source: self.whence.clean(cx),
1021 def_id: cx.tcx.hir().local_def_id(self.id),
1022 visibility: self.vis.clean(cx),
1023 stability: cx.stability(self.id).clean(cx),
1024 deprecation: cx.deprecation(self.id).clean(cx),
1025 inner: TraitItem(Trait {
1026 auto: self.is_auto.clean(cx),
1027 unsafety: self.unsafety,
1028 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1029 generics: self.generics.clean(cx),
1030 bounds: self.bounds.clean(cx),
1032 is_auto: self.is_auto.clean(cx),
1038 impl Clean<Item> for doctree::TraitAlias<'_> {
1039 fn clean(&self, cx: &DocContext<'_>) -> Item {
1040 let attrs = self.attrs.clean(cx);
1042 name: Some(self.name.clean(cx)),
1044 source: self.whence.clean(cx),
1045 def_id: cx.tcx.hir().local_def_id(self.id),
1046 visibility: self.vis.clean(cx),
1047 stability: cx.stability(self.id).clean(cx),
1048 deprecation: cx.deprecation(self.id).clean(cx),
1049 inner: TraitAliasItem(TraitAlias {
1050 generics: self.generics.clean(cx),
1051 bounds: self.bounds.clean(cx),
1057 impl Clean<bool> for hir::IsAuto {
1058 fn clean(&self, _: &DocContext<'_>) -> bool {
1060 hir::IsAuto::Yes => true,
1061 hir::IsAuto::No => false,
1066 impl Clean<Type> for hir::TraitRef<'_> {
1067 fn clean(&self, cx: &DocContext<'_>) -> Type {
1068 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1072 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1073 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1075 trait_: self.trait_ref.clean(cx),
1076 generic_params: self.bound_generic_params.clean(cx),
1081 impl Clean<Item> for hir::TraitItem<'_> {
1082 fn clean(&self, cx: &DocContext<'_>) -> Item {
1083 let inner = match self.kind {
1084 hir::TraitItemKind::Const(ref ty, default) => {
1085 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1087 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1088 MethodItem((sig, &self.generics, body, None).clean(cx))
1090 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1091 let (generics, decl) = enter_impl_trait(cx, || {
1092 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1094 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1095 TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types })
1097 hir::TraitItemKind::Type(ref bounds, ref default) => {
1098 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1101 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1103 name: Some(self.ident.name.clean(cx)),
1104 attrs: self.attrs.clean(cx),
1105 source: self.span.clean(cx),
1107 visibility: Visibility::Inherited,
1108 stability: get_stability(cx, local_did),
1109 deprecation: get_deprecation(cx, local_did),
1115 impl Clean<Item> for hir::ImplItem<'_> {
1116 fn clean(&self, cx: &DocContext<'_>) -> Item {
1117 let inner = match self.kind {
1118 hir::ImplItemKind::Const(ref ty, expr) => {
1119 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1121 hir::ImplItemKind::Method(ref sig, body) => {
1122 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1124 hir::ImplItemKind::TyAlias(ref ty) => {
1125 let type_ = ty.clean(cx);
1126 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1127 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1129 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(
1130 OpaqueTy { bounds: bounds.clean(cx), generics: Generics::default() },
1134 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1136 name: Some(self.ident.name.clean(cx)),
1137 source: self.span.clean(cx),
1138 attrs: self.attrs.clean(cx),
1140 visibility: self.vis.clean(cx),
1141 stability: get_stability(cx, local_did),
1142 deprecation: get_deprecation(cx, local_did),
1148 impl Clean<Item> for ty::AssocItem {
1149 fn clean(&self, cx: &DocContext<'_>) -> Item {
1150 let inner = match self.kind {
1151 ty::AssocKind::Const => {
1152 let ty = cx.tcx.type_of(self.def_id);
1153 let default = if self.defaultness.has_value() {
1154 Some(inline::print_inlined_const(cx, self.def_id))
1158 AssocConstItem(ty.clean(cx), default)
1160 ty::AssocKind::Method => {
1162 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1164 let sig = cx.tcx.fn_sig(self.def_id);
1165 let mut decl = (self.def_id, sig).clean(cx);
1167 if self.method_has_self_argument {
1168 let self_ty = match self.container {
1169 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1170 ty::TraitContainer(_) => cx.tcx.types.self_param,
1172 let self_arg_ty = *sig.input(0).skip_binder();
1173 if self_arg_ty == self_ty {
1174 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1175 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1177 match decl.inputs.values[0].type_ {
1178 BorrowedRef { ref mut type_, .. } => {
1179 **type_ = Generic(String::from("Self"))
1181 _ => unreachable!(),
1187 let provided = match self.container {
1188 ty::ImplContainer(_) => true,
1189 ty::TraitContainer(_) => self.defaultness.has_value(),
1191 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1193 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1194 hir::Constness::Const
1196 hir::Constness::NotConst
1198 let asyncness = cx.tcx.asyncness(self.def_id);
1199 let defaultness = match self.container {
1200 ty::ImplContainer(_) => Some(self.defaultness),
1201 ty::TraitContainer(_) => None,
1206 header: hir::FnHeader {
1207 unsafety: sig.unsafety(),
1217 TyMethodItem(TyMethod {
1220 header: hir::FnHeader {
1221 unsafety: sig.unsafety(),
1223 constness: hir::Constness::NotConst,
1224 asyncness: hir::IsAsync::NotAsync,
1231 ty::AssocKind::Type => {
1232 let my_name = self.ident.name.clean(cx);
1234 if let ty::TraitContainer(did) = self.container {
1235 // When loading a cross-crate associated type, the bounds for this type
1236 // are actually located on the trait/impl itself, so we need to load
1237 // all of the generics from there and then look for bounds that are
1238 // applied to this associated type in question.
1239 let predicates = cx.tcx.explicit_predicates_of(did);
1240 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1241 let mut bounds = generics
1244 .filter_map(|pred| {
1245 let (name, self_type, trait_, bounds) = match *pred {
1246 WherePredicate::BoundPredicate {
1247 ty: QPath { ref name, ref self_type, ref trait_ },
1249 } => (name, self_type, trait_, bounds),
1252 if *name != my_name {
1256 ResolvedPath { did, .. } if did == self.container.id() => {}
1260 Generic(ref s) if *s == "Self" => {}
1265 .flat_map(|i| i.iter().cloned())
1266 .collect::<Vec<_>>();
1267 // Our Sized/?Sized bound didn't get handled when creating the generics
1268 // because we didn't actually get our whole set of bounds until just now
1269 // (some of them may have come from the trait). If we do have a sized
1270 // bound, we remove it, and if we don't then we add the `?Sized` bound
1272 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1276 None => bounds.push(GenericBound::maybe_sized(cx)),
1279 let ty = if self.defaultness.has_value() {
1280 Some(cx.tcx.type_of(self.def_id))
1285 AssocTypeItem(bounds, ty.clean(cx))
1287 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1288 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1292 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1299 ty::AssocKind::OpaqueTy => unimplemented!(),
1302 let visibility = match self.container {
1303 ty::ImplContainer(_) => self.vis.clean(cx),
1304 ty::TraitContainer(_) => Inherited,
1308 name: Some(self.ident.name.clean(cx)),
1310 stability: get_stability(cx, self.def_id),
1311 deprecation: get_deprecation(cx, self.def_id),
1312 def_id: self.def_id,
1313 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1314 source: cx.tcx.def_span(self.def_id).clean(cx),
1320 impl Clean<Type> for hir::Ty<'_> {
1321 fn clean(&self, cx: &DocContext<'_>) -> Type {
1325 TyKind::Never => Never,
1326 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1327 TyKind::Rptr(ref l, ref m) => {
1328 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1329 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1331 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1332 TyKind::Array(ref ty, ref length) => {
1333 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1334 let length = match cx.tcx.const_eval_poly(def_id) {
1335 Ok(length) => print_const(cx, length),
1339 .span_to_snippet(cx.tcx.def_span(def_id))
1340 .unwrap_or_else(|_| "_".to_string()),
1342 Array(box ty.clean(cx), length)
1344 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1345 TyKind::Def(item_id, _) => {
1346 let item = cx.tcx.hir().expect_item(item_id.id);
1347 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1348 ImplTrait(ty.bounds.clean(cx))
1353 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1354 if let Res::Def(DefKind::TyParam, did) = path.res {
1355 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1358 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1359 return ImplTrait(bounds);
1363 let mut alias = None;
1364 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1365 // Substitute private type aliases
1366 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1367 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1368 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1373 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1374 let provided_params = &path.segments.last().expect("segments were empty");
1375 let mut ty_substs = FxHashMap::default();
1376 let mut lt_substs = FxHashMap::default();
1377 let mut ct_substs = FxHashMap::default();
1378 let generic_args = provided_params.generic_args();
1380 let mut indices: GenericParamCount = Default::default();
1381 for param in generics.params.iter() {
1383 hir::GenericParamKind::Lifetime { .. } => {
1386 generic_args.args.iter().find_map(|arg| match arg {
1387 hir::GenericArg::Lifetime(lt) => {
1388 if indices.lifetimes == j {
1396 if let Some(lt) = lifetime.cloned() {
1397 if !lt.is_elided() {
1398 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1399 lt_substs.insert(lt_def_id, lt.clean(cx));
1402 indices.lifetimes += 1;
1404 hir::GenericParamKind::Type { ref default, .. } => {
1405 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1408 generic_args.args.iter().find_map(|arg| match arg {
1409 hir::GenericArg::Type(ty) => {
1410 if indices.types == j {
1418 if let Some(ty) = type_ {
1419 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1420 } else if let Some(default) = default.clone() {
1421 ty_substs.insert(ty_param_def_id, default.clean(cx));
1425 hir::GenericParamKind::Const { .. } => {
1426 let const_param_def_id =
1427 cx.tcx.hir().local_def_id(param.hir_id);
1430 generic_args.args.iter().find_map(|arg| match arg {
1431 hir::GenericArg::Const(ct) => {
1432 if indices.consts == j {
1440 if let Some(ct) = const_ {
1441 ct_substs.insert(const_param_def_id, ct.clean(cx));
1443 // FIXME(const_generics:defaults)
1444 indices.consts += 1;
1449 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1451 resolve_type(cx, path.clean(cx), self.hir_id)
1453 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1454 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1455 let trait_segments = &segments[..segments.len() - 1];
1456 let trait_path = self::Path {
1457 global: p.is_global(),
1460 cx.tcx.associated_item(p.res.def_id()).container.id(),
1462 segments: trait_segments.clean(cx),
1465 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1466 self_type: box qself.clean(cx),
1467 trait_: box resolve_type(cx, trait_path, self.hir_id),
1470 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1471 let mut res = Res::Err;
1472 let ty = hir_ty_to_ty(cx.tcx, self);
1473 if let ty::Projection(proj) = ty.kind {
1474 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1476 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1478 name: segment.ident.name.clean(cx),
1479 self_type: box qself.clean(cx),
1480 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1483 TyKind::TraitObject(ref bounds, ref lifetime) => {
1484 match bounds[0].clean(cx).trait_ {
1485 ResolvedPath { path, param_names: None, did, is_generic } => {
1486 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1489 self::GenericBound::TraitBound(
1491 hir::TraitBoundModifier::None,
1495 if !lifetime.is_elided() {
1496 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1498 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1500 _ => Infer, // shouldn't happen
1503 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1504 TyKind::Infer | TyKind::Err => Infer,
1505 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1510 impl<'tcx> Clean<Type> for Ty<'tcx> {
1511 fn clean(&self, cx: &DocContext<'_>) -> Type {
1512 debug!("cleaning type: {:?}", self);
1515 ty::Bool => Primitive(PrimitiveType::Bool),
1516 ty::Char => Primitive(PrimitiveType::Char),
1517 ty::Int(int_ty) => Primitive(int_ty.into()),
1518 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1519 ty::Float(float_ty) => Primitive(float_ty.into()),
1520 ty::Str => Primitive(PrimitiveType::Str),
1521 ty::Slice(ty) => Slice(box ty.clean(cx)),
1522 ty::Array(ty, n) => {
1523 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1524 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1525 let n = print_const(cx, n);
1526 Array(box ty.clean(cx), n)
1528 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1529 ty::Ref(r, ty, mutbl) => {
1530 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1532 ty::FnDef(..) | ty::FnPtr(_) => {
1533 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1534 let sig = ty.fn_sig(cx.tcx);
1535 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1536 BareFunction(box BareFunctionDecl {
1537 unsafety: sig.unsafety(),
1538 generic_params: Vec::new(),
1539 decl: (local_def_id, sig).clean(cx),
1543 ty::Adt(def, substs) => {
1545 let kind = match def.adt_kind() {
1546 AdtKind::Struct => TypeKind::Struct,
1547 AdtKind::Union => TypeKind::Union,
1548 AdtKind::Enum => TypeKind::Enum,
1550 inline::record_extern_fqn(cx, did, kind);
1551 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1552 ResolvedPath { path, param_names: None, did, is_generic: false }
1554 ty::Foreign(did) => {
1555 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1556 let path = external_path(
1558 cx.tcx.item_name(did),
1562 InternalSubsts::empty(),
1564 ResolvedPath { path, param_names: None, did, is_generic: false }
1566 ty::Dynamic(ref obj, ref reg) => {
1567 // HACK: pick the first `did` as the `did` of the trait object. Someone
1568 // might want to implement "native" support for marker-trait-only
1570 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1573 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1574 let substs = match obj.principal() {
1575 Some(principal) => principal.skip_binder().substs,
1576 // marker traits have no substs.
1577 _ => cx.tcx.intern_substs(&[]),
1580 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1582 let mut param_names = vec![];
1583 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1585 let empty = cx.tcx.intern_substs(&[]);
1587 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1588 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1589 let bound = GenericBound::TraitBound(
1591 trait_: ResolvedPath {
1597 generic_params: Vec::new(),
1599 hir::TraitBoundModifier::None,
1601 param_names.push(bound);
1604 let mut bindings = vec![];
1605 for pb in obj.projection_bounds() {
1606 bindings.push(TypeBinding {
1607 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1608 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1613 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1614 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1616 ty::Tuple(ref t) => {
1617 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1620 ty::Projection(ref data) => data.clean(cx),
1622 ty::Param(ref p) => {
1623 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1626 Generic(p.name.to_string())
1630 ty::Opaque(def_id, substs) => {
1631 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1632 // by looking up the projections associated with the def_id.
1633 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1634 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1635 let bounds = predicates_of.instantiate(cx.tcx, substs);
1636 let mut regions = vec![];
1637 let mut has_sized = false;
1638 let mut bounds = bounds
1641 .filter_map(|predicate| {
1642 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1644 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1645 // these should turn up at the end
1649 .map(|r| regions.push(GenericBound::Outlives(r)));
1655 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1656 if trait_ref.def_id() == sized {
1665 .filter_map(|pred| {
1666 if let ty::Predicate::Projection(proj) = *pred {
1667 let proj = proj.skip_binder();
1668 if proj.projection_ty.trait_ref(cx.tcx)
1669 == *trait_ref.skip_binder()
1674 .associated_item(proj.projection_ty.item_def_id)
1678 kind: TypeBindingKind::Equality {
1679 ty: proj.ty.clean(cx),
1691 Some((trait_ref.skip_binder(), bounds).clean(cx))
1693 .collect::<Vec<_>>();
1694 bounds.extend(regions);
1695 if !has_sized && !bounds.is_empty() {
1696 bounds.insert(0, GenericBound::maybe_sized(cx));
1701 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1703 ty::Bound(..) => panic!("Bound"),
1704 ty::Placeholder(..) => panic!("Placeholder"),
1705 ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1706 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1707 ty::Infer(..) => panic!("Infer"),
1708 ty::Error => panic!("Error"),
1713 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1714 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1716 type_: self.ty.clean(cx),
1717 expr: format!("{}", self),
1724 impl Clean<Item> for hir::StructField<'_> {
1725 fn clean(&self, cx: &DocContext<'_>) -> Item {
1726 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1729 name: Some(self.ident.name).clean(cx),
1730 attrs: self.attrs.clean(cx),
1731 source: self.span.clean(cx),
1732 visibility: self.vis.clean(cx),
1733 stability: get_stability(cx, local_did),
1734 deprecation: get_deprecation(cx, local_did),
1736 inner: StructFieldItem(self.ty.clean(cx)),
1741 impl Clean<Item> for ty::FieldDef {
1742 fn clean(&self, cx: &DocContext<'_>) -> Item {
1744 name: Some(self.ident.name).clean(cx),
1745 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1746 source: cx.tcx.def_span(self.did).clean(cx),
1747 visibility: self.vis.clean(cx),
1748 stability: get_stability(cx, self.did),
1749 deprecation: get_deprecation(cx, self.did),
1751 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1756 impl Clean<Visibility> for hir::Visibility<'_> {
1757 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1759 hir::VisibilityKind::Public => Visibility::Public,
1760 hir::VisibilityKind::Inherited => Visibility::Inherited,
1761 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1762 hir::VisibilityKind::Restricted { ref path, .. } => {
1763 let path = path.clean(cx);
1764 let did = register_res(cx, path.res);
1765 Visibility::Restricted(did, path)
1771 impl Clean<Visibility> for ty::Visibility {
1772 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1773 if *self == ty::Visibility::Public { Public } else { Inherited }
1777 impl Clean<Item> for doctree::Struct<'_> {
1778 fn clean(&self, cx: &DocContext<'_>) -> Item {
1780 name: Some(self.name.clean(cx)),
1781 attrs: self.attrs.clean(cx),
1782 source: self.whence.clean(cx),
1783 def_id: cx.tcx.hir().local_def_id(self.id),
1784 visibility: self.vis.clean(cx),
1785 stability: cx.stability(self.id).clean(cx),
1786 deprecation: cx.deprecation(self.id).clean(cx),
1787 inner: StructItem(Struct {
1788 struct_type: self.struct_type,
1789 generics: self.generics.clean(cx),
1790 fields: self.fields.clean(cx),
1791 fields_stripped: false,
1797 impl Clean<Item> for doctree::Union<'_> {
1798 fn clean(&self, cx: &DocContext<'_>) -> Item {
1800 name: Some(self.name.clean(cx)),
1801 attrs: self.attrs.clean(cx),
1802 source: self.whence.clean(cx),
1803 def_id: cx.tcx.hir().local_def_id(self.id),
1804 visibility: self.vis.clean(cx),
1805 stability: cx.stability(self.id).clean(cx),
1806 deprecation: cx.deprecation(self.id).clean(cx),
1807 inner: UnionItem(Union {
1808 struct_type: self.struct_type,
1809 generics: self.generics.clean(cx),
1810 fields: self.fields.clean(cx),
1811 fields_stripped: false,
1817 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1818 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1820 struct_type: doctree::struct_type_from_def(self),
1821 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1822 fields_stripped: false,
1827 impl Clean<Item> for doctree::Enum<'_> {
1828 fn clean(&self, cx: &DocContext<'_>) -> Item {
1830 name: Some(self.name.clean(cx)),
1831 attrs: self.attrs.clean(cx),
1832 source: self.whence.clean(cx),
1833 def_id: cx.tcx.hir().local_def_id(self.id),
1834 visibility: self.vis.clean(cx),
1835 stability: cx.stability(self.id).clean(cx),
1836 deprecation: cx.deprecation(self.id).clean(cx),
1837 inner: EnumItem(Enum {
1838 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1839 generics: self.generics.clean(cx),
1840 variants_stripped: false,
1846 impl Clean<Item> for doctree::Variant<'_> {
1847 fn clean(&self, cx: &DocContext<'_>) -> Item {
1849 name: Some(self.name.clean(cx)),
1850 attrs: self.attrs.clean(cx),
1851 source: self.whence.clean(cx),
1852 visibility: Inherited,
1853 stability: cx.stability(self.id).clean(cx),
1854 deprecation: cx.deprecation(self.id).clean(cx),
1855 def_id: cx.tcx.hir().local_def_id(self.id),
1856 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1861 impl Clean<Item> for ty::VariantDef {
1862 fn clean(&self, cx: &DocContext<'_>) -> Item {
1863 let kind = match self.ctor_kind {
1864 CtorKind::Const => VariantKind::CLike,
1865 CtorKind::Fn => VariantKind::Tuple(
1866 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1868 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1869 struct_type: doctree::Plain,
1870 fields_stripped: false,
1875 source: cx.tcx.def_span(field.did).clean(cx),
1876 name: Some(field.ident.name.clean(cx)),
1877 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1878 visibility: field.vis.clean(cx),
1880 stability: get_stability(cx, field.did),
1881 deprecation: get_deprecation(cx, field.did),
1882 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1888 name: Some(self.ident.clean(cx)),
1889 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1890 source: cx.tcx.def_span(self.def_id).clean(cx),
1891 visibility: Inherited,
1892 def_id: self.def_id,
1893 inner: VariantItem(Variant { kind }),
1894 stability: get_stability(cx, self.def_id),
1895 deprecation: get_deprecation(cx, self.def_id),
1900 impl Clean<VariantKind> for hir::VariantData<'_> {
1901 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1903 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1904 hir::VariantData::Tuple(..) => {
1905 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1907 hir::VariantData::Unit(..) => VariantKind::CLike,
1912 impl Clean<Span> for rustc_span::Span {
1913 fn clean(&self, cx: &DocContext<'_>) -> Span {
1914 if self.is_dummy() {
1915 return Span::empty();
1918 let cm = cx.sess().source_map();
1919 let filename = cm.span_to_filename(*self);
1920 let lo = cm.lookup_char_pos(self.lo());
1921 let hi = cm.lookup_char_pos(self.hi());
1925 locol: lo.col.to_usize(),
1927 hicol: hi.col.to_usize(),
1933 impl Clean<Path> for hir::Path<'_> {
1934 fn clean(&self, cx: &DocContext<'_>) -> Path {
1936 global: self.is_global(),
1938 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1943 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1944 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1945 if self.parenthesized {
1946 let output = self.bindings[0].ty().clean(cx);
1947 GenericArgs::Parenthesized {
1948 inputs: self.inputs().clean(cx),
1949 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1952 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1953 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1956 GenericArgs::AngleBracketed {
1960 .filter_map(|arg| match arg {
1961 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1962 Some(GenericArg::Lifetime(lt.clean(cx)))
1964 hir::GenericArg::Lifetime(_) => None,
1965 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1966 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1969 bindings: self.bindings.clean(cx),
1975 impl Clean<PathSegment> for hir::PathSegment<'_> {
1976 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1977 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1981 impl Clean<String> for Ident {
1983 fn clean(&self, cx: &DocContext<'_>) -> String {
1988 impl Clean<String> for ast::Name {
1990 fn clean(&self, _: &DocContext<'_>) -> String {
1995 impl Clean<Item> for doctree::Typedef<'_> {
1996 fn clean(&self, cx: &DocContext<'_>) -> Item {
1997 let type_ = self.ty.clean(cx);
1998 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
2000 name: Some(self.name.clean(cx)),
2001 attrs: self.attrs.clean(cx),
2002 source: self.whence.clean(cx),
2003 def_id: cx.tcx.hir().local_def_id(self.id),
2004 visibility: self.vis.clean(cx),
2005 stability: cx.stability(self.id).clean(cx),
2006 deprecation: cx.deprecation(self.id).clean(cx),
2007 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2012 impl Clean<Item> for doctree::OpaqueTy<'_> {
2013 fn clean(&self, cx: &DocContext<'_>) -> Item {
2015 name: Some(self.name.clean(cx)),
2016 attrs: self.attrs.clean(cx),
2017 source: self.whence.clean(cx),
2018 def_id: cx.tcx.hir().local_def_id(self.id),
2019 visibility: self.vis.clean(cx),
2020 stability: cx.stability(self.id).clean(cx),
2021 deprecation: cx.deprecation(self.id).clean(cx),
2022 inner: OpaqueTyItem(
2024 bounds: self.opaque_ty.bounds.clean(cx),
2025 generics: self.opaque_ty.generics.clean(cx),
2033 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2034 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2035 let (generic_params, decl) = enter_impl_trait(cx, || {
2036 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2038 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2042 impl Clean<Item> for doctree::Static<'_> {
2043 fn clean(&self, cx: &DocContext<'_>) -> Item {
2044 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2046 name: Some(self.name.clean(cx)),
2047 attrs: self.attrs.clean(cx),
2048 source: self.whence.clean(cx),
2049 def_id: cx.tcx.hir().local_def_id(self.id),
2050 visibility: self.vis.clean(cx),
2051 stability: cx.stability(self.id).clean(cx),
2052 deprecation: cx.deprecation(self.id).clean(cx),
2053 inner: StaticItem(Static {
2054 type_: self.type_.clean(cx),
2055 mutability: self.mutability,
2056 expr: print_const_expr(cx, self.expr),
2062 impl Clean<Item> for doctree::Constant<'_> {
2063 fn clean(&self, cx: &DocContext<'_>) -> Item {
2064 let def_id = cx.tcx.hir().local_def_id(self.id);
2067 name: Some(self.name.clean(cx)),
2068 attrs: self.attrs.clean(cx),
2069 source: self.whence.clean(cx),
2071 visibility: self.vis.clean(cx),
2072 stability: cx.stability(self.id).clean(cx),
2073 deprecation: cx.deprecation(self.id).clean(cx),
2074 inner: ConstantItem(Constant {
2075 type_: self.type_.clean(cx),
2076 expr: print_const_expr(cx, self.expr),
2077 value: print_evaluated_const(cx, def_id),
2078 is_literal: is_literal_expr(cx, self.expr.hir_id),
2084 impl Clean<ImplPolarity> for ty::ImplPolarity {
2085 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2087 &ty::ImplPolarity::Positive |
2088 // FIXME: do we want to do something else here?
2089 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2090 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2095 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2096 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2097 let mut ret = Vec::new();
2098 let trait_ = self.trait_.clean(cx);
2099 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2100 let def_id = cx.tcx.hir().local_def_id(self.id);
2102 // If this impl block is an implementation of the Deref trait, then we
2103 // need to try inlining the target's inherent impl blocks as well.
2104 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2105 build_deref_target_impls(cx, &items, &mut ret);
2108 let provided: FxHashSet<String> = trait_
2112 .provided_trait_methods(did)
2114 .map(|meth| meth.ident.to_string())
2117 .unwrap_or_default();
2119 let for_ = self.for_.clean(cx);
2120 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2121 Some(DefKind::TyAlias) => Some(cx.tcx.type_of(did).clean(cx)),
2124 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2126 attrs: self.attrs.clean(cx),
2127 source: self.whence.clean(cx),
2129 visibility: self.vis.clean(cx),
2130 stability: cx.stability(self.id).clean(cx),
2131 deprecation: cx.deprecation(self.id).clean(cx),
2132 inner: ImplItem(Impl {
2133 unsafety: self.unsafety,
2134 generics: self.generics.clean(cx),
2135 provided_trait_methods: provided.clone(),
2139 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2144 if let Some(type_alias) = type_alias {
2145 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2147 ret.push(make_item(trait_, for_, items));
2152 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2153 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2154 let please_inline = self.vis.node.is_pub()
2155 && self.attrs.iter().any(|a| {
2156 a.check_name(sym::doc)
2157 && match a.meta_item_list() {
2158 Some(l) => attr::list_contains_name(&l, sym::inline),
2164 let mut visited = FxHashSet::default();
2166 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2168 if let Some(items) = inline::try_inline(
2172 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2181 attrs: self.attrs.clean(cx),
2182 source: self.whence.clean(cx),
2183 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2184 visibility: self.vis.clean(cx),
2187 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2192 impl Clean<Vec<Item>> for doctree::Import<'_> {
2193 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2194 // We consider inlining the documentation of `pub use` statements, but we
2195 // forcefully don't inline if this is not public or if the
2196 // #[doc(no_inline)] attribute is present.
2197 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2198 let mut denied = !self.vis.node.is_pub()
2199 || self.attrs.iter().any(|a| {
2200 a.check_name(sym::doc)
2201 && match a.meta_item_list() {
2203 attr::list_contains_name(&l, sym::no_inline)
2204 || attr::list_contains_name(&l, sym::hidden)
2209 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2210 // crate in Rust 2018+
2211 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2212 let path = self.path.clean(cx);
2213 let inner = if self.glob {
2215 let mut visited = FxHashSet::default();
2216 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2221 Import::Glob(resolve_use_source(cx, path))
2223 let name = self.name;
2226 Res::Def(DefKind::Mod, did) => {
2227 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2228 // if we're `pub use`ing an extern crate root, don't inline it unless we
2229 // were specifically asked for it
2237 let mut visited = FxHashSet::default();
2238 if let Some(items) = inline::try_inline(
2242 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2248 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2253 attrs: self.attrs.clean(cx),
2254 source: self.whence.clean(cx),
2255 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2256 visibility: self.vis.clean(cx),
2259 inner: ImportItem(inner),
2264 impl Clean<Item> for doctree::ForeignItem<'_> {
2265 fn clean(&self, cx: &DocContext<'_>) -> Item {
2266 let inner = match self.kind {
2267 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2268 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2269 let (generics, decl) =
2270 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2271 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2272 ForeignFunctionItem(Function {
2275 header: hir::FnHeader {
2276 unsafety: hir::Unsafety::Unsafe,
2278 constness: hir::Constness::NotConst,
2279 asyncness: hir::IsAsync::NotAsync,
2285 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2286 type_: ty.clean(cx),
2288 expr: String::new(),
2290 hir::ForeignItemKind::Type => ForeignTypeItem,
2294 name: Some(self.name.clean(cx)),
2295 attrs: self.attrs.clean(cx),
2296 source: self.whence.clean(cx),
2297 def_id: cx.tcx.hir().local_def_id(self.id),
2298 visibility: self.vis.clean(cx),
2299 stability: cx.stability(self.id).clean(cx),
2300 deprecation: cx.deprecation(self.id).clean(cx),
2306 impl Clean<Item> for doctree::Macro<'_> {
2307 fn clean(&self, cx: &DocContext<'_>) -> Item {
2308 let name = self.name.clean(cx);
2310 name: Some(name.clone()),
2311 attrs: self.attrs.clean(cx),
2312 source: self.whence.clean(cx),
2314 stability: cx.stability(self.hid).clean(cx),
2315 deprecation: cx.deprecation(self.hid).clean(cx),
2316 def_id: self.def_id,
2317 inner: MacroItem(Macro {
2319 "macro_rules! {} {{\n{}}}",
2323 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2324 .collect::<String>()
2326 imported_from: self.imported_from.clean(cx),
2332 impl Clean<Item> for doctree::ProcMacro<'_> {
2333 fn clean(&self, cx: &DocContext<'_>) -> Item {
2335 name: Some(self.name.clean(cx)),
2336 attrs: self.attrs.clean(cx),
2337 source: self.whence.clean(cx),
2339 stability: cx.stability(self.id).clean(cx),
2340 deprecation: cx.deprecation(self.id).clean(cx),
2341 def_id: cx.tcx.hir().local_def_id(self.id),
2342 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2347 impl Clean<Stability> for attr::Stability {
2348 fn clean(&self, _: &DocContext<'_>) -> Stability {
2350 level: stability::StabilityLevel::from_attr_level(&self.level),
2351 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2352 since: match self.level {
2353 attr::Stable { ref since } => since.to_string(),
2356 deprecation: self.rustc_depr.as_ref().map(|d| Deprecation {
2357 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2358 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2360 unstable_reason: match self.level {
2361 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2364 issue: match self.level {
2365 attr::Unstable { issue, .. } => issue,
2372 impl Clean<Deprecation> for attr::Deprecation {
2373 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2375 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2376 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2381 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2382 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2383 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2387 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2388 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2390 hir::TypeBindingKind::Equality { ref ty } => {
2391 TypeBindingKind::Equality { ty: ty.clean(cx) }
2393 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2394 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2401 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2405 impl From<GenericBound> for SimpleBound {
2406 fn from(bound: GenericBound) -> Self {
2407 match bound.clone() {
2408 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2409 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2410 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2412 param_names.map_or_else(
2414 |v| v.iter().map(|p| SimpleBound::from(p.clone())).collect(),
2419 _ => panic!("Unexpected bound {:?}", bound),